code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
# Author: <NAME>
# Email: <EMAIL>
# License: MIT License
import scipy
import random
import numpy as np
from .search_tracker import SearchTracker
from ..converter import Converter
from ..results_manager import ResultsManager
from ..init_positions import Initializer
from ..utils import set_random_seed, move_random
def set_random_seed(nth_process, random_state):
"""
Sets the random seed separately for each thread
(to avoid getting the same results in each thread)
"""
if nth_process is None:
nth_process = 0
if random_state is None:
random_state = np.random.randint(0, high=2 ** 31 - 2, dtype=np.int64)
random.seed(random_state + nth_process)
np.random.seed(random_state + nth_process)
def get_n_inits(initialize):
n_inits = 0
for key_ in initialize.keys():
init_value = initialize[key_]
if isinstance(init_value, int):
n_inits += init_value
else:
n_inits += len(init_value)
return n_inits
class BaseOptimizer(SearchTracker):
def __init__(
self,
search_space,
initialize={"grid": 4, "random": 2, "vertices": 4},
random_state=None,
rand_rest_p=0,
nth_process=None,
):
super().__init__()
self.conv = Converter(search_space)
self.results_mang = ResultsManager(self.conv)
self.initialize = initialize
self.random_state = random_state
self.rand_rest_p = rand_rest_p
self.nth_process = nth_process
self.state = "init"
self.optimizers = [self]
set_random_seed(nth_process, random_state)
# get init positions
init = Initializer(self.conv)
self.init_positions = init.set_pos(self.initialize)
self.n_inits = get_n_inits(initialize)
def move_random(self):
return move_random(self.conv.search_space_positions)
def track_nth_iter(func):
def wrapper(self, *args, **kwargs):
self.nth_iter = len(self.pos_new_list)
pos = func(self, *args, **kwargs)
self.pos_new = pos
return pos
return wrapper
def random_restart(func):
def wrapper(self, *args, **kwargs):
if self.rand_rest_p > random.uniform(0, 1):
return self.move_random()
else:
return func(self, *args, **kwargs)
return wrapper
def conv2pos(self, pos):
# position to int
r_pos = np.rint(pos)
n_zeros = [0] * len(self.conv.max_positions)
# clip into search space boundaries
pos = np.clip(r_pos, n_zeros, self.conv.max_positions).astype(int)
dist = scipy.spatial.distance.cdist(r_pos.reshape(1, -1), pos.reshape(1, -1))
threshold = self.conv.search_space_size / (100 ** self.conv.n_dimensions)
if dist > threshold:
return self.move_random()
return pos
def init_pos(self, pos):
self.pos_new = pos
self.nth_iter = len(self.pos_new_list)
return pos
def finish_initialization(self):
pass
def evaluate(self, score_new):
self.score_new = score_new
if self.pos_best is None:
self.pos_best = self.pos_new
self.pos_current = self.pos_new
self.score_best = score_new
self.score_current = score_new
# self._evaluate_new2current(score_new)
# self._evaluate_current2best()
| [
"numpy.random.seed",
"random.uniform",
"numpy.clip",
"numpy.rint",
"numpy.random.randint",
"random.seed"
] | [((654, 693), 'random.seed', 'random.seed', (['(random_state + nth_process)'], {}), '(random_state + nth_process)\n', (665, 693), False, 'import random\n'), ((698, 740), 'numpy.random.seed', 'np.random.seed', (['(random_state + nth_process)'], {}), '(random_state + nth_process)\n', (712, 740), True, 'import numpy as np\n'), ((594, 648), 'numpy.random.randint', 'np.random.randint', (['(0)'], {'high': '(2 ** 31 - 2)', 'dtype': 'np.int64'}), '(0, high=2 ** 31 - 2, dtype=np.int64)\n', (611, 648), True, 'import numpy as np\n'), ((2491, 2503), 'numpy.rint', 'np.rint', (['pos'], {}), '(pos)\n', (2498, 2503), True, 'import numpy as np\n'), ((2262, 2282), 'random.uniform', 'random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (2276, 2282), False, 'import random\n'), ((2616, 2664), 'numpy.clip', 'np.clip', (['r_pos', 'n_zeros', 'self.conv.max_positions'], {}), '(r_pos, n_zeros, self.conv.max_positions)\n', (2623, 2664), True, 'import numpy as np\n')] |
import gzip
import importlib
import json
import pkgutil
import shutil
import tarfile
import zipfile
import requests
from pathlib import Path
from types import ModuleType
from typing import Dict, Tuple, Union, Any, NoReturn
from urllib.request import urlretrieve
import numpy as np
import pandas as pd
import wget
from _jsonnet import evaluate_file
from tqdm import tqdm
from lexsubgen.utils.register import CACHE_DIR, memory
def extract_archive(arch_path: Union[str, Path], dest: str):
"""
Extracts archive into a given folder.
Args:
arch_path: path to archive file.
Could be given as string or `pathlib.Path`.
dest: path to destination folder.
"""
arch_path = Path(arch_path)
file_suffixes = arch_path.suffixes
outer_suffix = file_suffixes[-1]
inner_suffix = file_suffixes[-2] if len(file_suffixes) > 1 else ""
if outer_suffix == ".zip":
with zipfile.ZipFile(arch_path, "r") as fp:
fp.extractall(path=dest)
elif outer_suffix == ".tgz" or (outer_suffix == ".gz" and inner_suffix == ".tar"):
with tarfile.open(arch_path, "r:gz") as tar:
dirs = [member for member in tar.getmembers()]
tar.extractall(path=dest, members=dirs)
elif outer_suffix == ".gz":
with gzip.open(arch_path, "rb") as gz:
with open(
arch_path.parent / (arch_path.stem + inner_suffix), "wb"
) as uncomp:
shutil.copyfileobj(gz, uncomp)
@memory.cache
def load_word2freq() -> Dict[str, int]:
"""
Loads word frequencies data.
Returns:
mapping from words to their counts
"""
freq_words_path = CACHE_DIR / "resources" / "count_1w.txt"
if not freq_words_path.exists():
freq_words_path.mkdir(freq_words_path.parent, parents=True, exist_ok=True)
urlretrieve("http://norvig.com/ngrams/count_1w.txt", filename=freq_words_path)
frequency_words = pd.read_csv(
freq_words_path, sep="\t", header=None, names=["word", "count"]
)
total = len(frequency_words)
gen = zip(frequency_words["word"], frequency_words["count"])
word2freq = {
word: count
for word, count in tqdm(gen, desc="Loading frequency words", total=total)
}
return word2freq
def download_embeddings(url: str, dest: Union[str, Path]):
dest_path = Path(dest)
if not dest_path.exists():
dest_path.mkdir(parents=True)
file_name = wget.download(url, out=str(dest))
extract_archive(file_name, dest)
file_path = Path(file_name)
file_path.unlink()
@memory.cache
def get_emb_matrix(file_name: str) -> Tuple[np.ndarray, Dict, Dict]:
"""
Loads embedding matrix from a given file. The embeddings should be stored
in the following format. First row of data consists of two values: vocabulary size
and size of the embeddings. Each next row contains word represented as a string and
sequence of embedding vector values.
Args:
file_name: path to the file containing embeddings.
Returns:
`numpy.ndarray` - embedding matrix, and two representations of vocabulary:
mapping from words to their indexes and list of words.
"""
count = 0
word2id = {}
vocab = {}
embeddings_list = []
with open(file_name) as f:
vocab_size, embedding_size = f.readline().split()
vocab_size, embedding_size = int(vocab_size), int(embedding_size)
for idx in range(vocab_size):
word, values = f.readline().split(maxsplit=1)
values = values.split()
if len(values) == embedding_size:
word2id[word] = count
vocab[count] = word
embeddings_list.append(np.array([float(val) for val in values]))
count += 1
else:
raise ValueError(
f"Wrong size of word embedding {len(values)}. "
f"Expected {embedding_size} elements."
)
return np.stack(embeddings_list, axis=0), word2id, vocab
def download_large_gdrive_file(
file_id: str, dst: str,
gdrive_url: str = "https://docs.google.com/uc?export=download",
) -> NoReturn:
with requests.Session() as s:
response = s.get(
gdrive_url,
params={"id": file_id},
stream=True,
)
token = None
for key, value in response.cookies.items():
if key.startswith('download_warning'):
token = value
break
if token:
response = s.get(
gdrive_url,
params={"id": file_id, "confirm": token},
stream=True,
)
with open(dst, "wb") as f:
for chunk in response.iter_content(8192):
if chunk:
f.write(chunk)
def dump_json(path: Union[str, Path], object: Any):
"""
Saves object in the given directory in JSON format
Args:
path: This directory must have already been created.
Could be a string or `pathlib.Path` object.
object: data to store.
"""
with Path(path).open("w") as fp:
json.dump(object, fp, indent=4)
def create_run_dir(run_dir: Union[str, Path], force: bool = False):
"""
Creates experiment (run) directory. Saves experiment configuration file.
If `force` is true, will overwrite data in an existing directory.
Args:
run_dir: path to a directory where to store experiment results.
Could be a string or `pathlib.Path` object.
force: whether to overwrite data in an existing directory.
"""
run_path = Path(run_dir)
if run_path.exists() and force:
shutil.rmtree(run_path)
run_path.mkdir(parents=True, exist_ok=False)
def import_submodules(module: Union[str, ModuleType], recursive: bool = True):
"""
Imports submodules from a given path. This could also be done recursively.
Args:
module: module path.
recursive: whether to load submodules recursively (default: True).
"""
importlib.invalidate_caches()
if isinstance(module, str):
module = importlib.import_module(module)
module_path = module.__path__
first_path = module_path[0] if module_path else ""
for module_finder, name, is_pkg in pkgutil.walk_packages(module_path):
if first_path and module_finder.path != first_path:
# skip 3-rd party packages
continue
submodule_name = module.__name__ + "." + name
if recursive and is_pkg:
import_submodules(submodule_name, recursive)
def is_valid_jsonnet(file_path: Union[str, Path]) -> bool:
file_path = Path(file_path)
assert file_path.suffix == ".jsonnet"
try:
evaluate_file(str(file_path))
return True
except Exception as e:
return False
| [
"numpy.stack",
"json.dump",
"tqdm.tqdm",
"importlib.invalidate_caches",
"pkgutil.walk_packages",
"importlib.import_module",
"zipfile.ZipFile",
"pandas.read_csv",
"gzip.open",
"requests.Session",
"urllib.request.urlretrieve",
"pathlib.Path",
"tarfile.open",
"shutil.rmtree",
"shutil.copyfi... | [((714, 729), 'pathlib.Path', 'Path', (['arch_path'], {}), '(arch_path)\n', (718, 729), False, 'from pathlib import Path\n'), ((1950, 2026), 'pandas.read_csv', 'pd.read_csv', (['freq_words_path'], {'sep': '"""\t"""', 'header': 'None', 'names': "['word', 'count']"}), "(freq_words_path, sep='\\t', header=None, names=['word', 'count'])\n", (1961, 2026), True, 'import pandas as pd\n'), ((2363, 2373), 'pathlib.Path', 'Path', (['dest'], {}), '(dest)\n', (2367, 2373), False, 'from pathlib import Path\n'), ((2546, 2561), 'pathlib.Path', 'Path', (['file_name'], {}), '(file_name)\n', (2550, 2561), False, 'from pathlib import Path\n'), ((5685, 5698), 'pathlib.Path', 'Path', (['run_dir'], {}), '(run_dir)\n', (5689, 5698), False, 'from pathlib import Path\n'), ((6112, 6141), 'importlib.invalidate_caches', 'importlib.invalidate_caches', ([], {}), '()\n', (6139, 6141), False, 'import importlib\n'), ((6354, 6388), 'pkgutil.walk_packages', 'pkgutil.walk_packages', (['module_path'], {}), '(module_path)\n', (6375, 6388), False, 'import pkgutil\n'), ((6731, 6746), 'pathlib.Path', 'Path', (['file_path'], {}), '(file_path)\n', (6735, 6746), False, 'from pathlib import Path\n'), ((1848, 1926), 'urllib.request.urlretrieve', 'urlretrieve', (['"""http://norvig.com/ngrams/count_1w.txt"""'], {'filename': 'freq_words_path'}), "('http://norvig.com/ngrams/count_1w.txt', filename=freq_words_path)\n", (1859, 1926), False, 'from urllib.request import urlretrieve\n'), ((4012, 4045), 'numpy.stack', 'np.stack', (['embeddings_list'], {'axis': '(0)'}), '(embeddings_list, axis=0)\n', (4020, 4045), True, 'import numpy as np\n'), ((4217, 4235), 'requests.Session', 'requests.Session', ([], {}), '()\n', (4233, 4235), False, 'import requests\n'), ((5198, 5229), 'json.dump', 'json.dump', (['object', 'fp'], {'indent': '(4)'}), '(object, fp, indent=4)\n', (5207, 5229), False, 'import json\n'), ((5743, 5766), 'shutil.rmtree', 'shutil.rmtree', (['run_path'], {}), '(run_path)\n', (5756, 5766), False, 'import shutil\n'), ((6192, 6223), 'importlib.import_module', 'importlib.import_module', (['module'], {}), '(module)\n', (6215, 6223), False, 'import importlib\n'), ((921, 952), 'zipfile.ZipFile', 'zipfile.ZipFile', (['arch_path', '"""r"""'], {}), "(arch_path, 'r')\n", (936, 952), False, 'import zipfile\n'), ((2204, 2258), 'tqdm.tqdm', 'tqdm', (['gen'], {'desc': '"""Loading frequency words"""', 'total': 'total'}), "(gen, desc='Loading frequency words', total=total)\n", (2208, 2258), False, 'from tqdm import tqdm\n'), ((1097, 1128), 'tarfile.open', 'tarfile.open', (['arch_path', '"""r:gz"""'], {}), "(arch_path, 'r:gz')\n", (1109, 1128), False, 'import tarfile\n'), ((5162, 5172), 'pathlib.Path', 'Path', (['path'], {}), '(path)\n', (5166, 5172), False, 'from pathlib import Path\n'), ((1293, 1319), 'gzip.open', 'gzip.open', (['arch_path', '"""rb"""'], {}), "(arch_path, 'rb')\n", (1302, 1319), False, 'import gzip\n'), ((1464, 1494), 'shutil.copyfileobj', 'shutil.copyfileobj', (['gz', 'uncomp'], {}), '(gz, uncomp)\n', (1482, 1494), False, 'import shutil\n')] |
# *****************************************************************************
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the NVIDIA CORPORATION nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# *****************************************************************************\
import os
import random
import argparse
import json
import torch
import torch.utils.data
import sys
from scipy.io.wavfile import read
import binpacking
import numpy as np
# We're using the audio processing from TacoTron2 to make sure it matches
sys.path.insert(0, 'tacotron2')
from tacotron2.layers import TacotronSTFT
MAX_WAV_VALUE = 32768.0
def files_to_list(filename):
"""
Takes a text file of filenames and makes a list of filenames
"""
with open(filename, encoding='utf-8') as f:
files = f.readlines()
files = [f.rstrip() for f in files]
return files
def load_wav_to_torch(full_path):
"""
Loads wavdata into torch array
"""
sampling_rate, data = read(full_path)
return torch.from_numpy(data).float(), sampling_rate
# forward_input[0] = mel_spectrogram: batch x n_mel_channels x frames
# forward_input[1] = audio: batch x time
class Mel2SampSplit(torch.utils.data.Dataset):
"""
This is the main class that calculates the spectrogram and returns the
spectrogram, audio pair.
"""
def __init__(self, training_files, segment_length, filter_length,
hop_length, win_length, sampling_rate, mel_fmin, mel_fmax):
self.audio_files = files_to_list(training_files)
random.seed(1234)
self.stft = TacotronSTFT(filter_length=filter_length,
hop_length=hop_length,
win_length=win_length,
sampling_rate=sampling_rate,
mel_fmin=mel_fmin, mel_fmax=mel_fmax)
self.segment_length = segment_length
self.sampling_rate = sampling_rate
self.dataset = self.pack()
def pack(self):
timings = np.zeros(len(self.audio_files), dtype= np.int32)
PAD = 350
assert(self.sampling_rate % PAD == 0)
for i,file in enumerate(self.audio_files):
audio, sampling_rate = load_wav_to_torch(file)
if sampling_rate != self.sampling_rate:
raise ValueError("{} SR doesn't match target {} SR".format(
sampling_rate, self.sampling_rate))
t = audio.size(0)
t2 = t + t % PAD
timings[i] = t2
segment_len = self.sampling_rate
total_time = timings.sum()
n_data = int(total_time // segment_len) if total_time % segment_len == 0 else int((total_time // segment_len) + 1)
##import pdb; pdb.set_trace()
dataset = torch.zeros([ n_data,segment_len], dtype=torch.float32 ) ## all data will be here
offset = 0
cur = 0
for i,file in enumerate(self.audio_files):
audio, _ = load_wav_to_torch(file)
audio = torch.nn.functional.pad(audio, (0, timings[i] - audio.size(0)), 'constant').data
assert(timings[i] == audio.size(0))
data_left = audio.size(0)
data_offset = 0
space = segment_len - offset
while (data_left >= space): ## fill the next data segment to the end
dataset.data[cur,offset:offset+space] = audio[data_offset:data_offset+space]
data_left = data_left - space
data_offset = data_offset + space
offset = 0
space = segment_len
cur = cur + 1
## append whats left in the next data segement
if data_left > 0:
new_offset = offset + data_left
dataset.data[cur,offset:new_offset] = audio[data_offset:]
offset = new_offset
return dataset
def get_mel(self, audio):
audio_norm = audio / MAX_WAV_VALUE
audio_norm = audio_norm.unsqueeze(0)
audio_norm = torch.autograd.Variable(audio_norm, requires_grad=False)
melspec = self.stft.mel_spectrogram(audio_norm)
melspec = torch.squeeze(melspec, 0)
return melspec
def __getitem__(self, index):
# Read audio
audio = self.dataset.data[index,:]
mel = self.get_mel(audio)
audio = audio / MAX_WAV_VALUE
return (mel, audio)
def __len__(self):
return self.dataset.size(0)
class Mel2Samp2(torch.utils.data.Dataset):
"""
This is the main class that calculates the spectrogram and returns the
spectrogram, audio pair.
"""
def __init__(self, training_files, segment_length, filter_length,
hop_length, win_length, sampling_rate, mel_fmin, mel_fmax):
self.audio_files = files_to_list(training_files)
random.seed(1234)
random.shuffle(self.audio_files)
self.stft = TacotronSTFT(filter_length=filter_length,
hop_length=hop_length,
win_length=win_length,
sampling_rate=sampling_rate,
mel_fmin=mel_fmin, mel_fmax=mel_fmax)
self.segment_length = segment_length
self.sampling_rate = sampling_rate
self.everything = self.pack()
self.max_time = self.segment_length
best = -1
score = 0.0
if self.max_time == 0: ##auto configuration for maximum efficiency
for x in range(250000, 1000000,10000):
self.max_time = x
self.do_binpacking()
utilized = np.asarray(self.volumes).mean()/self.max_time
if utilized > score:
score = utilized
best= x
self.max_time = best
self.do_binpacking()
##import pdb; pdb.set_trace()
perm = list(range(len(self.balancer)))
random.shuffle(perm)
self.volumes = [self.volumes[p] for p in perm ]
self.balancer = [self.balancer[p] for p in perm ]
def pack(self):
for file in self.audio_files:
audio, sampling_rate = load_wav_to_torch(file)
if sampling_rate != self.sampling_rate:
raise ValueError("{} SR doesn't match target {} SR".format(
sampling_rate, self.sampling_rate))
timings.append(audio.size(0))
def get_timings(self):
timings = np.zeros(len(self.audio_files))
for file in self.audio_files:
audio, sampling_rate = load_wav_to_torch(file)
if sampling_rate != self.sampling_rate:
raise ValueError("{} SR doesn't match target {} SR".format(
sampling_rate, self.sampling_rate))
timings.append(audio.size(0))
def get_mel(self, audio):
audio_norm = audio / MAX_WAV_VALUE
audio_norm = audio_norm.unsqueeze(0)
audio_norm = torch.autograd.Variable(audio_norm, requires_grad=False)
melspec = self.stft.mel_spectrogram(audio_norm)
melspec = torch.squeeze(melspec, 0)
return melspec
def __getitem__(self, index):
# Read audio
print(index)
idxs = self.balancer[index]
time = self.volumes[index]
pad = (self.max_time - time) // (len(idxs)- 1)
print(pad)
print(time)
print(idxs)
audios = []
for k,idx in enumerate(idxs):
filename = self.audio_files[idx]
audio, sampling_rate = load_wav_to_torch(filename)
if sampling_rate != self.sampling_rate:
raise ValueError("{} SR doesn't match target {} SR".format(
sampling_rate, self.sampling_rate))
print("before pad %d: %s" % ( idx ,audio.shape))
if k != len(idxs) - 1:
audio = torch.nn.functional.pad(audio, (0, pad), 'constant').data
print("after pad %d: %s" % ( idx ,audio.shape))
audios.append(audio)
audio = torch.cat(audios)
print("after cat: %s" % audio.shape)
if audio.size(0) < self.max_time:
audio = torch.nn.functional.pad(audio, (0, self.max_time- audio.size(0)), 'constant').data
print("after last pad: %s" % audio.shape)
mel = self.get_mel(audio)
audio = audio / MAX_WAV_VALUE
return (mel, audio)
def __len__(self):
return len(self.balancer)
class Mel2Samp(torch.utils.data.Dataset):
"""
This is the main class that calculates the spectrogram and returns the
spectrogram, audio pair.
"""
def __init__(self, training_files, segment_length, filter_length,
hop_length, win_length, sampling_rate, mel_fmin, mel_fmax):
self.audio_files = files_to_list(training_files)
random.seed(1234)
random.shuffle(self.audio_files)
self.stft = TacotronSTFT(filter_length=filter_length,
hop_length=hop_length,
win_length=win_length,
sampling_rate=sampling_rate,
mel_fmin=mel_fmin, mel_fmax=mel_fmax)
self.segment_length = segment_length
self.sampling_rate = sampling_rate
def get_mel(self, audio):
audio_norm = audio / MAX_WAV_VALUE
audio_norm = audio_norm.unsqueeze(0)
audio_norm = torch.autograd.Variable(audio_norm, requires_grad=False)
melspec = self.stft.mel_spectrogram(audio_norm)
melspec = torch.squeeze(melspec, 0)
return melspec
def __getitem__(self, index):
# Read audio
filename = self.audio_files[index]
audio, sampling_rate = load_wav_to_torch(filename)
if sampling_rate != self.sampling_rate:
raise ValueError("{} SR doesn't match target {} SR".format(
sampling_rate, self.sampling_rate))
# Take segment
if audio.size(0) >= self.segment_length:
max_audio_start = audio.size(0) - self.segment_length
audio_start = random.randint(0, max_audio_start)
audio = audio[audio_start:audio_start+self.segment_length]
else:
audio = torch.nn.functional.pad(audio, (0, self.segment_length - audio.size(0)), 'constant').data
mel = self.get_mel(audio)
audio = audio / MAX_WAV_VALUE
return (mel, audio)
def __len__(self):
return len(self.audio_files)
# ===================================================================
# Takes directory of clean audio and makes directory of spectrograms
# Useful for making test sets
# ===================================================================
if __name__ == "__main__":
# Get defaults so it can work with no Sacred
parser = argparse.ArgumentParser()
parser.add_argument('-f', "--filelist_path", required=True)
parser.add_argument('-c', '--config', type=str,
help='JSON file for configuration')
parser.add_argument('-o', '--output_dir', type=str,
help='Output directory')
args = parser.parse_args()
with open(args.config) as f:
data = f.read()
data_config = json.loads(data)["data_config"]
mel2samp = Mel2Samp(**data_config)
filepaths = files_to_list(args.filelist_path)
# Make directory if it doesn't exist
if not os.path.isdir(args.output_dir):
os.makedirs(args.output_dir)
os.chmod(args.output_dir, 0o775)
for filepath in filepaths:
audio, sr = load_wav_to_torch(filepath)
melspectrogram = mel2samp.get_mel(audio)
filename = os.path.basename(filepath)
new_filepath = args.output_dir + '/' + filename + '.pt'
print(new_filepath)
torch.save(melspectrogram, new_filepath)
| [
"argparse.ArgumentParser",
"random.shuffle",
"torch.cat",
"scipy.io.wavfile.read",
"torch.nn.functional.pad",
"json.loads",
"random.randint",
"torch.squeeze",
"random.seed",
"torch.zeros",
"tacotron2.layers.TacotronSTFT",
"os.chmod",
"os.path.basename",
"torch.autograd.Variable",
"numpy.... | [((1985, 2016), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""tacotron2"""'], {}), "(0, 'tacotron2')\n", (2000, 2016), False, 'import sys\n'), ((2443, 2458), 'scipy.io.wavfile.read', 'read', (['full_path'], {}), '(full_path)\n', (2447, 2458), False, 'from scipy.io.wavfile import read\n'), ((12405, 12430), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (12428, 12430), False, 'import argparse\n'), ((3009, 3026), 'random.seed', 'random.seed', (['(1234)'], {}), '(1234)\n', (3020, 3026), False, 'import random\n'), ((3047, 3211), 'tacotron2.layers.TacotronSTFT', 'TacotronSTFT', ([], {'filter_length': 'filter_length', 'hop_length': 'hop_length', 'win_length': 'win_length', 'sampling_rate': 'sampling_rate', 'mel_fmin': 'mel_fmin', 'mel_fmax': 'mel_fmax'}), '(filter_length=filter_length, hop_length=hop_length, win_length\n =win_length, sampling_rate=sampling_rate, mel_fmin=mel_fmin, mel_fmax=\n mel_fmax)\n', (3059, 3211), False, 'from tacotron2.layers import TacotronSTFT\n'), ((4285, 4340), 'torch.zeros', 'torch.zeros', (['[n_data, segment_len]'], {'dtype': 'torch.float32'}), '([n_data, segment_len], dtype=torch.float32)\n', (4296, 4340), False, 'import torch\n'), ((5549, 5605), 'torch.autograd.Variable', 'torch.autograd.Variable', (['audio_norm'], {'requires_grad': '(False)'}), '(audio_norm, requires_grad=False)\n', (5572, 5605), False, 'import torch\n'), ((5680, 5705), 'torch.squeeze', 'torch.squeeze', (['melspec', '(0)'], {}), '(melspec, 0)\n', (5693, 5705), False, 'import torch\n'), ((6365, 6382), 'random.seed', 'random.seed', (['(1234)'], {}), '(1234)\n', (6376, 6382), False, 'import random\n'), ((6391, 6423), 'random.shuffle', 'random.shuffle', (['self.audio_files'], {}), '(self.audio_files)\n', (6405, 6423), False, 'import random\n'), ((6445, 6609), 'tacotron2.layers.TacotronSTFT', 'TacotronSTFT', ([], {'filter_length': 'filter_length', 'hop_length': 'hop_length', 'win_length': 'win_length', 'sampling_rate': 'sampling_rate', 'mel_fmin': 'mel_fmin', 'mel_fmax': 'mel_fmax'}), '(filter_length=filter_length, hop_length=hop_length, win_length\n =win_length, sampling_rate=sampling_rate, mel_fmin=mel_fmin, mel_fmax=\n mel_fmax)\n', (6457, 6609), False, 'from tacotron2.layers import TacotronSTFT\n'), ((7471, 7491), 'random.shuffle', 'random.shuffle', (['perm'], {}), '(perm)\n', (7485, 7491), False, 'import random\n'), ((8504, 8560), 'torch.autograd.Variable', 'torch.autograd.Variable', (['audio_norm'], {'requires_grad': '(False)'}), '(audio_norm, requires_grad=False)\n', (8527, 8560), False, 'import torch\n'), ((8635, 8660), 'torch.squeeze', 'torch.squeeze', (['melspec', '(0)'], {}), '(melspec, 0)\n', (8648, 8660), False, 'import torch\n'), ((9618, 9635), 'torch.cat', 'torch.cat', (['audios'], {}), '(audios)\n', (9627, 9635), False, 'import torch\n'), ((10414, 10431), 'random.seed', 'random.seed', (['(1234)'], {}), '(1234)\n', (10425, 10431), False, 'import random\n'), ((10440, 10472), 'random.shuffle', 'random.shuffle', (['self.audio_files'], {}), '(self.audio_files)\n', (10454, 10472), False, 'import random\n'), ((10493, 10657), 'tacotron2.layers.TacotronSTFT', 'TacotronSTFT', ([], {'filter_length': 'filter_length', 'hop_length': 'hop_length', 'win_length': 'win_length', 'sampling_rate': 'sampling_rate', 'mel_fmin': 'mel_fmin', 'mel_fmax': 'mel_fmax'}), '(filter_length=filter_length, hop_length=hop_length, win_length\n =win_length, sampling_rate=sampling_rate, mel_fmin=mel_fmin, mel_fmax=\n mel_fmax)\n', (10505, 10657), False, 'from tacotron2.layers import TacotronSTFT\n'), ((11008, 11064), 'torch.autograd.Variable', 'torch.autograd.Variable', (['audio_norm'], {'requires_grad': '(False)'}), '(audio_norm, requires_grad=False)\n', (11031, 11064), False, 'import torch\n'), ((11139, 11164), 'torch.squeeze', 'torch.squeeze', (['melspec', '(0)'], {}), '(melspec, 0)\n', (11152, 11164), False, 'import torch\n'), ((12819, 12835), 'json.loads', 'json.loads', (['data'], {}), '(data)\n', (12829, 12835), False, 'import json\n'), ((12994, 13024), 'os.path.isdir', 'os.path.isdir', (['args.output_dir'], {}), '(args.output_dir)\n', (13007, 13024), False, 'import os\n'), ((13034, 13062), 'os.makedirs', 'os.makedirs', (['args.output_dir'], {}), '(args.output_dir)\n', (13045, 13062), False, 'import os\n'), ((13071, 13101), 'os.chmod', 'os.chmod', (['args.output_dir', '(509)'], {}), '(args.output_dir, 509)\n', (13079, 13101), False, 'import os\n'), ((13252, 13278), 'os.path.basename', 'os.path.basename', (['filepath'], {}), '(filepath)\n', (13268, 13278), False, 'import os\n'), ((13379, 13419), 'torch.save', 'torch.save', (['melspectrogram', 'new_filepath'], {}), '(melspectrogram, new_filepath)\n', (13389, 13419), False, 'import torch\n'), ((11683, 11717), 'random.randint', 'random.randint', (['(0)', 'max_audio_start'], {}), '(0, max_audio_start)\n', (11697, 11717), False, 'import random\n'), ((2470, 2492), 'torch.from_numpy', 'torch.from_numpy', (['data'], {}), '(data)\n', (2486, 2492), False, 'import torch\n'), ((9433, 9485), 'torch.nn.functional.pad', 'torch.nn.functional.pad', (['audio', '(0, pad)', '"""constant"""'], {}), "(audio, (0, pad), 'constant')\n", (9456, 9485), False, 'import torch\n'), ((7170, 7194), 'numpy.asarray', 'np.asarray', (['self.volumes'], {}), '(self.volumes)\n', (7180, 7194), True, 'import numpy as np\n')] |
import numpy as np
from collections import defaultdict
from sympy import Matrix, MatrixSymbol, lambdify
from .icp import icp, tr_icp
POINT_DIM = 3
POINT_SHAPE = (3)
Xi = MatrixSymbol('Xi', 3, 1)
Xj = MatrixSymbol('Xj', 3, 1)
Z = MatrixSymbol('Z', 3, 1)
Z_ = Xj - Xi
# z_ = lambdify((Xi, Xj), Matrix(Z_), modules='numpy')
E = Matrix(Z - Z_)
e = lambdify((Z, Xi, Xj), E, modules='numpy')
A = lambdify((Z, Xi, Xj), E.jacobian(Xi), modules='numpy')
B = lambdify((Z, Xi, Xj), E.jacobian(Xj), modules='numpy')
class Vertex:
def __init__(self, point, laser_scanner_data=None):
self.point = point
self.laser_scanner_data = laser_scanner_data
class Edge:
def __init__(self, from_vertex_id, to_vertex_id, transform=None, z=None, info_matrix=None):
self.from_x = from_vertex_id
self.to_x = to_vertex_id
self.transform = transform
self.z = z
self.info_matrix = info_matrix
def getTransform(self, V):
return V[self.to_x].point - V[self.from_x].point
class ICPSLAM:
def __init__(self, optimized=True):
self.vertices = []
self.edges = []
self.adjacency_list = defaultdict(lambda: defaultdict(int))
self.optimized = optimized
self.init_pose = np.zeros(POINT_SHAPE)
def getVertices(self):
return self.vertices
def getEdges(self):
return self.edges
def getAdjList(self):
return self.adjacency_list
def mapping(self, transform, laser_scanner_data):
V = len(self.vertices)
E = len(self.edges)
# find a new vertex and edges
new_vertex, new_edges = self.predict(transform)
new_vertex.laser_scanner_data = laser_scanner_data
# append a new vertex and edges
if V == 0 or not np.all(np.fabs(self.vertices[-1].point - new_vertex.point) < 0.01):
self.vertices.append(new_vertex)
for edge in new_edges:
new_edge_id = len(self.edges)
self.edges.append(edge)
self.adjacency_list[edge.from_x][edge.to_x] = new_edge_id
# print('add new point at ', new_vertex.point)
if V > 0:
for edge in new_edges:
laser_scanner_data_i = self.vertices[edge.from_x].laser_scanner_data
laser_scanner_data_j = self.vertices[edge.to_x].laser_scanner_data
transform = edge.getTransform(self.vertices)
# get z, info_matrix from the measurement
# z_ij, info_matrix_ij = self.getMeasurement(
# laser_scanner_data_i, laser_scanner_data_j, transform)
# assign z, info_matrix to the edge
# edge.z = z_ij
# edge.info_matrix = info_matrix_ij
if self.optimized:
# TODO ICP optimization
self.optimize(self.vertices, new_edges)
def predict(self, transform):
if len(self.vertices) > 0:
V = len(self.vertices)
vi = self.vertices[-1]
vj = self.next_point(vi.point, transform)
edge = Edge(V - 1, V, transform=vj.point - vi.point)
return vj, [edge]
else:
vj = Vertex(self.init_pose)
return vj, []
def next_point(self, point, transform):
return Vertex(point + transform)
def getMeasurement(self, laser_scanner_data_i, laser_scanner_data_j, transform):
P_i = laser_scanner_data_i.copy()
P_j = laser_scanner_data_j.copy()
# dx, dy, dtheta = transform
# R = np.array([[np.cos(dtheta), np.sin(dtheta)],
# [- np.sin(dtheta), np.cos(dtheta)]])
# T = np.array([[dx], [dy]])
# P_i = P_i @ R.T + T.T
R, T = tr_icp(P_i, P_j, N_iter=15)
dtheta = np.arctan2(R[1, 0], R[0, 0])
dx = T[0]
dy = T[1]
z = np.array([dx, dy, dtheta])
# omega = np.linalg.inv(np.array([[2, 0.1, 0.1],
# [0.1, 2, 0.1],
# [0.1, 0.1, 2]]))
return z, None
def optimize(self, vertices, edges):
for edge in edges:
v_i = vertices[edge.from_x]
v_j = vertices[edge.to_x]
dx, dy, dtheta = v_j.point - v_i.point
P_i = v_i.laser_scanner_data.copy()
P_j = v_j.laser_scanner_data.copy()
R0 = np.array([[np.cos(dtheta), - np.sin(dtheta)],
[np.sin(dtheta), np.cos(dtheta)]])
T0 = np.array([dx, dy]).reshape((2, 1))
Q = P_i @ R0 + T0.T
R, T = tr_icp(Q, P_j, N_iter=25)
dtheta = np.arctan2(R[0, 1], R[0, 0])
dx = T[0]
dy = T[1]
v_j.point += np.array([dx, dy, dtheta])
def getImage(self):
return None
def getVertexPoints(self):
points = []
for vertex in self.vertices:
points.append(vertex.point)
return points
| [
"numpy.arctan2",
"numpy.zeros",
"sympy.Matrix",
"sympy.lambdify",
"collections.defaultdict",
"numpy.fabs",
"numpy.array",
"numpy.sin",
"sympy.MatrixSymbol",
"numpy.cos"
] | [((176, 200), 'sympy.MatrixSymbol', 'MatrixSymbol', (['"""Xi"""', '(3)', '(1)'], {}), "('Xi', 3, 1)\n", (188, 200), False, 'from sympy import Matrix, MatrixSymbol, lambdify\n'), ((206, 230), 'sympy.MatrixSymbol', 'MatrixSymbol', (['"""Xj"""', '(3)', '(1)'], {}), "('Xj', 3, 1)\n", (218, 230), False, 'from sympy import Matrix, MatrixSymbol, lambdify\n'), ((235, 258), 'sympy.MatrixSymbol', 'MatrixSymbol', (['"""Z"""', '(3)', '(1)'], {}), "('Z', 3, 1)\n", (247, 258), False, 'from sympy import Matrix, MatrixSymbol, lambdify\n'), ((331, 345), 'sympy.Matrix', 'Matrix', (['(Z - Z_)'], {}), '(Z - Z_)\n', (337, 345), False, 'from sympy import Matrix, MatrixSymbol, lambdify\n'), ((350, 391), 'sympy.lambdify', 'lambdify', (['(Z, Xi, Xj)', 'E'], {'modules': '"""numpy"""'}), "((Z, Xi, Xj), E, modules='numpy')\n", (358, 391), False, 'from sympy import Matrix, MatrixSymbol, lambdify\n'), ((1261, 1282), 'numpy.zeros', 'np.zeros', (['POINT_SHAPE'], {}), '(POINT_SHAPE)\n', (1269, 1282), True, 'import numpy as np\n'), ((3877, 3905), 'numpy.arctan2', 'np.arctan2', (['R[1, 0]', 'R[0, 0]'], {}), '(R[1, 0], R[0, 0])\n', (3887, 3905), True, 'import numpy as np\n'), ((3955, 3981), 'numpy.array', 'np.array', (['[dx, dy, dtheta]'], {}), '([dx, dy, dtheta])\n', (3963, 3981), True, 'import numpy as np\n'), ((4762, 4790), 'numpy.arctan2', 'np.arctan2', (['R[0, 1]', 'R[0, 0]'], {}), '(R[0, 1], R[0, 0])\n', (4772, 4790), True, 'import numpy as np\n'), ((4861, 4887), 'numpy.array', 'np.array', (['[dx, dy, dtheta]'], {}), '([dx, dy, dtheta])\n', (4869, 4887), True, 'import numpy as np\n'), ((1182, 1198), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (1193, 1198), False, 'from collections import defaultdict\n'), ((4618, 4636), 'numpy.array', 'np.array', (['[dx, dy]'], {}), '([dx, dy])\n', (4626, 4636), True, 'import numpy as np\n'), ((1794, 1845), 'numpy.fabs', 'np.fabs', (['(self.vertices[-1].point - new_vertex.point)'], {}), '(self.vertices[-1].point - new_vertex.point)\n', (1801, 1845), True, 'import numpy as np\n'), ((4503, 4517), 'numpy.cos', 'np.cos', (['dtheta'], {}), '(dtheta)\n', (4509, 4517), True, 'import numpy as np\n'), ((4567, 4581), 'numpy.sin', 'np.sin', (['dtheta'], {}), '(dtheta)\n', (4573, 4581), True, 'import numpy as np\n'), ((4583, 4597), 'numpy.cos', 'np.cos', (['dtheta'], {}), '(dtheta)\n', (4589, 4597), True, 'import numpy as np\n'), ((4521, 4535), 'numpy.sin', 'np.sin', (['dtheta'], {}), '(dtheta)\n', (4527, 4535), True, 'import numpy as np\n')] |
"""Helpers for reducing the resolution of various operators.
Intended for use in calculating the uncertainties at a coarser
resolution than the fluxes.
"""
from __future__ import division
from math import ceil
import numpy as np
from numpy import zeros, newaxis
DTYPE = np.float32
def get_remappers(domain_size, block_side=3):
"""Get matrices to remap from original to coarser resolution.
Parameters
----------
domain_size: Tuple[int, int]
The size of the spatial domain.
block_side: int, optional
The number of original cells in each direction to combine into
a single new cell.
Returns
-------
extensive_remapper: array_like
A matrix for changing extensive quantities or finding the sum.
In this package, that would be the observation operators.
intensive_remapper: array_like
A matrix for changing intensive quantities or finding the mean.
In this package, that would be the fluxes.
"""
domain_size = tuple(domain_size)
reduced_size = tuple(int(ceil(dim / block_side)) for dim in domain_size)
extensive_remapper = zeros(reduced_size + domain_size,
dtype=DTYPE)
for i in range(reduced_size[0]):
old_i = block_side * i
for j in range(reduced_size[1]):
old_j = block_side * j
extensive_remapper[i, j, old_i:old_i + block_side,
old_j:old_j + block_side] = 1
assert old_i + block_side >= domain_size[0] - 1
assert old_j + block_side >= domain_size[1] - 1
intensive_remapper = extensive_remapper.copy()
n_nz = intensive_remapper.sum(axis=(-1, -2))
intensive_remapper /= n_nz[:, :, newaxis, newaxis]
return extensive_remapper, intensive_remapper
| [
"numpy.zeros",
"math.ceil"
] | [((1129, 1175), 'numpy.zeros', 'zeros', (['(reduced_size + domain_size)'], {'dtype': 'DTYPE'}), '(reduced_size + domain_size, dtype=DTYPE)\n', (1134, 1175), False, 'from numpy import zeros, newaxis\n'), ((1056, 1078), 'math.ceil', 'ceil', (['(dim / block_side)'], {}), '(dim / block_side)\n', (1060, 1078), False, 'from math import ceil\n')] |
import numpy as np
import utils
def evaluate_by_metrics(model, params, data, metrics, tag_map_path):
X_valid = utils.process_data_for_keras(params.number_of_tags, data['data'])
length = np.array([len(sent) for sent in data['data']], dtype='int32')
y_pred = model.predict(X_valid)
y = np.argmax(y_pred, -1)
y_pred = [iy[:l] for iy, l in zip(y, length)]
idx2label = {}
with open(tag_map_path) as f:
for i, tag in enumerate(f.readlines()):
tag = tag.strip().split()[0]
idx2label[i] = tag
val_metrics = {metric: metrics[metric](data['labels'], y_pred, idx2label)
for metric in metrics}
return val_metrics
| [
"utils.process_data_for_keras",
"numpy.argmax"
] | [((118, 183), 'utils.process_data_for_keras', 'utils.process_data_for_keras', (['params.number_of_tags', "data['data']"], {}), "(params.number_of_tags, data['data'])\n", (146, 183), False, 'import utils\n'), ((303, 324), 'numpy.argmax', 'np.argmax', (['y_pred', '(-1)'], {}), '(y_pred, -1)\n', (312, 324), True, 'import numpy as np\n')] |
"""Database classes and support for measurements"""
from abc import ABC
import json
import logging
import os
import re
import sys
import time
import numpy as np
from typing import Tuple
from google.cloud import bigquery
logging.basicConfig(level=logging.INFO)
def get_database(style: str):
"""Retrieve database to the database to be used
Returns database client, database object, Integer type to be used
and a connection object (for Azure)
"""
conn = None
if style == "ms":
logging.info("Using Microsoft Azure backend")
server = "mysupertestserver.database.windows.net"
database = "mysupertestdatabase"
username = "mysupertestadmin"
password = "<PASSWORD>"
import pymssql
conn = pymssql.connect(server, username, password, database)
client = conn.cursor(as_dict=True)
dbo = "dbo"
integer = "INTEGER"
elif style == "google":
logging.info("Using Google Big Query backend")
client = bigquery.Client()
dbo = "ADataSet"
integer = "INT64"
elif style == "none":
logging.info("Using No Backend")
dbo = "Nopedb"
integer = "Nopeint"
client = None
else:
logging.error("Error in configuring database")
sys.exit(1)
return client, dbo, integer, conn
# Keep all this in case we want real SQL publshing again
# cpu_table = "ci_cpu_measurement_tedge_mapper"
# mem_table = "ci_mem_measurement_tedge_mapper"
# cpu_hist_table = "ci_cpu_hist"
# def myquery(client, query, conn, style):
#
# logging.info(query)
#
# if style == "ms":
# client.execute(query)
# conn.commit()
#
# elif style == "google":
#
# query_job = client.query(query)
# if query_job.errors:
# logging.error("Error", query_job.error_result)
# sys.exit(1)
# time.sleep(0.3)
# elif style == "none":
# pass
# else:
# sys.exit(1)
# def get_sql_create_cpu_table(dbo, name, integer):
# create_cpu = f"""
# CREATE TABLE {dbo}.{name} (
# id {integer},
# mid {integer},
# sample {integer},
# utime {integer},
# stime {integer},
# cutime {integer},
# cstime {integer}
# );
# """
# def get_sql_create_mem_table(dbo, name, integer):
# create_mem = f"""
# CREATE TABLE {dbo}.{name} (
# id {integer},
# mid {integer},
# sample {integer},
# size {integer},
# resident {integer},
# shared {integer},
# text {integer},
# data {integer}
# );
# """
# def get_sql_create_mem_table(dbo, name, integer):
# create_cpu_hist = f"""
# CREATE TABLE {dbo}.{name} (
# id {integer},
# last {integer},
# old {integer},
# older {integer},
# evenolder {integer},
# evenmovreolder {integer}
# );
# """
# def get_sql_create_mem_table(dbo, name, client):
# myquery(client, f"drop table {dbo}.{cpu_table}")
# def get_sql_create_mem_table(dbo, name, client):
# myquery(client, f"drop table {dbo}.{mem_table}")
# def get_sql_create_mem_table(dbo, name, client):
# myquery(client, f"drop table {dbo}.{cpu_hist_table}")
class MeasurementBase(ABC):
"""Abstract base class for type Measurements"""
def __init__(self, lake, name, data_amount, data_length, client, testmode):
# Amount of columns in the table
self.data_amount = data_amount
# Length of the measurement in seconds
self.data_length = data_length
self.size = data_length * data_amount
self.client = client
self.lake = lake
self.json_data = None
self.job_config = None
if testmode:
self.name = name + "_test"
else:
self.name = name
self.database = f"thin-edge-statistics.ThinEdgeDataSet.{self.name}"
def postprocess(self, folders, testname, filename, binary):
"""Postprocess all relevant folders"""
def show(self):
"""Show content on console"""
def update_table(self):
"""Create table and prepare loading via json and upload"""
def delete_table(self):
"""Delete the table from the cloud"""
try:
self.client.delete_table(self.database)
except: # TODO: Can' import this google.api_core.exceptions.NotFound:
pass
def upload_table(self):
"""Upload table to online database"""
if self.client:
load_job = self.client.load_table_from_json(
self.json_data,
self.database,
job_config=self.job_config,
)
while load_job.running():
time.sleep(0.5)
logging.info("Waiting")
if load_job.errors:
logging.error("Error %s", load_job.error_result)
logging.error(load_job.errors)
raise SystemError
@staticmethod
def foldername_to_index(foldername: str) -> int:
"""Convert results_N_unpack into N"""
reg = re.compile(r"^results_(\d+)_unpack$")
match = reg.match(foldername)
if match:
index = int(match.group(1))
else:
raise SystemError("Cannot convert foldername")
return index
class MeasurementMetadata(MeasurementBase):
"""Class to represent a table of measurement metadata"""
def __init__(self, lake, name, data_amount, data_length, client, testmode):
super().__init__(lake, name, data_amount, data_length, client, testmode)
self.array = np.zeros((self.size, 7), dtype=np.int32)
self.row_id = 0
self.array = []
self.client = client
def scrap_data(self, file: str) -> Tuple[str, str, str, str, str]:
"""Read measurement data from file"""
with open(file) as content:
data = json.load(content)
run = data["run_number"]
date = data["updated_at"]
url = data["html_url"]
name = data["name"]
branch = data["head_branch"]
return run, date, url, name, branch
def postprocess(self, folders):
"""Postprocess all relevant folders"""
idx = 0
for folder in folders:
index = self.foldername_to_index(folder)
name = f"system_test_{index}_metadata.json"
path = os.path.join(self.lake, name)
run, date, url, name, branch = self.scrap_data(path)
self.array.append((idx, run, date, url, name, branch))
idx += 1
return self.array
def show(self):
"""Show content on console"""
logging.info("Content of table %s", self.database)
for row in self.array:
logging.info(row)
def update_table(self):
"""Create table and prepare loading via json and upload"""
logging.info("Updating table: %s", self.name)
self.delete_table()
self.job_config = bigquery.LoadJobConfig(
schema=[
bigquery.SchemaField("id", "INT64"),
bigquery.SchemaField("mid", "INT64"),
bigquery.SchemaField("date", "STRING"),
bigquery.SchemaField("url", "STRING"),
bigquery.SchemaField("name", "STRING"),
bigquery.SchemaField("branch", "STRING"),
],
)
self.json_data = []
for index in range(self.data_amount):
self.json_data.append(
{
"id": self.array[index][0],
"mid": self.array[index][1],
"date": self.array[index][2],
"url": self.array[index][3],
"name": self.array[index][4],
"branch": self.array[index][5],
}
)
self.upload_table()
class CpuHistory(MeasurementBase):
"""Class to represent a table of measured CPU usage"""
def __init__(self, lake, name, data_amount, data_length, client, testmode):
super().__init__(lake, name, data_amount, data_length, client, testmode)
self.array = np.zeros((self.size, 7), dtype=np.int32)
# The current row index
self.row_id = 0
def scrap_zeros(self, measurement_index):
"""Fill a measurement with zeros"""
sample = 0
for i in range(self.data_length):
utime = 0
stime = 0
cutime = 0 # cutime
cstime = 0 # cstime
self.insert_line(
idx=self.row_id,
mid=measurement_index,
sample=sample,
utime=utime,
stime=stime,
cutime=cutime,
cstime=cstime,
)
sample += 1
self.row_id += 1
def scrap_data_collectd(self, file_utime, file_stime, measurement_index):
"""Read measurement data from collectd export"""
sample = 0
try:
with open(file_utime) as thestats_utime:
with open(file_stime) as thestats_stime:
lines_utime = thestats_utime.readlines()
lines_stime = thestats_stime.readlines()
assert len(lines_utime) == self.data_length
assert len(lines_stime) == self.data_length
for i in range(self.data_length):
timestamp_utime, utime_str = lines_utime[i].split()
timestamp_stime, stime_str = lines_stime[i].split()
if timestamp_utime != timestamp_stime:
print(
f"Warning timestamps are not equal {timestamp_utime} and {timestamp_stime}"
)
if utime_str == "None":
utime = 0
else:
utime = int(float(utime_str))
if stime_str == "None":
stime = 0
else:
stime = int(float(stime_str))
cutime = (
0 # glue cutime to zero, we do not have child processes
)
cstime = (
0 # glue cstime to zero, we do not have child processes
)
self.insert_line(
idx=self.row_id,
mid=measurement_index,
sample=sample,
utime=utime,
stime=stime,
cutime=cutime,
cstime=cstime,
)
sample += 1
self.row_id += 1
except FileNotFoundError as err:
logging.warning("File not found, skipping for now! %s", str(err))
missing = self.data_length - sample
assert missing == 0
def scrap_data(self, thefile, measurement_index, binary):
"""Read measurement data from file /proc/pid/stat
See manpage proc ($ man proc) in section /proc/[pid]/stat for colum descriptions
"""
sample = 0
try:
with open(thefile) as thestats:
lines = thestats.readlines()
for line in lines:
entries = line.split()
# In some cases there some entries from /proc/stat here.
# This can happen when the pid is not existing anymore
# then /proc/pid/stat is evaluated to /proc/stat
# We just filter here to match the right lines.
if len(entries) == 52 and entries[1] == f"({binary})":
# It can happen that there are 61 lines measured
# e.g. in the 60s interval, we just ignore them
if sample >= self.data_length:
logging.warning(
"Omitted a sample from mid %s", measurement_index
)
continue
utime = int(entries[13]) # utime
stime = int(entries[14]) # stime
cutime = int(entries[15]) # cutime
cstime = int(entries[16]) # cstime
self.insert_line(
idx=self.row_id,
mid=measurement_index,
sample=sample,
utime=utime,
stime=stime,
cutime=cutime,
cstime=cstime,
)
sample += 1
self.row_id += 1
except FileNotFoundError as err:
logging.warning("File not found, skipping for now! %s", str(err))
# In case that there are not enough lines in the file fix with zeros
# Can happen, depending on when the data recorder process is killed.
missing = self.data_length - sample
for miss in range(missing):
self.insert_line(
idx=self.row_id,
mid=measurement_index,
sample=sample,
utime=0,
stime=0,
cutime=0,
cstime=0,
)
sample += 1
self.row_id += 1
def postprocess(self, folders, testname, filename, binary):
"""Postprocess all relevant folders"""
for folder in folders:
index = self.foldername_to_index(folder)
statsfile = (
f"{self.lake}/{folder}/PySys/{testname}/Output/linux/{filename}.out"
)
if filename == "stat_mapper_stdout":
filename_rrd1 = "gauge-mapper-c8y-utime"
filename_rrd2 = "gauge-mapper-c8y-stime"
elif filename == "stat_mosquitto_stdout":
filename_rrd1 = "gauge-mosquitto-utime"
filename_rrd2 = "gauge-mosquitto-stime"
else:
raise SystemError("Cannot convert filename %s" % filename)
rrdfile1 = f"{self.lake}/{folder}/PySys/analytics/{testname}/Output/linux/{filename_rrd1}.rrd.txt"
rrdfile2 = f"{self.lake}/{folder}/PySys/analytics/{testname}/Output/linux/{filename_rrd2}.rrd.txt"
# After moving tests into folders
rrdfile1_old = f"{self.lake}/{folder}/PySys/{testname}/Output/linux/{filename_rrd1}.rrd.txt"
rrdfile2_old = f"{self.lake}/{folder}/PySys/{testname}/Output/linux/{filename_rrd2}.rrd.txt"
if os.path.exists(statsfile):
self.scrap_data(statsfile, index, binary)
elif os.path.exists(rrdfile1):
self.scrap_data_collectd(rrdfile1, rrdfile2, index)
elif os.path.exists(rrdfile1_old):
self.scrap_data_collectd(rrdfile1_old, rrdfile2_old, index)
else:
# breakpoint()
# raise SystemError("File does not exist !!!")
logging.info(
"CPU history file does not exist! %s or %s or %s" % (statsfile, rrdfile1, rrdfile2)
)
logging.info("Filling with zeros")
self.scrap_zeros(index)
def insert_line(self, idx, mid, sample, utime, stime, cutime, cstime):
"""Insert a line into the table"""
self.array[idx] = [idx, mid, sample, utime, stime, cutime, cstime]
def show(self):
"""Show content with matplotlib"""
import matplotlib.pyplot as plt
fig, axis = plt.subplots()
axis.plot(self.array[:, 1], ".", label="mid")
axis.plot(self.array[:, 2], "-", label="sample")
axis.plot(self.array[:, 3], "-", label="utime")
axis.plot(self.array[:, 4], "-", label="stime")
axis.plot(self.array[:, 5], "-", label="cutime")
axis.plot(self.array[:, 6], "-", label="cstime")
plt.legend()
plt.title("CPU History " + self.name)
plt.show()
def update_table(self):
"""Create table and prepare loading via json and upload"""
logging.info("Updating table: %s", self.name)
self.delete_table()
self.job_config = bigquery.LoadJobConfig(
schema=[
bigquery.SchemaField("id", "INT64"),
bigquery.SchemaField("mid", "INT64"),
bigquery.SchemaField("sample", "INT64"),
bigquery.SchemaField("utime", "INT64"),
bigquery.SchemaField("stime", "INT64"),
bigquery.SchemaField("cutime", "INT64"),
bigquery.SchemaField("cstime", "INT64"),
],
)
self.json_data = []
for i in range(self.size):
self.json_data.append(
{
"id": int(self.array[i, 0]),
"mid": int(self.array[i, 1]),
"sample": int(self.array[i, 2]),
"utime": int(self.array[i, 3]),
"stime": int(self.array[i, 4]),
"cutime": int(self.array[i, 5]),
"cstime": int(self.array[i, 6]),
}
)
self.upload_table()
class CpuHistoryStacked(MeasurementBase):
"""Class to represent a table of measured CPU usage as stacked graph.
The graph contains user and system cpu time for the last N test-runs.
"""
def __init__(self, lake, name, data_amount, data_length, client, testmode):
super().__init__(lake, name, data_amount, data_length, client, testmode)
self.row_id = 0
self.history = 10 # process the last 10 test runs
self.fields = [
("id", "INT64"),
("t0u", "INT64"),
("t0s", "INT64"),
("t1u", "INT64"),
("t1s", "INT64"),
("t2u", "INT64"),
("t2s", "INT64"),
("t3u", "INT64"),
("t3s", "INT64"),
("t4u", "INT64"),
("t4s", "INT64"),
("t5u", "INT64"),
("t5s", "INT64"),
("t6u", "INT64"),
("t6s", "INT64"),
("t7u", "INT64"),
("t7s", "INT64"),
("t8u", "INT64"),
("t8s", "INT64"),
("t9u", "INT64"),
("t9s", "INT64"),
]
self.array = np.zeros((self.data_length, len(self.fields)), dtype=np.int32)
def postprocess(
self,
measurement_folders,
cpu_array,
):
"""Postprocess all relevant folders"""
mlen = len(measurement_folders)
# Set the id in the first column
for index in range(self.data_length):
self.array[index, 0] = index
processing_range = min(mlen, self.history)
column = 1
# Iterate backwards through the measurement list
for measurement in range(mlen - 1, mlen - processing_range - 1, -1):
for index in range(self.data_length):
# Read user time from the cpu_table
self.array[index, column] = cpu_array.array[
measurement * self.data_length + index, 3
]
# Read system time from the cpu_table
self.array[index, column + 1] = cpu_array.array[
measurement * self.data_length + index, 4
]
column += 2
def insert_line(self, line, idx):
"""Insert a line into the table"""
assert len(line) == len(self.fields)
self.array[idx] = line
def show(self):
"""Show content with matplotlib"""
import matplotlib.pyplot as plt
fig, axis = plt.subplots()
for i in range(len(self.fields)):
if i % 2 == 0:
style = "-o"
else:
style = "-x"
axis.plot(self.array[:, i], style, label=self.fields[i][0])
plt.legend()
plt.title("CPU History Stacked " + self.name)
plt.show()
def update_table(self):
"""Create table and prepare loading via json and upload"""
logging.info("Updating table: %s", self.name)
self.delete_table()
schema = []
for i in range(len(self.fields)):
schema.append(bigquery.SchemaField(self.fields[i][0], self.fields[i][1]))
self.job_config = bigquery.LoadJobConfig(schema=schema)
self.json_data = []
for i in range(self.data_length):
line = {}
for j in range(len(self.fields)):
line[self.fields[j][0]] = int(self.array[i, j])
self.json_data.append(line)
self.upload_table()
class MemoryHistory(MeasurementBase):
"""Class to represent a table of measured memory"""
def __init__(self, lake, name, data_amount, data_length, client, testmode):
super().__init__(lake, name, data_amount, data_length, client, testmode)
self.lake = lake
self.size = self.size
self.data_length = data_length
self.array = np.zeros((self.size, 8), dtype=np.int32)
self.client = client
self.row_id = 0
def scrap_zeros(self, measurement_index):
"""Fill an empty measurement with zeros"""
for sample in range(self.data_length):
self.insert_line(
idx=self.row_id,
mid=measurement_index,
sample=sample,
size=0,
resident=0,
shared=0,
text=0,
data=0,
)
self.row_id += 1
def scrap_data_collectd(self, thefolder, measurement_index):
"""Read measurement data from collectd exports"""
if not os.path.exists(thefolder):
raise SystemError("Folder not existing %s" % thefolder)
types = ["size", "resident", "shared", "text", "data"]
db = {"size": {}, "resident": {}, "shared": {}, "text": {}, "data": {}}
for idx, file in enumerate(types):
# Iterate through all rrd exports
myfile = f"gauge-mapper-c8y-{file}.rrd.txt"
thefile = os.path.join(thefolder, myfile)
try:
with open(thefile) as thestats:
lines = thestats.readlines()
assert len(lines) == self.data_length
for index in range(len(lines)):
timestamp, utime_str = lines[index].split()
if utime_str == "None":
utime_str = 0
db[file][index] = (timestamp, utime_str)
except FileNotFoundError as err:
logging.warning("File not found, skipping for now! %s", str(err))
for sample in range(self.data_length):
# Warn if timestamps differ
size_stamp = int(float(db["size"][sample][0]))
resident_stamp = int(float(db["resident"][sample][0]))
shared_stamp = int(float(db["shared"][sample][0]))
text_stamp = int(float(db["text"][sample][0]))
data_stamp = int(float(db["data"][sample][0]))
if (
not size_stamp
== resident_stamp
== shared_stamp
== text_stamp
== data_stamp
):
logging.info(
"Warning: timestamps differ: %s %s %s %s %s"
% (size_stamp, resident_stamp, shared_stamp, text_stamp, data_stamp)
)
for sample in range(self.data_length):
self.insert_line(
idx=self.row_id,
mid=measurement_index,
sample=sample,
size=int(float(db["size"][sample][1])),
resident=int(float(db["resident"][sample][1])),
shared=int(float(db["shared"][sample][1])),
text=int(float(db["text"][sample][1])),
data=int(float(db["data"][sample][1])),
)
self.row_id += 1
def scrap_data(self, thefile, measurement_index, arr):
"""Read measurement data from file"""
with open(thefile) as thestats:
lines = thestats.readlines()
sample = 0
for line in lines:
entries = line.split()
size = entries[0] # (1) total program size
resident = entries[1] # (2) resident set size
shared = entries[2] # (3) number of resident shared pages
text = entries[3] # (4) text (code)
# lib = entries[4] # (5) library (unused since Linux 2.6; always 0)
data = entries[5] # (6) data + stack
arr.insert_line(
idx=self.row_id,
mid=measurement_index,
sample=sample,
size=size,
resident=resident,
shared=shared,
text=text,
data=data,
)
sample += 1
self.row_id += 1
logging.debug("Read %s Memory stats", sample)
missing = self.data_length - sample
for miss in range(missing):
arr.insert_line(
idx=self.row_id,
mid=measurement_index,
sample=sample,
size=0,
resident=0,
shared=0,
text=0,
data=0,
)
sample += 1
self.row_id += 1
def postprocess(self, folders, testname, filename, binary):
"""Postprocess all relevant folders"""
for folder in folders:
index = self.foldername_to_index(folder)
statsfile = (
f"{self.lake}/{folder}/PySys/{testname}/Output/linux/{filename}.out"
)
# Select one of them to check if we measured with collectd
rrdfile = f"{self.lake}/{folder}/PySys/analytics/{testname}/Output/linux/gauge-mapper-c8y-resident.rrd.txt"
rrdfolder = f"{self.lake}/{folder}/PySys/analytics/{testname}/Output/linux/"
# After sorting tests into folders
rrdfile_old = f"{self.lake}/{folder}/PySys/{testname}/Output/linux/gauge-mapper-c8y-resident.rrd.txt"
rrdfolder_old = f"{self.lake}/{folder}/PySys/{testname}/Output/linux/"
if os.path.exists(statsfile):
self.scrap_data(statsfile, index, self)
elif os.path.exists(rrdfile):
self.scrap_data_collectd(rrdfolder, index)
elif os.path.exists(rrdfile_old):
self.scrap_data_collectd(rrdfolder_old, index)
else:
# breakpoint()
# raise SystemError("File does not exist !!!")
logging.info(
"Memory analytics does not exist !!! %s or %s"
% (statsfile, rrdfile)
)
logging.info("Filling with zeros")
self.scrap_zeros(index)
def insert_line(self, idx, mid, sample, size, resident, shared, text, data):
"""Insert a line into the table"""
self.array[idx] = [idx, mid, sample, size, resident, shared, text, data]
def show(self):
"""Show content with matplotlib"""
import matplotlib.pyplot as plt
fig, axis = plt.subplots()
style = "."
# ax.plot(self.array[:,0], 'o-')
axis.plot(self.array[:, 1], style, label="mid")
axis.plot(self.array[:, 2], style, label="sample")
axis.plot(self.array[:, 3], style, label="size")
axis.plot(self.array[:, 4], style, label="resident")
axis.plot(self.array[:, 5], style, label="shared")
axis.plot(self.array[:, 6], style, label="text")
axis.plot(self.array[:, 7], style, label="data")
plt.legend()
plt.title("Memory History " + self.name)
plt.show()
# Keep this in case we want real SQL publishing again
#
# def update_table_one_by_one(self, dbo):
# for i in range(self.size):
# assert self.array[i, 0] == i
# q = (
# f"insert into {dbo}.{mem_table} values ( {i}, {self.array[i,1]},"
# f" {self.array[i,2]}, {self.array[i,3]},{self.array[i,4]},"
# f"{self.array[i,5]},{self.array[i,6]}, {self.array[i,7]} );"
# )
# # print(q)
# myquery(self.client, q)
def update_table(self):
"""Create table and prepare loading via json and upload"""
self.delete_table()
logging.info("Updating table: %s", self.name)
self.job_config = bigquery.LoadJobConfig(
schema=[
bigquery.SchemaField("id", "INT64"),
bigquery.SchemaField("mid", "INT64"),
bigquery.SchemaField("sample", "INT64"),
bigquery.SchemaField("size", "INT64"),
bigquery.SchemaField("resident", "INT64"),
bigquery.SchemaField("shared", "INT64"),
bigquery.SchemaField("text", "INT64"),
bigquery.SchemaField("data", "INT64"),
],
)
self.json_data = []
for i in range(self.size):
self.json_data.append(
{
"id": int(self.array[i, 0]),
"mid": int(self.array[i, 1]),
"sample": int(self.array[i, 2]),
"size": int(self.array[i, 3]),
"resident": int(self.array[i, 4]),
"shared": int(self.array[i, 5]),
"text": int(self.array[i, 6]),
"data": int(self.array[i, 6]),
}
)
self.upload_table()
| [
"matplotlib.pyplot.title",
"google.cloud.bigquery.SchemaField",
"pymssql.connect",
"google.cloud.bigquery.Client",
"os.path.join",
"logging.error",
"logging.warning",
"os.path.exists",
"google.cloud.bigquery.LoadJobConfig",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show",
"matplotlib.py... | [((223, 262), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (242, 262), False, 'import logging\n'), ((512, 557), 'logging.info', 'logging.info', (['"""Using Microsoft Azure backend"""'], {}), "('Using Microsoft Azure backend')\n", (524, 557), False, 'import logging\n'), ((767, 820), 'pymssql.connect', 'pymssql.connect', (['server', 'username', 'password', 'database'], {}), '(server, username, password, database)\n', (782, 820), False, 'import pymssql\n'), ((5230, 5267), 're.compile', 're.compile', (['"""^results_(\\\\d+)_unpack$"""'], {}), "('^results_(\\\\d+)_unpack$')\n", (5240, 5267), False, 'import re\n'), ((5751, 5791), 'numpy.zeros', 'np.zeros', (['(self.size, 7)'], {'dtype': 'np.int32'}), '((self.size, 7), dtype=np.int32)\n', (5759, 5791), True, 'import numpy as np\n'), ((6830, 6880), 'logging.info', 'logging.info', (['"""Content of table %s"""', 'self.database'], {}), "('Content of table %s', self.database)\n", (6842, 6880), False, 'import logging\n'), ((7047, 7092), 'logging.info', 'logging.info', (['"""Updating table: %s"""', 'self.name'], {}), "('Updating table: %s', self.name)\n", (7059, 7092), False, 'import logging\n'), ((8319, 8359), 'numpy.zeros', 'np.zeros', (['(self.size, 7)'], {'dtype': 'np.int32'}), '((self.size, 7), dtype=np.int32)\n', (8327, 8359), True, 'import numpy as np\n'), ((16032, 16046), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (16044, 16046), True, 'import matplotlib.pyplot as plt\n'), ((16393, 16405), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (16403, 16405), True, 'import matplotlib.pyplot as plt\n'), ((16414, 16452), 'matplotlib.pyplot.title', 'plt.title', (["('CPU History ' + self.name)"], {}), "('CPU History ' + self.name)\n", (16423, 16452), True, 'import matplotlib.pyplot as plt\n'), ((16462, 16472), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (16470, 16472), True, 'import matplotlib.pyplot as plt\n'), ((16577, 16622), 'logging.info', 'logging.info', (['"""Updating table: %s"""', 'self.name'], {}), "('Updating table: %s', self.name)\n", (16589, 16622), False, 'import logging\n'), ((20140, 20154), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (20152, 20154), True, 'import matplotlib.pyplot as plt\n'), ((20382, 20394), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (20392, 20394), True, 'import matplotlib.pyplot as plt\n'), ((20403, 20449), 'matplotlib.pyplot.title', 'plt.title', (["('CPU History Stacked ' + self.name)"], {}), "('CPU History Stacked ' + self.name)\n", (20412, 20449), True, 'import matplotlib.pyplot as plt\n'), ((20459, 20469), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (20467, 20469), True, 'import matplotlib.pyplot as plt\n'), ((20574, 20619), 'logging.info', 'logging.info', (['"""Updating table: %s"""', 'self.name'], {}), "('Updating table: %s', self.name)\n", (20586, 20619), False, 'import logging\n'), ((20824, 20861), 'google.cloud.bigquery.LoadJobConfig', 'bigquery.LoadJobConfig', ([], {'schema': 'schema'}), '(schema=schema)\n', (20846, 20861), False, 'from google.cloud import bigquery\n'), ((21509, 21549), 'numpy.zeros', 'np.zeros', (['(self.size, 8)'], {'dtype': 'np.int32'}), '((self.size, 8), dtype=np.int32)\n', (21517, 21549), True, 'import numpy as np\n'), ((25613, 25658), 'logging.debug', 'logging.debug', (['"""Read %s Memory stats"""', 'sample'], {}), "('Read %s Memory stats', sample)\n", (25626, 25658), False, 'import logging\n'), ((27914, 27928), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (27926, 27928), True, 'import matplotlib.pyplot as plt\n'), ((28405, 28417), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (28415, 28417), True, 'import matplotlib.pyplot as plt\n'), ((28426, 28467), 'matplotlib.pyplot.title', 'plt.title', (["('Memory History ' + self.name)"], {}), "('Memory History ' + self.name)\n", (28435, 28467), True, 'import matplotlib.pyplot as plt\n'), ((28477, 28487), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (28485, 28487), True, 'import matplotlib.pyplot as plt\n'), ((29181, 29226), 'logging.info', 'logging.info', (['"""Updating table: %s"""', 'self.name'], {}), "('Updating table: %s', self.name)\n", (29193, 29226), False, 'import logging\n'), ((949, 995), 'logging.info', 'logging.info', (['"""Using Google Big Query backend"""'], {}), "('Using Google Big Query backend')\n", (961, 995), False, 'import logging\n'), ((1013, 1030), 'google.cloud.bigquery.Client', 'bigquery.Client', ([], {}), '()\n', (1028, 1030), False, 'from google.cloud import bigquery\n'), ((6044, 6062), 'json.load', 'json.load', (['content'], {}), '(content)\n', (6053, 6062), False, 'import json\n'), ((6551, 6580), 'os.path.join', 'os.path.join', (['self.lake', 'name'], {}), '(self.lake, name)\n', (6563, 6580), False, 'import os\n'), ((6924, 6941), 'logging.info', 'logging.info', (['row'], {}), '(row)\n', (6936, 6941), False, 'import logging\n'), ((15039, 15064), 'os.path.exists', 'os.path.exists', (['statsfile'], {}), '(statsfile)\n', (15053, 15064), False, 'import os\n'), ((22191, 22216), 'os.path.exists', 'os.path.exists', (['thefolder'], {}), '(thefolder)\n', (22205, 22216), False, 'import os\n'), ((22599, 22630), 'os.path.join', 'os.path.join', (['thefolder', 'myfile'], {}), '(thefolder, myfile)\n', (22611, 22630), False, 'import os\n'), ((26929, 26954), 'os.path.exists', 'os.path.exists', (['statsfile'], {}), '(statsfile)\n', (26943, 26954), False, 'import os\n'), ((1117, 1149), 'logging.info', 'logging.info', (['"""Using No Backend"""'], {}), "('Using No Backend')\n", (1129, 1149), False, 'import logging\n'), ((1242, 1288), 'logging.error', 'logging.error', (['"""Error in configuring database"""'], {}), "('Error in configuring database')\n", (1255, 1288), False, 'import logging\n'), ((1297, 1308), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1305, 1308), False, 'import sys\n'), ((4863, 4878), 'time.sleep', 'time.sleep', (['(0.5)'], {}), '(0.5)\n', (4873, 4878), False, 'import time\n'), ((4895, 4918), 'logging.info', 'logging.info', (['"""Waiting"""'], {}), "('Waiting')\n", (4907, 4918), False, 'import logging\n'), ((4968, 5016), 'logging.error', 'logging.error', (['"""Error %s"""', 'load_job.error_result'], {}), "('Error %s', load_job.error_result)\n", (4981, 5016), False, 'import logging\n'), ((5033, 5063), 'logging.error', 'logging.error', (['load_job.errors'], {}), '(load_job.errors)\n', (5046, 5063), False, 'import logging\n'), ((15141, 15165), 'os.path.exists', 'os.path.exists', (['rrdfile1'], {}), '(rrdfile1)\n', (15155, 15165), False, 'import os\n'), ((20737, 20795), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['self.fields[i][0]', 'self.fields[i][1]'], {}), '(self.fields[i][0], self.fields[i][1])\n', (20757, 20795), False, 'from google.cloud import bigquery\n'), ((23811, 23942), 'logging.info', 'logging.info', (["('Warning: timestamps differ: %s %s %s %s %s' % (size_stamp, resident_stamp,\n shared_stamp, text_stamp, data_stamp))"], {}), "('Warning: timestamps differ: %s %s %s %s %s' % (size_stamp,\n resident_stamp, shared_stamp, text_stamp, data_stamp))\n", (23823, 23942), False, 'import logging\n'), ((27029, 27052), 'os.path.exists', 'os.path.exists', (['rrdfile'], {}), '(rrdfile)\n', (27043, 27052), False, 'import os\n'), ((7210, 7245), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""id"""', '"""INT64"""'], {}), "('id', 'INT64')\n", (7230, 7245), False, 'from google.cloud import bigquery\n'), ((7263, 7299), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""mid"""', '"""INT64"""'], {}), "('mid', 'INT64')\n", (7283, 7299), False, 'from google.cloud import bigquery\n'), ((7317, 7355), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""date"""', '"""STRING"""'], {}), "('date', 'STRING')\n", (7337, 7355), False, 'from google.cloud import bigquery\n'), ((7373, 7410), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""url"""', '"""STRING"""'], {}), "('url', 'STRING')\n", (7393, 7410), False, 'from google.cloud import bigquery\n'), ((7428, 7466), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""name"""', '"""STRING"""'], {}), "('name', 'STRING')\n", (7448, 7466), False, 'from google.cloud import bigquery\n'), ((7484, 7524), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""branch"""', '"""STRING"""'], {}), "('branch', 'STRING')\n", (7504, 7524), False, 'from google.cloud import bigquery\n'), ((15252, 15280), 'os.path.exists', 'os.path.exists', (['rrdfile1_old'], {}), '(rrdfile1_old)\n', (15266, 15280), False, 'import os\n'), ((16739, 16774), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""id"""', '"""INT64"""'], {}), "('id', 'INT64')\n", (16759, 16774), False, 'from google.cloud import bigquery\n'), ((16792, 16828), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""mid"""', '"""INT64"""'], {}), "('mid', 'INT64')\n", (16812, 16828), False, 'from google.cloud import bigquery\n'), ((16846, 16885), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""sample"""', '"""INT64"""'], {}), "('sample', 'INT64')\n", (16866, 16885), False, 'from google.cloud import bigquery\n'), ((16903, 16941), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""utime"""', '"""INT64"""'], {}), "('utime', 'INT64')\n", (16923, 16941), False, 'from google.cloud import bigquery\n'), ((16959, 16997), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""stime"""', '"""INT64"""'], {}), "('stime', 'INT64')\n", (16979, 16997), False, 'from google.cloud import bigquery\n'), ((17015, 17054), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""cutime"""', '"""INT64"""'], {}), "('cutime', 'INT64')\n", (17035, 17054), False, 'from google.cloud import bigquery\n'), ((17072, 17111), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""cstime"""', '"""INT64"""'], {}), "('cstime', 'INT64')\n", (17092, 17111), False, 'from google.cloud import bigquery\n'), ((27130, 27157), 'os.path.exists', 'os.path.exists', (['rrdfile_old'], {}), '(rrdfile_old)\n', (27144, 27157), False, 'import os\n'), ((29314, 29349), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""id"""', '"""INT64"""'], {}), "('id', 'INT64')\n", (29334, 29349), False, 'from google.cloud import bigquery\n'), ((29367, 29403), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""mid"""', '"""INT64"""'], {}), "('mid', 'INT64')\n", (29387, 29403), False, 'from google.cloud import bigquery\n'), ((29421, 29460), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""sample"""', '"""INT64"""'], {}), "('sample', 'INT64')\n", (29441, 29460), False, 'from google.cloud import bigquery\n'), ((29478, 29515), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""size"""', '"""INT64"""'], {}), "('size', 'INT64')\n", (29498, 29515), False, 'from google.cloud import bigquery\n'), ((29533, 29574), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""resident"""', '"""INT64"""'], {}), "('resident', 'INT64')\n", (29553, 29574), False, 'from google.cloud import bigquery\n'), ((29592, 29631), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""shared"""', '"""INT64"""'], {}), "('shared', 'INT64')\n", (29612, 29631), False, 'from google.cloud import bigquery\n'), ((29649, 29686), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""text"""', '"""INT64"""'], {}), "('text', 'INT64')\n", (29669, 29686), False, 'from google.cloud import bigquery\n'), ((29704, 29741), 'google.cloud.bigquery.SchemaField', 'bigquery.SchemaField', (['"""data"""', '"""INT64"""'], {}), "('data', 'INT64')\n", (29724, 29741), False, 'from google.cloud import bigquery\n'), ((15486, 15587), 'logging.info', 'logging.info', (["('CPU history file does not exist! %s or %s or %s' % (statsfile, rrdfile1,\n rrdfile2))"], {}), "('CPU history file does not exist! %s or %s or %s' % (statsfile,\n rrdfile1, rrdfile2))\n", (15498, 15587), False, 'import logging\n'), ((15638, 15672), 'logging.info', 'logging.info', (['"""Filling with zeros"""'], {}), "('Filling with zeros')\n", (15650, 15672), False, 'import logging\n'), ((27350, 27437), 'logging.info', 'logging.info', (["('Memory analytics does not exist !!! %s or %s' % (statsfile, rrdfile))"], {}), "('Memory analytics does not exist !!! %s or %s' % (statsfile,\n rrdfile))\n", (27362, 27437), False, 'import logging\n'), ((27508, 27542), 'logging.info', 'logging.info', (['"""Filling with zeros"""'], {}), "('Filling with zeros')\n", (27520, 27542), False, 'import logging\n'), ((12282, 12348), 'logging.warning', 'logging.warning', (['"""Omitted a sample from mid %s"""', 'measurement_index'], {}), "('Omitted a sample from mid %s', measurement_index)\n", (12297, 12348), False, 'import logging\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 numpy as np
d = 64 # dimension
nb = 100000 # database size
nq = 10000 # nb of queries
np.random.seed(1234) # make reproducible
xb = np.random.random((nb, d)).astype('float32')
xb[:, 0] += np.arange(nb) / 1000.
xq = np.random.random((nq, d)).astype('float32')
xq[:, 0] += np.arange(nq) / 1000.
import faiss # make faiss available
index = faiss.IndexFlatL2(d) # build the index
print(index.is_trained)
index.add(xb) # add vectors to the index
print(index.ntotal)
k = 4 # we want to see 4 nearest neighbors
D, I = index.search(xb[:5], k) # sanity check
print(I)
print(D)
D, I = index.search(xq, k) # actual search
print(I[:5]) # neighbors of the 5 first queries
print(I[-5:]) # neighbors of the 5 last queries
| [
"faiss.IndexFlatL2",
"numpy.random.random",
"numpy.random.seed",
"numpy.arange"
] | [((341, 361), 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), '(1234)\n', (355, 361), True, 'import numpy as np\n'), ((623, 643), 'faiss.IndexFlatL2', 'faiss.IndexFlatL2', (['d'], {}), '(d)\n', (640, 643), False, 'import faiss\n'), ((455, 468), 'numpy.arange', 'np.arange', (['nb'], {}), '(nb)\n', (464, 468), True, 'import numpy as np\n'), ((538, 551), 'numpy.arange', 'np.arange', (['nq'], {}), '(nq)\n', (547, 551), True, 'import numpy as np\n'), ((399, 424), 'numpy.random.random', 'np.random.random', (['(nb, d)'], {}), '((nb, d))\n', (415, 424), True, 'import numpy as np\n'), ((482, 507), 'numpy.random.random', 'np.random.random', (['(nq, d)'], {}), '((nq, d))\n', (498, 507), True, 'import numpy as np\n')] |
import numpy as np
class Perceptron:
def __init__(self, num_features):
self.num_features = num_features
self.weights = np.zeros((num_features, 1), dtype=np.float)
self.bias = np.zeros(1, dtype=np.float)
def forward(self, x):
# (n, m) X (m, 1) = (n, 1) + (1) = (n, 1)
linear = np.dot(x, self.weights) + self.bias
predictions = np.where(linear > 0., 1, 0)
return predictions
def backward(self, x, y):
predictions = self.forward(x)
# (n, 1) - (n, 1)
errors = y - predictions
return errors
def train(self, x, y, epochs):
for e in range(epochs):
for i in range(y.shape[0]):
# (1, m)(1)
errors = self.backward(x[i].reshape(1, self.num_features), y[i]).reshape(-1)
self.weights += (errors * x[i]).reshape(self.num_features, 1)
self.bias += errors
def evaluate(self, x, y):
predictions = self.forward(x).reshape(-1)
accuracy = np.sum(predictions == y) / y.shape[0]
return accuracy
| [
"numpy.dot",
"numpy.where",
"numpy.zeros",
"numpy.sum"
] | [((142, 185), 'numpy.zeros', 'np.zeros', (['(num_features, 1)'], {'dtype': 'np.float'}), '((num_features, 1), dtype=np.float)\n', (150, 185), True, 'import numpy as np\n'), ((206, 233), 'numpy.zeros', 'np.zeros', (['(1)'], {'dtype': 'np.float'}), '(1, dtype=np.float)\n', (214, 233), True, 'import numpy as np\n'), ((386, 414), 'numpy.where', 'np.where', (['(linear > 0.0)', '(1)', '(0)'], {}), '(linear > 0.0, 1, 0)\n', (394, 414), True, 'import numpy as np\n'), ((328, 351), 'numpy.dot', 'np.dot', (['x', 'self.weights'], {}), '(x, self.weights)\n', (334, 351), True, 'import numpy as np\n'), ((1034, 1058), 'numpy.sum', 'np.sum', (['(predictions == y)'], {}), '(predictions == y)\n', (1040, 1058), True, 'import numpy as np\n')] |
from itertools import product
import numpy as np
from skimage.color import rgb2hsv, rgb2lab, rgb2gray
from skimage.segmentation import felzenszwalb
def oversegmentation(img, k):
"""
Generating various starting regions using the method of
Felzenszwalb.
k effectively sets a scale of observation, in that
a larger k causes a preference for larger components.
sigma = 0.8 which was used in the original paper.
min_size = 100 refer to Keon's Matlab implementation.
"""
img_seg = felzenszwalb(img, scale=k, sigma=0.8, min_size=100)
return img_seg
def switch_color_space(img, target):
"""
RGB to target color space conversion.
I: the intensity (gray scale), Lab, rgI: the rg channels of
normalized RGB plus intensity, HSV, H: the Hue channel H from HSV
"""
if target == 'HSV':
return rgb2hsv(img)
elif target == 'Lab':
return rgb2lab(img)
elif target == 'I':
return rgb2gray(img)
elif target == 'rgb':
img = img / np.sum(img, axis=0)
return img
elif target == 'rgI':
img = img / np.sum(img, axis=0)
img[:, :, 2] = rgb2gray(img)
return img
elif target == 'H':
return rgb2hsv(img)[:, :, 0]
else:
raise "{} is not suported.".format(target)
def load_strategy(mode):
# TODO: Add mode sanity check
cfg = {
"single": {
"ks": [100],
"colors": ["HSV"],
"sims": ["CTSF"]
},
"fast": {
"ks": [50, 100],
"colors": ["HSV", "Lab"],
"sims": ["CTSF", "TSF"]
},
"quality": {
"ks": [50, 100, 150, 300],
"colors": ["HSV", "Lab", "I", "rgI", "H"],
"sims": ["CTSF", "TSF", "F", "S"]
}
}
if isinstance(mode, dict):
cfg['manual'] = mode
mode = 'manual'
colors, ks, sims = cfg[mode]['colors'], cfg[mode]['ks'], cfg[mode]['sims']
return product(colors, ks, sims)
| [
"skimage.color.rgb2gray",
"numpy.sum",
"skimage.color.rgb2hsv",
"itertools.product",
"skimage.segmentation.felzenszwalb",
"skimage.color.rgb2lab"
] | [((538, 589), 'skimage.segmentation.felzenszwalb', 'felzenszwalb', (['img'], {'scale': 'k', 'sigma': '(0.8)', 'min_size': '(100)'}), '(img, scale=k, sigma=0.8, min_size=100)\n', (550, 589), False, 'from skimage.segmentation import felzenszwalb\n'), ((2024, 2049), 'itertools.product', 'product', (['colors', 'ks', 'sims'], {}), '(colors, ks, sims)\n', (2031, 2049), False, 'from itertools import product\n'), ((893, 905), 'skimage.color.rgb2hsv', 'rgb2hsv', (['img'], {}), '(img)\n', (900, 905), False, 'from skimage.color import rgb2hsv, rgb2lab, rgb2gray\n'), ((948, 960), 'skimage.color.rgb2lab', 'rgb2lab', (['img'], {}), '(img)\n', (955, 960), False, 'from skimage.color import rgb2hsv, rgb2lab, rgb2gray\n'), ((1001, 1014), 'skimage.color.rgb2gray', 'rgb2gray', (['img'], {}), '(img)\n', (1009, 1014), False, 'from skimage.color import rgb2hsv, rgb2lab, rgb2gray\n'), ((1062, 1081), 'numpy.sum', 'np.sum', (['img'], {'axis': '(0)'}), '(img, axis=0)\n', (1068, 1081), True, 'import numpy as np\n'), ((1191, 1204), 'skimage.color.rgb2gray', 'rgb2gray', (['img'], {}), '(img)\n', (1199, 1204), False, 'from skimage.color import rgb2hsv, rgb2lab, rgb2gray\n'), ((1148, 1167), 'numpy.sum', 'np.sum', (['img'], {'axis': '(0)'}), '(img, axis=0)\n', (1154, 1167), True, 'import numpy as np\n'), ((1264, 1276), 'skimage.color.rgb2hsv', 'rgb2hsv', (['img'], {}), '(img)\n', (1271, 1276), False, 'from skimage.color import rgb2hsv, rgb2lab, rgb2gray\n')] |
import os
import cv2
cv2.setNumThreads(0)
cv2.ocl.setUseOpenCL(False)
import numpy as np
from .eval import Evaluator
class FullImageEvaluator(Evaluator):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def process_batch(self, predicted, model, data, prefix=""):
names = data['image_name']
for i in range(len(names)):
self.on_image_constructed(names[i], predicted[i,...], prefix)
def save(self, name, prediction, prefix=""):
cv2.imwrite(os.path.join(self.save_dir, prefix + name), (prediction * 255).astype(np.uint8))
class CropEvaluator(Evaluator):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.current_mask = None
self.current_prediction = None
self.current_image_name = None
def process_batch(self, predicted, model, data, prefix=""):
names = data['image_name']
config = self.config
batch_geometry = self.parse_geometry(data['geometry'])
for i in range(len(names)):
name = names[i]
geometry = batch_geometry[i]
sx, sy = geometry['sx'], geometry['sy']
pred = self.cut_border(np.squeeze(predicted[i,...]))
if name != self.current_image_name:
if self.current_image_name is None:
self.current_image_name = name
else:
self.on_image_constructed(self.current_image_name, self.current_prediction / self.current_mask, prefix=prefix)
self.construct_big_image(geometry)
self.current_prediction[sy + self.border:sy + config.target_rows - self.border, sx + self.border:sx + config.target_cols - self.border] += pred
self.current_mask[sy+self.border:sy + config.target_rows - self.border, sx + self.border:sx + config.target_cols - self.border] += 1
self.current_image_name = name
def parse_geometry(self, batch_geometry):
rows = batch_geometry['rows'].numpy()
cols = batch_geometry['cols'].numpy()
sx = batch_geometry['sx'].numpy()
sy = batch_geometry['sy'].numpy()
geometries = []
for idx in range(rows.shape[0]):
geometry = {'rows': rows[idx],
'cols': cols[idx],
'sx': sx[idx],
'sy': sy[idx]}
geometries.append(geometry)
return geometries
def construct_big_image(self, geometry):
self.current_mask = np.zeros((geometry['rows'], geometry['cols']), np.uint8)
self.current_prediction = np.zeros((geometry['rows'], geometry['cols']), np.float32)
def save(self, name, prediction, prefix=""):
cv2.imwrite(os.path.join(self.save_dir, prefix + name), (prediction * 255).astype(np.uint8))
def post_predict_action(self, prefix):
self.on_image_constructed(self.current_image_name, self.current_prediction / self.current_mask, prefix=prefix)
self.current_image_name = None
| [
"numpy.zeros",
"cv2.ocl.setUseOpenCL",
"cv2.setNumThreads",
"numpy.squeeze",
"os.path.join"
] | [((25, 45), 'cv2.setNumThreads', 'cv2.setNumThreads', (['(0)'], {}), '(0)\n', (42, 45), False, 'import cv2\n'), ((47, 74), 'cv2.ocl.setUseOpenCL', 'cv2.ocl.setUseOpenCL', (['(False)'], {}), '(False)\n', (67, 74), False, 'import cv2\n'), ((2599, 2655), 'numpy.zeros', 'np.zeros', (["(geometry['rows'], geometry['cols'])", 'np.uint8'], {}), "((geometry['rows'], geometry['cols']), np.uint8)\n", (2607, 2655), True, 'import numpy as np\n'), ((2691, 2749), 'numpy.zeros', 'np.zeros', (["(geometry['rows'], geometry['cols'])", 'np.float32'], {}), "((geometry['rows'], geometry['cols']), np.float32)\n", (2699, 2749), True, 'import numpy as np\n'), ((541, 583), 'os.path.join', 'os.path.join', (['self.save_dir', '(prefix + name)'], {}), '(self.save_dir, prefix + name)\n', (553, 583), False, 'import os\n'), ((2823, 2865), 'os.path.join', 'os.path.join', (['self.save_dir', '(prefix + name)'], {}), '(self.save_dir, prefix + name)\n', (2835, 2865), False, 'import os\n'), ((1252, 1281), 'numpy.squeeze', 'np.squeeze', (['predicted[i, ...]'], {}), '(predicted[i, ...])\n', (1262, 1281), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import warnings
import pytest
import numpy as np
from numpy import testing as npt
import erfa
from astropy import units as u
from astropy.time import Time
from astropy.coordinates.builtin_frames import ICRS, AltAz
from astropy.coordinates.builtin_frames.utils import get_jd12
from astropy.coordinates import EarthLocation
from astropy.coordinates import SkyCoord
from astropy.utils import iers
from astropy.coordinates.angle_utilities import golden_spiral_grid
# These fixtures are used in test_iau_fullstack
@pytest.fixture(scope="function")
def fullstack_icrs():
rep = golden_spiral_grid(size=1000)
return ICRS(rep)
@pytest.fixture(scope="function")
def fullstack_fiducial_altaz(fullstack_icrs):
altazframe = AltAz(location=EarthLocation(lat=0*u.deg, lon=0*u.deg, height=0*u.m),
obstime=Time('J2000'))
with warnings.catch_warnings(): # Ignore remote_data warning
warnings.simplefilter('ignore')
result = fullstack_icrs.transform_to(altazframe)
return result
@pytest.fixture(scope="function", params=['J2000.1', 'J2010'])
def fullstack_times(request):
return Time(request.param)
@pytest.fixture(scope="function", params=[(0, 0, 0), (23, 0, 0), (-70, 0, 0), (0, 100, 0), (23, 0, 3000)])
def fullstack_locations(request):
return EarthLocation(lat=request.param[0]*u.deg, lon=request.param[0]*u.deg,
height=request.param[0]*u.m)
@pytest.fixture(scope="function",
params=[(0*u.bar, 0*u.deg_C, 0, 1*u.micron),
(1*u.bar, 0*u.deg_C, 0*u.one, 1*u.micron),
(1*u.bar, 10*u.deg_C, 0, 1*u.micron),
(1*u.bar, 0*u.deg_C, 50*u.percent, 1*u.micron),
(1*u.bar, 0*u.deg_C, 0, 21*u.cm)])
def fullstack_obsconditions(request):
return request.param
def _erfa_check(ira, idec, astrom):
"""
This function does the same thing the astropy layer is supposed to do, but
all in erfa
"""
cra, cdec = erfa.atciq(ira, idec, 0, 0, 0, 0, astrom)
az, zen, ha, odec, ora = erfa.atioq(cra, cdec, astrom)
alt = np.pi/2-zen
cra2, cdec2 = erfa.atoiq('A', az, zen, astrom)
ira2, idec2 = erfa.aticq(cra2, cdec2, astrom)
dct = locals()
del dct['astrom']
return dct
def test_iau_fullstack(fullstack_icrs, fullstack_fiducial_altaz,
fullstack_times, fullstack_locations,
fullstack_obsconditions):
"""
Test the full transform from ICRS <-> AltAz
"""
# create the altaz frame
altazframe = AltAz(obstime=fullstack_times, location=fullstack_locations,
pressure=fullstack_obsconditions[0],
temperature=fullstack_obsconditions[1],
relative_humidity=fullstack_obsconditions[2],
obswl=fullstack_obsconditions[3])
aacoo = fullstack_icrs.transform_to(altazframe)
# compare aacoo to the fiducial AltAz - should always be different
assert np.all(np.abs(aacoo.alt - fullstack_fiducial_altaz.alt) > 50*u.milliarcsecond)
assert np.all(np.abs(aacoo.az - fullstack_fiducial_altaz.az) > 50*u.milliarcsecond)
# if the refraction correction is included, we *only* do the comparisons
# where altitude >5 degrees. The SOFA guides imply that below 5 is where
# where accuracy gets more problematic, and testing reveals that alt<~0
# gives garbage round-tripping, and <10 can give ~1 arcsec uncertainty
if fullstack_obsconditions[0].value == 0:
# but if there is no refraction correction, check everything
msk = slice(None)
tol = 5*u.microarcsecond
else:
msk = aacoo.alt > 5*u.deg
# most of them aren't this bad, but some of those at low alt are offset
# this much. For alt > 10, this is always better than 100 masec
tol = 750*u.milliarcsecond
# now make sure the full stack round-tripping works
icrs2 = aacoo.transform_to(ICRS())
adras = np.abs(fullstack_icrs.ra - icrs2.ra)[msk]
addecs = np.abs(fullstack_icrs.dec - icrs2.dec)[msk]
assert np.all(adras < tol), f'largest RA change is {np.max(adras.arcsec * 1000)} mas, > {tol}'
assert np.all(addecs < tol), f'largest Dec change is {np.max(addecs.arcsec * 1000)} mas, > {tol}'
# check that we're consistent with the ERFA alt/az result
iers_tab = iers.earth_orientation_table.get()
xp, yp = u.Quantity(iers_tab.pm_xy(fullstack_times)).to_value(u.radian)
lon = fullstack_locations.geodetic[0].to_value(u.radian)
lat = fullstack_locations.geodetic[1].to_value(u.radian)
height = fullstack_locations.geodetic[2].to_value(u.m)
jd1, jd2 = get_jd12(fullstack_times, 'utc')
pressure = fullstack_obsconditions[0].to_value(u.hPa)
temperature = fullstack_obsconditions[1].to_value(u.deg_C)
# Relative humidity can be a quantity or a number.
relative_humidity = u.Quantity(fullstack_obsconditions[2], u.one).value
obswl = fullstack_obsconditions[3].to_value(u.micron)
astrom, eo = erfa.apco13(jd1, jd2,
fullstack_times.delta_ut1_utc,
lon, lat, height,
xp, yp,
pressure, temperature, relative_humidity,
obswl)
erfadct = _erfa_check(fullstack_icrs.ra.rad, fullstack_icrs.dec.rad, astrom)
npt.assert_allclose(erfadct['alt'], aacoo.alt.radian, atol=1e-7)
npt.assert_allclose(erfadct['az'], aacoo.az.radian, atol=1e-7)
def test_fiducial_roudtrip(fullstack_icrs, fullstack_fiducial_altaz):
"""
Test the full transform from ICRS <-> AltAz
"""
aacoo = fullstack_icrs.transform_to(fullstack_fiducial_altaz)
# make sure the round-tripping works
icrs2 = aacoo.transform_to(ICRS())
npt.assert_allclose(fullstack_icrs.ra.deg, icrs2.ra.deg)
npt.assert_allclose(fullstack_icrs.dec.deg, icrs2.dec.deg)
def test_future_altaz():
"""
While this does test the full stack, it is mostly meant to check that a
warning is raised when attempting to get to AltAz in the future (beyond
IERS tables)
"""
from astropy.utils.exceptions import AstropyWarning
# this is an ugly hack to get the warning to show up even if it has already
# appeared
from astropy.coordinates.builtin_frames import utils
if hasattr(utils, '__warningregistry__'):
utils.__warningregistry__.clear()
location = EarthLocation(lat=0*u.deg, lon=0*u.deg)
t = Time('J2161')
# check that these message(s) appear among any other warnings. If tests are run with
# --remote-data then the IERS table will be an instance of IERS_Auto which is
# assured of being "fresh". In this case getting times outside the range of the
# table does not raise an exception. Only if using IERS_B (which happens without
# --remote-data, i.e. for all CI testing) do we expect another warning.
with pytest.warns(AstropyWarning, match=r"Tried to get polar motions for "
"times after IERS data is valid.*") as found_warnings:
SkyCoord(1*u.deg, 2*u.deg).transform_to(AltAz(location=location, obstime=t))
if isinstance(iers.earth_orientation_table.get(), iers.IERS_B):
messages_found = ["(some) times are outside of range covered by IERS "
"table." in str(w.message) for w in found_warnings]
assert any(messages_found)
| [
"erfa.apco13",
"astropy.coordinates.builtin_frames.ICRS",
"numpy.abs",
"erfa.atoiq",
"erfa.aticq",
"astropy.coordinates.builtin_frames.utils.__warningregistry__.clear",
"warnings.simplefilter",
"pytest.warns",
"erfa.atioq",
"erfa.atciq",
"numpy.max",
"warnings.catch_warnings",
"astropy.utils... | [((603, 635), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (617, 635), False, 'import pytest\n'), ((722, 754), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (736, 754), False, 'import pytest\n'), ((1118, 1179), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""', 'params': "['J2000.1', 'J2010']"}), "(scope='function', params=['J2000.1', 'J2010'])\n", (1132, 1179), False, 'import pytest\n'), ((1244, 1353), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""', 'params': '[(0, 0, 0), (23, 0, 0), (-70, 0, 0), (0, 100, 0), (23, 0, 3000)]'}), "(scope='function', params=[(0, 0, 0), (23, 0, 0), (-70, 0, 0),\n (0, 100, 0), (23, 0, 3000)])\n", (1258, 1353), False, 'import pytest\n'), ((1522, 1810), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""', 'params': '[(0 * u.bar, 0 * u.deg_C, 0, 1 * u.micron), (1 * u.bar, 0 * u.deg_C, 0 * u.\n one, 1 * u.micron), (1 * u.bar, 10 * u.deg_C, 0, 1 * u.micron), (1 * u.\n bar, 0 * u.deg_C, 50 * u.percent, 1 * u.micron), (1 * u.bar, 0 * u.\n deg_C, 0, 21 * u.cm)]'}), "(scope='function', params=[(0 * u.bar, 0 * u.deg_C, 0, 1 * u.\n micron), (1 * u.bar, 0 * u.deg_C, 0 * u.one, 1 * u.micron), (1 * u.bar,\n 10 * u.deg_C, 0, 1 * u.micron), (1 * u.bar, 0 * u.deg_C, 50 * u.percent,\n 1 * u.micron), (1 * u.bar, 0 * u.deg_C, 0, 21 * u.cm)])\n", (1536, 1810), False, 'import pytest\n'), ((668, 697), 'astropy.coordinates.angle_utilities.golden_spiral_grid', 'golden_spiral_grid', ([], {'size': '(1000)'}), '(size=1000)\n', (686, 697), False, 'from astropy.coordinates.angle_utilities import golden_spiral_grid\n'), ((709, 718), 'astropy.coordinates.builtin_frames.ICRS', 'ICRS', (['rep'], {}), '(rep)\n', (713, 718), False, 'from astropy.coordinates.builtin_frames import ICRS, AltAz\n'), ((1221, 1240), 'astropy.time.Time', 'Time', (['request.param'], {}), '(request.param)\n', (1225, 1240), False, 'from astropy.time import Time\n'), ((1395, 1503), 'astropy.coordinates.EarthLocation', 'EarthLocation', ([], {'lat': '(request.param[0] * u.deg)', 'lon': '(request.param[0] * u.deg)', 'height': '(request.param[0] * u.m)'}), '(lat=request.param[0] * u.deg, lon=request.param[0] * u.deg,\n height=request.param[0] * u.m)\n', (1408, 1503), False, 'from astropy.coordinates import EarthLocation\n'), ((2104, 2145), 'erfa.atciq', 'erfa.atciq', (['ira', 'idec', '(0)', '(0)', '(0)', '(0)', 'astrom'], {}), '(ira, idec, 0, 0, 0, 0, astrom)\n', (2114, 2145), False, 'import erfa\n'), ((2175, 2204), 'erfa.atioq', 'erfa.atioq', (['cra', 'cdec', 'astrom'], {}), '(cra, cdec, astrom)\n', (2185, 2204), False, 'import erfa\n'), ((2245, 2277), 'erfa.atoiq', 'erfa.atoiq', (['"""A"""', 'az', 'zen', 'astrom'], {}), "('A', az, zen, astrom)\n", (2255, 2277), False, 'import erfa\n'), ((2296, 2327), 'erfa.aticq', 'erfa.aticq', (['cra2', 'cdec2', 'astrom'], {}), '(cra2, cdec2, astrom)\n', (2306, 2327), False, 'import erfa\n'), ((2673, 2904), 'astropy.coordinates.builtin_frames.AltAz', 'AltAz', ([], {'obstime': 'fullstack_times', 'location': 'fullstack_locations', 'pressure': 'fullstack_obsconditions[0]', 'temperature': 'fullstack_obsconditions[1]', 'relative_humidity': 'fullstack_obsconditions[2]', 'obswl': 'fullstack_obsconditions[3]'}), '(obstime=fullstack_times, location=fullstack_locations, pressure=\n fullstack_obsconditions[0], temperature=fullstack_obsconditions[1],\n relative_humidity=fullstack_obsconditions[2], obswl=\n fullstack_obsconditions[3])\n', (2678, 2904), False, 'from astropy.coordinates.builtin_frames import ICRS, AltAz\n'), ((4218, 4237), 'numpy.all', 'np.all', (['(adras < tol)'], {}), '(adras < tol)\n', (4224, 4237), True, 'import numpy as np\n'), ((4317, 4337), 'numpy.all', 'np.all', (['(addecs < tol)'], {}), '(addecs < tol)\n', (4323, 4337), True, 'import numpy as np\n'), ((4486, 4520), 'astropy.utils.iers.earth_orientation_table.get', 'iers.earth_orientation_table.get', ([], {}), '()\n', (4518, 4520), False, 'from astropy.utils import iers\n'), ((4793, 4825), 'astropy.coordinates.builtin_frames.utils.get_jd12', 'get_jd12', (['fullstack_times', '"""utc"""'], {}), "(fullstack_times, 'utc')\n", (4801, 4825), False, 'from astropy.coordinates.builtin_frames.utils import get_jd12\n'), ((5153, 5284), 'erfa.apco13', 'erfa.apco13', (['jd1', 'jd2', 'fullstack_times.delta_ut1_utc', 'lon', 'lat', 'height', 'xp', 'yp', 'pressure', 'temperature', 'relative_humidity', 'obswl'], {}), '(jd1, jd2, fullstack_times.delta_ut1_utc, lon, lat, height, xp,\n yp, pressure, temperature, relative_humidity, obswl)\n', (5164, 5284), False, 'import erfa\n'), ((5511, 5576), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (["erfadct['alt']", 'aacoo.alt.radian'], {'atol': '(1e-07)'}), "(erfadct['alt'], aacoo.alt.radian, atol=1e-07)\n", (5530, 5576), True, 'from numpy import testing as npt\n'), ((5580, 5643), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (["erfadct['az']", 'aacoo.az.radian'], {'atol': '(1e-07)'}), "(erfadct['az'], aacoo.az.radian, atol=1e-07)\n", (5599, 5643), True, 'from numpy import testing as npt\n'), ((5930, 5986), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['fullstack_icrs.ra.deg', 'icrs2.ra.deg'], {}), '(fullstack_icrs.ra.deg, icrs2.ra.deg)\n', (5949, 5986), True, 'from numpy import testing as npt\n'), ((5991, 6049), 'numpy.testing.assert_allclose', 'npt.assert_allclose', (['fullstack_icrs.dec.deg', 'icrs2.dec.deg'], {}), '(fullstack_icrs.dec.deg, icrs2.dec.deg)\n', (6010, 6049), True, 'from numpy import testing as npt\n'), ((6575, 6618), 'astropy.coordinates.EarthLocation', 'EarthLocation', ([], {'lat': '(0 * u.deg)', 'lon': '(0 * u.deg)'}), '(lat=0 * u.deg, lon=0 * u.deg)\n', (6588, 6618), False, 'from astropy.coordinates import EarthLocation\n'), ((6623, 6636), 'astropy.time.Time', 'Time', (['"""J2161"""'], {}), "('J2161')\n", (6627, 6636), False, 'from astropy.time import Time\n'), ((943, 968), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (966, 968), False, 'import warnings\n'), ((1008, 1039), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (1029, 1039), False, 'import warnings\n'), ((4087, 4093), 'astropy.coordinates.builtin_frames.ICRS', 'ICRS', ([], {}), '()\n', (4091, 4093), False, 'from astropy.coordinates.builtin_frames import ICRS, AltAz\n'), ((4108, 4144), 'numpy.abs', 'np.abs', (['(fullstack_icrs.ra - icrs2.ra)'], {}), '(fullstack_icrs.ra - icrs2.ra)\n', (4114, 4144), True, 'import numpy as np\n'), ((4163, 4201), 'numpy.abs', 'np.abs', (['(fullstack_icrs.dec - icrs2.dec)'], {}), '(fullstack_icrs.dec - icrs2.dec)\n', (4169, 4201), True, 'import numpy as np\n'), ((5026, 5071), 'astropy.units.Quantity', 'u.Quantity', (['fullstack_obsconditions[2]', 'u.one'], {}), '(fullstack_obsconditions[2], u.one)\n', (5036, 5071), True, 'from astropy import units as u\n'), ((5918, 5924), 'astropy.coordinates.builtin_frames.ICRS', 'ICRS', ([], {}), '()\n', (5922, 5924), False, 'from astropy.coordinates.builtin_frames import ICRS, AltAz\n'), ((6525, 6558), 'astropy.coordinates.builtin_frames.utils.__warningregistry__.clear', 'utils.__warningregistry__.clear', ([], {}), '()\n', (6556, 6558), False, 'from astropy.coordinates.builtin_frames import utils\n'), ((7066, 7172), 'pytest.warns', 'pytest.warns', (['AstropyWarning'], {'match': '"""Tried to get polar motions for times after IERS data is valid.*"""'}), "(AstropyWarning, match=\n 'Tried to get polar motions for times after IERS data is valid.*')\n", (7078, 7172), False, 'import pytest\n'), ((7317, 7351), 'astropy.utils.iers.earth_orientation_table.get', 'iers.earth_orientation_table.get', ([], {}), '()\n', (7349, 7351), False, 'from astropy.utils import iers\n'), ((833, 892), 'astropy.coordinates.EarthLocation', 'EarthLocation', ([], {'lat': '(0 * u.deg)', 'lon': '(0 * u.deg)', 'height': '(0 * u.m)'}), '(lat=0 * u.deg, lon=0 * u.deg, height=0 * u.m)\n', (846, 892), False, 'from astropy.coordinates import EarthLocation\n'), ((919, 932), 'astropy.time.Time', 'Time', (['"""J2000"""'], {}), "('J2000')\n", (923, 932), False, 'from astropy.time import Time\n'), ((3126, 3174), 'numpy.abs', 'np.abs', (['(aacoo.alt - fullstack_fiducial_altaz.alt)'], {}), '(aacoo.alt - fullstack_fiducial_altaz.alt)\n', (3132, 3174), True, 'import numpy as np\n'), ((3216, 3262), 'numpy.abs', 'np.abs', (['(aacoo.az - fullstack_fiducial_altaz.az)'], {}), '(aacoo.az - fullstack_fiducial_altaz.az)\n', (3222, 3262), True, 'import numpy as np\n'), ((4263, 4290), 'numpy.max', 'np.max', (['(adras.arcsec * 1000)'], {}), '(adras.arcsec * 1000)\n', (4269, 4290), True, 'import numpy as np\n'), ((4364, 4392), 'numpy.max', 'np.max', (['(addecs.arcsec * 1000)'], {}), '(addecs.arcsec * 1000)\n', (4370, 4392), True, 'import numpy as np\n'), ((7261, 7296), 'astropy.coordinates.builtin_frames.AltAz', 'AltAz', ([], {'location': 'location', 'obstime': 't'}), '(location=location, obstime=t)\n', (7266, 7296), False, 'from astropy.coordinates.builtin_frames import ICRS, AltAz\n'), ((7221, 7251), 'astropy.coordinates.SkyCoord', 'SkyCoord', (['(1 * u.deg)', '(2 * u.deg)'], {}), '(1 * u.deg, 2 * u.deg)\n', (7229, 7251), False, 'from astropy.coordinates import SkyCoord\n')] |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 20 18:23:01 2020
@author: lamington1010
"""
import cv2
import numpy as np
def imgimport():
s1 = input("image filename without numbers, e.g. cats")
s2 = input("file type, e.g. .jpg, .tif, etc ")
s3 = int(input("what is the range of images?"))
s3a = 'file directory'
x = 1;
Matrix = [];
while x < s3:
s4 = str(x);
s5 = s3a+s1+s4+s2
img = cv2.imread(s5,cv2.IMREAD_GRAYSCALE);
img = np.array(img)
imgprime = np.transpose(img)
imgprimecol = imgprime.flatten()
Arr = np.reshape(imgprimecol,(len(imgprimecol),1))
Matrix.append(Arr);
x = x + 1;
print(np.size(Matrix))
A = np.shape(Matrix)
return np.reshape(Matrix,(A[0],A[1])) | [
"numpy.size",
"numpy.transpose",
"numpy.shape",
"cv2.imread",
"numpy.array",
"numpy.reshape"
] | [((748, 764), 'numpy.shape', 'np.shape', (['Matrix'], {}), '(Matrix)\n', (756, 764), True, 'import numpy as np\n'), ((785, 817), 'numpy.reshape', 'np.reshape', (['Matrix', '(A[0], A[1])'], {}), '(Matrix, (A[0], A[1]))\n', (795, 817), True, 'import numpy as np\n'), ((447, 483), 'cv2.imread', 'cv2.imread', (['s5', 'cv2.IMREAD_GRAYSCALE'], {}), '(s5, cv2.IMREAD_GRAYSCALE)\n', (457, 483), False, 'import cv2\n'), ((498, 511), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (506, 511), True, 'import numpy as np\n'), ((531, 548), 'numpy.transpose', 'np.transpose', (['img'], {}), '(img)\n', (543, 548), True, 'import numpy as np\n'), ((718, 733), 'numpy.size', 'np.size', (['Matrix'], {}), '(Matrix)\n', (725, 733), True, 'import numpy as np\n')] |
import os.path
import PIL.Image as pimg
import nibabel as nib
import numpy as np
import torch
from ....in_out.image_functions import rescale_image_intensities, points_to_voxels_transform
from ....support import utilities
import logging
logger = logging.getLogger(__name__)
class Image:
"""
Landmarks (i.e. labelled point sets).
The Landmark class represents a set of labelled points. This class assumes that the source and the target
have the same number of points with a point-to-point correspondence.
"""
####################################################################################################################
### Constructor:
####################################################################################################################
# Constructor.
def __init__(self, intensities, intensities_dtype, affine):
self.dimension = len(intensities.shape)
assert self.dimension in [2, 3], 'Ambient-space dimension must be either 2 or 3.'
self.type = 'Image'
self.is_modified = False
self.intensities = intensities
self.intensities_dtype = intensities_dtype
self.affine = affine
self.downsampling_factor = 1
self._update_corner_point_positions()
self.update_bounding_box()
####################################################################################################################
### Encapsulation methods:
####################################################################################################################
def get_number_of_points(self):
raise RuntimeError("Not implemented for Image yet.")
def set_affine(self, affine_matrix):
"""
The affine matrix A is a 4x4 matrix that gives the correspondence between the voxel coordinates and their
spatial positions in the 3D space: (x, y, z, 1) = A (u, v, w, 1).
See the nibabel documentation for further details (the same attribute name is used here).
"""
self.affine = affine_matrix
def set_intensities(self, intensities):
self.is_modified = True
self.intensities = intensities
def get_intensities(self):
return self.intensities
# def get_intensities_torch(self, tensor_scalar_type=default.tensor_scalar_type, device='cpu'):
# if isinstance(self.intensities, torch.Tensor):
# return self.intensities.to(device)
# else:
# return torch.from_numpy(self.intensities).type(tensor_scalar_type).to(device)
def get_points(self):
image_shape = self.intensities.shape
axes = []
for d in range(self.dimension):
axe = np.linspace(self.corner_points[0, d], self.corner_points[2 ** d, d],
image_shape[d] // self.downsampling_factor)
axes.append(axe)
points = np.array(np.meshgrid(*axes, indexing='ij')[:])
for d in range(self.dimension):
points = np.swapaxes(points, d, d + 1)
return points
# @jit(parallel=True)
def get_deformed_intensities(self, deformed_points, intensities):
"""
Torch input / output.
Interpolation function with zero-padding.
"""
assert isinstance(deformed_points, torch.Tensor)
assert isinstance(intensities, torch.Tensor)
intensities = utilities.move_data(intensities, dtype=deformed_points.type(), device=deformed_points.device)
assert deformed_points.device == intensities.device
tensor_integer_type = {
'cpu': 'torch.LongTensor',
'cuda': 'torch.cuda.LongTensor'
}[deformed_points.device.type]
image_shape = self.intensities.shape
deformed_voxels = points_to_voxels_transform(deformed_points, self.affine)
assert deformed_points.device == deformed_voxels.device, 'tensors must be on the same device'
if self.dimension == 2:
if not self.downsampling_factor == 1:
shape = deformed_points.shape
deformed_voxels = torch.nn.functional.interpolate(deformed_voxels.permute(2, 0, 1).contiguous().view(1, shape[2], shape[0], shape[1]),
size=image_shape, mode='bilinear', align_corners=True)[0].permute(1, 2, 0).contiguous()
u, v = deformed_voxels.view(-1, 2)[:, 0], deformed_voxels.view(-1, 2)[:, 1]
u1 = torch.floor(u.detach())
v1 = torch.floor(v.detach())
u1 = torch.clamp(u1, 0, image_shape[0] - 1)
v1 = torch.clamp(v1, 0, image_shape[1] - 1)
u2 = torch.clamp(u1 + 1, 0, image_shape[0] - 1)
v2 = torch.clamp(v1 + 1, 0, image_shape[1] - 1)
fu = u - u1
fv = v - v1
gu = (u1 + 1) - u
gv = (v1 + 1) - v
deformed_intensities = (intensities[u1.type(tensor_integer_type), v1.type(tensor_integer_type)] * gu * gv +
intensities[u1.type(tensor_integer_type), v2.type(tensor_integer_type)] * gu * fv +
intensities[u2.type(tensor_integer_type), v1.type(tensor_integer_type)] * fu * gv +
intensities[u2.type(tensor_integer_type), v2.type(tensor_integer_type)] * fu * fv).view(image_shape)
elif self.dimension == 3:
if not self.downsampling_factor == 1:
shape = deformed_points.shape
deformed_voxels = torch.nn.functional.interpolate(deformed_voxels.permute(3, 0, 1, 2).contiguous().view(1, shape[3], shape[0], shape[1], shape[2]),
size=image_shape, mode='trilinear', align_corners=True)[0].permute(1, 2, 3, 0).contiguous()
u, v, w = deformed_voxels.view(-1, 3)[:, 0], \
deformed_voxels.view(-1, 3)[:, 1], \
deformed_voxels.view(-1, 3)[:, 2]
u1 = torch.floor(u.detach())
v1 = torch.floor(v.detach())
w1 = torch.floor(w.detach())
u1 = torch.clamp(u1, 0, image_shape[0] - 1)
v1 = torch.clamp(v1, 0, image_shape[1] - 1)
w1 = torch.clamp(w1, 0, image_shape[2] - 1)
u2 = torch.clamp(u1 + 1, 0, image_shape[0] - 1)
v2 = torch.clamp(v1 + 1, 0, image_shape[1] - 1)
w2 = torch.clamp(w1 + 1, 0, image_shape[2] - 1)
fu = u - u1
fv = v - v1
fw = w - w1
gu = (u1 + 1) - u
gv = (v1 + 1) - v
gw = (w1 + 1) - w
deformed_intensities = (intensities[u1.type(tensor_integer_type), v1.type(tensor_integer_type), w1.type(tensor_integer_type)] * gu * gv * gw +
intensities[u1.type(tensor_integer_type), v1.type(tensor_integer_type), w2.type(tensor_integer_type)] * gu * gv * fw +
intensities[u1.type(tensor_integer_type), v2.type(tensor_integer_type), w1.type(tensor_integer_type)] * gu * fv * gw +
intensities[u1.type(tensor_integer_type), v2.type(tensor_integer_type), w2.type(tensor_integer_type)] * gu * fv * fw +
intensities[u2.type(tensor_integer_type), v1.type(tensor_integer_type), w1.type(tensor_integer_type)] * fu * gv * gw +
intensities[u2.type(tensor_integer_type), v1.type(tensor_integer_type), w2.type(tensor_integer_type)] * fu * gv * fw +
intensities[u2.type(tensor_integer_type), v2.type(tensor_integer_type), w1.type(tensor_integer_type)] * fu * fv * gw +
intensities[u2.type(tensor_integer_type), v2.type(tensor_integer_type), w2.type(tensor_integer_type)] * fu * fv * fw).view(image_shape)
else:
raise RuntimeError('Incorrect dimension of the ambient space: %d' % self.dimension)
return deformed_intensities
####################################################################################################################
### Public methods:
####################################################################################################################
# # Update the relevant information.
# def update(self):
# if self.is_modified:
# self._update_corner_point_positions()
# self.update_bounding_box()
# self.is_modified = False
def update_bounding_box(self):
"""
Compute a tight bounding box that contains all the 2/3D-embedded image data.
"""
self.bounding_box = np.zeros((self.dimension, 2))
for d in range(self.dimension):
self.bounding_box[d, 0] = np.min(self.corner_points[:, d])
self.bounding_box[d, 1] = np.max(self.corner_points[:, d])
def write(self, output_dir, name, intensities=None):
if intensities is None:
intensities = self.get_intensities()
intensities_rescaled = rescale_image_intensities(intensities, self.intensities_dtype)
if name.find(".png") > 0:
pimg.fromarray(intensities_rescaled).save(os.path.join(output_dir, name))
elif name.find(".nii") > 0:
img = nib.Nifti1Image(intensities_rescaled, self.affine)
nib.save(img, os.path.join(output_dir, name))
elif name.find(".npy") > 0:
np.save(os.path.join(output_dir, name), intensities_rescaled)
else:
raise ValueError('Writing images with the given extension "%s" is not coded yet.' % name)
####################################################################################################################
### Utility methods:
####################################################################################################################
def _update_corner_point_positions(self):
if self.dimension == 2:
corner_points = np.zeros((4, 2))
umax, vmax = np.subtract(self.intensities.shape, (1, 1))
corner_points[0] = np.array([0, 0])
corner_points[1] = np.array([umax, 0])
corner_points[2] = np.array([0, vmax])
corner_points[3] = np.array([umax, vmax])
elif self.dimension == 3:
corner_points = np.zeros((8, 3))
umax, vmax, wmax = np.subtract(self.intensities.shape, (1, 1, 1))
corner_points[0] = np.array([0, 0, 0])
corner_points[1] = np.array([umax, 0, 0])
corner_points[2] = np.array([0, vmax, 0])
corner_points[3] = np.array([umax, vmax, 0])
corner_points[4] = np.array([0, 0, wmax])
corner_points[5] = np.array([umax, 0, wmax])
corner_points[6] = np.array([0, vmax, wmax])
corner_points[7] = np.array([umax, vmax, wmax])
#################################
# VERSION FOR IMAGE + MESH DATA #
#################################
# if self.dimension == 2:
# corner_points = np.zeros((4, 2))
# umax, vmax = np.subtract(self.intensities.shape, (1, 1))
# corner_points[0] = np.dot(self.affine[0:2, 0:2], np.array([0, 0])) + self.affine[0:2, 2]
# corner_points[1] = np.dot(self.affine[0:2, 0:2], np.array([umax, 0])) + self.affine[0:2, 2]
# corner_points[2] = np.dot(self.affine[0:2, 0:2], np.array([0, vmax])) + self.affine[0:2, 2]
# corner_points[3] = np.dot(self.affine[0:2, 0:2], np.array([umax, vmax])) + self.affine[0:2, 2]
#
# elif self.dimension == 3:
# corner_points = np.zeros((8, 3))
# umax, vmax, wmax = np.subtract(self.intensities.shape, (1, 1, 1))
# corner_points[0] = np.dot(self.affine[0:3, 0:3], np.array([0, 0, 0])) + self.affine[0:3, 3]
# corner_points[1] = np.dot(self.affine[0:3, 0:3], np.array([umax, 0, 0])) + self.affine[0:3, 3]
# corner_points[2] = np.dot(self.affine[0:3, 0:3], np.array([0, vmax, 0])) + self.affine[0:3, 3]
# corner_points[3] = np.dot(self.affine[0:3, 0:3], np.array([umax, vmax, 0])) + self.affine[0:3, 3]
# corner_points[4] = np.dot(self.affine[0:3, 0:3], np.array([0, 0, wmax])) + self.affine[0:3, 3]
# corner_points[5] = np.dot(self.affine[0:3, 0:3], np.array([umax, 0, wmax])) + self.affine[0:3, 3]
# corner_points[6] = np.dot(self.affine[0:3, 0:3], np.array([0, vmax, wmax])) + self.affine[0:3, 3]
# corner_points[7] = np.dot(self.affine[0:3, 0:3], np.array([umax, vmax, wmax])) + self.affine[0:3, 3]
else:
raise RuntimeError('Invalid dimension: %d' % self.dimension)
self.corner_points = corner_points
| [
"nibabel.Nifti1Image",
"numpy.meshgrid",
"numpy.subtract",
"numpy.zeros",
"numpy.min",
"torch.clamp",
"numpy.max",
"numpy.swapaxes",
"numpy.linspace",
"numpy.array",
"PIL.Image.fromarray",
"logging.getLogger"
] | [((247, 274), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (264, 274), False, 'import logging\n'), ((8735, 8764), 'numpy.zeros', 'np.zeros', (['(self.dimension, 2)'], {}), '((self.dimension, 2))\n', (8743, 8764), True, 'import numpy as np\n'), ((2725, 2842), 'numpy.linspace', 'np.linspace', (['self.corner_points[0, d]', 'self.corner_points[2 ** d, d]', '(image_shape[d] // self.downsampling_factor)'], {}), '(self.corner_points[0, d], self.corner_points[2 ** d, d], \n image_shape[d] // self.downsampling_factor)\n', (2736, 2842), True, 'import numpy as np\n'), ((3023, 3052), 'numpy.swapaxes', 'np.swapaxes', (['points', 'd', '(d + 1)'], {}), '(points, d, d + 1)\n', (3034, 3052), True, 'import numpy as np\n'), ((4574, 4612), 'torch.clamp', 'torch.clamp', (['u1', '(0)', '(image_shape[0] - 1)'], {}), '(u1, 0, image_shape[0] - 1)\n', (4585, 4612), False, 'import torch\n'), ((4630, 4668), 'torch.clamp', 'torch.clamp', (['v1', '(0)', '(image_shape[1] - 1)'], {}), '(v1, 0, image_shape[1] - 1)\n', (4641, 4668), False, 'import torch\n'), ((4686, 4728), 'torch.clamp', 'torch.clamp', (['(u1 + 1)', '(0)', '(image_shape[0] - 1)'], {}), '(u1 + 1, 0, image_shape[0] - 1)\n', (4697, 4728), False, 'import torch\n'), ((4746, 4788), 'torch.clamp', 'torch.clamp', (['(v1 + 1)', '(0)', '(image_shape[1] - 1)'], {}), '(v1 + 1, 0, image_shape[1] - 1)\n', (4757, 4788), False, 'import torch\n'), ((8843, 8875), 'numpy.min', 'np.min', (['self.corner_points[:, d]'], {}), '(self.corner_points[:, d])\n', (8849, 8875), True, 'import numpy as np\n'), ((8914, 8946), 'numpy.max', 'np.max', (['self.corner_points[:, d]'], {}), '(self.corner_points[:, d])\n', (8920, 8946), True, 'import numpy as np\n'), ((10067, 10083), 'numpy.zeros', 'np.zeros', (['(4, 2)'], {}), '((4, 2))\n', (10075, 10083), True, 'import numpy as np\n'), ((10109, 10152), 'numpy.subtract', 'np.subtract', (['self.intensities.shape', '(1, 1)'], {}), '(self.intensities.shape, (1, 1))\n', (10120, 10152), True, 'import numpy as np\n'), ((10184, 10200), 'numpy.array', 'np.array', (['[0, 0]'], {}), '([0, 0])\n', (10192, 10200), True, 'import numpy as np\n'), ((10232, 10251), 'numpy.array', 'np.array', (['[umax, 0]'], {}), '([umax, 0])\n', (10240, 10251), True, 'import numpy as np\n'), ((10283, 10302), 'numpy.array', 'np.array', (['[0, vmax]'], {}), '([0, vmax])\n', (10291, 10302), True, 'import numpy as np\n'), ((10334, 10356), 'numpy.array', 'np.array', (['[umax, vmax]'], {}), '([umax, vmax])\n', (10342, 10356), True, 'import numpy as np\n'), ((2924, 2957), 'numpy.meshgrid', 'np.meshgrid', (['*axes'], {'indexing': '"""ij"""'}), "(*axes, indexing='ij')\n", (2935, 2957), True, 'import numpy as np\n'), ((6166, 6204), 'torch.clamp', 'torch.clamp', (['u1', '(0)', '(image_shape[0] - 1)'], {}), '(u1, 0, image_shape[0] - 1)\n', (6177, 6204), False, 'import torch\n'), ((6222, 6260), 'torch.clamp', 'torch.clamp', (['v1', '(0)', '(image_shape[1] - 1)'], {}), '(v1, 0, image_shape[1] - 1)\n', (6233, 6260), False, 'import torch\n'), ((6278, 6316), 'torch.clamp', 'torch.clamp', (['w1', '(0)', '(image_shape[2] - 1)'], {}), '(w1, 0, image_shape[2] - 1)\n', (6289, 6316), False, 'import torch\n'), ((6334, 6376), 'torch.clamp', 'torch.clamp', (['(u1 + 1)', '(0)', '(image_shape[0] - 1)'], {}), '(u1 + 1, 0, image_shape[0] - 1)\n', (6345, 6376), False, 'import torch\n'), ((6394, 6436), 'torch.clamp', 'torch.clamp', (['(v1 + 1)', '(0)', '(image_shape[1] - 1)'], {}), '(v1 + 1, 0, image_shape[1] - 1)\n', (6405, 6436), False, 'import torch\n'), ((6454, 6496), 'torch.clamp', 'torch.clamp', (['(w1 + 1)', '(0)', '(image_shape[2] - 1)'], {}), '(w1 + 1, 0, image_shape[2] - 1)\n', (6465, 6496), False, 'import torch\n'), ((9357, 9407), 'nibabel.Nifti1Image', 'nib.Nifti1Image', (['intensities_rescaled', 'self.affine'], {}), '(intensities_rescaled, self.affine)\n', (9372, 9407), True, 'import nibabel as nib\n'), ((10420, 10436), 'numpy.zeros', 'np.zeros', (['(8, 3)'], {}), '((8, 3))\n', (10428, 10436), True, 'import numpy as np\n'), ((10468, 10514), 'numpy.subtract', 'np.subtract', (['self.intensities.shape', '(1, 1, 1)'], {}), '(self.intensities.shape, (1, 1, 1))\n', (10479, 10514), True, 'import numpy as np\n'), ((10546, 10565), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (10554, 10565), True, 'import numpy as np\n'), ((10597, 10619), 'numpy.array', 'np.array', (['[umax, 0, 0]'], {}), '([umax, 0, 0])\n', (10605, 10619), True, 'import numpy as np\n'), ((10651, 10673), 'numpy.array', 'np.array', (['[0, vmax, 0]'], {}), '([0, vmax, 0])\n', (10659, 10673), True, 'import numpy as np\n'), ((10705, 10730), 'numpy.array', 'np.array', (['[umax, vmax, 0]'], {}), '([umax, vmax, 0])\n', (10713, 10730), True, 'import numpy as np\n'), ((10762, 10784), 'numpy.array', 'np.array', (['[0, 0, wmax]'], {}), '([0, 0, wmax])\n', (10770, 10784), True, 'import numpy as np\n'), ((10816, 10841), 'numpy.array', 'np.array', (['[umax, 0, wmax]'], {}), '([umax, 0, wmax])\n', (10824, 10841), True, 'import numpy as np\n'), ((10873, 10898), 'numpy.array', 'np.array', (['[0, vmax, wmax]'], {}), '([0, vmax, wmax])\n', (10881, 10898), True, 'import numpy as np\n'), ((10930, 10958), 'numpy.array', 'np.array', (['[umax, vmax, wmax]'], {}), '([umax, vmax, wmax])\n', (10938, 10958), True, 'import numpy as np\n'), ((9229, 9265), 'PIL.Image.fromarray', 'pimg.fromarray', (['intensities_rescaled'], {}), '(intensities_rescaled)\n', (9243, 9265), True, 'import PIL.Image as pimg\n')] |
# python frozen_raw.py --dump_path scratch/dump_word_embeddings_glove --dim_pca 17
import argparse
import numpy as np
import pickle
from pytorch_helper.util import cos_numpy
from scipy.stats import pearsonr, spearmanr
class RawFrozenEvaluator:
def __init__(self, hparams):
self.hparams = hparams
self.encoding = pickle.load(open(hparams.dump_path, 'rb'))
self.dim = len(self.encoding['train'][0][0][0])
if hparams.dim_pca > 0:
self.get_val_projection()
def get_val_projection(self):
embs = []
for vectors1, vectors2, _ in self.encoding['val']:
emb1 = self.get_rep(vectors1)
emb2 = self.get_rep(vectors2)
if isinstance(emb1, np.ndarray):
embs.append(emb1)
if isinstance(emb2, np.ndarray):
embs.append(emb2)
X = np.column_stack(embs) # d x 2*num_pairs
self.mu = np.mean(X, axis=1)
X -= np.expand_dims(self.mu, axis=1)
print('SVD on %d x %d data matrix, removing top-%d subspace from val '
'sentence embs' % (X.shape[0], X.shape[1], self.hparams.dim_pca))
U, S, Vt = np.linalg.svd(X)
U = U[:,:self.hparams.dim_pca]
self.P = np.matmul(U, U.transpose())
def get_rep(self, vectors):
if not vectors:
return None
vectors = [np.array(vector) for vector in vectors]
if self.hparams.pooling == 'mean':
rep = np.mean(vectors, axis=0)
elif self.hparams.pooling == 'max':
rep = np.amax(np.column_stack(vectors), axis=1)
else:
raise ValueError
return rep
def run(self):
p_train, s_train, num_preds_train \
= self.compute_correlations(self.encoding['train'])
p_val, s_val, num_preds_val \
= self.compute_correlations(self.encoding['val'])
p_test, s_test, num_preds_test \
= self.compute_correlations(self.encoding['test'])
return argparse.Namespace(p_train=p_train, s_train=s_train,
num_preds_train=num_preds_train,
p_val=p_val, s_val=s_val,
num_preds_val=num_preds_val,
p_test=p_test, s_test=s_test,
num_preds_test=num_preds_test)
def compute_correlations(self, examples):
preds = []
golds = []
for vectors1, vectors2, score in examples:
emb1 = self.get_rep(vectors1)
emb2 = self.get_rep(vectors2)
if not (isinstance(emb1, np.ndarray) and
isinstance(emb2, np.ndarray)):
continue # No tokens with emb
if self.hparams.dim_pca > 0:
emb1 -= self.mu
emb2 -= self.mu
emb1 -= self.P.dot(emb1)
emb2 -= self.P.dot(emb2)
preds.append(cos_numpy(emb1, emb2))
golds.append(score)
preds = np.array(preds)
golds = np.array(golds)
p = pearsonr(preds, golds)[0] * 100. if len(preds) > 0 else None
s = spearmanr(preds, golds)[0] * 100. if len(preds) > 0 else None
return p, s, len(preds)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--dump_path', type=str, default='scratch/dump',
help='path to encoding dump [%(default)s]')
parser.add_argument('--dim_pca', type=int, default=0,
help='PCA dimension [%(default)d]')
parser.add_argument('--pooling', default='mean',
choices=['mean', 'max'],
help='pooling method [%(default)s]')
hparams = parser.parse_args()
evaluator = RawFrozenEvaluator(hparams)
print('input embedding dimension %d' % evaluator.dim)
run = evaluator.run()
print(' train: {:4.1f}/{:4.1f} ({:d}/{:d} evaluated)'.format(
run.p_train, run.s_train, run.num_preds_train,
len(evaluator.encoding['train'])))
print(' val: {:4.1f}/{:4.1f} ({:d}/{:d} evaluated)'.format(
run.p_val, run.s_val, run.num_preds_val,
len(evaluator.encoding['val'])))
print(' test: {:4.1f}/{:4.1f} ({:d}/{:d} evaluated)'.format(
run.p_test, run.s_test, run.num_preds_test,
len(evaluator.encoding['test'])))
| [
"argparse.Namespace",
"argparse.ArgumentParser",
"scipy.stats.spearmanr",
"numpy.expand_dims",
"scipy.stats.pearsonr",
"numpy.linalg.svd",
"numpy.mean",
"numpy.array",
"pytorch_helper.util.cos_numpy",
"numpy.column_stack"
] | [((3313, 3338), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3336, 3338), False, 'import argparse\n'), ((874, 895), 'numpy.column_stack', 'np.column_stack', (['embs'], {}), '(embs)\n', (889, 895), True, 'import numpy as np\n'), ((933, 951), 'numpy.mean', 'np.mean', (['X'], {'axis': '(1)'}), '(X, axis=1)\n', (940, 951), True, 'import numpy as np\n'), ((965, 996), 'numpy.expand_dims', 'np.expand_dims', (['self.mu'], {'axis': '(1)'}), '(self.mu, axis=1)\n', (979, 996), True, 'import numpy as np\n'), ((1176, 1192), 'numpy.linalg.svd', 'np.linalg.svd', (['X'], {}), '(X)\n', (1189, 1192), True, 'import numpy as np\n'), ((2016, 2226), 'argparse.Namespace', 'argparse.Namespace', ([], {'p_train': 'p_train', 's_train': 's_train', 'num_preds_train': 'num_preds_train', 'p_val': 'p_val', 's_val': 's_val', 'num_preds_val': 'num_preds_val', 'p_test': 'p_test', 's_test': 's_test', 'num_preds_test': 'num_preds_test'}), '(p_train=p_train, s_train=s_train, num_preds_train=\n num_preds_train, p_val=p_val, s_val=s_val, num_preds_val=num_preds_val,\n p_test=p_test, s_test=s_test, num_preds_test=num_preds_test)\n', (2034, 2226), False, 'import argparse\n'), ((3044, 3059), 'numpy.array', 'np.array', (['preds'], {}), '(preds)\n', (3052, 3059), True, 'import numpy as np\n'), ((3076, 3091), 'numpy.array', 'np.array', (['golds'], {}), '(golds)\n', (3084, 3091), True, 'import numpy as np\n'), ((1377, 1393), 'numpy.array', 'np.array', (['vector'], {}), '(vector)\n', (1385, 1393), True, 'import numpy as np\n'), ((1478, 1502), 'numpy.mean', 'np.mean', (['vectors'], {'axis': '(0)'}), '(vectors, axis=0)\n', (1485, 1502), True, 'import numpy as np\n'), ((2973, 2994), 'pytorch_helper.util.cos_numpy', 'cos_numpy', (['emb1', 'emb2'], {}), '(emb1, emb2)\n', (2982, 2994), False, 'from pytorch_helper.util import cos_numpy\n'), ((1573, 1597), 'numpy.column_stack', 'np.column_stack', (['vectors'], {}), '(vectors)\n', (1588, 1597), True, 'import numpy as np\n'), ((3104, 3126), 'scipy.stats.pearsonr', 'pearsonr', (['preds', 'golds'], {}), '(preds, golds)\n', (3112, 3126), False, 'from scipy.stats import pearsonr, spearmanr\n'), ((3177, 3200), 'scipy.stats.spearmanr', 'spearmanr', (['preds', 'golds'], {}), '(preds, golds)\n', (3186, 3200), False, 'from scipy.stats import pearsonr, spearmanr\n')] |
import numpy as np
import pandas as pd
from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range
import pandas._testing as tm
class TestGetLevelValues:
def test_get_level_values_box_datetime64(self):
dates = date_range("1/1/2000", periods=4)
levels = [dates, [0, 1]]
codes = [[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1]]
index = MultiIndex(levels=levels, codes=codes)
assert isinstance(index.get_level_values(0)[0], Timestamp)
def test_get_level_values(idx):
result = idx.get_level_values(0)
expected = Index(["foo", "foo", "bar", "baz", "qux", "qux"], name="first")
tm.assert_index_equal(result, expected)
assert result.name == "first"
result = idx.get_level_values("first")
expected = idx.get_level_values(0)
tm.assert_index_equal(result, expected)
# GH 10460
index = MultiIndex(
levels=[CategoricalIndex(["A", "B"]), CategoricalIndex([1, 2, 3])],
codes=[np.array([0, 0, 0, 1, 1, 1]), np.array([0, 1, 2, 0, 1, 2])],
)
exp = CategoricalIndex(["A", "A", "A", "B", "B", "B"])
tm.assert_index_equal(index.get_level_values(0), exp)
exp = CategoricalIndex([1, 2, 3, 1, 2, 3])
tm.assert_index_equal(index.get_level_values(1), exp)
def test_get_level_values_all_na():
# GH#17924 when level entirely consists of nan
arrays = [[np.nan, np.nan, np.nan], ["a", np.nan, 1]]
index = MultiIndex.from_arrays(arrays)
result = index.get_level_values(0)
expected = Index([np.nan, np.nan, np.nan], dtype=np.float64)
tm.assert_index_equal(result, expected)
result = index.get_level_values(1)
expected = Index(["a", np.nan, 1], dtype=object)
tm.assert_index_equal(result, expected)
def test_get_level_values_int_with_na():
# GH#17924
arrays = [["a", "b", "b"], [1, np.nan, 2]]
index = MultiIndex.from_arrays(arrays)
result = index.get_level_values(1)
expected = Index([1, np.nan, 2])
tm.assert_index_equal(result, expected)
arrays = [["a", "b", "b"], [np.nan, np.nan, 2]]
index = MultiIndex.from_arrays(arrays)
result = index.get_level_values(1)
expected = Index([np.nan, np.nan, 2])
tm.assert_index_equal(result, expected)
def test_get_level_values_na():
arrays = [[np.nan, np.nan, np.nan], ["a", np.nan, 1]]
index = MultiIndex.from_arrays(arrays)
result = index.get_level_values(0)
expected = Index([np.nan, np.nan, np.nan])
tm.assert_index_equal(result, expected)
result = index.get_level_values(1)
expected = Index(["a", np.nan, 1])
tm.assert_index_equal(result, expected)
arrays = [["a", "b", "b"], pd.DatetimeIndex([0, 1, pd.NaT])]
index = MultiIndex.from_arrays(arrays)
result = index.get_level_values(1)
expected = pd.DatetimeIndex([0, 1, pd.NaT])
tm.assert_index_equal(result, expected)
arrays = [[], []]
index = MultiIndex.from_arrays(arrays)
result = index.get_level_values(0)
expected = Index([], dtype=object)
tm.assert_index_equal(result, expected)
def test_get_level_values_when_periods():
# GH33131. See also discussion in GH32669.
# This test can probably be removed when PeriodIndex._engine is removed.
from pandas import Period, PeriodIndex
idx = MultiIndex.from_arrays(
[PeriodIndex([Period("2019Q1"), Period("2019Q2")], name="b")]
)
idx2 = MultiIndex.from_arrays(
[idx._get_level_values(level) for level in range(idx.nlevels)]
)
assert all(x.is_monotonic for x in idx2.levels)
| [
"pandas.date_range",
"pandas.MultiIndex.from_arrays",
"pandas.DatetimeIndex",
"pandas.Index",
"pandas._testing.assert_index_equal",
"numpy.array",
"pandas.Period",
"pandas.MultiIndex",
"pandas.CategoricalIndex"
] | [((611, 674), 'pandas.Index', 'Index', (["['foo', 'foo', 'bar', 'baz', 'qux', 'qux']"], {'name': '"""first"""'}), "(['foo', 'foo', 'bar', 'baz', 'qux', 'qux'], name='first')\n", (616, 674), False, 'from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range\n'), ((680, 719), 'pandas._testing.assert_index_equal', 'tm.assert_index_equal', (['result', 'expected'], {}), '(result, expected)\n', (701, 719), True, 'import pandas._testing as tm\n'), ((846, 885), 'pandas._testing.assert_index_equal', 'tm.assert_index_equal', (['result', 'expected'], {}), '(result, expected)\n', (867, 885), True, 'import pandas._testing as tm\n'), ((1103, 1151), 'pandas.CategoricalIndex', 'CategoricalIndex', (["['A', 'A', 'A', 'B', 'B', 'B']"], {}), "(['A', 'A', 'A', 'B', 'B', 'B'])\n", (1119, 1151), False, 'from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range\n'), ((1222, 1258), 'pandas.CategoricalIndex', 'CategoricalIndex', (['[1, 2, 3, 1, 2, 3]'], {}), '([1, 2, 3, 1, 2, 3])\n', (1238, 1258), False, 'from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range\n'), ((1483, 1513), 'pandas.MultiIndex.from_arrays', 'MultiIndex.from_arrays', (['arrays'], {}), '(arrays)\n', (1505, 1513), False, 'from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range\n'), ((1570, 1619), 'pandas.Index', 'Index', (['[np.nan, np.nan, np.nan]'], {'dtype': 'np.float64'}), '([np.nan, np.nan, np.nan], dtype=np.float64)\n', (1575, 1619), False, 'from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range\n'), ((1625, 1664), 'pandas._testing.assert_index_equal', 'tm.assert_index_equal', (['result', 'expected'], {}), '(result, expected)\n', (1646, 1664), True, 'import pandas._testing as tm\n'), ((1723, 1760), 'pandas.Index', 'Index', (["['a', np.nan, 1]"], {'dtype': 'object'}), "(['a', np.nan, 1], dtype=object)\n", (1728, 1760), False, 'from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range\n'), ((1766, 1805), 'pandas._testing.assert_index_equal', 'tm.assert_index_equal', (['result', 'expected'], {}), '(result, expected)\n', (1787, 1805), True, 'import pandas._testing as tm\n'), ((1929, 1959), 'pandas.MultiIndex.from_arrays', 'MultiIndex.from_arrays', (['arrays'], {}), '(arrays)\n', (1951, 1959), False, 'from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range\n'), ((2016, 2037), 'pandas.Index', 'Index', (['[1, np.nan, 2]'], {}), '([1, np.nan, 2])\n', (2021, 2037), False, 'from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range\n'), ((2043, 2082), 'pandas._testing.assert_index_equal', 'tm.assert_index_equal', (['result', 'expected'], {}), '(result, expected)\n', (2064, 2082), True, 'import pandas._testing as tm\n'), ((2151, 2181), 'pandas.MultiIndex.from_arrays', 'MultiIndex.from_arrays', (['arrays'], {}), '(arrays)\n', (2173, 2181), False, 'from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range\n'), ((2238, 2264), 'pandas.Index', 'Index', (['[np.nan, np.nan, 2]'], {}), '([np.nan, np.nan, 2])\n', (2243, 2264), False, 'from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range\n'), ((2270, 2309), 'pandas._testing.assert_index_equal', 'tm.assert_index_equal', (['result', 'expected'], {}), '(result, expected)\n', (2291, 2309), True, 'import pandas._testing as tm\n'), ((2419, 2449), 'pandas.MultiIndex.from_arrays', 'MultiIndex.from_arrays', (['arrays'], {}), '(arrays)\n', (2441, 2449), False, 'from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range\n'), ((2506, 2537), 'pandas.Index', 'Index', (['[np.nan, np.nan, np.nan]'], {}), '([np.nan, np.nan, np.nan])\n', (2511, 2537), False, 'from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range\n'), ((2543, 2582), 'pandas._testing.assert_index_equal', 'tm.assert_index_equal', (['result', 'expected'], {}), '(result, expected)\n', (2564, 2582), True, 'import pandas._testing as tm\n'), ((2641, 2664), 'pandas.Index', 'Index', (["['a', np.nan, 1]"], {}), "(['a', np.nan, 1])\n", (2646, 2664), False, 'from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range\n'), ((2670, 2709), 'pandas._testing.assert_index_equal', 'tm.assert_index_equal', (['result', 'expected'], {}), '(result, expected)\n', (2691, 2709), True, 'import pandas._testing as tm\n'), ((2791, 2821), 'pandas.MultiIndex.from_arrays', 'MultiIndex.from_arrays', (['arrays'], {}), '(arrays)\n', (2813, 2821), False, 'from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range\n'), ((2878, 2910), 'pandas.DatetimeIndex', 'pd.DatetimeIndex', (['[0, 1, pd.NaT]'], {}), '([0, 1, pd.NaT])\n', (2894, 2910), True, 'import pandas as pd\n'), ((2916, 2955), 'pandas._testing.assert_index_equal', 'tm.assert_index_equal', (['result', 'expected'], {}), '(result, expected)\n', (2937, 2955), True, 'import pandas._testing as tm\n'), ((2994, 3024), 'pandas.MultiIndex.from_arrays', 'MultiIndex.from_arrays', (['arrays'], {}), '(arrays)\n', (3016, 3024), False, 'from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range\n'), ((3081, 3104), 'pandas.Index', 'Index', (['[]'], {'dtype': 'object'}), '([], dtype=object)\n', (3086, 3104), False, 'from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range\n'), ((3110, 3149), 'pandas._testing.assert_index_equal', 'tm.assert_index_equal', (['result', 'expected'], {}), '(result, expected)\n', (3131, 3149), True, 'import pandas._testing as tm\n'), ((254, 287), 'pandas.date_range', 'date_range', (['"""1/1/2000"""'], {'periods': '(4)'}), "('1/1/2000', periods=4)\n", (264, 287), False, 'from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range\n'), ((411, 449), 'pandas.MultiIndex', 'MultiIndex', ([], {'levels': 'levels', 'codes': 'codes'}), '(levels=levels, codes=codes)\n', (421, 449), False, 'from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range\n'), ((2744, 2776), 'pandas.DatetimeIndex', 'pd.DatetimeIndex', (['[0, 1, pd.NaT]'], {}), '([0, 1, pd.NaT])\n', (2760, 2776), True, 'import pandas as pd\n'), ((946, 974), 'pandas.CategoricalIndex', 'CategoricalIndex', (["['A', 'B']"], {}), "(['A', 'B'])\n", (962, 974), False, 'from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range\n'), ((976, 1003), 'pandas.CategoricalIndex', 'CategoricalIndex', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (992, 1003), False, 'from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range\n'), ((1022, 1050), 'numpy.array', 'np.array', (['[0, 0, 0, 1, 1, 1]'], {}), '([0, 0, 0, 1, 1, 1])\n', (1030, 1050), True, 'import numpy as np\n'), ((1052, 1080), 'numpy.array', 'np.array', (['[0, 1, 2, 0, 1, 2]'], {}), '([0, 1, 2, 0, 1, 2])\n', (1060, 1080), True, 'import numpy as np\n'), ((3427, 3443), 'pandas.Period', 'Period', (['"""2019Q1"""'], {}), "('2019Q1')\n", (3433, 3443), False, 'from pandas import Period, PeriodIndex\n'), ((3445, 3461), 'pandas.Period', 'Period', (['"""2019Q2"""'], {}), "('2019Q2')\n", (3451, 3461), False, 'from pandas import Period, PeriodIndex\n')] |
import numpy as np
# 忽略除数为0的warning, 对于除数为0的情况已有相应处理
np.seterr(divide='ignore', invalid='ignore')
from utils.f_boundary import eval_mask_boundary
class Evaluator(object):
def __init__(self, num_class):
self.num_class = num_class
self.confusion_matrix = np.zeros((self.num_class,)*2)
def Pixel_Accuracy(self):
Acc = np.diag(self.confusion_matrix).sum() / self.confusion_matrix.sum()
return Acc
def Pixel_Accuracy_Class(self):
Acc = np.diag(self.confusion_matrix) / self.confusion_matrix.sum(axis=1)
Acc = np.nanmean(Acc)
return Acc
def Precision(self):
assert self.num_class == 2
pr = self.confusion_matrix[1, 1] / (self.confusion_matrix[1, 1] + self.confusion_matrix[0, 1])
return 1.0 if np.isnan(pr) else pr
def Recall(self):
assert self.num_class == 2
re = self.confusion_matrix[1, 1] / (self.confusion_matrix[1, 1] + self.confusion_matrix[1, 0])
return 1.0 if np.isnan(re) else re
def F_score(self):
assert self.num_class == 2
pr, re = self.Precision(), self.Recall()
if pr + re == 0:
return 0.0
else:
return 2.0 * pr * re / (pr + re)
def Mean_Intersection_over_Union(self):
MIoU = np.diag(self.confusion_matrix) / (
np.sum(self.confusion_matrix, axis=1) + np.sum(self.confusion_matrix, axis=0) -
np.diag(self.confusion_matrix))
# MIoU = np.nanmean(MIoU)
return MIoU[1]
def Frequency_Weighted_Intersection_over_Union(self):
freq = np.sum(self.confusion_matrix, axis=1) / np.sum(self.confusion_matrix)
iu = np.diag(self.confusion_matrix) / (
np.sum(self.confusion_matrix, axis=1) + np.sum(self.confusion_matrix, axis=0) -
np.diag(self.confusion_matrix))
FWIoU = (freq[freq > 0] * iu[freq > 0]).sum()
return FWIoU
def _generate_matrix(self, gt_image, pre_image):
mask = (gt_image >= 0) & (gt_image < self.num_class)
label = self.num_class * gt_image[mask].astype('int') + pre_image[mask]
count = np.bincount(label, minlength=self.num_class**2)
confusion_matrix = count.reshape(self.num_class, self.num_class)
return confusion_matrix
def add_batch(self, gt_image, pre_image):
assert gt_image.shape == pre_image.shape
self.confusion_matrix += self._generate_matrix(gt_image, pre_image)
def reset(self):
self.confusion_matrix = np.zeros((self.num_class,) * 2)
class BoundaryEvaluator(object):
def __init__(self, num_class, p=None, num_proc=10, bound_th=0.008):
self.num_class = num_class
self.p = p
self.num_proc = num_proc
self.bound_th = bound_th
self.confusion_matrix_pc = np.zeros((self.num_class, 4))
def Precision_boundary(self):
pr = self.confusion_matrix_pc[:, 0] / self.confusion_matrix_pc[:, 1]
pr[np.isnan(pr)] = 1.0
return pr
def Recall_boundary(self):
re = self.confusion_matrix_pc[:, 2] / self.confusion_matrix_pc[:, 3]
re[np.isnan(re)] = 1.0
return re
def F_score_boundary(self):
pr, re = self.Precision_boundary(), self.Recall_boundary()
f_score = 2 * pr * re / (pr + re)
f_score[np.isnan(f_score)] = 0.0
return f_score
def _generate_matrix(self, gt_image, pre_image):
if len(gt_image.shape) == 2:
pre_image, gt_image = np.expand_dims(pre_image, axis=0), np.expand_dims(gt_image, axis=0)
return eval_mask_boundary(pre_image, gt_image, self.num_class, self.p, self.num_proc, self.bound_th)
def add_batch(self, gt_image, pre_image):
assert gt_image.shape == pre_image.shape
self.confusion_matrix_pc += self._generate_matrix(gt_image, pre_image)
def reset(self):
self.confusion_matrix_pc = np.zeros((self.num_class, 4))
| [
"numpy.sum",
"numpy.seterr",
"numpy.zeros",
"numpy.expand_dims",
"numpy.isnan",
"numpy.diag",
"numpy.bincount",
"utils.f_boundary.eval_mask_boundary",
"numpy.nanmean"
] | [((54, 98), 'numpy.seterr', 'np.seterr', ([], {'divide': '"""ignore"""', 'invalid': '"""ignore"""'}), "(divide='ignore', invalid='ignore')\n", (63, 98), True, 'import numpy as np\n'), ((277, 308), 'numpy.zeros', 'np.zeros', (['((self.num_class,) * 2)'], {}), '((self.num_class,) * 2)\n', (285, 308), True, 'import numpy as np\n'), ((570, 585), 'numpy.nanmean', 'np.nanmean', (['Acc'], {}), '(Acc)\n', (580, 585), True, 'import numpy as np\n'), ((2166, 2215), 'numpy.bincount', 'np.bincount', (['label'], {'minlength': '(self.num_class ** 2)'}), '(label, minlength=self.num_class ** 2)\n', (2177, 2215), True, 'import numpy as np\n'), ((2545, 2576), 'numpy.zeros', 'np.zeros', (['((self.num_class,) * 2)'], {}), '((self.num_class,) * 2)\n', (2553, 2576), True, 'import numpy as np\n'), ((2839, 2868), 'numpy.zeros', 'np.zeros', (['(self.num_class, 4)'], {}), '((self.num_class, 4))\n', (2847, 2868), True, 'import numpy as np\n'), ((3602, 3700), 'utils.f_boundary.eval_mask_boundary', 'eval_mask_boundary', (['pre_image', 'gt_image', 'self.num_class', 'self.p', 'self.num_proc', 'self.bound_th'], {}), '(pre_image, gt_image, self.num_class, self.p, self.\n num_proc, self.bound_th)\n', (3620, 3700), False, 'from utils.f_boundary import eval_mask_boundary\n'), ((3928, 3957), 'numpy.zeros', 'np.zeros', (['(self.num_class, 4)'], {}), '((self.num_class, 4))\n', (3936, 3957), True, 'import numpy as np\n'), ((489, 519), 'numpy.diag', 'np.diag', (['self.confusion_matrix'], {}), '(self.confusion_matrix)\n', (496, 519), True, 'import numpy as np\n'), ((791, 803), 'numpy.isnan', 'np.isnan', (['pr'], {}), '(pr)\n', (799, 803), True, 'import numpy as np\n'), ((995, 1007), 'numpy.isnan', 'np.isnan', (['re'], {}), '(re)\n', (1003, 1007), True, 'import numpy as np\n'), ((1291, 1321), 'numpy.diag', 'np.diag', (['self.confusion_matrix'], {}), '(self.confusion_matrix)\n', (1298, 1321), True, 'import numpy as np\n'), ((1609, 1646), 'numpy.sum', 'np.sum', (['self.confusion_matrix'], {'axis': '(1)'}), '(self.confusion_matrix, axis=1)\n', (1615, 1646), True, 'import numpy as np\n'), ((1649, 1678), 'numpy.sum', 'np.sum', (['self.confusion_matrix'], {}), '(self.confusion_matrix)\n', (1655, 1678), True, 'import numpy as np\n'), ((1692, 1722), 'numpy.diag', 'np.diag', (['self.confusion_matrix'], {}), '(self.confusion_matrix)\n', (1699, 1722), True, 'import numpy as np\n'), ((2992, 3004), 'numpy.isnan', 'np.isnan', (['pr'], {}), '(pr)\n', (3000, 3004), True, 'import numpy as np\n'), ((3150, 3162), 'numpy.isnan', 'np.isnan', (['re'], {}), '(re)\n', (3158, 3162), True, 'import numpy as np\n'), ((3346, 3363), 'numpy.isnan', 'np.isnan', (['f_score'], {}), '(f_score)\n', (3354, 3363), True, 'import numpy as np\n'), ((1446, 1476), 'numpy.diag', 'np.diag', (['self.confusion_matrix'], {}), '(self.confusion_matrix)\n', (1453, 1476), True, 'import numpy as np\n'), ((1847, 1877), 'numpy.diag', 'np.diag', (['self.confusion_matrix'], {}), '(self.confusion_matrix)\n', (1854, 1877), True, 'import numpy as np\n'), ((3519, 3552), 'numpy.expand_dims', 'np.expand_dims', (['pre_image'], {'axis': '(0)'}), '(pre_image, axis=0)\n', (3533, 3552), True, 'import numpy as np\n'), ((3554, 3586), 'numpy.expand_dims', 'np.expand_dims', (['gt_image'], {'axis': '(0)'}), '(gt_image, axis=0)\n', (3568, 3586), True, 'import numpy as np\n'), ((352, 382), 'numpy.diag', 'np.diag', (['self.confusion_matrix'], {}), '(self.confusion_matrix)\n', (359, 382), True, 'import numpy as np\n'), ((1346, 1383), 'numpy.sum', 'np.sum', (['self.confusion_matrix'], {'axis': '(1)'}), '(self.confusion_matrix, axis=1)\n', (1352, 1383), True, 'import numpy as np\n'), ((1386, 1423), 'numpy.sum', 'np.sum', (['self.confusion_matrix'], {'axis': '(0)'}), '(self.confusion_matrix, axis=0)\n', (1392, 1423), True, 'import numpy as np\n'), ((1747, 1784), 'numpy.sum', 'np.sum', (['self.confusion_matrix'], {'axis': '(1)'}), '(self.confusion_matrix, axis=1)\n', (1753, 1784), True, 'import numpy as np\n'), ((1787, 1824), 'numpy.sum', 'np.sum', (['self.confusion_matrix'], {'axis': '(0)'}), '(self.confusion_matrix, axis=0)\n', (1793, 1824), True, 'import numpy as np\n')] |
from shapely.geometry import Point, Polygon, LineString
import cv2
import numpy as np
from scipy import signal
from pathlib import Path
import pathlib
import math
import copy
from blender_scripts.util import _get_furniture_info
def place_multi_furniture_scoring(furniture_obj_dir="./data/basic_furniture/", wall_objs_dir="./data/mid/panel_384478_洋室/", room_scale_factor=1):
if not isinstance(wall_objs_dir, pathlib.PosixPath):
wall_objs_dir = Path(wall_objs_dir)
coords, min_x, max_x, min_y, max_y = _parse_obj(wall_objs_dir / "floor.obj")
poly = Polygon(coords)
inside_outside_map = np.full((max_y-min_y+1, max_x-min_x+1), -np.inf)
print(inside_outside_map.shape)
for r in range(min_y, max_y):
for c in range(min_x, max_x):
if Point(c, r).within(poly):
inside_outside_map[r - min_y, c - min_x] = 255
image_files = list(Path("/Users/taku-ueki/HorizonNet/data/mid/panel_384478_洋室/").glob("wall_*.jpg"))
# wall2smoothness = {}
wall2smoothness_coords = {}
edge_level_all = 0
for image_file in image_files:
if "wall" in str(image_file):
ima = cv2.imread(str(image_file))
gray_img = cv2.cvtColor(ima, cv2.COLOR_BGR2GRAY)
edge_level = cv2.Laplacian(gray_img, cv2.CV_64F).var()
edge_level_all += edge_level
line = _parse_obj_wall(image_file.parent / (image_file.stem + ".obj"))
wall2smoothness_coords[image_file.stem] = {"edge_level": edge_level, "line": line}
for k,v in wall2smoothness_coords.items():
v["edge_level"] /= edge_level_all
score_map = np.full((max_y-min_y+1, max_x-min_x+1), -np.inf)
scores = []
for r in range(min_y, max_y):
for c in range(min_x, max_x):
current_point = Point(c, r)
# if current_point.within(poly):
if inside_outside_map[r - min_y, c - min_x] > 0:
score = 0
for wall_name, smoothness_coords in wall2smoothness_coords.items():
smoothness = 1- smoothness_coords["edge_level"]
line = smoothness_coords["line"]
# score += smoothness * (1/current_point.distance(line))
score += (1/1+current_point.distance(line))*smoothness
scores.append(score)
score_map[r - min_y, c - min_x] = score
else:
scores.append(0)
score_map = score_map / score_map.max()
if not isinstance(furniture_obj_dir, pathlib.PosixPath):
furniture_obj_dir = Path(furniture_obj_dir)
furniture_objs = list(furniture_obj_dir.glob("*.obj"))
"""sort the furniture objs by its size"""
furniture_obj_volume = [[furniture_obj] + list(_get_furniture_info(furniture_obj)) for furniture_obj in furniture_objs]
furniture_obj_volume.sort(key=lambda x:x[-1], reverse=True)
furniture_obj2position = {}
score_map_history = [copy.deepcopy(score_map)]
for i, (furniture_obj, furniture_axis2width, volume) in enumerate(furniture_obj_volume):
# if the furniture is too big, ignore it.
if (furniture_axis2width["x"]*100 > score_map.shape[0] and furniture_axis2width["x"]*100 > score_map.shape[1]) or (furniture_axis2width["z"]*100 > score_map.shape[0] and furniture_axis2width["z"]*100 > score_map.shape[1]):
continue
print(furniture_obj)
# place furniture horizontally
kernel1 = np.ones((int(100*furniture_axis2width["x"]), int(100*furniture_axis2width["z"])))
kernel_size = kernel1.sum()
try:
convolved_res1 = signal.convolve2d(score_map, kernel1, boundary='symm', mode='valid')/kernel_size
except:
convolved_res1 = None
# place furniture vertically
kernel2 = np.ones((int(100*furniture_axis2width["z"]), int(100*furniture_axis2width["x"])))
try:
convolved_res2 = signal.convolve2d(score_map, kernel2, boundary='symm', mode='valid')/kernel_size
except:
convolved_res2 = None
if convolved_res2 is None or convolved_res1.max() > convolved_res2.max():
convolved_res = convolved_res1
kernel_shape = (int(100*furniture_axis2width["x"]), int(100*furniture_axis2width["z"]))
else:
convolved_res = convolved_res2
kernel_shape = (int(100*furniture_axis2width["z"]), int(100*furniture_axis2width["x"]))
best_row_topLeft, best_col_topLeft = np.unravel_index(np.argmax(convolved_res), convolved_res.shape)
best_row_center = best_row_topLeft + kernel_shape[0]//2
best_col_center = best_col_topLeft + kernel_shape[1]//2
score_map[best_row_topLeft:best_row_topLeft+kernel_shape[0], best_col_topLeft:best_col_topLeft+kernel_shape[1]] = -np.inf
score_map_history.append(copy.deepcopy(score_map))
furniture_obj2position[furniture_obj] = (best_row_topLeft, best_col_topLeft)
return furniture_obj2position, score_map_history
def place_multi_furniture(furniture_obj_dir="./data/basic_furniture/", wall_objs_dir="./data/mid/panel_384478_洋室/", room_scale_factor=1):
"""compute each wall's smoothness"""
if not isinstance(wall_objs_dir, pathlib.PosixPath):
wall_objs_dir = Path(wall_objs_dir)
image_files = list(wall_objs_dir.glob("*.jpg"))
wall2smoothness = {}
for image_file in image_files:
if "wall" in str(image_file):
ima = cv2.imread(str(image_file))
gray_img = cv2.cvtColor(ima, cv2.COLOR_BGR2GRAY)
wall2smoothness[image_file.stem] = cv2.Laplacian(gray_img, cv2.CV_64F).var()
wall2smoothness = sorted(wall2smoothness.items(), key=lambda x: x[1])
walls = []
for wall_name, smoothness in wall2smoothness:
current_wall_obj = wall_objs_dir / (wall_name+".obj")
wall_coords, wall_width, vn, vn_axis, vn_direnction = _cal_wall_width(current_wall_obj, room_scale_factor)
walls.append({"wall_name":wall_name, "smoothness":smoothness, "wall_coords":wall_coords, "wall_width":wall_width, "vn":vn, "vn_axis":vn_axis, "vn_direnction":vn_direnction})
for wall in walls:
print(wall)
if not isinstance(furniture_obj_dir, pathlib.PosixPath):
furniture_obj_dir = Path(furniture_obj_dir)
furniture_objs = list(furniture_obj_dir.glob("*.obj"))
"""sort the furniture objs by its size"""
furniture_obj_volume = [[furniture_obj] + list(_get_furniture_info(furniture_obj)) for furniture_obj in furniture_objs]
furniture_obj_volume.sort(key=lambda x:x[-1], reverse=True)
furniture_obj_file2transform_info = {}
for furniture_obj, furniture_axis2width, volume in furniture_obj_volume:
print()
print(furniture_obj)
print(furniture_axis2width)
if furniture_axis2width["y"] < 0.05:
location_slide = np.zeros(3)
location_slide[0] = -furniture_axis2width["x"]/2
location_slide[1] = -furniture_axis2width["z"]/2
furniture_obj_file2transform_info[furniture_obj] = {"location":location_slide, "rotation":0}
continue
for wall in walls:
# check if the wall is wider than the width of the furniture
if wall["wall_width"] > furniture_axis2width["x"]:
wall_width_margin = wall["wall_width"] - furniture_axis2width["x"]
rotation_angle = np.arctan2(wall["vn"][1], wall["vn"][0]) - np.arctan2(1, 0)
# print((int(vn[0]+math.copysign(0.5,vn[0])), int(vn[1]+math.copysign(0.5,vn[1]))))
wall_vn_rounded_X = int(wall["vn"][0]+math.copysign(0.5,wall["vn"][0])) # round the wall's normal vector along X-axis
wall_vn_rounded_Y = int(wall["vn"][1]+math.copysign(0.5,wall["vn"][1])) # round the wall's normal vector along Y-axis
# corner = nv2corner_location_func[(int(wall["vn"][0]+math.copysign(0.5,wall["vn"][0])), int(wall["vn"][1]+math.copysign(0.5,wall["vn"][1])))](wall["wall_coords"])
corner = nv2corner_location_func[(wall_vn_rounded_X, wall_vn_rounded_Y)](wall["wall_coords"])
location_slide = np.zeros(3)
location_slide[0] = corner[0]
location_slide[1] = corner[1]
print(wall["wall_width"])
wall["wall_width"] -= (furniture_axis2width["x"] + 0.1)
print(wall["wall_coords"])
if wall_vn_rounded_X==0 and wall_vn_rounded_Y==1: wall["wall_coords"][0,0] += (furniture_axis2width["x"] + 0.1)
elif wall_vn_rounded_X==0 and wall_vn_rounded_Y==-1: wall["wall_coords"][0,0] -= (furniture_axis2width["x"] + 0.1)
elif wall_vn_rounded_X==1 and wall_vn_rounded_Y==0: wall["wall_coords"][0,1] -= (furniture_axis2width["x"] + 0.1)
elif wall_vn_rounded_X==-1 and wall_vn_rounded_Y==0: wall["wall_coords"][0,1] += (furniture_axis2width["x"] + 0.1)
print(wall["wall_width"])
print(wall["wall_coords"])
# print(wall_coords)
# print(rotation_angle / 3.14 * 180)
# print(corner)
# print(current_wall_obj)
# return location_slide, rotation_angle
furniture_obj_file2transform_info[furniture_obj] = {"location":location_slide, "rotation":rotation_angle}
break
return furniture_obj_file2transform_info
def _cal_wall_width(obj_filepath, room_scale_factor):
fin = open(str(obj_filepath), "r", encoding="utf-8")
lines = fin.readlines()
coords = np.zeros((2,2))
i = 0
for line in lines:
if len(line.split()) == 0:
continue
if i <= 1 and line.split()[0] == "v" and float(line.split()[3]) == 0: # refer only coordinates on the floor
coords[i,:] = np.array([float(line.split()[1]), float(line.split()[2])])
i += 1
if line.split()[0] == "vn":
vn = np.array([float(vn) for vn in line.split()[1:]])
vn_axis = np.argmin(1.0 - np.abs(vn))
vn_direnction = 1.0 if vn[vn_axis] > 0 else -1.0
wall_width = np.max([np.abs(coords[0,0] - coords[1,0]), np.abs(coords[0,1] - coords[1,1])])
new_coords = np.zeros((2,2))
if vn_axis == 0 and vn_direnction == 1: new_coords[0],new_coords[1] = coords[np.argmax(coords[:,1])], coords[np.argmin(coords[:,1])] # wall facing +x
elif vn_axis == 0 and vn_direnction == -1: new_coords[0],new_coords[1] = coords[np.argmin(coords[:,1])], coords[np.argmax(coords[:,1])] # wall facing -x
elif vn_axis != 0 and vn_direnction == 1: new_coords[0],new_coords[1] = coords[np.argmin(coords[:,0])], coords[np.argmax(coords[:,0])] # wall facing +y
elif vn_axis != 0 and vn_direnction == -1: new_coords[0],new_coords[1] = coords[np.argmax(coords[:,0])], coords[np.argmin(coords[:,0])] # wall facing -y
return new_coords*room_scale_factor, wall_width*room_scale_factor, vn, "xyz"[vn_axis], vn_direnction
# def _get_furniture_info(furniture_obj_filepath):
# """obj file parser
# input: path to a furniture_obj file (furniture size is written before hand during the preprocess)
# output: axis2width: dict ex) {"x": 0.5 , "y": 0.5, "z":0.5}, volume: float
# """
# with open(str(furniture_obj_filepath), "r", encoding="utf-8") as f:
# lines = f.readlines()
# axis2width = {}
# volume = 1
# for line in lines:
# if line.split()[0] == "###":
# axis2width[line.split()[2]] = float(line.split()[3])
# volume *= float(line.split()[3])
# return axis2width, volume
nv2corner_location_func = {
(0,1): lambda wall_coords: [min(wall_coords[:, 0])+0.1, wall_coords[np.argmin(wall_coords[:, 0]), 1]+0.1], # the wall is facing +y direction, return left bottom corner
(0,-1): lambda wall_coords: [max(wall_coords[:, 0])-0.1, wall_coords[np.argmax(wall_coords[:, 0]), 1]-0.1], # the wall is facing -y direction, return right top corner
(1,0): lambda wall_coords: [wall_coords[np.argmax(wall_coords[:, 1]), 0]+0.1, max(wall_coords[:, 1])-0.1], # the wall is facing +x direction, return right top corner
(-1,0): lambda wall_coords: [wall_coords[np.argmin(wall_coords[:, 1]), 0]-0.1, min(wall_coords[:, 1])+0.1], # the wall is facing -x direction, return left bottom corner
}
def _parse_obj(file_path = "/Users/taku-ueki/HorizonNet/data/mid/panel_384478_洋室/floor.obj"):
with open(file_path, "r") as f:
lines = f.readlines()
min_x = math.inf
min_y = math.inf
max_x = -math.inf
max_y = -math.inf
coords = []
for line in lines:
tokens = line.split()
try:
if tokens[0] == "v":
# print(tokens)
x = int(float(tokens[1]) * 100)
y = int(float(tokens[2]) * 100)
if x != 0 and y!= 0:
coords.append((x,y))
if x > max_x: max_x = x
elif x < min_x: min_x = x
if y > max_y: max_y = y
elif y < min_y: min_y = y
except:
continue
return coords, min_x, max_x, min_y, max_y
def _parse_obj_wall(file_path):
with open(file_path, "r") as f:
lines = f.readlines()
x1,y1 = None, None
x2,y2 = None, None
for line in lines:
tokens = line.split()
if tokens[0] == "v":
x = int(float(tokens[1]) * 100)
y = int(float(tokens[2]) * 100)
# print(x,y)
if x1 is None:
x1 = x
y1 = y
elif x1 != x or y1 != y:
x2 = x
y2 = y
break
print("x1:{}, y1:{}, x2:{}, y2:{}".format(x1,y1,x2,y2))
return LineString([(x1,y1), (x2,y2)]) | [
"numpy.full",
"copy.deepcopy",
"shapely.geometry.Point",
"numpy.abs",
"numpy.arctan2",
"shapely.geometry.Polygon",
"numpy.argmax",
"cv2.cvtColor",
"scipy.signal.convolve2d",
"numpy.zeros",
"blender_scripts.util._get_furniture_info",
"numpy.argmin",
"math.copysign",
"shapely.geometry.LineSt... | [((571, 586), 'shapely.geometry.Polygon', 'Polygon', (['coords'], {}), '(coords)\n', (578, 586), False, 'from shapely.geometry import Point, Polygon, LineString\n'), ((613, 669), 'numpy.full', 'np.full', (['(max_y - min_y + 1, max_x - min_x + 1)', '(-np.inf)'], {}), '((max_y - min_y + 1, max_x - min_x + 1), -np.inf)\n', (620, 669), True, 'import numpy as np\n'), ((1670, 1726), 'numpy.full', 'np.full', (['(max_y - min_y + 1, max_x - min_x + 1)', '(-np.inf)'], {}), '((max_y - min_y + 1, max_x - min_x + 1), -np.inf)\n', (1677, 1726), True, 'import numpy as np\n'), ((9655, 9671), 'numpy.zeros', 'np.zeros', (['(2, 2)'], {}), '((2, 2))\n', (9663, 9671), True, 'import numpy as np\n'), ((10310, 10326), 'numpy.zeros', 'np.zeros', (['(2, 2)'], {}), '((2, 2))\n', (10318, 10326), True, 'import numpy as np\n'), ((13879, 13911), 'shapely.geometry.LineString', 'LineString', (['[(x1, y1), (x2, y2)]'], {}), '([(x1, y1), (x2, y2)])\n', (13889, 13911), False, 'from shapely.geometry import Point, Polygon, LineString\n'), ((458, 477), 'pathlib.Path', 'Path', (['wall_objs_dir'], {}), '(wall_objs_dir)\n', (462, 477), False, 'from pathlib import Path\n'), ((2616, 2639), 'pathlib.Path', 'Path', (['furniture_obj_dir'], {}), '(furniture_obj_dir)\n', (2620, 2639), False, 'from pathlib import Path\n'), ((2991, 3015), 'copy.deepcopy', 'copy.deepcopy', (['score_map'], {}), '(score_map)\n', (3004, 3015), False, 'import copy\n'), ((5337, 5356), 'pathlib.Path', 'Path', (['wall_objs_dir'], {}), '(wall_objs_dir)\n', (5341, 5356), False, 'from pathlib import Path\n'), ((6336, 6359), 'pathlib.Path', 'Path', (['furniture_obj_dir'], {}), '(furniture_obj_dir)\n', (6340, 6359), False, 'from pathlib import Path\n'), ((1204, 1241), 'cv2.cvtColor', 'cv2.cvtColor', (['ima', 'cv2.COLOR_BGR2GRAY'], {}), '(ima, cv2.COLOR_BGR2GRAY)\n', (1216, 1241), False, 'import cv2\n'), ((1835, 1846), 'shapely.geometry.Point', 'Point', (['c', 'r'], {}), '(c, r)\n', (1840, 1846), False, 'from shapely.geometry import Point, Polygon, LineString\n'), ((4564, 4588), 'numpy.argmax', 'np.argmax', (['convolved_res'], {}), '(convolved_res)\n', (4573, 4588), True, 'import numpy as np\n'), ((4903, 4927), 'copy.deepcopy', 'copy.deepcopy', (['score_map'], {}), '(score_map)\n', (4916, 4927), False, 'import copy\n'), ((5577, 5614), 'cv2.cvtColor', 'cv2.cvtColor', (['ima', 'cv2.COLOR_BGR2GRAY'], {}), '(ima, cv2.COLOR_BGR2GRAY)\n', (5589, 5614), False, 'import cv2\n'), ((6932, 6943), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (6940, 6943), True, 'import numpy as np\n'), ((10220, 10255), 'numpy.abs', 'np.abs', (['(coords[0, 0] - coords[1, 0])'], {}), '(coords[0, 0] - coords[1, 0])\n', (10226, 10255), True, 'import numpy as np\n'), ((10255, 10290), 'numpy.abs', 'np.abs', (['(coords[0, 1] - coords[1, 1])'], {}), '(coords[0, 1] - coords[1, 1])\n', (10261, 10290), True, 'import numpy as np\n'), ((898, 959), 'pathlib.Path', 'Path', (['"""/Users/taku-ueki/HorizonNet/data/mid/panel_384478_洋室/"""'], {}), "('/Users/taku-ueki/HorizonNet/data/mid/panel_384478_洋室/')\n", (902, 959), False, 'from pathlib import Path\n'), ((2796, 2830), 'blender_scripts.util._get_furniture_info', '_get_furniture_info', (['furniture_obj'], {}), '(furniture_obj)\n', (2815, 2830), False, 'from blender_scripts.util import _get_furniture_info\n'), ((3668, 3736), 'scipy.signal.convolve2d', 'signal.convolve2d', (['score_map', 'kernel1'], {'boundary': '"""symm"""', 'mode': '"""valid"""'}), "(score_map, kernel1, boundary='symm', mode='valid')\n", (3685, 3736), False, 'from scipy import signal\n'), ((3987, 4055), 'scipy.signal.convolve2d', 'signal.convolve2d', (['score_map', 'kernel2'], {'boundary': '"""symm"""', 'mode': '"""valid"""'}), "(score_map, kernel2, boundary='symm', mode='valid')\n", (4004, 4055), False, 'from scipy import signal\n'), ((6516, 6550), 'blender_scripts.util._get_furniture_info', '_get_furniture_info', (['furniture_obj'], {}), '(furniture_obj)\n', (6535, 6550), False, 'from blender_scripts.util import _get_furniture_info\n'), ((8223, 8234), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (8231, 8234), True, 'import numpy as np\n'), ((10407, 10430), 'numpy.argmax', 'np.argmax', (['coords[:, 1]'], {}), '(coords[:, 1])\n', (10416, 10430), True, 'import numpy as np\n'), ((10439, 10462), 'numpy.argmin', 'np.argmin', (['coords[:, 1]'], {}), '(coords[:, 1])\n', (10448, 10462), True, 'import numpy as np\n'), ((785, 796), 'shapely.geometry.Point', 'Point', (['c', 'r'], {}), '(c, r)\n', (790, 796), False, 'from shapely.geometry import Point, Polygon, LineString\n'), ((1267, 1302), 'cv2.Laplacian', 'cv2.Laplacian', (['gray_img', 'cv2.CV_64F'], {}), '(gray_img, cv2.CV_64F)\n', (1280, 1302), False, 'import cv2\n'), ((5662, 5697), 'cv2.Laplacian', 'cv2.Laplacian', (['gray_img', 'cv2.CV_64F'], {}), '(gray_img, cv2.CV_64F)\n', (5675, 5697), False, 'import cv2\n'), ((7472, 7512), 'numpy.arctan2', 'np.arctan2', (["wall['vn'][1]", "wall['vn'][0]"], {}), "(wall['vn'][1], wall['vn'][0])\n", (7482, 7512), True, 'import numpy as np\n'), ((7515, 7531), 'numpy.arctan2', 'np.arctan2', (['(1)', '(0)'], {}), '(1, 0)\n', (7525, 7531), True, 'import numpy as np\n'), ((10121, 10131), 'numpy.abs', 'np.abs', (['vn'], {}), '(vn)\n', (10127, 10131), True, 'import numpy as np\n'), ((10564, 10587), 'numpy.argmin', 'np.argmin', (['coords[:, 1]'], {}), '(coords[:, 1])\n', (10573, 10587), True, 'import numpy as np\n'), ((10596, 10619), 'numpy.argmax', 'np.argmax', (['coords[:, 1]'], {}), '(coords[:, 1])\n', (10605, 10619), True, 'import numpy as np\n'), ((7686, 7719), 'math.copysign', 'math.copysign', (['(0.5)', "wall['vn'][0]"], {}), "(0.5, wall['vn'][0])\n", (7699, 7719), False, 'import math\n'), ((7820, 7853), 'math.copysign', 'math.copysign', (['(0.5)', "wall['vn'][1]"], {}), "(0.5, wall['vn'][1])\n", (7833, 7853), False, 'import math\n'), ((10720, 10743), 'numpy.argmin', 'np.argmin', (['coords[:, 0]'], {}), '(coords[:, 0])\n', (10729, 10743), True, 'import numpy as np\n'), ((10752, 10775), 'numpy.argmax', 'np.argmax', (['coords[:, 0]'], {}), '(coords[:, 0])\n', (10761, 10775), True, 'import numpy as np\n'), ((11793, 11821), 'numpy.argmin', 'np.argmin', (['wall_coords[:, 0]'], {}), '(wall_coords[:, 0])\n', (11802, 11821), True, 'import numpy as np\n'), ((11966, 11994), 'numpy.argmax', 'np.argmax', (['wall_coords[:, 0]'], {}), '(wall_coords[:, 0])\n', (11975, 11994), True, 'import numpy as np\n'), ((12108, 12136), 'numpy.argmax', 'np.argmax', (['wall_coords[:, 1]'], {}), '(wall_coords[:, 1])\n', (12117, 12136), True, 'import numpy as np\n'), ((12279, 12307), 'numpy.argmin', 'np.argmin', (['wall_coords[:, 1]'], {}), '(wall_coords[:, 1])\n', (12288, 12307), True, 'import numpy as np\n'), ((10877, 10900), 'numpy.argmax', 'np.argmax', (['coords[:, 0]'], {}), '(coords[:, 0])\n', (10886, 10900), True, 'import numpy as np\n'), ((10909, 10932), 'numpy.argmin', 'np.argmin', (['coords[:, 0]'], {}), '(coords[:, 0])\n', (10918, 10932), True, 'import numpy as np\n')] |
import numpy as np
from six.moves import zip_longest
import unittest
import chainer
from chainer.iterators import SerialIterator
from chainer import testing
from chainercv.utils import apply_prediction_to_iterator
@testing.parameterize(*testing.product({
'multi_pred_values': [False, True],
'with_gt_values': [False, True],
'with_hook': [False, True],
}))
class TestApplyPredictionToIterator(unittest.TestCase):
def test_apply_prediction_to_iterator(self):
if self.multi_pred_values:
def predict(imgs):
n_img = len(imgs)
return (
[np.random.uniform(size=(10, 4)) for _ in range(n_img)],
[np.random.uniform(size=10) for _ in range(n_img)],
[np.random.uniform(size=10) for _ in range(n_img)])
n_pred_values = 3
else:
def predict(imgs):
n_img = len(imgs)
return [np.random.uniform(size=(48, 64)) for _ in range(n_img)]
n_pred_values = 1
dataset_imgs = list()
for _ in range(5):
H, W = np.random.randint(8, 16, size=2)
dataset_imgs.append(np.random.randint(0, 256, size=(3, H, W)))
if self.with_gt_values:
strs = ['a', 'bc', 'def', 'ghij', 'klmno']
nums = [0, 1, 2, 3, 4]
arrays = [np.random.uniform(size=10) for _ in range(5)]
dataset = chainer.datasets.TupleDataset(
dataset_imgs, strs, nums, arrays)
dataset_gt_values = (strs, nums, arrays)
else:
dataset = dataset_imgs
dataset_gt_values = tuple()
iterator = SerialIterator(dataset, 2, repeat=False, shuffle=False)
if self.with_hook:
def hook(imgs, pred_values, gt_values):
self.assertEqual(len(pred_values), n_pred_values)
for pred_vals in pred_values:
self.assertEqual(len(pred_vals), len(imgs))
self.assertEqual(len(gt_values), len(dataset_gt_values))
for gt_vals in gt_values:
self.assertEqual(len(gt_vals), len(imgs))
else:
hook = None
imgs, pred_values, gt_values = apply_prediction_to_iterator(
predict, iterator, hook=hook)
for img, dataset_img in zip_longest(imgs, dataset_imgs):
np.testing.assert_equal(img, dataset_img)
self.assertEqual(len(pred_values), n_pred_values)
for vals in pred_values:
self.assertEqual(len(list(vals)), len(dataset_imgs))
for vals, dataset_vals in zip_longest(gt_values, dataset_gt_values):
for val, dataset_val in zip_longest(vals, dataset_vals):
if isinstance(dataset_val, np.ndarray):
np.testing.assert_equal(val, dataset_val)
else:
self.assertEqual(val, dataset_val)
class TestApplyPredictionToIteratorWithInfiniteIterator(unittest.TestCase):
def test_apply_prediction_to_iterator_with_infinite_iterator(self):
def predict(imgs):
n_img = len(imgs)
return [np.random.uniform(size=(48, 64)) for _ in range(n_img)]
dataset = list()
for _ in range(5):
H, W = np.random.randint(8, 16, size=2)
dataset.append(np.random.randint(0, 256, size=(3, H, W)))
iterator = SerialIterator(dataset, 2)
imgs, pred_values, gt_values = apply_prediction_to_iterator(
predict, iterator)
for _ in range(10):
next(imgs)
for _ in range(10):
next(pred_values[0])
testing.run_module(__name__, __file__)
| [
"chainer.testing.product",
"numpy.random.uniform",
"chainer.datasets.TupleDataset",
"six.moves.zip_longest",
"numpy.random.randint",
"chainer.iterators.SerialIterator",
"numpy.testing.assert_equal",
"chainer.testing.run_module",
"chainercv.utils.apply_prediction_to_iterator"
] | [((3668, 3706), 'chainer.testing.run_module', 'testing.run_module', (['__name__', '__file__'], {}), '(__name__, __file__)\n', (3686, 3706), False, 'from chainer import testing\n'), ((1686, 1741), 'chainer.iterators.SerialIterator', 'SerialIterator', (['dataset', '(2)'], {'repeat': '(False)', 'shuffle': '(False)'}), '(dataset, 2, repeat=False, shuffle=False)\n', (1700, 1741), False, 'from chainer.iterators import SerialIterator\n'), ((2254, 2312), 'chainercv.utils.apply_prediction_to_iterator', 'apply_prediction_to_iterator', (['predict', 'iterator'], {'hook': 'hook'}), '(predict, iterator, hook=hook)\n', (2282, 2312), False, 'from chainercv.utils import apply_prediction_to_iterator\n'), ((2359, 2390), 'six.moves.zip_longest', 'zip_longest', (['imgs', 'dataset_imgs'], {}), '(imgs, dataset_imgs)\n', (2370, 2390), False, 'from six.moves import zip_longest\n'), ((2638, 2679), 'six.moves.zip_longest', 'zip_longest', (['gt_values', 'dataset_gt_values'], {}), '(gt_values, dataset_gt_values)\n', (2649, 2679), False, 'from six.moves import zip_longest\n'), ((241, 360), 'chainer.testing.product', 'testing.product', (["{'multi_pred_values': [False, True], 'with_gt_values': [False, True],\n 'with_hook': [False, True]}"], {}), "({'multi_pred_values': [False, True], 'with_gt_values': [\n False, True], 'with_hook': [False, True]})\n", (256, 360), False, 'from chainer import testing\n'), ((3424, 3450), 'chainer.iterators.SerialIterator', 'SerialIterator', (['dataset', '(2)'], {}), '(dataset, 2)\n', (3438, 3450), False, 'from chainer.iterators import SerialIterator\n'), ((3491, 3538), 'chainercv.utils.apply_prediction_to_iterator', 'apply_prediction_to_iterator', (['predict', 'iterator'], {}), '(predict, iterator)\n', (3519, 3538), False, 'from chainercv.utils import apply_prediction_to_iterator\n'), ((1122, 1154), 'numpy.random.randint', 'np.random.randint', (['(8)', '(16)'], {'size': '(2)'}), '(8, 16, size=2)\n', (1139, 1154), True, 'import numpy as np\n'), ((1444, 1507), 'chainer.datasets.TupleDataset', 'chainer.datasets.TupleDataset', (['dataset_imgs', 'strs', 'nums', 'arrays'], {}), '(dataset_imgs, strs, nums, arrays)\n', (1473, 1507), False, 'import chainer\n'), ((2404, 2445), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['img', 'dataset_img'], {}), '(img, dataset_img)\n', (2427, 2445), True, 'import numpy as np\n'), ((2717, 2748), 'six.moves.zip_longest', 'zip_longest', (['vals', 'dataset_vals'], {}), '(vals, dataset_vals)\n', (2728, 2748), False, 'from six.moves import zip_longest\n'), ((3301, 3333), 'numpy.random.randint', 'np.random.randint', (['(8)', '(16)'], {'size': '(2)'}), '(8, 16, size=2)\n', (3318, 3333), True, 'import numpy as np\n'), ((1187, 1228), 'numpy.random.randint', 'np.random.randint', (['(0)', '(256)'], {'size': '(3, H, W)'}), '(0, 256, size=(3, H, W))\n', (1204, 1228), True, 'import numpy as np\n'), ((1375, 1401), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(10)'}), '(size=10)\n', (1392, 1401), True, 'import numpy as np\n'), ((3173, 3205), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(48, 64)'}), '(size=(48, 64))\n', (3190, 3205), True, 'import numpy as np\n'), ((3361, 3402), 'numpy.random.randint', 'np.random.randint', (['(0)', '(256)'], {'size': '(3, H, W)'}), '(0, 256, size=(3, H, W))\n', (3378, 3402), True, 'import numpy as np\n'), ((958, 990), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(48, 64)'}), '(size=(48, 64))\n', (975, 990), True, 'import numpy as np\n'), ((2826, 2867), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['val', 'dataset_val'], {}), '(val, dataset_val)\n', (2849, 2867), True, 'import numpy as np\n'), ((624, 655), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(10, 4)'}), '(size=(10, 4))\n', (641, 655), True, 'import numpy as np\n'), ((701, 727), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(10)'}), '(size=10)\n', (718, 727), True, 'import numpy as np\n'), ((773, 799), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(10)'}), '(size=10)\n', (790, 799), True, 'import numpy as np\n')] |
"""
.. _tut_inverse_mne_dspm:
Source localization with MNE/dSPM/sLORETA
=========================================
The aim of this tutorials is to teach you how to compute and apply a linear
inverse method such as MNE/dSPM/sLORETA on evoked/raw/epochs data.
"""
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.datasets import sample
from mne.minimum_norm import (make_inverse_operator, apply_inverse,
write_inverse_operator)
# sphinx_gallery_thumbnail_number = 7
###############################################################################
# Process MEG data
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
raw = mne.io.read_raw_fif(raw_fname) # already has an average reference
events = mne.find_events(raw, stim_channel='STI 014')
event_id = dict(aud_r=1) # event trigger and conditions
tmin = -0.2 # start of each epoch (200ms before the trigger)
tmax = 0.5 # end of each epoch (500ms after the trigger)
raw.info['bads'] = ['MEG 2443', 'EEG 053']
picks = mne.pick_types(raw.info, meg=True, eeg=False, eog=True,
exclude='bads')
baseline = (None, 0) # means from the first instant to t = 0
reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks,
baseline=baseline, reject=reject)
###############################################################################
# Compute regularized noise covariance
# ------------------------------------
#
# For more details see :ref:`tut_compute_covariance`.
noise_cov = mne.compute_covariance(
epochs, tmax=0., method=['shrunk', 'empirical'])
fig_cov, fig_spectra = mne.viz.plot_cov(noise_cov, raw.info)
###############################################################################
# Compute the evoked response
# ---------------------------
evoked = epochs.average()
evoked.plot()
evoked.plot_topomap(times=np.linspace(0.05, 0.15, 5), ch_type='mag')
# Show whitening
evoked.plot_white(noise_cov)
###############################################################################
# Inverse modeling: MNE/dSPM on evoked and raw data
# -------------------------------------------------
# Read the forward solution and compute the inverse operator
fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-oct-6-fwd.fif'
fwd = mne.read_forward_solution(fname_fwd, surf_ori=True)
# Restrict forward solution as necessary for MEG
fwd = mne.pick_types_forward(fwd, meg=True, eeg=False)
# make an MEG inverse operator
info = evoked.info
inverse_operator = make_inverse_operator(info, fwd, noise_cov,
loose=0.2, depth=0.8)
write_inverse_operator('sample_audvis-meg-oct-6-inv.fif',
inverse_operator)
###############################################################################
# Compute inverse solution
# ------------------------
method = "dSPM"
snr = 3.
lambda2 = 1. / snr ** 2
stc = apply_inverse(evoked, inverse_operator, lambda2,
method=method, pick_ori=None)
del fwd, inverse_operator, epochs # to save memory
###############################################################################
# Visualization
# -------------
# View activation time-series
plt.plot(1e3 * stc.times, stc.data[::100, :].T)
plt.xlabel('time (ms)')
plt.ylabel('%s value' % method)
plt.show()
###############################################################################
# Here we use peak getter to move visualization to the time point of the peak
# and draw a marker at the maximum peak vertex.
vertno_max, time_max = stc.get_peak(hemi='rh')
subjects_dir = data_path + '/subjects'
brain = stc.plot(surface='inflated', hemi='rh', subjects_dir=subjects_dir,
clim=dict(kind='value', lims=[8, 12, 15]),
initial_time=time_max, time_unit='s')
brain.add_foci(vertno_max, coords_as_verts=True, hemi='rh', color='blue',
scale_factor=0.6)
brain.show_view('lateral')
###############################################################################
# Morph data to average brain
# ---------------------------
fs_vertices = [np.arange(10242)] * 2 # fsaverage is special this way
morph_mat = mne.compute_morph_matrix('sample', 'fsaverage', stc.vertices,
fs_vertices, smooth=None,
subjects_dir=subjects_dir)
stc_fsaverage = stc.morph_precomputed('fsaverage', fs_vertices, morph_mat)
brain_fsaverage = stc_fsaverage.plot(
surface='inflated', hemi='rh', subjects_dir=subjects_dir,
clim=dict(kind='value', lims=[8, 12, 15]), initial_time=time_max,
time_unit='s', size=(800, 800), smoothing_steps=5)
brain_fsaverage.show_view('lateral')
###############################################################################
# Exercise
# --------
# - By changing the method parameter to 'sloreta' recompute the source
# estimates using the sLORETA method.
| [
"mne.pick_types",
"mne.find_events",
"mne.compute_covariance",
"numpy.arange",
"mne.minimum_norm.make_inverse_operator",
"numpy.linspace",
"mne.compute_morph_matrix",
"matplotlib.pyplot.show",
"mne.pick_types_forward",
"mne.viz.plot_cov",
"mne.read_forward_solution",
"matplotlib.pyplot.ylabel"... | [((633, 651), 'mne.datasets.sample.data_path', 'sample.data_path', ([], {}), '()\n', (649, 651), False, 'from mne.datasets import sample\n'), ((729, 759), 'mne.io.read_raw_fif', 'mne.io.read_raw_fif', (['raw_fname'], {}), '(raw_fname)\n', (748, 759), False, 'import mne\n'), ((805, 849), 'mne.find_events', 'mne.find_events', (['raw'], {'stim_channel': '"""STI 014"""'}), "(raw, stim_channel='STI 014')\n", (820, 849), False, 'import mne\n'), ((1079, 1150), 'mne.pick_types', 'mne.pick_types', (['raw.info'], {'meg': '(True)', 'eeg': '(False)', 'eog': '(True)', 'exclude': '"""bads"""'}), "(raw.info, meg=True, eeg=False, eog=True, exclude='bads')\n", (1093, 1150), False, 'import mne\n'), ((1298, 1405), 'mne.Epochs', 'mne.Epochs', (['raw', 'events', 'event_id', 'tmin', 'tmax'], {'proj': '(True)', 'picks': 'picks', 'baseline': 'baseline', 'reject': 'reject'}), '(raw, events, event_id, tmin, tmax, proj=True, picks=picks,\n baseline=baseline, reject=reject)\n', (1308, 1405), False, 'import mne\n'), ((1650, 1722), 'mne.compute_covariance', 'mne.compute_covariance', (['epochs'], {'tmax': '(0.0)', 'method': "['shrunk', 'empirical']"}), "(epochs, tmax=0.0, method=['shrunk', 'empirical'])\n", (1672, 1722), False, 'import mne\n'), ((1751, 1788), 'mne.viz.plot_cov', 'mne.viz.plot_cov', (['noise_cov', 'raw.info'], {}), '(noise_cov, raw.info)\n', (1767, 1788), False, 'import mne\n'), ((2411, 2462), 'mne.read_forward_solution', 'mne.read_forward_solution', (['fname_fwd'], {'surf_ori': '(True)'}), '(fname_fwd, surf_ori=True)\n', (2436, 2462), False, 'import mne\n'), ((2519, 2567), 'mne.pick_types_forward', 'mne.pick_types_forward', (['fwd'], {'meg': '(True)', 'eeg': '(False)'}), '(fwd, meg=True, eeg=False)\n', (2541, 2567), False, 'import mne\n'), ((2638, 2703), 'mne.minimum_norm.make_inverse_operator', 'make_inverse_operator', (['info', 'fwd', 'noise_cov'], {'loose': '(0.2)', 'depth': '(0.8)'}), '(info, fwd, noise_cov, loose=0.2, depth=0.8)\n', (2659, 2703), False, 'from mne.minimum_norm import make_inverse_operator, apply_inverse, write_inverse_operator\n'), ((2746, 2821), 'mne.minimum_norm.write_inverse_operator', 'write_inverse_operator', (['"""sample_audvis-meg-oct-6-inv.fif"""', 'inverse_operator'], {}), "('sample_audvis-meg-oct-6-inv.fif', inverse_operator)\n", (2768, 2821), False, 'from mne.minimum_norm import make_inverse_operator, apply_inverse, write_inverse_operator\n'), ((3036, 3114), 'mne.minimum_norm.apply_inverse', 'apply_inverse', (['evoked', 'inverse_operator', 'lambda2'], {'method': 'method', 'pick_ori': 'None'}), '(evoked, inverse_operator, lambda2, method=method, pick_ori=None)\n', (3049, 3114), False, 'from mne.minimum_norm import make_inverse_operator, apply_inverse, write_inverse_operator\n'), ((3332, 3382), 'matplotlib.pyplot.plot', 'plt.plot', (['(1000.0 * stc.times)', 'stc.data[::100, :].T'], {}), '(1000.0 * stc.times, stc.data[::100, :].T)\n', (3340, 3382), True, 'import matplotlib.pyplot as plt\n'), ((3380, 3403), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""time (ms)"""'], {}), "('time (ms)')\n", (3390, 3403), True, 'import matplotlib.pyplot as plt\n'), ((3404, 3435), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (["('%s value' % method)"], {}), "('%s value' % method)\n", (3414, 3435), True, 'import matplotlib.pyplot as plt\n'), ((3436, 3446), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3444, 3446), True, 'import matplotlib.pyplot as plt\n'), ((4290, 4408), 'mne.compute_morph_matrix', 'mne.compute_morph_matrix', (['"""sample"""', '"""fsaverage"""', 'stc.vertices', 'fs_vertices'], {'smooth': 'None', 'subjects_dir': 'subjects_dir'}), "('sample', 'fsaverage', stc.vertices, fs_vertices,\n smooth=None, subjects_dir=subjects_dir)\n", (4314, 4408), False, 'import mne\n'), ((1997, 2023), 'numpy.linspace', 'np.linspace', (['(0.05)', '(0.15)', '(5)'], {}), '(0.05, 0.15, 5)\n', (2008, 2023), True, 'import numpy as np\n'), ((4223, 4239), 'numpy.arange', 'np.arange', (['(10242)'], {}), '(10242)\n', (4232, 4239), True, 'import numpy as np\n')] |
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,20,100)
plt.plot(x, np.sin(x))
plt.show() | [
"numpy.sin",
"matplotlib.pyplot.show",
"numpy.linspace"
] | [((58, 81), 'numpy.linspace', 'np.linspace', (['(0)', '(20)', '(100)'], {}), '(0, 20, 100)\n', (69, 81), True, 'import numpy as np\n'), ((104, 114), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (112, 114), True, 'import matplotlib.pyplot as plt\n'), ((93, 102), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (99, 102), True, 'import numpy as np\n')] |
import sys
import numpy as np
import cv2
import os
MIN_CONTOUR_AREA = 100
RESIZED_IMAGE_WIDTH = 20
RESIZED_IMAGE_HEIGHT = 30
def main():
imgTrainingNumbers = cv2.imread("Citra_Plate_Training/training_0.jpg")
# Resize Citra menjadi skala 80%
scale_percent = 80
width = int(imgTrainingNumbers.shape[1] * scale_percent / 100)
height = int(imgTrainingNumbers.shape[0] * scale_percent / 100)
dimensi = (width, height)
# Citra Setelah di Resize
imgTrainingResize = cv2.resize(imgTrainingNumbers, dimensi, interpolation=cv2.INTER_AREA)
if imgTrainingNumbers is None:
print("error: image not read from file \n\n")
os.system("pause")
return
# end if
imgGray = cv2.cvtColor(imgTrainingResize, cv2.COLOR_BGR2GRAY)
imgBlurred = cv2.GaussianBlur(imgGray, (5, 5), 0)
imgThresh = cv2.adaptiveThreshold(imgBlurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
cv2.imshow("imgThresh", imgThresh)
imgThreshCopy = imgThresh.copy()
npaContours, npaHierarchy = cv2.findContours(imgThreshCopy, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
npaFlattenedImages = np.empty((0, RESIZED_IMAGE_WIDTH * RESIZED_IMAGE_HEIGHT))
intClassifications = []
intValidChars = [ord('0'), ord('1'), ord('2'), ord('3'), ord('4'), ord('5'), ord('6'), ord('7'), ord('8'), ord('9'),
ord('A'), ord('B'), ord('C'), ord('D'), ord('E'), ord('F'), ord('G'), ord('H'), ord('I'), ord('J'),
ord('K'), ord('L'), ord('M'), ord('N'), ord('O'), ord('P'), ord('Q'), ord('R'), ord('S'), ord('T'),
ord('U'), ord('V'), ord('W'), ord('X'), ord('Y'), ord('Z')]
for npaContour in npaContours:
if cv2.contourArea(npaContour) > MIN_CONTOUR_AREA:
[intX, intY, intW, intH] = cv2.boundingRect(npaContour)
cv2.rectangle(imgTrainingResize,
(intX, intY),
(intX + intW, intY + intH),
(0, 179, 0), # green
2)
imgROI = imgThresh[intY:intY + intH, intX:intX + intW]
imgROIResized = cv2.resize(imgROI, (RESIZED_IMAGE_WIDTH, RESIZED_IMAGE_HEIGHT))
cv2.imshow("imgROI", imgROI)
cv2.imshow("imgROIResized", imgROIResized)
cv2.imshow("training_numbers.png", imgTrainingResize)
intChar = cv2.waitKey(0)
print(intChar)
if intChar == 27:
sys.exit()
elif intChar in intValidChars:
intClassifications.append(intChar)
npaFlattenedImage = imgROIResized.reshape((1, RESIZED_IMAGE_WIDTH * RESIZED_IMAGE_HEIGHT))
npaFlattenedImages = np.append(npaFlattenedImages, npaFlattenedImage, 0)
# end if
# end if
# end for
fltClassifications = np.array(intClassifications, np.float32)
npaClassifications = fltClassifications.reshape((fltClassifications.size, 1))
print("\n\ntraining selesai !!\n")
# print(fltClassifications)
# print(npaFlattenedImages)
np.savetxt("Classifications.txt", npaClassifications)
np.savetxt("Flattened_Images.txt", npaFlattenedImages)
# changeCaption()
cv2.destroyAllWindows() # remove windows from memory
return
# def changeCaption():
# data = np.loadtxt("classifications.txt")
# i = 0
# for a in data:
# a = int(round(a))
# if a == ord('a'):
# data[i] = ord('A')
# if a == ord('b'):
# data[i] = ord('B')
# if a == ord('c'):
# data[i] = ord('C')
# if a == ord('d'):
# data[i] = ord('D')
# if a == ord('e'):
# data[i] = ord('E')
# if a == ord('f'):
# data[i] = ord('F')
# if a == ord('g'):
# data[i] = ord('G')
# if a == ord('h'):
# data[i] = ord('H')
# if a == ord('i'):
# data[i] = ord('I')
# if a == ord('j'):
# data[i] = ord('J')
# if a == ord('k'):
# data[i] = ord('K')
# if a == ord('l'):
# data[i] = ord('L')
# if a == ord('m'):
# data[i] = ord('M')
# if a == ord('n'):
# data[i] = ord('N')
# if a == ord('o'):
# data[i] = ord('O')
# if a == ord('p'):
# data[i] = ord('P')
# if a == ord('q'):
# data[i] = ord('Q')
# if a == ord('r'):
# data[i] = ord('R')
# if a == ord('s'):
# data[i] = ord('S')
# if a == ord('t'):
# data[i] = ord('T')
# if a == ord('u'):
# data[i] = ord('U')
# if a == ord('v'):
# data[i] = ord('V')
# if a == ord('w'):
# data[i] = ord('W')
# if a == ord('x'):
# data[i] = ord('X')
# if a == ord('y'):
# data[i] = ord('Y')
# if a == ord('z'):
# data[i] = ord('Z')
# i = i + 1
#
# # fltClassifications = np.array(intClassifications, np.float32)
# hasil = np.array(data, np.float32) # convert classifications list of ints to numpy array of floats
# npaClassifications = hasil.reshape((hasil.size, 1))
#
# np.savetxt("Classifications.txt", npaClassifications)
if __name__ == "__main__":
main()
# end if
| [
"cv2.GaussianBlur",
"cv2.findContours",
"cv2.contourArea",
"cv2.boundingRect",
"cv2.cvtColor",
"numpy.empty",
"cv2.destroyAllWindows",
"numpy.savetxt",
"cv2.waitKey",
"os.system",
"cv2.adaptiveThreshold",
"cv2.imread",
"numpy.append",
"numpy.array",
"cv2.rectangle",
"sys.exit",
"cv2.... | [((164, 213), 'cv2.imread', 'cv2.imread', (['"""Citra_Plate_Training/training_0.jpg"""'], {}), "('Citra_Plate_Training/training_0.jpg')\n", (174, 213), False, 'import cv2\n'), ((494, 563), 'cv2.resize', 'cv2.resize', (['imgTrainingNumbers', 'dimensi'], {'interpolation': 'cv2.INTER_AREA'}), '(imgTrainingNumbers, dimensi, interpolation=cv2.INTER_AREA)\n', (504, 563), False, 'import cv2\n'), ((724, 775), 'cv2.cvtColor', 'cv2.cvtColor', (['imgTrainingResize', 'cv2.COLOR_BGR2GRAY'], {}), '(imgTrainingResize, cv2.COLOR_BGR2GRAY)\n', (736, 775), False, 'import cv2\n'), ((793, 829), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['imgGray', '(5, 5)', '(0)'], {}), '(imgGray, (5, 5), 0)\n', (809, 829), False, 'import cv2\n'), ((847, 952), 'cv2.adaptiveThreshold', 'cv2.adaptiveThreshold', (['imgBlurred', '(255)', 'cv2.ADAPTIVE_THRESH_GAUSSIAN_C', 'cv2.THRESH_BINARY_INV', '(11)', '(2)'], {}), '(imgBlurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.\n THRESH_BINARY_INV, 11, 2)\n', (868, 952), False, 'import cv2\n'), ((953, 987), 'cv2.imshow', 'cv2.imshow', (['"""imgThresh"""', 'imgThresh'], {}), "('imgThresh', imgThresh)\n", (963, 987), False, 'import cv2\n'), ((1059, 1134), 'cv2.findContours', 'cv2.findContours', (['imgThreshCopy', 'cv2.RETR_EXTERNAL', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(imgThreshCopy, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n', (1075, 1134), False, 'import cv2\n'), ((1161, 1218), 'numpy.empty', 'np.empty', (['(0, RESIZED_IMAGE_WIDTH * RESIZED_IMAGE_HEIGHT)'], {}), '((0, RESIZED_IMAGE_WIDTH * RESIZED_IMAGE_HEIGHT))\n', (1169, 1218), True, 'import numpy as np\n'), ((2888, 2928), 'numpy.array', 'np.array', (['intClassifications', 'np.float32'], {}), '(intClassifications, np.float32)\n', (2896, 2928), True, 'import numpy as np\n'), ((3119, 3172), 'numpy.savetxt', 'np.savetxt', (['"""Classifications.txt"""', 'npaClassifications'], {}), "('Classifications.txt', npaClassifications)\n", (3129, 3172), True, 'import numpy as np\n'), ((3177, 3231), 'numpy.savetxt', 'np.savetxt', (['"""Flattened_Images.txt"""', 'npaFlattenedImages'], {}), "('Flattened_Images.txt', npaFlattenedImages)\n", (3187, 3231), True, 'import numpy as np\n'), ((3259, 3282), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (3280, 3282), False, 'import cv2\n'), ((662, 680), 'os.system', 'os.system', (['"""pause"""'], {}), "('pause')\n", (671, 680), False, 'import os\n'), ((1740, 1767), 'cv2.contourArea', 'cv2.contourArea', (['npaContour'], {}), '(npaContour)\n', (1755, 1767), False, 'import cv2\n'), ((1827, 1855), 'cv2.boundingRect', 'cv2.boundingRect', (['npaContour'], {}), '(npaContour)\n', (1843, 1855), False, 'import cv2\n'), ((1869, 1963), 'cv2.rectangle', 'cv2.rectangle', (['imgTrainingResize', '(intX, intY)', '(intX + intW, intY + intH)', '(0, 179, 0)', '(2)'], {}), '(imgTrainingResize, (intX, intY), (intX + intW, intY + intH),\n (0, 179, 0), 2)\n', (1882, 1963), False, 'import cv2\n'), ((2169, 2232), 'cv2.resize', 'cv2.resize', (['imgROI', '(RESIZED_IMAGE_WIDTH, RESIZED_IMAGE_HEIGHT)'], {}), '(imgROI, (RESIZED_IMAGE_WIDTH, RESIZED_IMAGE_HEIGHT))\n', (2179, 2232), False, 'import cv2\n'), ((2246, 2274), 'cv2.imshow', 'cv2.imshow', (['"""imgROI"""', 'imgROI'], {}), "('imgROI', imgROI)\n", (2256, 2274), False, 'import cv2\n'), ((2287, 2329), 'cv2.imshow', 'cv2.imshow', (['"""imgROIResized"""', 'imgROIResized'], {}), "('imgROIResized', imgROIResized)\n", (2297, 2329), False, 'import cv2\n'), ((2342, 2395), 'cv2.imshow', 'cv2.imshow', (['"""training_numbers.png"""', 'imgTrainingResize'], {}), "('training_numbers.png', imgTrainingResize)\n", (2352, 2395), False, 'import cv2\n'), ((2419, 2433), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (2430, 2433), False, 'import cv2\n'), ((2507, 2517), 'sys.exit', 'sys.exit', ([], {}), '()\n', (2515, 2517), False, 'import sys\n'), ((2758, 2809), 'numpy.append', 'np.append', (['npaFlattenedImages', 'npaFlattenedImage', '(0)'], {}), '(npaFlattenedImages, npaFlattenedImage, 0)\n', (2767, 2809), True, 'import numpy as np\n')] |
# encoding: utf-8
__author__ = "<NAME>"
# Parts of the code have been taken from https://github.com/facebookresearch/fastMRI
import numpy as np
import pytest
import torch
from mridc.data import transforms
from mridc.data.subsample import RandomMaskFunc
from mridc.nn import CIRIM, Unet, VarNet
from tests.fastmri.conftest import create_input
@pytest.mark.parametrize(
"shape, cascades, center_fractions, accelerations",
[
([1, 3, 32, 16, 2], 1, [0.08], [4]),
([1, 5, 15, 12, 2], 32, [0.04], [8]),
([1, 8, 13, 18, 2], 16, [0.08], [4]),
([1, 2, 17, 19, 2], 8, [0.08], [4]),
([1, 2, 17, 19, 2], 8, [0.08], [4]),
],
)
def test_cirim(shape, cascades, center_fractions, accelerations):
"""
Test CIRIM with different parameters
Args:
shape: shape of the input
cascades: number of cascades
center_fractions: center fractions
accelerations: accelerations
Returns:
None
"""
mask_func = RandomMaskFunc(center_fractions, accelerations)
x = create_input(shape)
outputs, masks = [], []
for i in range(x.shape[0]):
output, mask, _ = transforms.apply_mask(x[i : i + 1], mask_func, seed=123)
outputs.append(output)
masks.append(mask)
output = torch.cat(outputs)
mask = torch.cat(masks)
cirim = CIRIM(
recurrent_layer="IndRNN",
num_cascades=cascades,
no_dc=True,
keep_eta=True,
use_sens_net=False,
sens_mask_type="1D",
)
with torch.no_grad():
y = torch.view_as_complex(
next(cirim.inference(output, output, mask, accumulate_estimates=True))[0][-1]
) # type: ignore
if y.shape[1:] != x.shape[2:4]:
raise AssertionError
@pytest.mark.parametrize(
"shape, out_chans, chans",
[([1, 1, 32, 16], 5, 1), ([5, 1, 15, 12], 10, 32), ([3, 2, 13, 18], 1, 16), ([1, 2, 17, 19], 3, 8)],
)
def test_unet(shape, out_chans, chans):
"""
Test Unet with different parameters
Args:
shape: shape of the input
out_chans: number of channels
chans: number of channels
Returns:
None
"""
x = create_input(shape)
num_chans = x.shape[1]
unet = Unet(in_chans=num_chans, out_chans=out_chans, chans=chans, num_pool_layers=2)
y = unet(x)
if y.shape[1] != out_chans:
raise AssertionError
@pytest.mark.parametrize(
"shape, chans, center_fractions, accelerations, mask_center",
[
([1, 3, 32, 16, 2], 1, [0.08], [4], True),
([5, 5, 15, 12, 2], 32, [0.04], [8], True),
([3, 8, 13, 18, 2], 16, [0.08], [4], True),
([1, 2, 17, 19, 2], 8, [0.08], [4], True),
([1, 2, 17, 19, 2], 8, [0.08], [4], False),
],
)
def test_varnet(shape, chans, center_fractions, accelerations, mask_center):
"""
Test VarNet with different parameters
Args:
shape: shape of the input
chans: number of channels
center_fractions: center fractions
accelerations: accelerations
mask_center: whether to mask the center
Returns:
None
"""
mask_func = RandomMaskFunc(center_fractions, accelerations)
x = create_input(shape)
outputs, masks = [], []
for i in range(x.shape[0]):
output, mask, _ = transforms.apply_mask(x[i : i + 1], mask_func, seed=123)
outputs.append(output)
masks.append(mask)
output = torch.cat(outputs)
mask = torch.cat(masks)
varnet = VarNet(num_cascades=2, sens_chans=4, sens_pools=2, chans=chans, pools=2, use_sens_net=True)
y = varnet(output, np.array([]), mask.byte())
if y.shape[1:] != x.shape[2:4]:
raise AssertionError
| [
"mridc.nn.CIRIM",
"tests.fastmri.conftest.create_input",
"mridc.nn.Unet",
"torch.cat",
"mridc.data.subsample.RandomMaskFunc",
"mridc.data.transforms.apply_mask",
"mridc.nn.VarNet",
"numpy.array",
"pytest.mark.parametrize",
"torch.no_grad"
] | [((348, 626), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""shape, cascades, center_fractions, accelerations"""', '[([1, 3, 32, 16, 2], 1, [0.08], [4]), ([1, 5, 15, 12, 2], 32, [0.04], [8]),\n ([1, 8, 13, 18, 2], 16, [0.08], [4]), ([1, 2, 17, 19, 2], 8, [0.08], [4\n ]), ([1, 2, 17, 19, 2], 8, [0.08], [4])]'], {}), "('shape, cascades, center_fractions, accelerations',\n [([1, 3, 32, 16, 2], 1, [0.08], [4]), ([1, 5, 15, 12, 2], 32, [0.04], [\n 8]), ([1, 8, 13, 18, 2], 16, [0.08], [4]), ([1, 2, 17, 19, 2], 8, [0.08\n ], [4]), ([1, 2, 17, 19, 2], 8, [0.08], [4])])\n", (371, 626), False, 'import pytest\n'), ((1776, 1931), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""shape, out_chans, chans"""', '[([1, 1, 32, 16], 5, 1), ([5, 1, 15, 12], 10, 32), ([3, 2, 13, 18], 1, 16),\n ([1, 2, 17, 19], 3, 8)]'], {}), "('shape, out_chans, chans', [([1, 1, 32, 16], 5, 1),\n ([5, 1, 15, 12], 10, 32), ([3, 2, 13, 18], 1, 16), ([1, 2, 17, 19], 3, 8)])\n", (1799, 1931), False, 'import pytest\n'), ((2407, 2731), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""shape, chans, center_fractions, accelerations, mask_center"""', '[([1, 3, 32, 16, 2], 1, [0.08], [4], True), ([5, 5, 15, 12, 2], 32, [0.04],\n [8], True), ([3, 8, 13, 18, 2], 16, [0.08], [4], True), ([1, 2, 17, 19,\n 2], 8, [0.08], [4], True), ([1, 2, 17, 19, 2], 8, [0.08], [4], False)]'], {}), "(\n 'shape, chans, center_fractions, accelerations, mask_center', [([1, 3, \n 32, 16, 2], 1, [0.08], [4], True), ([5, 5, 15, 12, 2], 32, [0.04], [8],\n True), ([3, 8, 13, 18, 2], 16, [0.08], [4], True), ([1, 2, 17, 19, 2], \n 8, [0.08], [4], True), ([1, 2, 17, 19, 2], 8, [0.08], [4], False)])\n", (2430, 2731), False, 'import pytest\n'), ((999, 1046), 'mridc.data.subsample.RandomMaskFunc', 'RandomMaskFunc', (['center_fractions', 'accelerations'], {}), '(center_fractions, accelerations)\n', (1013, 1046), False, 'from mridc.data.subsample import RandomMaskFunc\n'), ((1055, 1074), 'tests.fastmri.conftest.create_input', 'create_input', (['shape'], {}), '(shape)\n', (1067, 1074), False, 'from tests.fastmri.conftest import create_input\n'), ((1291, 1309), 'torch.cat', 'torch.cat', (['outputs'], {}), '(outputs)\n', (1300, 1309), False, 'import torch\n'), ((1321, 1337), 'torch.cat', 'torch.cat', (['masks'], {}), '(masks)\n', (1330, 1337), False, 'import torch\n'), ((1351, 1478), 'mridc.nn.CIRIM', 'CIRIM', ([], {'recurrent_layer': '"""IndRNN"""', 'num_cascades': 'cascades', 'no_dc': '(True)', 'keep_eta': '(True)', 'use_sens_net': '(False)', 'sens_mask_type': '"""1D"""'}), "(recurrent_layer='IndRNN', num_cascades=cascades, no_dc=True, keep_eta\n =True, use_sens_net=False, sens_mask_type='1D')\n", (1356, 1478), False, 'from mridc.nn import CIRIM, Unet, VarNet\n'), ((2187, 2206), 'tests.fastmri.conftest.create_input', 'create_input', (['shape'], {}), '(shape)\n', (2199, 2206), False, 'from tests.fastmri.conftest import create_input\n'), ((2247, 2324), 'mridc.nn.Unet', 'Unet', ([], {'in_chans': 'num_chans', 'out_chans': 'out_chans', 'chans': 'chans', 'num_pool_layers': '(2)'}), '(in_chans=num_chans, out_chans=out_chans, chans=chans, num_pool_layers=2)\n', (2251, 2324), False, 'from mridc.nn import CIRIM, Unet, VarNet\n'), ((3156, 3203), 'mridc.data.subsample.RandomMaskFunc', 'RandomMaskFunc', (['center_fractions', 'accelerations'], {}), '(center_fractions, accelerations)\n', (3170, 3203), False, 'from mridc.data.subsample import RandomMaskFunc\n'), ((3212, 3231), 'tests.fastmri.conftest.create_input', 'create_input', (['shape'], {}), '(shape)\n', (3224, 3231), False, 'from tests.fastmri.conftest import create_input\n'), ((3447, 3465), 'torch.cat', 'torch.cat', (['outputs'], {}), '(outputs)\n', (3456, 3465), False, 'import torch\n'), ((3477, 3493), 'torch.cat', 'torch.cat', (['masks'], {}), '(masks)\n', (3486, 3493), False, 'import torch\n'), ((3508, 3603), 'mridc.nn.VarNet', 'VarNet', ([], {'num_cascades': '(2)', 'sens_chans': '(4)', 'sens_pools': '(2)', 'chans': 'chans', 'pools': '(2)', 'use_sens_net': '(True)'}), '(num_cascades=2, sens_chans=4, sens_pools=2, chans=chans, pools=2,\n use_sens_net=True)\n', (3514, 3603), False, 'from mridc.nn import CIRIM, Unet, VarNet\n'), ((1162, 1216), 'mridc.data.transforms.apply_mask', 'transforms.apply_mask', (['x[i:i + 1]', 'mask_func'], {'seed': '(123)'}), '(x[i:i + 1], mask_func, seed=123)\n', (1183, 1216), False, 'from mridc.data import transforms\n'), ((1539, 1554), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1552, 1554), False, 'import torch\n'), ((3318, 3372), 'mridc.data.transforms.apply_mask', 'transforms.apply_mask', (['x[i:i + 1]', 'mask_func'], {'seed': '(123)'}), '(x[i:i + 1], mask_func, seed=123)\n', (3339, 3372), False, 'from mridc.data import transforms\n'), ((3624, 3636), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3632, 3636), True, 'import numpy as np\n')] |
import argparse
import multiprocessing as mp
import os
import os.path as osp
from functools import partial
import numpy as np
import torch
import yaml
from munch import Munch
from softgroup.data import build_dataloader, build_dataset
from softgroup.evaluation import (ScanNetEval, evaluate_offset_mae, evaluate_semantic_acc,
evaluate_semantic_miou)
from softgroup.model import SoftGroup
from softgroup.util import (collect_results_gpu, get_dist_info, get_root_logger, init_dist,
is_main_process, load_checkpoint, rle_decode)
from torch.nn.parallel import DistributedDataParallel
from tqdm import tqdm
def get_args():
parser = argparse.ArgumentParser('SoftGroup')
parser.add_argument('config', type=str, help='path to config file')
parser.add_argument('checkpoint', type=str, help='path to checkpoint')
parser.add_argument('--dist', action='store_true', help='run with distributed parallel')
parser.add_argument('--out', type=str, help='directory for output results')
args = parser.parse_args()
return args
def save_npy(root, name, scan_ids, arrs):
root = osp.join(root, name)
os.makedirs(root, exist_ok=True)
paths = [osp.join(root, f'{i}.npy') for i in scan_ids]
pool = mp.Pool()
pool.starmap(np.save, zip(paths, arrs))
pool.close()
pool.join()
def save_single_instance(root, scan_id, insts):
f = open(osp.join(root, f'{scan_id}.txt'), 'w')
os.makedirs(osp.join(root, 'predicted_masks'), exist_ok=True)
for i, inst in enumerate(insts):
assert scan_id == inst['scan_id']
label_id = inst['label_id']
conf = inst['conf']
f.write(f'predicted_masks/{scan_id}_{i:03d}.txt {label_id} {conf:.4f}\n')
mask_path = osp.join(root, 'predicted_masks', f'{scan_id}_{i:03d}.txt')
mask = rle_decode(inst['pred_mask'])
np.savetxt(mask_path, mask, fmt='%d')
f.close()
def save_pred_instances(root, name, scan_ids, pred_insts):
root = osp.join(root, name)
os.makedirs(root, exist_ok=True)
roots = [root] * len(scan_ids)
pool = mp.Pool()
pool.starmap(save_single_instance, zip(roots, scan_ids, pred_insts))
pool.close()
pool.join()
def save_gt_instances(root, name, scan_ids, gt_insts):
root = osp.join(root, name)
os.makedirs(root, exist_ok=True)
paths = [osp.join(root, f'{i}.txt') for i in scan_ids]
pool = mp.Pool()
map_func = partial(np.savetxt, fmt='%d')
pool.starmap(map_func, zip(paths, gt_insts))
pool.close()
pool.join()
def main():
args = get_args()
cfg_txt = open(args.config, 'r').read()
cfg = Munch.fromDict(yaml.safe_load(cfg_txt))
if args.dist:
init_dist()
logger = get_root_logger()
model = SoftGroup(**cfg.model).cuda()
if args.dist:
model = DistributedDataParallel(model, device_ids=[torch.cuda.current_device()])
logger.info(f'Load state dict from {args.checkpoint}')
load_checkpoint(args.checkpoint, logger, model)
dataset = build_dataset(cfg.data.test, logger)
dataloader = build_dataloader(dataset, training=False, dist=args.dist, **cfg.dataloader.test)
results = []
scan_ids, coords, sem_preds, sem_labels, offset_preds, offset_labels = [], [], [], [], [], []
inst_labels, pred_insts, gt_insts = [], [], []
_, world_size = get_dist_info()
progress_bar = tqdm(total=len(dataloader) * world_size, disable=not is_main_process())
with torch.no_grad():
model.eval()
for i, batch in enumerate(dataloader):
result = model(batch)
results.append(result)
progress_bar.update(world_size)
progress_bar.close()
results = collect_results_gpu(results, len(dataset))
if is_main_process():
for res in results:
scan_ids.append(res['scan_id'])
coords.append(res['coords_float'])
sem_preds.append(res['semantic_preds'])
sem_labels.append(res['semantic_labels'])
offset_preds.append(res['offset_preds'])
offset_labels.append(res['offset_labels'])
inst_labels.append(res['instance_labels'])
if not cfg.model.semantic_only:
pred_insts.append(res['pred_instances'])
gt_insts.append(res['gt_instances'])
if not cfg.model.semantic_only:
logger.info('Evaluate instance segmentation')
scannet_eval = ScanNetEval(dataset.CLASSES)
scannet_eval.evaluate(pred_insts, gt_insts)
logger.info('Evaluate semantic segmentation and offset MAE')
ignore_label = cfg.model.ignore_label
evaluate_semantic_miou(sem_preds, sem_labels, ignore_label, logger)
evaluate_semantic_acc(sem_preds, sem_labels, ignore_label, logger)
evaluate_offset_mae(offset_preds, offset_labels, inst_labels, ignore_label, logger)
# save output
if not args.out:
return
logger.info('Save results')
save_npy(args.out, 'coords', scan_ids, coords)
if cfg.save_cfg.semantic:
save_npy(args.out, 'semantic_pred', scan_ids, sem_preds)
save_npy(args.out, 'semantic_label', scan_ids, sem_labels)
if cfg.save_cfg.offset:
save_npy(args.out, 'offset_pred', scan_ids, offset_preds)
save_npy(args.out, 'offset_label', scan_ids, offset_labels)
if cfg.save_cfg.instance:
save_pred_instances(args.out, 'pred_instance', scan_ids, pred_insts)
save_gt_instances(args.out, 'gt_instance', scan_ids, gt_insts)
if __name__ == '__main__':
main()
| [
"argparse.ArgumentParser",
"softgroup.util.get_root_logger",
"yaml.safe_load",
"torch.cuda.current_device",
"torch.no_grad",
"os.path.join",
"softgroup.evaluation.ScanNetEval",
"numpy.savetxt",
"softgroup.model.SoftGroup",
"softgroup.util.init_dist",
"softgroup.util.get_dist_info",
"functools.... | [((695, 731), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""SoftGroup"""'], {}), "('SoftGroup')\n", (718, 731), False, 'import argparse\n'), ((1154, 1174), 'os.path.join', 'osp.join', (['root', 'name'], {}), '(root, name)\n', (1162, 1174), True, 'import os.path as osp\n'), ((1179, 1211), 'os.makedirs', 'os.makedirs', (['root'], {'exist_ok': '(True)'}), '(root, exist_ok=True)\n', (1190, 1211), False, 'import os\n'), ((1282, 1291), 'multiprocessing.Pool', 'mp.Pool', ([], {}), '()\n', (1289, 1291), True, 'import multiprocessing as mp\n'), ((2019, 2039), 'os.path.join', 'osp.join', (['root', 'name'], {}), '(root, name)\n', (2027, 2039), True, 'import os.path as osp\n'), ((2044, 2076), 'os.makedirs', 'os.makedirs', (['root'], {'exist_ok': '(True)'}), '(root, exist_ok=True)\n', (2055, 2076), False, 'import os\n'), ((2123, 2132), 'multiprocessing.Pool', 'mp.Pool', ([], {}), '()\n', (2130, 2132), True, 'import multiprocessing as mp\n'), ((2307, 2327), 'os.path.join', 'osp.join', (['root', 'name'], {}), '(root, name)\n', (2315, 2327), True, 'import os.path as osp\n'), ((2332, 2364), 'os.makedirs', 'os.makedirs', (['root'], {'exist_ok': '(True)'}), '(root, exist_ok=True)\n', (2343, 2364), False, 'import os\n'), ((2435, 2444), 'multiprocessing.Pool', 'mp.Pool', ([], {}), '()\n', (2442, 2444), True, 'import multiprocessing as mp\n'), ((2460, 2489), 'functools.partial', 'partial', (['np.savetxt'], {'fmt': '"""%d"""'}), "(np.savetxt, fmt='%d')\n", (2467, 2489), False, 'from functools import partial\n'), ((2753, 2770), 'softgroup.util.get_root_logger', 'get_root_logger', ([], {}), '()\n', (2768, 2770), False, 'from softgroup.util import collect_results_gpu, get_dist_info, get_root_logger, init_dist, is_main_process, load_checkpoint, rle_decode\n'), ((2984, 3031), 'softgroup.util.load_checkpoint', 'load_checkpoint', (['args.checkpoint', 'logger', 'model'], {}), '(args.checkpoint, logger, model)\n', (2999, 3031), False, 'from softgroup.util import collect_results_gpu, get_dist_info, get_root_logger, init_dist, is_main_process, load_checkpoint, rle_decode\n'), ((3047, 3083), 'softgroup.data.build_dataset', 'build_dataset', (['cfg.data.test', 'logger'], {}), '(cfg.data.test, logger)\n', (3060, 3083), False, 'from softgroup.data import build_dataloader, build_dataset\n'), ((3101, 3186), 'softgroup.data.build_dataloader', 'build_dataloader', (['dataset'], {'training': '(False)', 'dist': 'args.dist'}), '(dataset, training=False, dist=args.dist, **cfg.dataloader.test\n )\n', (3117, 3186), False, 'from softgroup.data import build_dataloader, build_dataset\n'), ((3368, 3383), 'softgroup.util.get_dist_info', 'get_dist_info', ([], {}), '()\n', (3381, 3383), False, 'from softgroup.util import collect_results_gpu, get_dist_info, get_root_logger, init_dist, is_main_process, load_checkpoint, rle_decode\n'), ((3779, 3796), 'softgroup.util.is_main_process', 'is_main_process', ([], {}), '()\n', (3794, 3796), False, 'from softgroup.util import collect_results_gpu, get_dist_info, get_root_logger, init_dist, is_main_process, load_checkpoint, rle_decode\n'), ((1225, 1251), 'os.path.join', 'osp.join', (['root', 'f"""{i}.npy"""'], {}), "(root, f'{i}.npy')\n", (1233, 1251), True, 'import os.path as osp\n'), ((1432, 1464), 'os.path.join', 'osp.join', (['root', 'f"""{scan_id}.txt"""'], {}), "(root, f'{scan_id}.txt')\n", (1440, 1464), True, 'import os.path as osp\n'), ((1487, 1520), 'os.path.join', 'osp.join', (['root', '"""predicted_masks"""'], {}), "(root, 'predicted_masks')\n", (1495, 1520), True, 'import os.path as osp\n'), ((1782, 1841), 'os.path.join', 'osp.join', (['root', '"""predicted_masks"""', 'f"""{scan_id}_{i:03d}.txt"""'], {}), "(root, 'predicted_masks', f'{scan_id}_{i:03d}.txt')\n", (1790, 1841), True, 'import os.path as osp\n'), ((1857, 1886), 'softgroup.util.rle_decode', 'rle_decode', (["inst['pred_mask']"], {}), "(inst['pred_mask'])\n", (1867, 1886), False, 'from softgroup.util import collect_results_gpu, get_dist_info, get_root_logger, init_dist, is_main_process, load_checkpoint, rle_decode\n'), ((1895, 1932), 'numpy.savetxt', 'np.savetxt', (['mask_path', 'mask'], {'fmt': '"""%d"""'}), "(mask_path, mask, fmt='%d')\n", (1905, 1932), True, 'import numpy as np\n'), ((2378, 2404), 'os.path.join', 'osp.join', (['root', 'f"""{i}.txt"""'], {}), "(root, f'{i}.txt')\n", (2386, 2404), True, 'import os.path as osp\n'), ((2677, 2700), 'yaml.safe_load', 'yaml.safe_load', (['cfg_txt'], {}), '(cfg_txt)\n', (2691, 2700), False, 'import yaml\n'), ((2728, 2739), 'softgroup.util.init_dist', 'init_dist', ([], {}), '()\n', (2737, 2739), False, 'from softgroup.util import collect_results_gpu, get_dist_info, get_root_logger, init_dist, is_main_process, load_checkpoint, rle_decode\n'), ((3484, 3499), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3497, 3499), False, 'import torch\n'), ((4673, 4740), 'softgroup.evaluation.evaluate_semantic_miou', 'evaluate_semantic_miou', (['sem_preds', 'sem_labels', 'ignore_label', 'logger'], {}), '(sem_preds, sem_labels, ignore_label, logger)\n', (4695, 4740), False, 'from softgroup.evaluation import ScanNetEval, evaluate_offset_mae, evaluate_semantic_acc, evaluate_semantic_miou\n'), ((4749, 4815), 'softgroup.evaluation.evaluate_semantic_acc', 'evaluate_semantic_acc', (['sem_preds', 'sem_labels', 'ignore_label', 'logger'], {}), '(sem_preds, sem_labels, ignore_label, logger)\n', (4770, 4815), False, 'from softgroup.evaluation import ScanNetEval, evaluate_offset_mae, evaluate_semantic_acc, evaluate_semantic_miou\n'), ((4824, 4911), 'softgroup.evaluation.evaluate_offset_mae', 'evaluate_offset_mae', (['offset_preds', 'offset_labels', 'inst_labels', 'ignore_label', 'logger'], {}), '(offset_preds, offset_labels, inst_labels, ignore_label,\n logger)\n', (4843, 4911), False, 'from softgroup.evaluation import ScanNetEval, evaluate_offset_mae, evaluate_semantic_acc, evaluate_semantic_miou\n'), ((2784, 2806), 'softgroup.model.SoftGroup', 'SoftGroup', ([], {}), '(**cfg.model)\n', (2793, 2806), False, 'from softgroup.model import SoftGroup\n'), ((4465, 4493), 'softgroup.evaluation.ScanNetEval', 'ScanNetEval', (['dataset.CLASSES'], {}), '(dataset.CLASSES)\n', (4476, 4493), False, 'from softgroup.evaluation import ScanNetEval, evaluate_offset_mae, evaluate_semantic_acc, evaluate_semantic_miou\n'), ((3456, 3473), 'softgroup.util.is_main_process', 'is_main_process', ([], {}), '()\n', (3471, 3473), False, 'from softgroup.util import collect_results_gpu, get_dist_info, get_root_logger, init_dist, is_main_process, load_checkpoint, rle_decode\n'), ((2891, 2918), 'torch.cuda.current_device', 'torch.cuda.current_device', ([], {}), '()\n', (2916, 2918), False, 'import torch\n')] |
import os
# hacky, but whatever
import sys
my_path = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(my_path, '..'))
import mdpsim # noqa: #402
import pytest # noqa: E402
import tensorflow as tf # noqa: E402
import numpy as np # noqa: E402
pytest.register_assert_rewrite('models')
from models import check_prob_dom_meta, get_domain_meta, \
get_problem_meta # noqa: E402
from tf_utils import masked_softmax # noqa: E402
def test_prob_dom_meta():
tt_path = os.path.join(my_path, 'triangle-tire.pddl')
mdpsim.parse_file(tt_path)
domain = mdpsim.get_domains()['triangle-tire']
problem = mdpsim.get_problems()['triangle-tire-2']
dom_meta = get_domain_meta(domain)
prob_meta = get_problem_meta(problem)
check_prob_dom_meta(prob_meta, dom_meta)
class TestMaskedSoftmax(tf.test.TestCase):
def test_masked_softmax(self):
with self.test_session():
values = [[-1, 3.5, 2], [-1, 3.5, 2], [1, 0, 3]]
mask = [[0, 0, 0], [1, 1, 1], [0, 1, 1]]
result = masked_softmax(values, mask)
def real_softmax(vec):
exps = np.exp(vec)
return exps / np.sum(exps, axis=-1, keepdims=True)
# uniform because nothing's enabled
row0 = [1 / 3.0, 1 / 3.0, 1 / 3.0]
# not uniform
row1 = real_softmax([-1, 3.5, 2])
# not uniform, but first one doesn't count
row2 = np.concatenate([[0], real_softmax([0, 3])])
expected = [row0, row1, row2]
self.assertAllClose(expected, result.eval())
| [
"os.path.abspath",
"models.get_problem_meta",
"numpy.sum",
"models.check_prob_dom_meta",
"mdpsim.parse_file",
"mdpsim.get_problems",
"tf_utils.masked_softmax",
"mdpsim.get_domains",
"models.get_domain_meta",
"numpy.exp",
"pytest.register_assert_rewrite",
"os.path.join"
] | [((270, 310), 'pytest.register_assert_rewrite', 'pytest.register_assert_rewrite', (['"""models"""'], {}), "('models')\n", (300, 310), False, 'import pytest\n'), ((69, 94), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (84, 94), False, 'import os\n'), ((112, 139), 'os.path.join', 'os.path.join', (['my_path', '""".."""'], {}), "(my_path, '..')\n", (124, 139), False, 'import os\n'), ((497, 540), 'os.path.join', 'os.path.join', (['my_path', '"""triangle-tire.pddl"""'], {}), "(my_path, 'triangle-tire.pddl')\n", (509, 540), False, 'import os\n'), ((545, 571), 'mdpsim.parse_file', 'mdpsim.parse_file', (['tt_path'], {}), '(tt_path)\n', (562, 571), False, 'import mdpsim\n'), ((694, 717), 'models.get_domain_meta', 'get_domain_meta', (['domain'], {}), '(domain)\n', (709, 717), False, 'from models import check_prob_dom_meta, get_domain_meta, get_problem_meta\n'), ((734, 759), 'models.get_problem_meta', 'get_problem_meta', (['problem'], {}), '(problem)\n', (750, 759), False, 'from models import check_prob_dom_meta, get_domain_meta, get_problem_meta\n'), ((765, 805), 'models.check_prob_dom_meta', 'check_prob_dom_meta', (['prob_meta', 'dom_meta'], {}), '(prob_meta, dom_meta)\n', (784, 805), False, 'from models import check_prob_dom_meta, get_domain_meta, get_problem_meta\n'), ((585, 605), 'mdpsim.get_domains', 'mdpsim.get_domains', ([], {}), '()\n', (603, 605), False, 'import mdpsim\n'), ((637, 658), 'mdpsim.get_problems', 'mdpsim.get_problems', ([], {}), '()\n', (656, 658), False, 'import mdpsim\n'), ((1055, 1083), 'tf_utils.masked_softmax', 'masked_softmax', (['values', 'mask'], {}), '(values, mask)\n', (1069, 1083), False, 'from tf_utils import masked_softmax\n'), ((1143, 1154), 'numpy.exp', 'np.exp', (['vec'], {}), '(vec)\n', (1149, 1154), True, 'import numpy as np\n'), ((1185, 1221), 'numpy.sum', 'np.sum', (['exps'], {'axis': '(-1)', 'keepdims': '(True)'}), '(exps, axis=-1, keepdims=True)\n', (1191, 1221), True, 'import numpy as np\n')] |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import unittest
import numpy as np
from extensions.ops.activation_ops import Elu, SoftPlus, Mish
from mo.graph.graph import Node
from mo.utils.unittest.graph import build_graph
class TestActivationOp(unittest.TestCase):
nodes_attributes = {
'node_1': {
'shape': np.array([4]),
'value': None
},
'activation_node': {
'op': 'Activation',
'kind': 'op',
'operation': None
},
'node_3': {
'shape': None
}
}
def test_activation_elu_infer(self):
graph = build_graph(self.nodes_attributes,
[
('node_1', 'activation_node'),
('activation_node', 'node_3')
],
{
'node_1': {
'value': np.array([6, -4, -2, -1])
},
'activation_node': {
'operation': 'elu',
'alpha': 1.0,
},
'node_3': {
'value': None
}
})
graph.graph['layout'] = 'NCHW'
activation_node = Node(graph, 'activation_node')
Elu.infer(activation_node)
exp_shape = np.array([4])
res_shape = graph.node['node_3']['shape']
res_value = graph.node['node_3']['value']
exp_value = np.array([6., -0.98168436, -0.86466472, -0.63212056])
for i, value in enumerate(exp_shape):
self.assertEqual(res_shape[i], value)
for i, value in enumerate(exp_value):
self.assertAlmostEqual(res_value[i], value)
def test_activation_softplus_infer(self):
graph = build_graph(self.nodes_attributes,
[
('node_1', 'activation_node'),
('activation_node', 'node_3')
],
{
'node_1': {
'value': np.array([-1.0, 0.0, 1.0, 20.0])
},
'activation_node': {
'op': 'SoftPlus',
'operation': SoftPlus.operation,
},
'node_3': {
'value': None
}
})
graph.graph['layout'] = 'NCHW'
activation_node = Node(graph, 'activation_node')
SoftPlus.infer(activation_node)
exp_shape = np.array([4])
res_shape = graph.node['node_3']['shape']
res_value = graph.node['node_3']['value']
exp_value = np.array([0.3132617, 0.6931472, 1.3132617, 20.0])
for i, value in enumerate(exp_shape):
self.assertEqual(res_shape[i], value)
for i, value in enumerate(exp_value):
self.assertAlmostEqual(res_value[i], value)
def test_activation_mish_infer(self):
graph = build_graph(self.nodes_attributes,
[
('node_1', 'activation_node'),
('activation_node', 'node_3')
],
{
'node_1': {
'value': np.array([-1.0, 0.0, 1.0, 20.0])
},
'activation_node': {
'op': 'Mish',
'operation': Mish.operation,
},
'node_3': {
'value': None
}
})
graph.graph['layout'] = 'NCHW'
activation_node = Node(graph, 'activation_node')
Mish.infer(activation_node)
exp_shape = np.array([4])
res_shape = graph.node['node_3']['shape']
res_value = graph.node['node_3']['value']
exp_value = np.array([-0.30340146, 0.0, 0.8650984, 20.0])
for i, value in enumerate(exp_shape):
self.assertEqual(res_shape[i], value)
for i, value in enumerate(exp_value):
self.assertAlmostEqual(res_value[i], value)
| [
"extensions.ops.activation_ops.SoftPlus.infer",
"mo.graph.graph.Node",
"extensions.ops.activation_ops.Mish.infer",
"numpy.array",
"extensions.ops.activation_ops.Elu.infer"
] | [((1492, 1522), 'mo.graph.graph.Node', 'Node', (['graph', '"""activation_node"""'], {}), "(graph, 'activation_node')\n", (1496, 1522), False, 'from mo.graph.graph import Node\n'), ((1531, 1557), 'extensions.ops.activation_ops.Elu.infer', 'Elu.infer', (['activation_node'], {}), '(activation_node)\n', (1540, 1557), False, 'from extensions.ops.activation_ops import Elu, SoftPlus, Mish\n'), ((1578, 1591), 'numpy.array', 'np.array', (['[4]'], {}), '([4])\n', (1586, 1591), True, 'import numpy as np\n'), ((1712, 1766), 'numpy.array', 'np.array', (['[6.0, -0.98168436, -0.86466472, -0.63212056]'], {}), '([6.0, -0.98168436, -0.86466472, -0.63212056])\n', (1720, 1766), True, 'import numpy as np\n'), ((2870, 2900), 'mo.graph.graph.Node', 'Node', (['graph', '"""activation_node"""'], {}), "(graph, 'activation_node')\n", (2874, 2900), False, 'from mo.graph.graph import Node\n'), ((2909, 2940), 'extensions.ops.activation_ops.SoftPlus.infer', 'SoftPlus.infer', (['activation_node'], {}), '(activation_node)\n', (2923, 2940), False, 'from extensions.ops.activation_ops import Elu, SoftPlus, Mish\n'), ((2961, 2974), 'numpy.array', 'np.array', (['[4]'], {}), '([4])\n', (2969, 2974), True, 'import numpy as np\n'), ((3095, 3144), 'numpy.array', 'np.array', (['[0.3132617, 0.6931472, 1.3132617, 20.0]'], {}), '([0.3132617, 0.6931472, 1.3132617, 20.0])\n', (3103, 3144), True, 'import numpy as np\n'), ((4237, 4267), 'mo.graph.graph.Node', 'Node', (['graph', '"""activation_node"""'], {}), "(graph, 'activation_node')\n", (4241, 4267), False, 'from mo.graph.graph import Node\n'), ((4276, 4303), 'extensions.ops.activation_ops.Mish.infer', 'Mish.infer', (['activation_node'], {}), '(activation_node)\n', (4286, 4303), False, 'from extensions.ops.activation_ops import Elu, SoftPlus, Mish\n'), ((4324, 4337), 'numpy.array', 'np.array', (['[4]'], {}), '([4])\n', (4332, 4337), True, 'import numpy as np\n'), ((4458, 4503), 'numpy.array', 'np.array', (['[-0.30340146, 0.0, 0.8650984, 20.0]'], {}), '([-0.30340146, 0.0, 0.8650984, 20.0])\n', (4466, 4503), True, 'import numpy as np\n'), ((373, 386), 'numpy.array', 'np.array', (['[4]'], {}), '([4])\n', (381, 386), True, 'import numpy as np\n'), ((1013, 1038), 'numpy.array', 'np.array', (['[6, -4, -2, -1]'], {}), '([6, -4, -2, -1])\n', (1021, 1038), True, 'import numpy as np\n'), ((2367, 2399), 'numpy.array', 'np.array', (['[-1.0, 0.0, 1.0, 20.0]'], {}), '([-1.0, 0.0, 1.0, 20.0])\n', (2375, 2399), True, 'import numpy as np\n'), ((3742, 3774), 'numpy.array', 'np.array', (['[-1.0, 0.0, 1.0, 20.0]'], {}), '([-1.0, 0.0, 1.0, 20.0])\n', (3750, 3774), True, 'import numpy as np\n')] |
import math
import numpy as np
import random
import neuron as nu
# f_FPC_unit: a one unit of f-PFC,2
W = np.array([[0, 1], [0.917, 0]])
class f_PFC_unit:
def __init__(self, V_d, V_c):
self.random_del = 1
self.dt = 0.01
self.Tau = 10
self.Wl = np.array([[0, 1], [0.93, 0]])
self.Wh = np.array([[0, 1.02], [0.875, 0]])
self.b = np.array([[0.0, 0.0]])
self.V_d = V_d
self.V_c = V_c
self.f_FPC_unit_d = nu.neuron()
self.f_FPC_unit_d.def_parameter(
self.Tau, self.dt, self.random_del)
self.f_FPC_unit_c = nu.neuron()
self.f_FPC_unit_c.def_parameter(
self.Tau, self.dt, self.random_del)
def def_parameter(self, Tau, dt, random_del):
self.random_del = random_del
self.dt = dt
self.Tau = Tau
self.f_FPC_unit_c.def_parameter(
self.Tau, self.dt, self.random_del)
self.f_FPC_unit_d.def_parameter(
self.Tau, self.dt, self.random_del)
# print("**f=pfc")
# print(self.random_del)
def forward(self, S_d, S_c, ITd, ITc):
b_d = np.zeros_like(S_d)
b_c = np.zeros_like(S_c)
self.V_d, S_d = self.f_FPC_unit_d.forward(
self.V_d, S_d, self.Wl, b_d, ITd)
self.V_c, S_c = self.f_FPC_unit_d.forward(
self.V_c, S_c, self.Wl, b_c, ITc)
return S_d, S_c
"""
def forward(self, S_d, S_c, ITd, ITc):
b_d = np.zeros_like(S_d)
b_c = np.zeros_like(S_c)
self.V_d, S_d = self.f_FPC_unit_d.forward(
self.V_d, S_d, self.Wl, b_d, ITd)
self.V_c, S_c = self.f_FPC_unit_c.forward(
self.V_c, S_c, self.Wl, b_c, ITc)
return S_d, S_c
"""
| [
"neuron.neuron",
"numpy.zeros_like",
"numpy.array"
] | [((114, 144), 'numpy.array', 'np.array', (['[[0, 1], [0.917, 0]]'], {}), '([[0, 1], [0.917, 0]])\n', (122, 144), True, 'import numpy as np\n'), ((298, 327), 'numpy.array', 'np.array', (['[[0, 1], [0.93, 0]]'], {}), '([[0, 1], [0.93, 0]])\n', (306, 327), True, 'import numpy as np\n'), ((347, 380), 'numpy.array', 'np.array', (['[[0, 1.02], [0.875, 0]]'], {}), '([[0, 1.02], [0.875, 0]])\n', (355, 380), True, 'import numpy as np\n'), ((399, 421), 'numpy.array', 'np.array', (['[[0.0, 0.0]]'], {}), '([[0.0, 0.0]])\n', (407, 421), True, 'import numpy as np\n'), ((499, 510), 'neuron.neuron', 'nu.neuron', ([], {}), '()\n', (508, 510), True, 'import neuron as nu\n'), ((631, 642), 'neuron.neuron', 'nu.neuron', ([], {}), '()\n', (640, 642), True, 'import neuron as nu\n'), ((1176, 1194), 'numpy.zeros_like', 'np.zeros_like', (['S_d'], {}), '(S_d)\n', (1189, 1194), True, 'import numpy as np\n'), ((1210, 1228), 'numpy.zeros_like', 'np.zeros_like', (['S_c'], {}), '(S_c)\n', (1223, 1228), True, 'import numpy as np\n')] |
from datetime import datetime
import math
import numpy as np
import random
from utils \
import is_good, is_get_good, send_mail, test_bern_get, test_bern_post, query
FROM_GMAIL_ADDR = 'YOUR_GMAIL_ADDR'
FROM_GMAIL_ACCOUNT_PASSWORD = '<PASSWORD>'
TO_EMAIL_ADDR = 'TO_EMAIL_ADDR'
def check_bern(from_gmail, to_email, from_google_account, from_google_password):
results = list()
# 0. raw text
results.append(is_good())
# 1. pmid, json
results.append(is_get_good(29446767, 'json', 3, 10))
# 2. pmid, pubtator
results.append(is_get_good(29446767, 'pubtator', 3, 10))
# 3. mutiple pmid
results.append(is_get_good([29446767, 25681199], 'json', 4, 32))
acceptables = ['success', 'tmtool error']
problems = list()
for ridx, r in enumerate(results):
if r in acceptables:
continue
problems.append('{}: {}'.format(ridx, r))
if len(problems) == 0:
print(datetime.now(), 'No problem')
else:
problems_total = ', '.join(problems)
print(datetime.now(), 'Found', problems_total)
send_mail(from_gmail, to_email,
'[BERN] Error(s) {}'.format(problems_total),
'\n'.join(problems),
from_google_account, from_google_password)
def benchmark(tries, batch_size=None, log_interval=100):
mutation_times = list()
ner_times = list()
normalization_times = list()
total_times = list()
pmids = random.sample(range(0, 31113013), tries)
print('pmids[:10]', pmids[:min(10, tries)])
if batch_size is not None:
batch_pmids = list()
num_batches = math.ceil(len(pmids) / batch_size)
for i in range(num_batches):
# last
if i == num_batches - 1:
batch_pmids.append(pmids[i * batch_size:])
else:
batch_pmids.append(pmids[i * batch_size:(i+1) * batch_size])
pmids = batch_pmids
num_na = 0
num_not_list = 0
num_not_dict = 0
ooi_list = list()
num_error_dict = dict()
with open('benchmark.tsv', 'w', encoding='utf-8') as f:
for pidx, pmid in enumerate(pmids):
res_dict_list = query(pmid)
if type(res_dict_list) is not list:
print('not list', pmid, sep='\t')
num_not_list += 1
continue
if type(res_dict_list[0]) is not dict:
print('not dict', pmid, sep='\t')
num_not_dict += 1
continue
if 'text' in res_dict_list[0]:
if 'out of index range' in res_dict_list[0]['text']:
ooi_list.append(pmid)
print('out of index range', pmid, sep='\t')
elif 'BioC.key' in res_dict_list[0]['text']:
num_na += 1
# print(res_dict_list[0]['text'], pmid, sep='\t')
elif 'error: ' in res_dict_list[0]['text'] \
and 'elapsed_time' not in res_dict_list[0]:
if res_dict_list[0]['text'] in num_error_dict:
num_error_dict[res_dict_list[0]['text']] += 1
else:
num_error_dict[res_dict_list[0]['text']] = 1
if 'elapsed_time' not in res_dict_list[0]:
# print('no elapsed_time', pmid, sep='\t')
continue
elapsed_time_dict = res_dict_list[0]['elapsed_time']
mutation_times.append(elapsed_time_dict['tmtool'])
ner_times.append(elapsed_time_dict['ner'])
normalization_times.append(elapsed_time_dict['normalization'])
total_times.append(elapsed_time_dict['total'])
valid_results = len(mutation_times)
if pidx > 0 and (pidx + 1) % log_interval == 0:
print(datetime.now(), '{}/{}'.format(pidx + 1, tries),
'#valid_results', valid_results, '#N/A', num_na,
'#not_list', num_not_list, '#not_dict', num_not_dict,
'#ooi', len(ooi_list), ooi_list, '#err', num_error_dict)
if valid_results > 0 and valid_results % log_interval == 0:
print(datetime.now(), '#valid_results', valid_results)
mutation_res = \
'\t'.join(['{:.3f}'.format(v)
for v in get_stats(mutation_times,
batch_size=batch_size)])
ner_res = \
'\t'.join(['{:.3f}'.format(v)
for v in get_stats(ner_times,
batch_size=batch_size)])
normalization_res = \
'\t'.join(['{:.3f}'.format(v)
for v in get_stats(normalization_times,
batch_size=batch_size)])
total_res = \
'\t'.join(['{:.3f}'.format(v)
for v in get_stats(total_times,
batch_size=batch_size)])
print(valid_results, 'mutation', mutation_res, sep='\t')
print(valid_results, 'ner', ner_res, sep='\t')
print(valid_results, 'normalization', normalization_res,
sep='\t')
print(valid_results, 'total', total_res, sep='\t')
f.write('{}\t{}\t{}\n'.format(valid_results, 'mutation NER',
mutation_res))
f.write('{}\t{}\t{}\n'.format(valid_results, 'NER',
ner_res))
f.write('{}\t{}\t{}\n'.format(valid_results, 'normalization',
normalization_res))
f.write('{}\t{}\t{}\n'.format(valid_results, 'total',
total_res))
f.flush()
print('#valid_results', len(mutation_times))
print('mutation',
'\t'.join(['{:.3f}'.format(v)
for v in get_stats(mutation_times,
batch_size=batch_size)]), sep='\t')
print('ner',
'\t'.join(['{:.3f}'.format(v)
for v in get_stats(ner_times,
batch_size=batch_size)]), sep='\t')
print('normalization',
'\t'.join(['{:.3f}'.format(v)
for v in get_stats(normalization_times,
batch_size=batch_size)]), sep='\t')
print('total',
'\t'.join(['{:.3f}'.format(v)
for v in get_stats(total_times,
batch_size=batch_size)]), sep='\t')
def get_stats(lst, batch_size=None):
if not lst:
return None
if batch_size is None:
return sum(lst) / len(lst), np.std(lst), min(lst), max(lst)
else:
return (sum(lst) / len(lst)) / batch_size, \
np.std(lst), min(lst) / batch_size, max(lst) / batch_size
def stress_test(num_threads, wait_seconds, num_try):
test_bern_get(num_threads, wait_seconds, num_try)
test_bern_post('CLAPO syndrome: identification of somatic activating '
'PIK3CA mutations and delineation of the natural history '
'and phenotype. Purpose CLAPO syndrome is a rare vascular '
'disorder characterized by capillary malformation of the '
'lower lip, lymphatic malformation predominant on the face'
' and neck, asymmetry and partial/generalized overgrowth. '
'Here we tested the hypothesis that, although the genetic '
'cause is not known, the tissue distribution of the '
'clinical manifestations in CLAPO seems to follow a '
'pattern of somatic mosaicism. Methods We clinically '
'evaluated a cohort of 13 patients with CLAPO and screened'
' 20 DNA blood/tissue samples from 9 patients using '
'high-throughput, deep sequencing. Results We identified '
'five activating mutations in the PIK3CA gene in affected '
'tissues from 6 of the 9 patients studied; one of the '
'variants (NM_006218.2:c.248T>C; p.Phe83Ser) has not been '
'previously described in developmental disorders. '
'Conclusion We describe for the first time the presence '
'of somatic activating PIK3CA mutations in patients with '
'CLAPO. We also report an update of the phenotype and '
'natural history of the syndrome.',
num_threads, wait_seconds, num_try)
if __name__ == '__main__':
check_bern(FROM_GMAIL_ADDR, TO_EMAIL_ADDR,
FROM_GMAIL_ADDR, FROM_GMAIL_ACCOUNT_PASSWORD)
| [
"utils.is_good",
"utils.test_bern_post",
"numpy.std",
"utils.query",
"utils.is_get_good",
"utils.test_bern_get",
"datetime.datetime.now"
] | [((7218, 7267), 'utils.test_bern_get', 'test_bern_get', (['num_threads', 'wait_seconds', 'num_try'], {}), '(num_threads, wait_seconds, num_try)\n', (7231, 7267), False, 'from utils import is_good, is_get_good, send_mail, test_bern_get, test_bern_post, query\n'), ((7272, 8459), 'utils.test_bern_post', 'test_bern_post', (['"""CLAPO syndrome: identification of somatic activating PIK3CA mutations and delineation of the natural history and phenotype. Purpose CLAPO syndrome is a rare vascular disorder characterized by capillary malformation of the lower lip, lymphatic malformation predominant on the face and neck, asymmetry and partial/generalized overgrowth. Here we tested the hypothesis that, although the genetic cause is not known, the tissue distribution of the clinical manifestations in CLAPO seems to follow a pattern of somatic mosaicism. Methods We clinically evaluated a cohort of 13 patients with CLAPO and screened 20 DNA blood/tissue samples from 9 patients using high-throughput, deep sequencing. Results We identified five activating mutations in the PIK3CA gene in affected tissues from 6 of the 9 patients studied; one of the variants (NM_006218.2:c.248T>C; p.Phe83Ser) has not been previously described in developmental disorders. Conclusion We describe for the first time the presence of somatic activating PIK3CA mutations in patients with CLAPO. We also report an update of the phenotype and natural history of the syndrome."""', 'num_threads', 'wait_seconds', 'num_try'], {}), "(\n 'CLAPO syndrome: identification of somatic activating PIK3CA mutations and delineation of the natural history and phenotype. Purpose CLAPO syndrome is a rare vascular disorder characterized by capillary malformation of the lower lip, lymphatic malformation predominant on the face and neck, asymmetry and partial/generalized overgrowth. Here we tested the hypothesis that, although the genetic cause is not known, the tissue distribution of the clinical manifestations in CLAPO seems to follow a pattern of somatic mosaicism. Methods We clinically evaluated a cohort of 13 patients with CLAPO and screened 20 DNA blood/tissue samples from 9 patients using high-throughput, deep sequencing. Results We identified five activating mutations in the PIK3CA gene in affected tissues from 6 of the 9 patients studied; one of the variants (NM_006218.2:c.248T>C; p.Phe83Ser) has not been previously described in developmental disorders. Conclusion We describe for the first time the presence of somatic activating PIK3CA mutations in patients with CLAPO. We also report an update of the phenotype and natural history of the syndrome.'\n , num_threads, wait_seconds, num_try)\n", (7286, 8459), False, 'from utils import is_good, is_get_good, send_mail, test_bern_get, test_bern_post, query\n'), ((423, 432), 'utils.is_good', 'is_good', ([], {}), '()\n', (430, 432), False, 'from utils import is_good, is_get_good, send_mail, test_bern_get, test_bern_post, query\n'), ((474, 510), 'utils.is_get_good', 'is_get_good', (['(29446767)', '"""json"""', '(3)', '(10)'], {}), "(29446767, 'json', 3, 10)\n", (485, 510), False, 'from utils import is_good, is_get_good, send_mail, test_bern_get, test_bern_post, query\n'), ((556, 596), 'utils.is_get_good', 'is_get_good', (['(29446767)', '"""pubtator"""', '(3)', '(10)'], {}), "(29446767, 'pubtator', 3, 10)\n", (567, 596), False, 'from utils import is_good, is_get_good, send_mail, test_bern_get, test_bern_post, query\n'), ((640, 688), 'utils.is_get_good', 'is_get_good', (['[29446767, 25681199]', '"""json"""', '(4)', '(32)'], {}), "([29446767, 25681199], 'json', 4, 32)\n", (651, 688), False, 'from utils import is_good, is_get_good, send_mail, test_bern_get, test_bern_post, query\n'), ((943, 957), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (955, 957), False, 'from datetime import datetime\n'), ((1042, 1056), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1054, 1056), False, 'from datetime import datetime\n'), ((2192, 2203), 'utils.query', 'query', (['pmid'], {}), '(pmid)\n', (2197, 2203), False, 'from utils import is_good, is_get_good, send_mail, test_bern_get, test_bern_post, query\n'), ((6991, 7002), 'numpy.std', 'np.std', (['lst'], {}), '(lst)\n', (6997, 7002), True, 'import numpy as np\n'), ((7101, 7112), 'numpy.std', 'np.std', (['lst'], {}), '(lst)\n', (7107, 7112), True, 'import numpy as np\n'), ((3855, 3869), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (3867, 3869), False, 'from datetime import datetime\n'), ((4225, 4239), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4237, 4239), False, 'from datetime import datetime\n')] |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2021 <NAME> <<EMAIL>>
#
# Distributed under terms of the BSD 3-Clause license.
"""Regression test 2."""
# pylint: disable=redefined-outer-name
import os
import sys
import csv
import pathlib
import numpy
import pytest
import rasterio
import matplotlib
import matplotlib.pyplot
import gclandspill.__main__
import gclandspill.pyclaw
@pytest.fixture(scope="session")
def create_case(tmp_path_factory):
"""A pytest fixture to make a temp case available across different tests."""
# pylint: disable=invalid-name
# force to use only 4 threads
os.environ["OMP_NUM_THREADS"] = "4"
# to avoid wayland session or none-X environment
matplotlib.use("agg")
case_dir = tmp_path_factory.mktemp("regression-test-2")
content = (
"#! /usr/bin/env python\n"
"import gclandspill\n"
"def setrun():\n"
"\trundata = gclandspill.data.ClawRunData()\n"
"\trundata.clawdata.lower[:] = [0.0, 0.0]\n"
"\trundata.clawdata.upper[:] = [152.0, 60.0]\n"
"\trundata.clawdata.num_cells[:] = [38, 15]\n"
"\trundata.clawdata.output_style = 1\n"
"\trundata.clawdata.num_output_times = 5\n"
"\trundata.clawdata.tfinal = 65\n"
"\trundata.clawdata.output_t0 = True\n"
"\trundata.clawdata.dt_initial = 0.6\n"
"\trundata.clawdata.dt_max = 4.0\n"
"\trundata.topo_data.topofiles.append([3, 'topo.asc'])\n"
"\trundata.landspill_data.ref_mu = 0.6512\n"
"\trundata.landspill_data.density = 800.\n"
"\trundata.landspill_data.point_sources.n_point_sources = 1\n"
"\trundata.landspill_data.point_sources.point_sources.append([[20., 30.], 1, [1800.], [0.5]])\n"
"\trundata.landspill_data.darcy_weisbach_friction.type = 4\n"
"\trundata.landspill_data.darcy_weisbach_friction.default_roughness = 0.0\n"
"\trundata.landspill_data.darcy_weisbach_friction.filename = 'roughness.asc'\n"
"\trundata.landspill_data.hydro_features.files.append('hydro.asc')\n"
"\treturn rundata\n"
)
with open(case_dir.joinpath("setrun.py"), "w") as fileobj:
fileobj.write(content)
X, Y = numpy.meshgrid(numpy.linspace(-0.5, 152.5, 154), numpy.linspace(-0.5, 60.5, 62))
# init
elevation = numpy.zeros_like(X, dtype=numpy.float64)
hydro = numpy.ones_like(X, dtype=numpy.float64) * -9999
# inclined entrance
elevation[X <= 60.] = (60. - X[X <= 60.]) * numpy.tan(numpy.pi/36.)
# mountains and channels
idx_base = (X <= 70.)
idx_low = numpy.logical_and(idx_base, (X-70.)**2+(Y+20.)**2 <= 48.5**2)
idx_high = numpy.logical_and(idx_base, (X-70.)**2+(Y-80.)**2 <= 48.5**2)
elevation[idx_low] = numpy.sqrt(48.5**2-(X[idx_low]-70.)**2-(Y[idx_low]+20.)**2)
elevation[idx_high] = numpy.sqrt(48.5**2-(X[idx_high]-70.)**2-(Y[idx_high]-80.)**2)
idx_base = numpy.logical_and(X > 70., X <= 90)
idx_low = numpy.logical_and(idx_base, Y <= 28.5)
idx_high = numpy.logical_and(idx_base, Y >= 31.5)
elevation[idx_low] = numpy.sqrt(48.5**2-(Y[idx_low]+20)**2)
elevation[idx_high] = numpy.sqrt(48.5**2-(Y[idx_high]-80.)**2)
idx_base = (X >= 90.)
idx_low = numpy.logical_and(idx_base, (X-90.)**2+(Y+20.)**2 <= 48.5**2)
idx_high = numpy.logical_and(idx_base, (X-90.)**2+(Y-80.)**2 <= 48.5**2)
elevation[idx_low] = numpy.sqrt(48.5**2-(X[idx_low]-90.)**2-(Y[idx_low]+20.)**2)
elevation[idx_high] = numpy.sqrt(48.5**2-(X[idx_high]-90.)**2-(Y[idx_high]-80.)**2)
# pool
idx_low = numpy.logical_and(X >= 124., X <= 144.)
idx_high = numpy.logical_and(Y >= 16, Y <= 44)
idx_base = numpy.logical_and(idx_low, idx_high)
elevation[idx_base] = -1.0
hydro[idx_base] = 10.
# clip high elevation values, because we don't need them
elevation[elevation > 20.] = 20.
# lift the elevation to above sea level
elevation += 10.0
headers = \
"ncols {}\n".format(X.shape[1]) + \
"nrows {}\n".format(X.shape[0]) + \
"xllcorner {}\n".format(-1.0) + \
"yllcorner {}\n".format(-1.0) + \
"cellsize {}\n".format(1.0) + \
"NODATA_value {}\n".format(-9999)
with open(case_dir.joinpath("topo.asc"), "w") as fileobj:
fileobj.write(headers)
for j in reversed(range(X.shape[0])):
elevation[j, :].tofile(fileobj, " ")
fileobj.write("\n")
roughness = numpy.zeros_like(elevation)
with open(case_dir.joinpath("roughness.asc"), "w") as fileobj:
fileobj.write(headers)
for j in reversed(range(X.shape[0])):
roughness[j, :].tofile(fileobj, " ")
fileobj.write("\n")
with open(case_dir.joinpath("hydro.asc"), "w") as fileobj:
fileobj.write(headers)
for j in reversed(range(X.shape[0])):
hydro[j, :].tofile(fileobj, " ")
fileobj.write("\n")
return case_dir
def test_no_setrun(tmpdir):
"""Test expected error raised when no setrun.py exists."""
sys.argv = ["geoclaw-landspill", "run", str(tmpdir)]
with pytest.raises(FileNotFoundError) as err:
gclandspill.__main__.main()
assert err.type == FileNotFoundError
def test_run(create_case):
"""Test if the run succeeded."""
case_dir = create_case
sys.argv = ["geoclaw-landspill", "run", str(case_dir)]
gclandspill.__main__.main()
out_dir = case_dir.joinpath("_output")
assert out_dir.is_dir()
for prefix in ["b", "q", "t"]:
for i in range(6):
file_path = out_dir.joinpath("fort.{}{:04d}".format(prefix, i))
assert file_path.is_file(), "{} not found".format(file_path)
file_path = out_dir.joinpath("evaporated_fluid.dat")
file_path = out_dir.joinpath("volumes.csv")
@pytest.mark.parametrize("frame", list(range(6)))
def test_raw_result(create_case, frame):
"""Test if the values of simulation results match."""
case_dir = create_case
ref = gclandspill.pyclaw.Solution()
ref.read(frame, pathlib.Path(__file__).parent.joinpath("data", "regression-2"), "binary", read_aux=True)
soln = gclandspill.pyclaw.Solution()
soln.read(frame, case_dir.joinpath("_output"), "binary", read_aux=False)
assert soln.state.t == pytest.approx(ref.state.t), "Frame {} does not match.".format(frame)
assert len(soln.states) == len(ref.states), "Frame {} does not match.".format(frame)
for this, that in zip(soln.states, ref.states):
assert this.q.shape == that.q.shape, "Frame {} does not match.".format(frame)
assert this.q == pytest.approx(that.q), "Frame {} does not match.".format(frame)
def test_createnc(create_case):
"""Test if the createnc succeeded."""
case_dir = create_case
sys.argv = ["geoclaw-landspill", "createnc", str(case_dir)]
gclandspill.__main__.main()
assert case_dir.joinpath("_output", "{}-depth-lvl02.nc".format(case_dir.name)).is_file()
def test_netcdf(create_case):
"""Test if the resulting NetCDF file matches the reference solution."""
case_dir = create_case
ref_file = pathlib.Path(__file__).parent.joinpath("data", "regression-2", "regression-2.nc")
raster_file = case_dir.joinpath("_output", "{}-depth-lvl02.nc".format(case_dir.name))
with rasterio.open(ref_file, "r") as ref, rasterio.open(raster_file, "r") as raster:
assert str(raster.crs) == str(ref.crs)
assert list(raster.bounds) == pytest.approx(list(ref.bounds))
assert list(raster.transform) == pytest.approx(list(ref.transform))
assert raster.count == ref.count
assert raster.nodatavals == pytest.approx(ref.nodatavals)
assert raster.block_shapes == pytest.approx(ref.block_shapes)
assert raster.read().shape == pytest.approx(ref.read().shape)
def test_plotdepth(create_case):
"""Test if the plotdepth succeeded."""
case_dir = create_case
sys.argv = ["geoclaw-landspill", "plotdepth", "--border", "--nprocs", "1", str(case_dir)]
gclandspill.__main__.main()
plot_dir = case_dir.joinpath("_plots", "depth", "level02")
assert plot_dir.is_dir()
for i in range(6):
file_path = plot_dir.joinpath("frame0000{}.png".format(i))
assert file_path.is_file(), "{} not found".format(file_path)
@pytest.mark.skipif(matplotlib.__version__ != "3.3.3", reason="only check against matplotlib v3.3.3")
@pytest.mark.parametrize("frame", list(range(6)))
def test_depth_png(create_case, frame):
"""Test if the RGB values of created figures match."""
case_dir = create_case
filename = "frame{:05d}.png".format(frame)
ref = matplotlib.pyplot.imread(pathlib.Path(__file__).parent.joinpath("data", "regression-2", "depth", filename))
img = matplotlib.pyplot.imread(case_dir.joinpath("_plots", "depth", "level02", filename))
assert img.shape == ref.shape
assert img == pytest.approx(ref)
def test_plottopo(create_case):
"""Test if the plottopo succeeded."""
case_dir = create_case
sys.argv = ["geoclaw-landspill", "plottopo", "--border", "--nprocs", "1", str(case_dir)]
gclandspill.__main__.main()
plot_dir = case_dir.joinpath("_plots", "topo")
assert plot_dir.is_dir()
for i in range(6):
file_path = plot_dir.joinpath("frame0000{}.png".format(i))
assert file_path.is_file(), "{} not found".format(file_path)
@pytest.mark.skipif(matplotlib.__version__ != "3.3.3", reason="only check against matplotlib v3.3.3")
@pytest.mark.parametrize("frame", list(range(6)))
def test_topo_png(create_case, frame):
"""Test if the RGB values of created topo figures match."""
case_dir = create_case
filename = "frame{:05d}.png".format(frame)
ref = matplotlib.pyplot.imread(pathlib.Path(__file__).parent.joinpath("data", "regression-2", "topo", filename))
img = matplotlib.pyplot.imread(case_dir.joinpath("_plots", "topo", filename))
assert img.shape == ref.shape
assert img == pytest.approx(ref)
def test_volumes(create_case):
"""Test subcommand volumes and the values."""
case_dir = create_case
# execute the subcommand
sys.argv = ["geoclaw-landspill", "volumes", str(case_dir)]
gclandspill.__main__.main()
file_1 = pathlib.Path(__file__).parent.joinpath("data", "regression-2", "volumes.csv")
file_2 = case_dir.joinpath("_output", "volumes.csv")
with open(file_1, "r") as ref, open(file_2, "r") as result:
reader_1 = csv.reader(ref)
reader_2 = csv.reader(result)
for line_1, line_2 in zip(reader_1, reader_2):
try:
line_1 = [float(i) for i in line_1]
line_2 = [float(i) for i in line_2]
except ValueError as err:
if str(err) == "could not convert string to float: 'frame'":
pass
assert line_2 == pytest.approx(line_1)
def test_evaporated_fluid(create_case):
"""Test the value in evaporated_fluid.dat."""
case_dir = create_case
file_1 = pathlib.Path(__file__).parent.joinpath("data", "regression-2", "evaporated_fluid.dat")
file_2 = case_dir.joinpath("_output", "evaporated_fluid.dat")
with open(file_1, "r") as ref, open(file_2, "r") as result:
val_1 = float(ref.read())
val_2 = float(result.read())
assert val_2 == pytest.approx(val_1)
def test_removed_fluid(create_case):
"""Test the value in test_removed_fluid.csv."""
case_dir = create_case
file_1 = pathlib.Path(__file__).parent.joinpath("data", "regression-2", "removed_fluid.csv")
file_2 = case_dir.joinpath("_output", "removed_fluid.csv")
with open(file_1, "r") as ref, open(file_2, "r") as result:
reader_1 = csv.reader(ref)
reader_2 = csv.reader(result)
for line_1, line_2 in zip(reader_1, reader_2):
line_1 = [float(i) for i in line_1]
line_2 = [float(i) for i in line_2]
assert line_2 == pytest.approx(line_1)
| [
"rasterio.open",
"numpy.zeros_like",
"numpy.ones_like",
"csv.reader",
"numpy.logical_and",
"pytest.fixture",
"pytest.raises",
"pytest.mark.skipif",
"matplotlib.use",
"numpy.tan",
"numpy.linspace",
"pathlib.Path",
"pytest.approx",
"numpy.sqrt"
] | [((414, 445), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (428, 445), False, 'import pytest\n'), ((8348, 8453), 'pytest.mark.skipif', 'pytest.mark.skipif', (["(matplotlib.__version__ != '3.3.3')"], {'reason': '"""only check against matplotlib v3.3.3"""'}), "(matplotlib.__version__ != '3.3.3', reason=\n 'only check against matplotlib v3.3.3')\n", (8366, 8453), False, 'import pytest\n'), ((9428, 9533), 'pytest.mark.skipif', 'pytest.mark.skipif', (["(matplotlib.__version__ != '3.3.3')"], {'reason': '"""only check against matplotlib v3.3.3"""'}), "(matplotlib.__version__ != '3.3.3', reason=\n 'only check against matplotlib v3.3.3')\n", (9446, 9533), False, 'import pytest\n'), ((730, 751), 'matplotlib.use', 'matplotlib.use', (['"""agg"""'], {}), "('agg')\n", (744, 751), False, 'import matplotlib\n'), ((2343, 2383), 'numpy.zeros_like', 'numpy.zeros_like', (['X'], {'dtype': 'numpy.float64'}), '(X, dtype=numpy.float64)\n', (2359, 2383), False, 'import numpy\n'), ((2611, 2686), 'numpy.logical_and', 'numpy.logical_and', (['idx_base', '((X - 70.0) ** 2 + (Y + 20.0) ** 2 <= 48.5 ** 2)'], {}), '(idx_base, (X - 70.0) ** 2 + (Y + 20.0) ** 2 <= 48.5 ** 2)\n', (2628, 2686), False, 'import numpy\n'), ((2688, 2763), 'numpy.logical_and', 'numpy.logical_and', (['idx_base', '((X - 70.0) ** 2 + (Y - 80.0) ** 2 <= 48.5 ** 2)'], {}), '(idx_base, (X - 70.0) ** 2 + (Y - 80.0) ** 2 <= 48.5 ** 2)\n', (2705, 2763), False, 'import numpy\n'), ((2775, 2850), 'numpy.sqrt', 'numpy.sqrt', (['(48.5 ** 2 - (X[idx_low] - 70.0) ** 2 - (Y[idx_low] + 20.0) ** 2)'], {}), '(48.5 ** 2 - (X[idx_low] - 70.0) ** 2 - (Y[idx_low] + 20.0) ** 2)\n', (2785, 2850), False, 'import numpy\n'), ((2861, 2938), 'numpy.sqrt', 'numpy.sqrt', (['(48.5 ** 2 - (X[idx_high] - 70.0) ** 2 - (Y[idx_high] - 80.0) ** 2)'], {}), '(48.5 ** 2 - (X[idx_high] - 70.0) ** 2 - (Y[idx_high] - 80.0) ** 2)\n', (2871, 2938), False, 'import numpy\n'), ((2939, 2975), 'numpy.logical_and', 'numpy.logical_and', (['(X > 70.0)', '(X <= 90)'], {}), '(X > 70.0, X <= 90)\n', (2956, 2975), False, 'import numpy\n'), ((2989, 3027), 'numpy.logical_and', 'numpy.logical_and', (['idx_base', '(Y <= 28.5)'], {}), '(idx_base, Y <= 28.5)\n', (3006, 3027), False, 'import numpy\n'), ((3043, 3081), 'numpy.logical_and', 'numpy.logical_and', (['idx_base', '(Y >= 31.5)'], {}), '(idx_base, Y >= 31.5)\n', (3060, 3081), False, 'import numpy\n'), ((3107, 3153), 'numpy.sqrt', 'numpy.sqrt', (['(48.5 ** 2 - (Y[idx_low] + 20) ** 2)'], {}), '(48.5 ** 2 - (Y[idx_low] + 20) ** 2)\n', (3117, 3153), False, 'import numpy\n'), ((3172, 3221), 'numpy.sqrt', 'numpy.sqrt', (['(48.5 ** 2 - (Y[idx_high] - 80.0) ** 2)'], {}), '(48.5 ** 2 - (Y[idx_high] - 80.0) ** 2)\n', (3182, 3221), False, 'import numpy\n'), ((3254, 3329), 'numpy.logical_and', 'numpy.logical_and', (['idx_base', '((X - 90.0) ** 2 + (Y + 20.0) ** 2 <= 48.5 ** 2)'], {}), '(idx_base, (X - 90.0) ** 2 + (Y + 20.0) ** 2 <= 48.5 ** 2)\n', (3271, 3329), False, 'import numpy\n'), ((3331, 3406), 'numpy.logical_and', 'numpy.logical_and', (['idx_base', '((X - 90.0) ** 2 + (Y - 80.0) ** 2 <= 48.5 ** 2)'], {}), '(idx_base, (X - 90.0) ** 2 + (Y - 80.0) ** 2 <= 48.5 ** 2)\n', (3348, 3406), False, 'import numpy\n'), ((3418, 3493), 'numpy.sqrt', 'numpy.sqrt', (['(48.5 ** 2 - (X[idx_low] - 90.0) ** 2 - (Y[idx_low] + 20.0) ** 2)'], {}), '(48.5 ** 2 - (X[idx_low] - 90.0) ** 2 - (Y[idx_low] + 20.0) ** 2)\n', (3428, 3493), False, 'import numpy\n'), ((3504, 3581), 'numpy.sqrt', 'numpy.sqrt', (['(48.5 ** 2 - (X[idx_high] - 90.0) ** 2 - (Y[idx_high] - 80.0) ** 2)'], {}), '(48.5 ** 2 - (X[idx_high] - 90.0) ** 2 - (Y[idx_high] - 80.0) ** 2)\n', (3514, 3581), False, 'import numpy\n'), ((3592, 3633), 'numpy.logical_and', 'numpy.logical_and', (['(X >= 124.0)', '(X <= 144.0)'], {}), '(X >= 124.0, X <= 144.0)\n', (3609, 3633), False, 'import numpy\n'), ((3647, 3682), 'numpy.logical_and', 'numpy.logical_and', (['(Y >= 16)', '(Y <= 44)'], {}), '(Y >= 16, Y <= 44)\n', (3664, 3682), False, 'import numpy\n'), ((3698, 3734), 'numpy.logical_and', 'numpy.logical_and', (['idx_low', 'idx_high'], {}), '(idx_low, idx_high)\n', (3715, 3734), False, 'import numpy\n'), ((4509, 4536), 'numpy.zeros_like', 'numpy.zeros_like', (['elevation'], {}), '(elevation)\n', (4525, 4536), False, 'import numpy\n'), ((2249, 2281), 'numpy.linspace', 'numpy.linspace', (['(-0.5)', '(152.5)', '(154)'], {}), '(-0.5, 152.5, 154)\n', (2263, 2281), False, 'import numpy\n'), ((2283, 2313), 'numpy.linspace', 'numpy.linspace', (['(-0.5)', '(60.5)', '(62)'], {}), '(-0.5, 60.5, 62)\n', (2297, 2313), False, 'import numpy\n'), ((2396, 2435), 'numpy.ones_like', 'numpy.ones_like', (['X'], {'dtype': 'numpy.float64'}), '(X, dtype=numpy.float64)\n', (2411, 2435), False, 'import numpy\n'), ((2517, 2543), 'numpy.tan', 'numpy.tan', (['(numpy.pi / 36.0)'], {}), '(numpy.pi / 36.0)\n', (2526, 2543), False, 'import numpy\n'), ((5161, 5193), 'pytest.raises', 'pytest.raises', (['FileNotFoundError'], {}), '(FileNotFoundError)\n', (5174, 5193), False, 'import pytest\n'), ((6329, 6355), 'pytest.approx', 'pytest.approx', (['ref.state.t'], {}), '(ref.state.t)\n', (6342, 6355), False, 'import pytest\n'), ((7341, 7369), 'rasterio.open', 'rasterio.open', (['ref_file', '"""r"""'], {}), "(ref_file, 'r')\n", (7354, 7369), False, 'import rasterio\n'), ((7378, 7409), 'rasterio.open', 'rasterio.open', (['raster_file', '"""r"""'], {}), "(raster_file, 'r')\n", (7391, 7409), False, 'import rasterio\n'), ((8937, 8955), 'pytest.approx', 'pytest.approx', (['ref'], {}), '(ref)\n', (8950, 8955), False, 'import pytest\n'), ((10008, 10026), 'pytest.approx', 'pytest.approx', (['ref'], {}), '(ref)\n', (10021, 10026), False, 'import pytest\n'), ((10495, 10510), 'csv.reader', 'csv.reader', (['ref'], {}), '(ref)\n', (10505, 10510), False, 'import csv\n'), ((10530, 10548), 'csv.reader', 'csv.reader', (['result'], {}), '(result)\n', (10540, 10548), False, 'import csv\n'), ((11746, 11761), 'csv.reader', 'csv.reader', (['ref'], {}), '(ref)\n', (11756, 11761), False, 'import csv\n'), ((11781, 11799), 'csv.reader', 'csv.reader', (['result'], {}), '(result)\n', (11791, 11799), False, 'import csv\n'), ((6651, 6672), 'pytest.approx', 'pytest.approx', (['that.q'], {}), '(that.q)\n', (6664, 6672), False, 'import pytest\n'), ((7691, 7720), 'pytest.approx', 'pytest.approx', (['ref.nodatavals'], {}), '(ref.nodatavals)\n', (7704, 7720), False, 'import pytest\n'), ((7759, 7790), 'pytest.approx', 'pytest.approx', (['ref.block_shapes'], {}), '(ref.block_shapes)\n', (7772, 7790), False, 'import pytest\n'), ((11362, 11382), 'pytest.approx', 'pytest.approx', (['val_1'], {}), '(val_1)\n', (11375, 11382), False, 'import pytest\n'), ((7159, 7181), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (7171, 7181), False, 'import pathlib\n'), ((10276, 10298), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (10288, 10298), False, 'import pathlib\n'), ((10895, 10916), 'pytest.approx', 'pytest.approx', (['line_1'], {}), '(line_1)\n', (10908, 10916), False, 'import pytest\n'), ((11049, 11071), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (11061, 11071), False, 'import pathlib\n'), ((11515, 11537), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (11527, 11537), False, 'import pathlib\n'), ((11981, 12002), 'pytest.approx', 'pytest.approx', (['line_1'], {}), '(line_1)\n', (11994, 12002), False, 'import pytest\n'), ((6091, 6113), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (6103, 6113), False, 'import pathlib\n'), ((8708, 8730), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (8720, 8730), False, 'import pathlib\n'), ((9792, 9814), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (9804, 9814), False, 'import pathlib\n')] |
import numpy as np
import pytest
import gbmc_v0.pad_dump_file as pad
import gbmc_v0.util_funcs as uf
@pytest.mark.parametrize('filename0, lat_par, non_p',
[("data/dump_1", 4.05, 2),
("data/dump_2", 4.05, 1)])
def test_pad_gb_perp(filename0, lat_par, non_p):
data = uf.compute_ovito_data(filename0)
rCut = 2 * lat_par
GbRegion, GbIndex, GbWidth, w_bottom_SC, w_top_SC = pad.GB_finder(data, lat_par, non_p)
pts1, gb1_inds = pad.pad_gb_perp(data, GbRegion, GbIndex, rCut, non_p)
p_pos = pts1[gb1_inds]
d_pos = data.particles['Position'][...][GbIndex, :]
err = np.linalg.norm(p_pos - d_pos)
assert np.allclose(0, err)
| [
"gbmc_v0.pad_dump_file.GB_finder",
"gbmc_v0.pad_dump_file.pad_gb_perp",
"numpy.allclose",
"numpy.linalg.norm",
"pytest.mark.parametrize",
"gbmc_v0.util_funcs.compute_ovito_data"
] | [((104, 214), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""filename0, lat_par, non_p"""', "[('data/dump_1', 4.05, 2), ('data/dump_2', 4.05, 1)]"], {}), "('filename0, lat_par, non_p', [('data/dump_1', 4.05,\n 2), ('data/dump_2', 4.05, 1)])\n", (127, 214), False, 'import pytest\n'), ((322, 354), 'gbmc_v0.util_funcs.compute_ovito_data', 'uf.compute_ovito_data', (['filename0'], {}), '(filename0)\n', (343, 354), True, 'import gbmc_v0.util_funcs as uf\n'), ((434, 469), 'gbmc_v0.pad_dump_file.GB_finder', 'pad.GB_finder', (['data', 'lat_par', 'non_p'], {}), '(data, lat_par, non_p)\n', (447, 469), True, 'import gbmc_v0.pad_dump_file as pad\n'), ((491, 544), 'gbmc_v0.pad_dump_file.pad_gb_perp', 'pad.pad_gb_perp', (['data', 'GbRegion', 'GbIndex', 'rCut', 'non_p'], {}), '(data, GbRegion, GbIndex, rCut, non_p)\n', (506, 544), True, 'import gbmc_v0.pad_dump_file as pad\n'), ((638, 667), 'numpy.linalg.norm', 'np.linalg.norm', (['(p_pos - d_pos)'], {}), '(p_pos - d_pos)\n', (652, 667), True, 'import numpy as np\n'), ((679, 698), 'numpy.allclose', 'np.allclose', (['(0)', 'err'], {}), '(0, err)\n', (690, 698), True, 'import numpy as np\n')] |
r"""
Visualization of normal modes from an elastic network model
===========================================================
The *elastic network model* (ENM) is a fast method to estimate movements
in a protein structure, without the need to run time-consuming MD
simulations.
A protein is modelled as *mass-and-spring* model, with the masses being
the :math:`C_\alpha` atoms and the springs being the non-covalent bonds
between adjacent residues.
Via *normal mode analysis* distinct movements/oscillations can be
extracted from the model.
An *anisotropic network model* (ANM), is an ENM that includes
directional information.
Hence, the normal mode analysis yields eigenvectors, where each atom is
represented by three vector components (*x*, *y*, *z*).
Thus these vectors can be used for 3D representation.
In the case of this example a normal mode analysis on an ANM was already
conducted.
This script merely takes the structure and obtained eigenvectors
to add a smooth oscillation of the chosen normal mode to the structure.
The newly created structure has multiple models, where each model
depicts a different time in the oscillation period.
Then the multi-model structure can be used to create a video of the
oscillation using a molecular visualization program.
The file containing the eigenvectors can be downloaded via this
:download:`link </examples/download/glycosylase_anm_vectors.csv>`.
"""
# Code source: <NAME>
# License: BSD 3 clause
from tempfile import NamedTemporaryFile
from os.path import join
import numpy as np
from numpy import newaxis
import biotite.structure as struc
import biotite.structure.io as strucio
import biotite.structure.io.mmtf as mmtf
import biotite.database.rcsb as rcsb
# A CSV file containing the eigenvectors for the CA atoms
VECTOR_FILE = "../../download/glycosylase_anm_vectors.csv"
# The corresponding structure
PDB_ID = "1MUG"
# The normal mode to be visualized
# '-1' is the last (and most significant) one
MODE = -1
# The amount of frames (models) per oscillation
FRAMES = 60
# The maximum oscillation amplitude for an atom
# (The length of the ANM's eigenvectors make only sense when compared
# relative to each other, the absolute values have no significance)
MAX_AMPLITUDE = 5
# Load structure
mmtf_file = mmtf.MMTFFile.read(rcsb.fetch(PDB_ID, "mmtf"))
structure = mmtf.get_structure(mmtf_file, model=1)
# Filter first peptide chain
protein_chain = structure[
struc.filter_amino_acids(structure)
& (structure.chain_id == structure.chain_id[0])
]
# Filter CA atoms
ca = protein_chain[protein_chain.atom_name == "CA"]
# Load eigenvectors for CA atoms
# The first axis indicates the mode,
# the second axis indicates the vector component
vectors = np.loadtxt(VECTOR_FILE, delimiter=",").transpose()
# Discard the last 6 modes, as these are movements of the entire system:
# A system with N atoms has only 3N - 6 degrees of freedom
# ^^^
vectors = vectors[:-6]
# Extract vectors for given mode and reshape to (n,3) array
mode_vectors = vectors[MODE].reshape((-1, 3))
# Rescale, so that the largest vector has the length 'MAX_AMPLITUDE'
vector_lenghts = np.sqrt(np.sum(mode_vectors**2, axis=-1))
scale = MAX_AMPLITUDE / np.max(vector_lenghts)
mode_vectors *= scale
# Stepwise application of eigenvectors as smooth sine oscillation
time = np.linspace(0, 2*np.pi, FRAMES, endpoint=False)
deviation = np.sin(time)[:, newaxis, newaxis] * mode_vectors
# Apply oscillation of CA atom to all atoms in the corresponding residue
oscillation = np.zeros((FRAMES, len(protein_chain), 3))
residue_starts = struc.get_residue_starts(
protein_chain,
# The last array element will be the length of the atom array,
# i.e. no valid index
add_exclusive_stop=True
)
for i in range(len(residue_starts) -1):
res_start = residue_starts[i]
res_stop = residue_starts[i+1]
oscillation[:, res_start:res_stop, :] \
= protein_chain.coord[res_start:res_stop, :] + deviation[:, i:i+1, :]
# An atom array stack containing all frames
oscillating_structure = struc.from_template(protein_chain, oscillation)
# Save as PDB for rendering a video with PyMOL
temp = NamedTemporaryFile(suffix=".pdb")
strucio.save_structure(temp.name, oscillating_structure)
# biotite_static_image = normal_modes.gif
temp.close() | [
"tempfile.NamedTemporaryFile",
"biotite.structure.from_template",
"numpy.sum",
"biotite.structure.get_residue_starts",
"biotite.structure.io.save_structure",
"biotite.structure.io.mmtf.get_structure",
"numpy.max",
"numpy.sin",
"numpy.loadtxt",
"numpy.linspace",
"biotite.database.rcsb.fetch",
"... | [((2327, 2365), 'biotite.structure.io.mmtf.get_structure', 'mmtf.get_structure', (['mmtf_file'], {'model': '(1)'}), '(mmtf_file, model=1)\n', (2345, 2365), True, 'import biotite.structure.io.mmtf as mmtf\n'), ((3344, 3393), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', 'FRAMES'], {'endpoint': '(False)'}), '(0, 2 * np.pi, FRAMES, endpoint=False)\n', (3355, 3393), True, 'import numpy as np\n'), ((3600, 3664), 'biotite.structure.get_residue_starts', 'struc.get_residue_starts', (['protein_chain'], {'add_exclusive_stop': '(True)'}), '(protein_chain, add_exclusive_stop=True)\n', (3624, 3664), True, 'import biotite.structure as struc\n'), ((4068, 4115), 'biotite.structure.from_template', 'struc.from_template', (['protein_chain', 'oscillation'], {}), '(protein_chain, oscillation)\n', (4087, 4115), True, 'import biotite.structure as struc\n'), ((4170, 4203), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ([], {'suffix': '""".pdb"""'}), "(suffix='.pdb')\n", (4188, 4203), False, 'from tempfile import NamedTemporaryFile\n'), ((4204, 4260), 'biotite.structure.io.save_structure', 'strucio.save_structure', (['temp.name', 'oscillating_structure'], {}), '(temp.name, oscillating_structure)\n', (4226, 4260), True, 'import biotite.structure.io as strucio\n'), ((2287, 2313), 'biotite.database.rcsb.fetch', 'rcsb.fetch', (['PDB_ID', '"""mmtf"""'], {}), "(PDB_ID, 'mmtf')\n", (2297, 2313), True, 'import biotite.database.rcsb as rcsb\n'), ((3165, 3199), 'numpy.sum', 'np.sum', (['(mode_vectors ** 2)'], {'axis': '(-1)'}), '(mode_vectors ** 2, axis=-1)\n', (3171, 3199), True, 'import numpy as np\n'), ((3223, 3245), 'numpy.max', 'np.max', (['vector_lenghts'], {}), '(vector_lenghts)\n', (3229, 3245), True, 'import numpy as np\n'), ((2428, 2463), 'biotite.structure.filter_amino_acids', 'struc.filter_amino_acids', (['structure'], {}), '(structure)\n', (2452, 2463), True, 'import biotite.structure as struc\n'), ((2719, 2757), 'numpy.loadtxt', 'np.loadtxt', (['VECTOR_FILE'], {'delimiter': '""","""'}), "(VECTOR_FILE, delimiter=',')\n", (2729, 2757), True, 'import numpy as np\n'), ((3404, 3416), 'numpy.sin', 'np.sin', (['time'], {}), '(time)\n', (3410, 3416), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
import os
import scipy
import time
import cv2
# Remove previous weights and biases
tf.compat.v1.reset_default_graph()
# Dir of model check point
# save_file = "./model.ckpt"
# Get path where dog image place
data_path = "C:/Users/mabin/Dropbox/SKaggle/generative-dog-images/resized/"
data_name = os.listdir(data_path)
data_size = []
for i in data_name:
size = os.stat(data_path + i).st_size
data_size.append(size)
img_size = 64
img_channels = 3
noise_size = 256 # 이게 image size와 관련이 있을거니... 함 잘 짜보자.
X = tf.compat.v1.placeholder(tf.float32, [None, img_size, img_size, img_channels])
Z = tf.compat.v1.placeholder(tf.float32, [None, noise_size])
keep_prob = tf.placeholder(tf.float32)
G_w1 = tf.Variable(tf.random.normal([256, 16*16], stddev=0.01), dtype=tf.float32)
G_b1 = tf.Variable(tf.random.normal([16*16], stddev=0.01), dtype=tf.float32)
G_w2 = tf.Variable(tf.random.normal([3, 3, 32, 1], stddev=0.01))
G_w3 = tf.Variable(tf.random.normal([3, 3, 3, 32], stddev=0.01))
G_w4 = tf.Variable(tf.random.normal([3, 3, 3, 3], stddev=0.01))
# Put integer in generator's batch size -> error doesn't occur
# https://stackoverflow.com/questions/35488717/confused-about-conv2d-transpose
def generator(noise, b_size):
# 256 -> 16*16*64
# print(noise.shape)
G_L_1 = tf.nn.relu(tf.matmul(noise, G_w1) + G_b1)
# Reshape 16*16*64 -> 16, 16, 64
G_L_2 = tf.reshape(G_L_1, [b_size, 16, 16, 1])
# print(G_L_2.shape)
# print(G_w2.shape)
G_L_3 = tf.nn.conv2d_transpose(value=G_L_2, filter=G_w2,
output_shape=[b_size, 32, 32, 32],
strides=[1, 2, 2, 1], padding="SAME")
# print(G_L_3.shape)
output = tf.nn.sigmoid(tf.nn.conv2d_transpose(value=G_L_3, filter=G_w3,
output_shape=[b_size, 64, 64, 3],
strides=[1, 2, 2, 1], padding="SAME"))
# output = tf.nn.conv2d(G_L_4, G_w4, strides=[1, 1, 1, 1], padding="SAME")
# output = tf.nn.conv2d_transpose(value=G_L_4, filter=G_w4,
# output_shape=[-1, 64, 64, 3],
# strides=[1, 2, 2, 1], padding="SAME")
return output
D_w1 = tf.Variable(tf.random.normal([3, 3, 3, 32], stddev=0.01))
D_b1 = tf.Variable(tf.zeros([32]))
# D_b1 = tf.Variable(tf.constant(0.1, [32]))
D_w2 = tf.Variable(tf.random.normal([3, 3, 32, 64], stddev=0.01))
D_b2 = tf.Variable(tf.zeros([64]))
# D_b2 = tf.Variable(tf.constant(0.1, [64]))
D_w3 = tf.Variable(tf.random.normal([16*16*64, 256]))
D_b3 = tf.Variable(tf.zeros([256]))
# D_b3 = tf.Variable(tf.constant(0.1, [256]))
D_w4 = tf.Variable(tf.random.normal([256, 1], stddev=0.01))
D_b4 = tf.Variable(tf.random.normal([1], stddev=0.01))
def discriminator(input, b_size):
# 64x64x1 -> 32x32x1x32
D_L_1 = tf.nn.relu(tf.nn.conv2d(input, D_w1, strides=[1, 1, 1, 1], padding="SAME"))
D_L_1 = tf.nn.max_pool(D_L_1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME")
# 32x32x1x32 -> 16x16x1x64
D_L_2 = tf.nn.relu(tf.nn.conv2d(D_L_1, D_w2, strides=[1, 1, 1, 1], padding="SAME"))
D_L_2 = tf.nn.max_pool(D_L_2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME")
# 16x16x1x64 -> 256
D_L_3 = tf.reshape(D_L_2, [b_size, 16*16*64])
D_L_3 = tf.nn.relu(tf.matmul(D_L_3, D_w3) + D_b3)
# No dropout
# D_L_3 = tf.nn.dropout(D_L_3, keep_prob=keep_prob)
output = tf.nn.sigmoid(tf.matmul(D_L_3, D_w4) + D_b4)
return output
test_size = 10
image_save_friq = 10
# noise_test = np.random.normal(size=(test_size, noise_size))
epoch = 100
batch_size = 200
total_batch = int(len(data_size) / batch_size)
loss_val_D = 0
loss_val_G = 0
G = generator(Z, batch_size)
D_real = discriminator(X, batch_size)
D_gene = discriminator(G, batch_size)
loss_D = -tf.reduce_mean(tf.math.log(D_real) + tf.math.log(1 - D_gene))
loss_G = -tf.reduce_mean(tf.math.log(D_gene))
# Learning rate
global_step = tf.compat.v1.Variable(0, trainable=False)
starter_learning_rate = 0.0002 # learning rate 0.002 -> loss inf
learning_rate = tf.compat.v1.train.exponential_decay(
learning_rate=starter_learning_rate, global_step=global_step,
decay_steps=epoch*total_batch, decay_rate=0.98, staircase=True,
name="ExponentialDecay")
# learning_rate=0.0002
train_D = tf.compat.v1.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss_D, var_list=[D_w1, D_b1, D_w2, D_b2, D_w3, D_b3, D_w4, D_b4]) # compat.train.v1.
train_G = tf.compat.v1.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss_G, var_list=[G_w1, G_b1, G_w2, G_w3, G_w4])
sess = tf.compat.v1.Session()
sess.run(tf.compat.v1.global_variables_initializer())
# saver = tf.compat.v1.train.Saver(tf.compat.v1.global_variables_initializer()) # tf.train.Saver()
# batch = int(data_size / batch_size)
for i in range(epoch): # epoch
for j in range(total_batch): # total_batch
# Load data
for k in range(batch_size): # batch_size
k = k + j * batch_size
if k % batch_size == 0:
tmpimg = cv2.imread(data_path + data_name[k]) #, cv2.IMREAD_GRAYSCALE)
tmpimg = tmpimg / 255.
# tmpimg = tmpimg[:, :, np.newaxis]
# tmpimg = tmpimg[np.newaxis, :, :, 1]
tmpimg = tmpimg[np.newaxis, :, :, :]
imgdata = np.array(tmpimg)
else:
tmpimg = cv2.imread(data_path + data_name[k])
tmpimg = tmpimg / 255.
# tmpimg = tmpimg[:, :, np.newaxis]
# tmpimg = tmpimg[np.newaxis, :, :, 1]
tmpimg = tmpimg[np.newaxis, :, :, :]
imgdata = np.append(imgdata, tmpimg, axis=0)
batch_xs = imgdata
_noise = np.random.normal(size=(batch_size, noise_size))
# print(batch_xs.shape)
# print(_noise.shape)
_, loss_val_D = sess.run([train_D, loss_D], feed_dict={X: batch_xs, Z: _noise})
_, loss_val_G = sess.run([train_G, loss_G], feed_dict={Z: _noise})
print(loss_val_D, loss_val_G)
print(learning_rate)
# saver.save(sess, "./model.ckpt")
print("epoch {tryNum} finished".format(tryNum=i))
if True: # i == 0 or (i + 1) % image_save_friq == 0:
fig, ax = plt.subplots(1, int(test_size), figsize=(int(test_size), 1))
for l in range(test_size):
noise_test = np.random.normal(size=(test_size, noise_size))#.astype(np.float32)
# samples = generator(noise_test, batch_size)
samples = sess.run(generator(Z, test_size), feed_dict={Z: noise_test})
# IsSampleDog = sess.run(discriminator(X, test_size), feed_dict={X: samples})
# for k in range(test_size): # batch_size
# k = k + i * epoch
# if k % batch_size == 0:
# tmpimg = cv2.imread(data_path + data_name[k]) # , cv2.IMREAD_GRAYSCALE)
# tmpimg = tmpimg / 255.
# tmpimg = tmpimg[np.newaxis, :, :, :]
# imgdata = np.array(tmpimg)
# else:
# tmpimg = cv2.imread(data_path + data_name[k])
# tmpimg = tmpimg / 255.
# tmpimg = tmpimg[np.newaxis, :, :, :]
# imgdata = np.append(imgdata, tmpimg, axis=0)
# imgdata = imgdata.astype(dtype=np.float32)
# IsDogDog = sess.run(discriminator(X, test_size), feed_dict={X: imgdata})
# print("Are samples dogs?", IsSampleDog)
# print("Are dogs dogs?", IsDogDog)
ax[l].set_axis_off()
ax[l].imshow(np.reshape(samples[l], [img_size, img_size, img_channels]))
plt.savefig('./Gen/{}.png'.format(str(i+1).zfill(3)), bbox_inches='tight') | [
"tensorflow.reshape",
"tensorflow.matmul",
"tensorflow.compat.v1.train.exponential_decay",
"tensorflow.nn.conv2d",
"numpy.random.normal",
"tensorflow.nn.conv2d_transpose",
"tensorflow.compat.v1.global_variables_initializer",
"tensorflow.math.log",
"tensorflow.compat.v1.placeholder",
"tensorflow.pl... | [((182, 216), 'tensorflow.compat.v1.reset_default_graph', 'tf.compat.v1.reset_default_graph', ([], {}), '()\n', (214, 216), True, 'import tensorflow as tf\n'), ((401, 422), 'os.listdir', 'os.listdir', (['data_path'], {}), '(data_path)\n', (411, 422), False, 'import os\n'), ((625, 703), 'tensorflow.compat.v1.placeholder', 'tf.compat.v1.placeholder', (['tf.float32', '[None, img_size, img_size, img_channels]'], {}), '(tf.float32, [None, img_size, img_size, img_channels])\n', (649, 703), True, 'import tensorflow as tf\n'), ((708, 764), 'tensorflow.compat.v1.placeholder', 'tf.compat.v1.placeholder', (['tf.float32', '[None, noise_size]'], {}), '(tf.float32, [None, noise_size])\n', (732, 764), True, 'import tensorflow as tf\n'), ((777, 803), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (791, 803), True, 'import tensorflow as tf\n'), ((4086, 4127), 'tensorflow.compat.v1.Variable', 'tf.compat.v1.Variable', (['(0)'], {'trainable': '(False)'}), '(0, trainable=False)\n', (4107, 4127), True, 'import tensorflow as tf\n'), ((4212, 4410), 'tensorflow.compat.v1.train.exponential_decay', 'tf.compat.v1.train.exponential_decay', ([], {'learning_rate': 'starter_learning_rate', 'global_step': 'global_step', 'decay_steps': '(epoch * total_batch)', 'decay_rate': '(0.98)', 'staircase': '(True)', 'name': '"""ExponentialDecay"""'}), "(learning_rate=starter_learning_rate,\n global_step=global_step, decay_steps=epoch * total_batch, decay_rate=\n 0.98, staircase=True, name='ExponentialDecay')\n", (4248, 4410), True, 'import tensorflow as tf\n'), ((4748, 4770), 'tensorflow.compat.v1.Session', 'tf.compat.v1.Session', ([], {}), '()\n', (4768, 4770), True, 'import tensorflow as tf\n'), ((824, 869), 'tensorflow.random.normal', 'tf.random.normal', (['[256, 16 * 16]'], {'stddev': '(0.01)'}), '([256, 16 * 16], stddev=0.01)\n', (840, 869), True, 'import tensorflow as tf\n'), ((906, 946), 'tensorflow.random.normal', 'tf.random.normal', (['[16 * 16]'], {'stddev': '(0.01)'}), '([16 * 16], stddev=0.01)\n', (922, 946), True, 'import tensorflow as tf\n'), ((984, 1028), 'tensorflow.random.normal', 'tf.random.normal', (['[3, 3, 32, 1]'], {'stddev': '(0.01)'}), '([3, 3, 32, 1], stddev=0.01)\n', (1000, 1028), True, 'import tensorflow as tf\n'), ((1050, 1094), 'tensorflow.random.normal', 'tf.random.normal', (['[3, 3, 3, 32]'], {'stddev': '(0.01)'}), '([3, 3, 3, 32], stddev=0.01)\n', (1066, 1094), True, 'import tensorflow as tf\n'), ((1116, 1159), 'tensorflow.random.normal', 'tf.random.normal', (['[3, 3, 3, 3]'], {'stddev': '(0.01)'}), '([3, 3, 3, 3], stddev=0.01)\n', (1132, 1159), True, 'import tensorflow as tf\n'), ((1495, 1533), 'tensorflow.reshape', 'tf.reshape', (['G_L_1', '[b_size, 16, 16, 1]'], {}), '(G_L_1, [b_size, 16, 16, 1])\n', (1505, 1533), True, 'import tensorflow as tf\n'), ((1595, 1721), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', ([], {'value': 'G_L_2', 'filter': 'G_w2', 'output_shape': '[b_size, 32, 32, 32]', 'strides': '[1, 2, 2, 1]', 'padding': '"""SAME"""'}), "(value=G_L_2, filter=G_w2, output_shape=[b_size, 32, \n 32, 32], strides=[1, 2, 2, 1], padding='SAME')\n", (1617, 1721), True, 'import tensorflow as tf\n'), ((2354, 2398), 'tensorflow.random.normal', 'tf.random.normal', (['[3, 3, 3, 32]'], {'stddev': '(0.01)'}), '([3, 3, 3, 32], stddev=0.01)\n', (2370, 2398), True, 'import tensorflow as tf\n'), ((2419, 2433), 'tensorflow.zeros', 'tf.zeros', (['[32]'], {}), '([32])\n', (2427, 2433), True, 'import tensorflow as tf\n'), ((2500, 2545), 'tensorflow.random.normal', 'tf.random.normal', (['[3, 3, 32, 64]'], {'stddev': '(0.01)'}), '([3, 3, 32, 64], stddev=0.01)\n', (2516, 2545), True, 'import tensorflow as tf\n'), ((2566, 2580), 'tensorflow.zeros', 'tf.zeros', (['[64]'], {}), '([64])\n', (2574, 2580), True, 'import tensorflow as tf\n'), ((2647, 2684), 'tensorflow.random.normal', 'tf.random.normal', (['[16 * 16 * 64, 256]'], {}), '([16 * 16 * 64, 256])\n', (2663, 2684), True, 'import tensorflow as tf\n'), ((2701, 2716), 'tensorflow.zeros', 'tf.zeros', (['[256]'], {}), '([256])\n', (2709, 2716), True, 'import tensorflow as tf\n'), ((2784, 2823), 'tensorflow.random.normal', 'tf.random.normal', (['[256, 1]'], {'stddev': '(0.01)'}), '([256, 1], stddev=0.01)\n', (2800, 2823), True, 'import tensorflow as tf\n'), ((2844, 2878), 'tensorflow.random.normal', 'tf.random.normal', (['[1]'], {'stddev': '(0.01)'}), '([1], stddev=0.01)\n', (2860, 2878), True, 'import tensorflow as tf\n'), ((3045, 3124), 'tensorflow.nn.max_pool', 'tf.nn.max_pool', (['D_L_1'], {'ksize': '[1, 2, 2, 1]', 'strides': '[1, 2, 2, 1]', 'padding': '"""SAME"""'}), "(D_L_1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n", (3059, 3124), True, 'import tensorflow as tf\n'), ((3259, 3338), 'tensorflow.nn.max_pool', 'tf.nn.max_pool', (['D_L_2'], {'ksize': '[1, 2, 2, 1]', 'strides': '[1, 2, 2, 1]', 'padding': '"""SAME"""'}), "(D_L_2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n", (3273, 3338), True, 'import tensorflow as tf\n'), ((3378, 3419), 'tensorflow.reshape', 'tf.reshape', (['D_L_2', '[b_size, 16 * 16 * 64]'], {}), '(D_L_2, [b_size, 16 * 16 * 64])\n', (3388, 3419), True, 'import tensorflow as tf\n'), ((4780, 4823), 'tensorflow.compat.v1.global_variables_initializer', 'tf.compat.v1.global_variables_initializer', ([], {}), '()\n', (4821, 4823), True, 'import tensorflow as tf\n'), ((469, 491), 'os.stat', 'os.stat', (['(data_path + i)'], {}), '(data_path + i)\n', (476, 491), False, 'import os\n'), ((1839, 1964), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', ([], {'value': 'G_L_3', 'filter': 'G_w3', 'output_shape': '[b_size, 64, 64, 3]', 'strides': '[1, 2, 2, 1]', 'padding': '"""SAME"""'}), "(value=G_L_3, filter=G_w3, output_shape=[b_size, 64, \n 64, 3], strides=[1, 2, 2, 1], padding='SAME')\n", (1861, 1964), True, 'import tensorflow as tf\n'), ((2968, 3031), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['input', 'D_w1'], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(input, D_w1, strides=[1, 1, 1, 1], padding='SAME')\n", (2980, 3031), True, 'import tensorflow as tf\n'), ((3182, 3245), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['D_L_1', 'D_w2'], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(D_L_1, D_w2, strides=[1, 1, 1, 1], padding='SAME')\n", (3194, 3245), True, 'import tensorflow as tf\n'), ((4032, 4051), 'tensorflow.math.log', 'tf.math.log', (['D_gene'], {}), '(D_gene)\n', (4043, 4051), True, 'import tensorflow as tf\n'), ((4448, 4509), 'tensorflow.compat.v1.train.AdamOptimizer', 'tf.compat.v1.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate'}), '(learning_rate=learning_rate)\n', (4480, 4509), True, 'import tensorflow as tf\n'), ((4620, 4681), 'tensorflow.compat.v1.train.AdamOptimizer', 'tf.compat.v1.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate'}), '(learning_rate=learning_rate)\n', (4652, 4681), True, 'import tensorflow as tf\n'), ((5911, 5958), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(batch_size, noise_size)'}), '(size=(batch_size, noise_size))\n', (5927, 5958), True, 'import numpy as np\n'), ((1413, 1435), 'tensorflow.matmul', 'tf.matmul', (['noise', 'G_w1'], {}), '(noise, G_w1)\n', (1422, 1435), True, 'import tensorflow as tf\n'), ((3439, 3461), 'tensorflow.matmul', 'tf.matmul', (['D_L_3', 'D_w3'], {}), '(D_L_3, D_w3)\n', (3448, 3461), True, 'import tensorflow as tf\n'), ((3573, 3595), 'tensorflow.matmul', 'tf.matmul', (['D_L_3', 'D_w4'], {}), '(D_L_3, D_w4)\n', (3582, 3595), True, 'import tensorflow as tf\n'), ((3960, 3979), 'tensorflow.math.log', 'tf.math.log', (['D_real'], {}), '(D_real)\n', (3971, 3979), True, 'import tensorflow as tf\n'), ((3982, 4005), 'tensorflow.math.log', 'tf.math.log', (['(1 - D_gene)'], {}), '(1 - D_gene)\n', (3993, 4005), True, 'import tensorflow as tf\n'), ((6541, 6587), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(test_size, noise_size)'}), '(size=(test_size, noise_size))\n', (6557, 6587), True, 'import numpy as np\n'), ((5221, 5257), 'cv2.imread', 'cv2.imread', (['(data_path + data_name[k])'], {}), '(data_path + data_name[k])\n', (5231, 5257), False, 'import cv2\n'), ((5510, 5526), 'numpy.array', 'np.array', (['tmpimg'], {}), '(tmpimg)\n', (5518, 5526), True, 'import numpy as np\n'), ((5570, 5606), 'cv2.imread', 'cv2.imread', (['(data_path + data_name[k])'], {}), '(data_path + data_name[k])\n', (5580, 5606), False, 'import cv2\n'), ((5832, 5866), 'numpy.append', 'np.append', (['imgdata', 'tmpimg'], {'axis': '(0)'}), '(imgdata, tmpimg, axis=0)\n', (5841, 5866), True, 'import numpy as np\n'), ((7787, 7845), 'numpy.reshape', 'np.reshape', (['samples[l]', '[img_size, img_size, img_channels]'], {}), '(samples[l], [img_size, img_size, img_channels])\n', (7797, 7845), True, 'import numpy as np\n')] |
import numpy as np
import torch
import scipy.sparse as sp
idx_features_labels = np.genfromtxt("./cora.content", dtype=np.dtype(str))
features = sp.csr_matrix(idx_features_labels[:, 1:-1], dtype=np.float32)
features = torch.FloatTensor(np.array(features.todense()))
print(features.size())
list = features.numpy().tolist()
with open('./node_feature_01.txt', 'w') as file_object:
for line in list:
for item in line:
file_object.write(str(item) + ',')
file_object.write('\n') | [
"scipy.sparse.csr_matrix",
"numpy.dtype"
] | [((145, 206), 'scipy.sparse.csr_matrix', 'sp.csr_matrix', (['idx_features_labels[:, 1:-1]'], {'dtype': 'np.float32'}), '(idx_features_labels[:, 1:-1], dtype=np.float32)\n', (158, 206), True, 'import scipy.sparse as sp\n'), ((119, 132), 'numpy.dtype', 'np.dtype', (['str'], {}), '(str)\n', (127, 132), True, 'import numpy as np\n')] |
#!/usr/bin/python3
import requests
import pandas as pd
import numpy as np
PLAYERS_URL = (
"https://raw.githubusercontent.com/mesosbrodleto/"
"soccerDataChallenge/master/players.json"
)
EVENTS_URL = (
"https://raw.githubusercontent.com/mesosbrodleto/"
"soccerDataChallenge/master/worldCup-final.json"
)
ACCURATE_TAG = 1801
def get_players():
"""
get the list of players
"""
return requests.get(PLAYERS_URL).json()
def get_events():
"""
get the list of events in the match
"""
return requests.get(EVENTS_URL).json()
def position_to_cell(position):
"""
get position in the 5X5 grid
"""
x = position["x"]
y = position["y"]
if x <= 20:
cell_x = 0
elif x > 20 and x <= 40:
cell_x = 1
elif x > 40 and x <= 60:
cell_x = 2
elif x > 60 and x <= 80:
cell_x = 3
elif x > 80:
cell_x = 4
if y <= 20:
cell_y = 0
elif y > 20 and y <= 40:
cell_y = 1
elif y > 40 and y <= 60:
cell_y = 2
elif y > 60 and y <= 80:
cell_y = 3
elif y > 80:
cell_y = 4
return cell_x, cell_y
def check_event_in_the_cell(cell_position, x, y):
"""
return a Booelan
"""
if cell_position == (x, y):
return True
return False
def main():
match = get_events()
players = get_players()
events = pd.DataFrame(
match, columns=["teamId", "playerId", "tags", "eventId", "positions"]
)
events["cell_positions"] = events["positions"].apply(
lambda x: [position_to_cell(k) for k in x]
)
team = {}
for t in events["teamId"].unique():
tot_events = len(events.loc[(events["teamId"] == t)])
tot_accurate_passes = len(
events.loc[
(events["teamId"] == t)
& (events["eventId"] == 8)
& (events["tags"].apply(lambda x: {"id": ACCURATE_TAG} in x))
]
)
tot_shots = len(events.loc[(events["teamId"] == t) & (events["eventId"] == 10)])
tot_foul = len(events.loc[(events["teamId"] != t) & (events["eventId"] == 2)])
frequenza_eventi = np.matrix(5 * [5 * [0.]])
frequenza_passaggi_accurati = np.matrix(5 * [5 * [0.]])
frequenza_tiri = np.matrix(5 * [5 * [0.]])
frequenza_falli_subiti = np.matrix(5 * [5 * [0.]])
for x in range(5):
for y in range(5):
events_in_the_cell = len(
events.loc[
(events["teamId"] == t)
& (
events["cell_positions"].apply(
lambda k: check_event_in_the_cell(k[0], x, y)
)
)
]
)
accurate_passes_in_the_cell = len(
events.loc[
(events["teamId"] == t)
& (events["eventId"] == 8)
& (events["tags"].apply(lambda x: {"id": ACCURATE_TAG} in x))
& (
events["cell_positions"].apply(
lambda k: check_event_in_the_cell(k[0], x, y)
)
)
]
)
shots_in_the_cell = len(
events.loc[
(events["teamId"] == t)
& (events["eventId"] == 10)
& (
events["cell_positions"].apply(
lambda k: check_event_in_the_cell(k[0], x, y)
)
)
]
)
foul_in_the_cell = len(
events.loc[
(events["teamId"] != t)
& (events["eventId"] == 2)
& (
events["cell_positions"].apply(
lambda k: check_event_in_the_cell(k[0], x, y)
)
)
]
)
frequenza_eventi[x, y] = events_in_the_cell / float(tot_events)
frequenza_passaggi_accurati[x, y] = accurate_passes_in_the_cell / float(
tot_accurate_passes
)
frequenza_tiri[x, y] = shots_in_the_cell / float(tot_shots)
frequenza_falli_subiti[x, y] = foul_in_the_cell / float(tot_foul)
team[t] = {
"frequenza_eventi": frequenza_eventi,
"frequenza_passaggi_accurati": frequenza_passaggi_accurati,
"frequenza_tiri": frequenza_tiri,
"frequenza_falli_subiti": frequenza_falli_subiti,
}
results = []
for tipo_griglia in [
"frequenza_eventi",
"frequenza_passaggi_accurati",
"frequenza_tiri",
"frequenza_falli_subiti",
]:
for x in range(5):
for y in range(5):
temp = {}
temp["tipo_griglia"] = tipo_griglia
temp["numero_cella_x"] = x
temp["numero_cella_y"] = y
temp["differenza_di_frequenza"] = abs(
team[events["teamId"].unique()[0]][tipo_griglia][x, y]
- team[events["teamId"].unique()[1]][tipo_griglia][x, y]
)
temp["squadra_dominante"] = (
events["teamId"].unique()[0]
if team[events["teamId"].unique()[0]][tipo_griglia][x, y]
> team[events["teamId"].unique()[1]][tipo_griglia][x, y]
else events["teamId"].unique()[1]
)
results.append(temp)
pd.DataFrame(results).to_csv("problema_3_c.csv", index=False)
if __name__ == "__main__":
main()
| [
"pandas.DataFrame",
"numpy.matrix",
"requests.get"
] | [((1398, 1485), 'pandas.DataFrame', 'pd.DataFrame', (['match'], {'columns': "['teamId', 'playerId', 'tags', 'eventId', 'positions']"}), "(match, columns=['teamId', 'playerId', 'tags', 'eventId',\n 'positions'])\n", (1410, 1485), True, 'import pandas as pd\n'), ((2177, 2203), 'numpy.matrix', 'np.matrix', (['(5 * [5 * [0.0]])'], {}), '(5 * [5 * [0.0]])\n', (2186, 2203), True, 'import numpy as np\n'), ((2241, 2267), 'numpy.matrix', 'np.matrix', (['(5 * [5 * [0.0]])'], {}), '(5 * [5 * [0.0]])\n', (2250, 2267), True, 'import numpy as np\n'), ((2292, 2318), 'numpy.matrix', 'np.matrix', (['(5 * [5 * [0.0]])'], {}), '(5 * [5 * [0.0]])\n', (2301, 2318), True, 'import numpy as np\n'), ((2351, 2377), 'numpy.matrix', 'np.matrix', (['(5 * [5 * [0.0]])'], {}), '(5 * [5 * [0.0]])\n', (2360, 2377), True, 'import numpy as np\n'), ((418, 443), 'requests.get', 'requests.get', (['PLAYERS_URL'], {}), '(PLAYERS_URL)\n', (430, 443), False, 'import requests\n'), ((539, 563), 'requests.get', 'requests.get', (['EVENTS_URL'], {}), '(EVENTS_URL)\n', (551, 563), False, 'import requests\n'), ((5856, 5877), 'pandas.DataFrame', 'pd.DataFrame', (['results'], {}), '(results)\n', (5868, 5877), True, 'import pandas as pd\n')] |
"""
The AxesCache class alters how an Axes instance is rendered.
While enabled, the AxesCache quickly re-renders an original view,
properly scaled and translated to reflect changes in the viewport.
The downside is that the re-rendered image is fuzzy and/or truncated.
The best way to use an AxesCache is to enable it during
window resize drags and pan/zoom mouse drags; these generate
rapid draw requests, and users might prefer high refresh
rates to pixel-perfect renders.
Unfortunately, Matplotlib on it's own doesn't provide an easy
mechanism to attach event handlers to either window resize drags
or pan/zoom drags. This code must be added separately.
"""
import numpy as np
from matplotlib.axes import Axes
from matplotlib.image import AxesImage
from matplotlib.collections import QuadMesh
class RenderCapture(object):
"""
A RemderCapture saves an image of a fully-rendered
Axes instance, and provides a method for re-rendering
a properly transformed image during panning and zooming
"""
def __init__(self, axes, renderer):
self.axes = axes
self._corners = self._get_corners(axes)
px, py, dx, dy = self._corners
im = self.extract_image(renderer)
im = im[py[0]: py[-1] + 1, px[0]: px[-1] + 1, :]
self.im = im
self._mesh = None
self._image = None
self.image
@property
def image(self):
if self._image is not None:
return self._image
px, py, dx, dy = self._corners
self._image = AxesImage(self.axes,
origin='lower',
interpolation='nearest')
self._image.set_data(self.im)
self._image.set_extent((dx[0], dx[-1], dy[0], dy[-1]))
self.axes._set_artist_props(self._image)
return self._image
@property
def mesh(self):
if self._mesh is not None:
return self._mesh
px, py, dx, dy = self._corners
x, y, c = self.axes._pcolorargs('pcolormesh', dx, dy,
self.im[:, :, 0],
allmatch=False)
ny, nx = x.shape
coords = np.column_stack((x.ravel(), y.ravel()))
collection = QuadMesh(nx - 1, ny - 1, coords,
shading='flat', antialiased=False,
edgecolors='None',
cmap='gray')
collection.set_array(c.ravel())
collection.set_clip_path(self.axes.patch)
collection.set_transform(self.axes.transData)
self._mesh = collection
return self._mesh
def draw(self, renderer, *args, **kwargs):
if self.axes.get_xscale() == 'linear' and \
self.axes.get_yscale() == 'linear':
self.image.draw(renderer, *args, **kwargs)
else:
self.mesh.draw(renderer, *args, **kwargs)
@staticmethod
def _get_corners(axes):
"""
Return the device and data coordinates
for a box slightly inset from the edge
of an axes instance
Returns 4 1D arrays:
px : Pixel X locations for each column of the box
py : Pixel Y locations for each row of the box
dx : Data X locations for each column of the box
dy : Data Y locations for each row of the box
"""
xlim = axes.get_xlim()
ylim = axes.get_ylim()
pts = np.array([[xlim[0], ylim[0]],
[xlim[1], ylim[1]]])
corners = axes.transData.transform(pts).astype(np.int)
# move in 5 pixels, to avoid grabbing the tick marks
px = np.arange(corners[0, 0] + 5, corners[1, 0] - 5)
py = np.arange(corners[0, 1] + 5, corners[1, 1] - 5)
tr = axes.transData.inverted().transform
dx = tr(np.column_stack((px, px)))[:, 0]
dy = tr(np.column_stack((py, py)))[:, 1]
return px, py, dx, dy
@staticmethod
def extract_image(renderer):
try:
buf = renderer.buffer_rgba()
except TypeError: # mpl v1.1 has different signature
buf = renderer.buffer_rgba(0, 0)
result = np.frombuffer(buf, dtype=np.uint8)
result = result.reshape((int(renderer.height),
int(renderer.width), 4)).copy()
return np.flipud(result)
class AxesCache(object):
def __init__(self, axes):
self.axes = axes
self._capture = None
self.axes.draw = self.draw
self._enabled = False
def draw(self, renderer, *args, **kwargs):
if self._capture is None or not self._enabled:
Axes.draw(self.axes, renderer, *args, **kwargs)
if hasattr(renderer, 'buffer_rgba'):
self._capture = RenderCapture(self.axes, renderer)
else:
self.axes.axesPatch.draw(renderer, *args, **kwargs)
self._capture.draw(renderer, *args, **kwargs)
self.axes.xaxis.draw(renderer, *args, **kwargs)
self.axes.yaxis.draw(renderer, *args, **kwargs)
for s in self.axes.spines.values():
s.draw(renderer, *args, **kwargs)
def clear_cache(self):
"""
Clear the cache, forcing the a full re-render
"""
self._capture = None
def disable(self):
"""
Temporarily disable cache re-renders. Render
results are still saved, for when
enable() is next called
"""
self._enabled = False
self.axes.figure.canvas.draw()
def enable(self):
"""
Enable cached-rerenders
"""
self._enabled = True
def teardown(self):
"""
Permanently disable this cache, and restore
normal Axes render behavior
"""
self.axes.draw = Axes.draw.__get__(self.axes)
if __name__ == "__main__":
import matplotlib.pyplot as plt
num = 1000000
plt.subplot(111)
plt.subplots_adjust(bottom=.5, top=.8)
plt.scatter(np.random.randn(num), np.random.randn(num),
s=np.random.randint(10, 50, num),
c=np.random.randint(0, 255, num),
alpha=.2, linewidths=0)
plt.plot([0, 1, 2, 3], [0, 1, 2, 3])
cache = AxesCache(plt.gca())
cache.enable()
plt.grid('on')
# plt.xscale('log')
plt.show()
| [
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"matplotlib.collections.QuadMesh",
"matplotlib.pyplot.plot",
"numpy.random.randn",
"numpy.frombuffer",
"numpy.column_stack",
"numpy.flipud",
"matplotlib.axes.Axes.draw",
"numpy.random.randint",
"matplotlib.image.AxesImage",
"numpy.array",
... | [((5938, 5954), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (5949, 5954), True, 'import matplotlib.pyplot as plt\n'), ((5959, 5999), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'bottom': '(0.5)', 'top': '(0.8)'}), '(bottom=0.5, top=0.8)\n', (5978, 5999), True, 'import matplotlib.pyplot as plt\n'), ((6202, 6238), 'matplotlib.pyplot.plot', 'plt.plot', (['[0, 1, 2, 3]', '[0, 1, 2, 3]'], {}), '([0, 1, 2, 3], [0, 1, 2, 3])\n', (6210, 6238), True, 'import matplotlib.pyplot as plt\n'), ((6295, 6309), 'matplotlib.pyplot.grid', 'plt.grid', (['"""on"""'], {}), "('on')\n", (6303, 6309), True, 'import matplotlib.pyplot as plt\n'), ((6339, 6349), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6347, 6349), True, 'import matplotlib.pyplot as plt\n'), ((1529, 1590), 'matplotlib.image.AxesImage', 'AxesImage', (['self.axes'], {'origin': '"""lower"""', 'interpolation': '"""nearest"""'}), "(self.axes, origin='lower', interpolation='nearest')\n", (1538, 1590), False, 'from matplotlib.image import AxesImage\n'), ((2251, 2354), 'matplotlib.collections.QuadMesh', 'QuadMesh', (['(nx - 1)', '(ny - 1)', 'coords'], {'shading': '"""flat"""', 'antialiased': '(False)', 'edgecolors': '"""None"""', 'cmap': '"""gray"""'}), "(nx - 1, ny - 1, coords, shading='flat', antialiased=False,\n edgecolors='None', cmap='gray')\n", (2259, 2354), False, 'from matplotlib.collections import QuadMesh\n'), ((3441, 3491), 'numpy.array', 'np.array', (['[[xlim[0], ylim[0]], [xlim[1], ylim[1]]]'], {}), '([[xlim[0], ylim[0]], [xlim[1], ylim[1]]])\n', (3449, 3491), True, 'import numpy as np\n'), ((3655, 3702), 'numpy.arange', 'np.arange', (['(corners[0, 0] + 5)', '(corners[1, 0] - 5)'], {}), '(corners[0, 0] + 5, corners[1, 0] - 5)\n', (3664, 3702), True, 'import numpy as np\n'), ((3716, 3763), 'numpy.arange', 'np.arange', (['(corners[0, 1] + 5)', '(corners[1, 1] - 5)'], {}), '(corners[0, 1] + 5, corners[1, 1] - 5)\n', (3725, 3763), True, 'import numpy as np\n'), ((4173, 4207), 'numpy.frombuffer', 'np.frombuffer', (['buf'], {'dtype': 'np.uint8'}), '(buf, dtype=np.uint8)\n', (4186, 4207), True, 'import numpy as np\n'), ((4343, 4360), 'numpy.flipud', 'np.flipud', (['result'], {}), '(result)\n', (4352, 4360), True, 'import numpy as np\n'), ((5821, 5849), 'matplotlib.axes.Axes.draw.__get__', 'Axes.draw.__get__', (['self.axes'], {}), '(self.axes)\n', (5838, 5849), False, 'from matplotlib.axes import Axes\n'), ((6014, 6034), 'numpy.random.randn', 'np.random.randn', (['num'], {}), '(num)\n', (6029, 6034), True, 'import numpy as np\n'), ((6036, 6056), 'numpy.random.randn', 'np.random.randn', (['num'], {}), '(num)\n', (6051, 6056), True, 'import numpy as np\n'), ((6261, 6270), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (6268, 6270), True, 'import matplotlib.pyplot as plt\n'), ((4654, 4701), 'matplotlib.axes.Axes.draw', 'Axes.draw', (['self.axes', 'renderer', '*args'], {}), '(self.axes, renderer, *args, **kwargs)\n', (4663, 4701), False, 'from matplotlib.axes import Axes\n'), ((6076, 6106), 'numpy.random.randint', 'np.random.randint', (['(10)', '(50)', 'num'], {}), '(10, 50, num)\n', (6093, 6106), True, 'import numpy as np\n'), ((6126, 6156), 'numpy.random.randint', 'np.random.randint', (['(0)', '(255)', 'num'], {}), '(0, 255, num)\n', (6143, 6156), True, 'import numpy as np\n'), ((3830, 3855), 'numpy.column_stack', 'np.column_stack', (['(px, px)'], {}), '((px, px))\n', (3845, 3855), True, 'import numpy as np\n'), ((3879, 3904), 'numpy.column_stack', 'np.column_stack', (['(py, py)'], {}), '((py, py))\n', (3894, 3904), True, 'import numpy as np\n')] |
"""
Interface for system identification data (Actuator and Drives).
"""
from __future__ import print_function
import os
import sys
import zipfile
import warnings
import numpy as np
import scipy.io as sio
from six.moves import urllib
from six.moves import cPickle as pkl
SOURCE_URLS = {
'actuator': 'https://www.cs.cmu.edu/~mshediva/data/actuator.mat',
'drives': 'https://www.cs.cmu.edu/~mshediva/data/NonlinearData.zip',
}
def maybe_download(data_path, dataset_name, verbose=1):
source_url = SOURCE_URLS[dataset_name]
datadir_path = os.path.join(data_path, 'sysid')
dataset_path = os.path.join(datadir_path, dataset_name + '.mat')
# Create directories (if necessary)
if not os.path.isdir(datadir_path):
os.makedirs(datadir_path)
# Download & extract the data (if necessary)
if not os.path.isfile(dataset_path):
if dataset_name == 'actuator':
urllib.request.urlretrieve(source_url, dataset_path)
if dataset_name == 'drives':
assert source_url.endswith('.zip')
archive_path = os.path.join(datadir_path, 'tmp.zip')
urllib.request.urlretrieve(source_url, archive_path)
with zipfile.ZipFile(archive_path, 'r') as zfp:
zfp.extract('DATAPRBS.MAT', datadir_path)
os.rename(os.path.join(datadir_path, 'DATAPRBS.MAT'), dataset_path)
os.remove(archive_path)
if verbose:
print("Successfully downloaded `%s` dataset from %s." %
(dataset_name, source_url))
return dataset_path
def load_data(dataset_name, t_step=1, start=0., stop=100.,
use_targets=True, batch_size=None, verbose=1):
"""Load the system identification data.
Arguments:
----------
t_step : uint (default: 1)
Take data points t_step apart from each other in time.
start : float in [0., 100.) (default: 0.)
stop : float in (0., 100.] (default: 100.)
use_targets : bool (default: True)
batch_size : uint or None (default: None)
verbose : uint (default: 1)
"""
if dataset_name not in {'actuator', 'drives'}:
raise ValueError("Unknown dataset: %s" % dataset_name)
if 'DATA_PATH' not in os.environ:
warnings.warn("Cannot find DATA_PATH variable in the environment. "
"Using <current_working_directory>/data/ instead.")
DATA_PATH = os.path.join(os.getcwd(), 'data')
else:
DATA_PATH = os.environ['DATA_PATH']
dataset_path = maybe_download(DATA_PATH, dataset_name, verbose=verbose)
if not os.path.exists(dataset_path):
raise Exception("Cannot find data: %s" % dataset_path)
if verbose:
sys.stdout.write('Loading data...')
sys.stdout.flush()
data_mat = sio.loadmat(dataset_path)
if dataset_name == 'actuator':
X, Y = data_mat['u'], data_mat['p']
if dataset_name == 'drives':
X, Y = data_mat['u1'], data_mat['z1']
start = int((start/100.) * len(X))
stop = int((stop/100.) * len(X))
X = X[start:stop:t_step,:]
Y = Y[start:stop:t_step,:]
if use_targets:
X = np.hstack([X, Y])
if batch_size:
nb_examples = (len(X) // batch_size) * batch_size
X = X[:nb_examples]
Y = Y[:nb_examples]
if verbose:
sys.stdout.write('Done.\n')
print('# of loaded points: %d' % len(X))
return X, Y
| [
"sys.stdout.write",
"os.remove",
"zipfile.ZipFile",
"os.makedirs",
"scipy.io.loadmat",
"os.path.isdir",
"os.getcwd",
"os.path.exists",
"numpy.hstack",
"os.path.isfile",
"sys.stdout.flush",
"six.moves.urllib.request.urlretrieve",
"warnings.warn",
"os.path.join"
] | [((555, 587), 'os.path.join', 'os.path.join', (['data_path', '"""sysid"""'], {}), "(data_path, 'sysid')\n", (567, 587), False, 'import os\n'), ((607, 656), 'os.path.join', 'os.path.join', (['datadir_path', "(dataset_name + '.mat')"], {}), "(datadir_path, dataset_name + '.mat')\n", (619, 656), False, 'import os\n'), ((2807, 2832), 'scipy.io.loadmat', 'sio.loadmat', (['dataset_path'], {}), '(dataset_path)\n', (2818, 2832), True, 'import scipy.io as sio\n'), ((709, 736), 'os.path.isdir', 'os.path.isdir', (['datadir_path'], {}), '(datadir_path)\n', (722, 736), False, 'import os\n'), ((746, 771), 'os.makedirs', 'os.makedirs', (['datadir_path'], {}), '(datadir_path)\n', (757, 771), False, 'import os\n'), ((833, 861), 'os.path.isfile', 'os.path.isfile', (['dataset_path'], {}), '(dataset_path)\n', (847, 861), False, 'import os\n'), ((2272, 2398), 'warnings.warn', 'warnings.warn', (['"""Cannot find DATA_PATH variable in the environment. Using <current_working_directory>/data/ instead."""'], {}), "(\n 'Cannot find DATA_PATH variable in the environment. Using <current_working_directory>/data/ instead.'\n )\n", (2285, 2398), False, 'import warnings\n'), ((2610, 2638), 'os.path.exists', 'os.path.exists', (['dataset_path'], {}), '(dataset_path)\n', (2624, 2638), False, 'import os\n'), ((2728, 2763), 'sys.stdout.write', 'sys.stdout.write', (['"""Loading data..."""'], {}), "('Loading data...')\n", (2744, 2763), False, 'import sys\n'), ((2772, 2790), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (2788, 2790), False, 'import sys\n'), ((3164, 3181), 'numpy.hstack', 'np.hstack', (['[X, Y]'], {}), '([X, Y])\n', (3173, 3181), True, 'import numpy as np\n'), ((3341, 3368), 'sys.stdout.write', 'sys.stdout.write', (['"""Done.\n"""'], {}), "('Done.\\n')\n", (3357, 3368), False, 'import sys\n'), ((914, 966), 'six.moves.urllib.request.urlretrieve', 'urllib.request.urlretrieve', (['source_url', 'dataset_path'], {}), '(source_url, dataset_path)\n', (940, 966), False, 'from six.moves import urllib\n'), ((1078, 1115), 'os.path.join', 'os.path.join', (['datadir_path', '"""tmp.zip"""'], {}), "(datadir_path, 'tmp.zip')\n", (1090, 1115), False, 'import os\n'), ((1128, 1180), 'six.moves.urllib.request.urlretrieve', 'urllib.request.urlretrieve', (['source_url', 'archive_path'], {}), '(source_url, archive_path)\n', (1154, 1180), False, 'from six.moves import urllib\n'), ((1391, 1414), 'os.remove', 'os.remove', (['archive_path'], {}), '(archive_path)\n', (1400, 1414), False, 'import os\n'), ((2447, 2458), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2456, 2458), False, 'import os\n'), ((1198, 1232), 'zipfile.ZipFile', 'zipfile.ZipFile', (['archive_path', '"""r"""'], {}), "(archive_path, 'r')\n", (1213, 1232), False, 'import zipfile\n'), ((1321, 1363), 'os.path.join', 'os.path.join', (['datadir_path', '"""DATAPRBS.MAT"""'], {}), "(datadir_path, 'DATAPRBS.MAT')\n", (1333, 1363), False, 'import os\n')] |
"""
@file orthogonal_3.py
@description solutions to linear algebra textbook 6.3
@author <NAME>
@version 1.0 May 28, 2021
"""
#!/bin/python
from sympy import Matrix
import numpy as np
import random
def problem25():
"""
Find neareast point in Col A to vector p in R^n
"""
print("broblem 25")
A = np.array([[-6,-3,6,1],[-1,2,1,-6],[3,6,3,-2],[6,-3,6,-1],[2,-1,2,3],[-3,6,3,2],[-2,-1,2,-3],[1,2,1,6]])
p = np.array([1,1,1,1,1,1,1,1])
pp = np.array([0,0,0,0,0,0,0,0])
for x in A.T:
pp = pp + np.dot(x, p) / np.dot(x, x) * x
print(pp)
print("-"*20)
def problem26():
"""
Find distance from p to A
"""
print("broblem 26")
A = np.array([[-6,-3,6,1],[-1,2,1,-6],[3,6,3,-2],[6,-3,6,-1],[2,-1,2,3],[-3,6,3,2],[-2,-1,2,-3],[1,2,1,6]])
p = np.array([1,1,1,1,-1,-1,-1,-1])
pp = np.array([0,0,0,0,0,0,0,0])
for x in A.T:
pp =pp + np.dot(x, p) / np.dot(x, x) * x
dis = np.linalg.norm(p - pp)
print(dis)
print("-"*20)
if __name__ == "__main__":
problem25()
problem26() | [
"numpy.dot",
"numpy.linalg.norm",
"numpy.array"
] | [((320, 458), 'numpy.array', 'np.array', (['[[-6, -3, 6, 1], [-1, 2, 1, -6], [3, 6, 3, -2], [6, -3, 6, -1], [2, -1, 2, \n 3], [-3, 6, 3, 2], [-2, -1, 2, -3], [1, 2, 1, 6]]'], {}), '([[-6, -3, 6, 1], [-1, 2, 1, -6], [3, 6, 3, -2], [6, -3, 6, -1], [2,\n -1, 2, 3], [-3, 6, 3, 2], [-2, -1, 2, -3], [1, 2, 1, 6]])\n', (328, 458), True, 'import numpy as np\n'), ((432, 466), 'numpy.array', 'np.array', (['[1, 1, 1, 1, 1, 1, 1, 1]'], {}), '([1, 1, 1, 1, 1, 1, 1, 1])\n', (440, 466), True, 'import numpy as np\n'), ((474, 508), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 0, 0, 0, 0]'], {}), '([0, 0, 0, 0, 0, 0, 0, 0])\n', (482, 508), True, 'import numpy as np\n'), ((717, 855), 'numpy.array', 'np.array', (['[[-6, -3, 6, 1], [-1, 2, 1, -6], [3, 6, 3, -2], [6, -3, 6, -1], [2, -1, 2, \n 3], [-3, 6, 3, 2], [-2, -1, 2, -3], [1, 2, 1, 6]]'], {}), '([[-6, -3, 6, 1], [-1, 2, 1, -6], [3, 6, 3, -2], [6, -3, 6, -1], [2,\n -1, 2, 3], [-3, 6, 3, 2], [-2, -1, 2, -3], [1, 2, 1, 6]])\n', (725, 855), True, 'import numpy as np\n'), ((829, 867), 'numpy.array', 'np.array', (['[1, 1, 1, 1, -1, -1, -1, -1]'], {}), '([1, 1, 1, 1, -1, -1, -1, -1])\n', (837, 867), True, 'import numpy as np\n'), ((875, 909), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 0, 0, 0, 0]'], {}), '([0, 0, 0, 0, 0, 0, 0, 0])\n', (883, 909), True, 'import numpy as np\n'), ((985, 1007), 'numpy.linalg.norm', 'np.linalg.norm', (['(p - pp)'], {}), '(p - pp)\n', (999, 1007), True, 'import numpy as np\n'), ((538, 550), 'numpy.dot', 'np.dot', (['x', 'p'], {}), '(x, p)\n', (544, 550), True, 'import numpy as np\n'), ((553, 565), 'numpy.dot', 'np.dot', (['x', 'x'], {}), '(x, x)\n', (559, 565), True, 'import numpy as np\n'), ((938, 950), 'numpy.dot', 'np.dot', (['x', 'p'], {}), '(x, p)\n', (944, 950), True, 'import numpy as np\n'), ((953, 965), 'numpy.dot', 'np.dot', (['x', 'x'], {}), '(x, x)\n', (959, 965), True, 'import numpy as np\n')] |
import unittest
import numpy
from molml.molecule import Connectivity
from molml.crystal import GenerallizedCrystal
from molml.crystal import EwaldSumMatrix, SineMatrix
H_ELES = ['H']
H_NUMS = [1]
H_COORDS = numpy.array([[0.0, 0.0, 0.0]])
H_UNIT = numpy.array([
[2., .5, 0.],
[.25, 1., 0.],
[0., .3, 1.],
])
H_INPUT = ("elements", "coords", "unit_cell")
H = (H_ELES, H_COORDS, H_UNIT)
H2_ELES = ['H', 'H']
H2_NUMS = [1, 1]
H2_COORDS = numpy.array([
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
])
H2_CONNS = {
0: {1: '1'},
1: {0: '1'},
}
H2_UNIT = numpy.array([
[2., .5, 0.],
[.25, 1., 0.],
[0., .3, 1.],
])
H2 = (H2_ELES, H2_COORDS, H2_UNIT)
class GenerallizedCrystalTest(unittest.TestCase):
def test_fit(self):
t = Connectivity(input_type=H_INPUT)
a = GenerallizedCrystal(transformer=t, radius=2.5)
a.fit([H])
self.assertEqual(a.transformer.get_labels(), ('H', ))
def test_transform(self):
t = Connectivity(input_type=H_INPUT)
a = GenerallizedCrystal(transformer=t, radius=2.5)
a.fit([H])
res = a.transform([H])
self.assertEqual(res, numpy.array([[37]]))
def test_transform_before_fit(self):
t = Connectivity(input_type=H_INPUT)
a = GenerallizedCrystal(transformer=t, radius=2.5)
with self.assertRaises(ValueError):
a.transform([H])
def test_fit_transform(self):
t = Connectivity(input_type=H_INPUT)
a = GenerallizedCrystal(transformer=t, radius=2.5)
res = a.fit_transform([H])
self.assertEqual(res, numpy.array([[37]]))
def test_radius_and_units(self):
t = Connectivity(input_type=H_INPUT)
with self.assertRaises(ValueError):
GenerallizedCrystal(transformer=t, radius=2.5, units=2)
class EwaldSumMatrixCrystalTest(unittest.TestCase):
def test_fit(self):
a = EwaldSumMatrix()
a.fit([(H2_ELES, H2_COORDS)])
self.assertEqual(a._max_size, 2)
def test_transform(self):
a = EwaldSumMatrix(input_type=H_INPUT)
a.fit([H2])
res = a.transform([H2])
expected = numpy.array([[-1.68059225, 0.94480435,
0.94480435, -1.68059225]])
try:
numpy.testing.assert_array_almost_equal(
res,
expected)
except AssertionError as e:
self.fail(e)
def test_G_max(self):
a = EwaldSumMatrix(input_type=H_INPUT, G_max=2)
a.fit([H2])
res = a.transform([H2])
expected = numpy.array([[-1.68059225, 0.945167,
0.945167, -1.68059225]])
try:
numpy.testing.assert_array_almost_equal(
res,
expected)
except AssertionError as e:
self.fail(e)
def test_L_max(self):
a = EwaldSumMatrix(input_type=H_INPUT, L_max=2)
a.fit([H2])
res = a.transform([H2])
expected = numpy.array([[-1.68059225, 0.43748,
0.43748, -1.68059225]])
try:
numpy.testing.assert_array_almost_equal(
res,
expected)
except AssertionError as e:
self.fail(e)
def test_small_to_large_transform(self):
a = EwaldSumMatrix(input_type=H_INPUT)
a.fit([H])
with self.assertRaises(ValueError):
a.transform([H2])
def test_large_to_small_transform(self):
a = EwaldSumMatrix(input_type=H_INPUT)
a.fit([(H2_ELES, H2_COORDS, H2_UNIT)])
res = a.transform([H])
expected = numpy.array([[-1.944276, 0., 0., 0.]])
try:
numpy.testing.assert_array_almost_equal(
res,
expected)
except AssertionError as e:
self.fail(e)
def test_transform_before_fit(self):
a = EwaldSumMatrix()
with self.assertRaises(ValueError):
a.transform([H])
def test_fit_transform(self):
a = EwaldSumMatrix(input_type=H_INPUT)
res = a.fit_transform([H2])
expected = numpy.array([[-1.68059225, 0.94480435,
0.94480435, -1.68059225]])
try:
numpy.testing.assert_array_almost_equal(
res,
expected)
except AssertionError as e:
self.fail(e)
def test_sort(self):
a = EwaldSumMatrix(input_type=H_INPUT, sort=True)
res = a.fit_transform([H2])
expected = numpy.array([[-1.68059225, 0.94480435,
0.94480435, -1.68059225]])
try:
numpy.testing.assert_array_almost_equal(
res,
expected)
except AssertionError as e:
self.fail(e)
def test_eigen(self):
a = EwaldSumMatrix(input_type=H_INPUT, eigen=True)
res = a.fit_transform([H2])
expected = numpy.array([[-0.735788, -2.625397]])
try:
numpy.testing.assert_array_almost_equal(
res,
expected)
except AssertionError as e:
self.fail(e)
class SineMatrixTest(unittest.TestCase):
def test_fit(self):
a = SineMatrix()
a.fit([(H2_ELES, H2_COORDS)])
self.assertEqual(a._max_size, 2)
def test_transform(self):
a = SineMatrix(input_type=H_INPUT)
a.fit([H2])
res = a.transform([H2])
expected = numpy.array([[0.5, 0.475557, 0.475557, 0.5]])
try:
numpy.testing.assert_array_almost_equal(
res,
expected)
except AssertionError as e:
self.fail(e)
def test_small_to_large_transform(self):
a = SineMatrix(input_type=H_INPUT)
a.fit([H])
with self.assertRaises(ValueError):
a.transform([H2])
def test_large_to_small_transform(self):
a = SineMatrix(input_type=H_INPUT)
a.fit([H2])
res = a.transform([H])
expected = numpy.array([[0.5, 0., 0., 0.]])
try:
numpy.testing.assert_array_almost_equal(
res,
expected)
except AssertionError as e:
self.fail(e)
def test_transform_before_fit(self):
a = SineMatrix()
with self.assertRaises(ValueError):
a.transform([H])
def test_fit_transform(self):
a = SineMatrix(input_type=H_INPUT)
res = a.fit_transform([H2])
expected = numpy.array([[0.5, 0.475557, 0.475557, 0.5]])
try:
numpy.testing.assert_array_almost_equal(
res,
expected)
except AssertionError as e:
self.fail(e)
def test_sort(self):
a = SineMatrix(input_type=H_INPUT, sort=True)
res = a.fit_transform([H2])
expected = numpy.array([[0.5, 0.475557, 0.475557, 0.5]])
try:
numpy.testing.assert_array_almost_equal(
res,
expected)
except AssertionError as e:
self.fail(e)
def test_eigen(self):
a = SineMatrix(input_type=H_INPUT, eigen=True)
res = a.fit_transform([H2])
expected = numpy.array([[0.975557, 0.024443]])
try:
numpy.testing.assert_array_almost_equal(
res,
expected)
except AssertionError as e:
self.fail(e)
if __name__ == '__main__':
unittest.main()
| [
"unittest.main",
"molml.crystal.GenerallizedCrystal",
"molml.crystal.EwaldSumMatrix",
"molml.molecule.Connectivity",
"numpy.array",
"molml.crystal.SineMatrix",
"numpy.testing.assert_array_almost_equal"
] | [((211, 241), 'numpy.array', 'numpy.array', (['[[0.0, 0.0, 0.0]]'], {}), '([[0.0, 0.0, 0.0]])\n', (222, 241), False, 'import numpy\n'), ((251, 316), 'numpy.array', 'numpy.array', (['[[2.0, 0.5, 0.0], [0.25, 1.0, 0.0], [0.0, 0.3, 1.0]]'], {}), '([[2.0, 0.5, 0.0], [0.25, 1.0, 0.0], [0.0, 0.3, 1.0]])\n', (262, 316), False, 'import numpy\n'), ((452, 499), 'numpy.array', 'numpy.array', (['[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]'], {}), '([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]])\n', (463, 499), False, 'import numpy\n'), ((570, 635), 'numpy.array', 'numpy.array', (['[[2.0, 0.5, 0.0], [0.25, 1.0, 0.0], [0.0, 0.3, 1.0]]'], {}), '([[2.0, 0.5, 0.0], [0.25, 1.0, 0.0], [0.0, 0.3, 1.0]])\n', (581, 635), False, 'import numpy\n'), ((7485, 7500), 'unittest.main', 'unittest.main', ([], {}), '()\n', (7498, 7500), False, 'import unittest\n'), ((765, 797), 'molml.molecule.Connectivity', 'Connectivity', ([], {'input_type': 'H_INPUT'}), '(input_type=H_INPUT)\n', (777, 797), False, 'from molml.molecule import Connectivity\n'), ((810, 856), 'molml.crystal.GenerallizedCrystal', 'GenerallizedCrystal', ([], {'transformer': 't', 'radius': '(2.5)'}), '(transformer=t, radius=2.5)\n', (829, 856), False, 'from molml.crystal import GenerallizedCrystal\n'), ((981, 1013), 'molml.molecule.Connectivity', 'Connectivity', ([], {'input_type': 'H_INPUT'}), '(input_type=H_INPUT)\n', (993, 1013), False, 'from molml.molecule import Connectivity\n'), ((1026, 1072), 'molml.crystal.GenerallizedCrystal', 'GenerallizedCrystal', ([], {'transformer': 't', 'radius': '(2.5)'}), '(transformer=t, radius=2.5)\n', (1045, 1072), False, 'from molml.crystal import GenerallizedCrystal\n'), ((1228, 1260), 'molml.molecule.Connectivity', 'Connectivity', ([], {'input_type': 'H_INPUT'}), '(input_type=H_INPUT)\n', (1240, 1260), False, 'from molml.molecule import Connectivity\n'), ((1273, 1319), 'molml.crystal.GenerallizedCrystal', 'GenerallizedCrystal', ([], {'transformer': 't', 'radius': '(2.5)'}), '(transformer=t, radius=2.5)\n', (1292, 1319), False, 'from molml.crystal import GenerallizedCrystal\n'), ((1440, 1472), 'molml.molecule.Connectivity', 'Connectivity', ([], {'input_type': 'H_INPUT'}), '(input_type=H_INPUT)\n', (1452, 1472), False, 'from molml.molecule import Connectivity\n'), ((1485, 1531), 'molml.crystal.GenerallizedCrystal', 'GenerallizedCrystal', ([], {'transformer': 't', 'radius': '(2.5)'}), '(transformer=t, radius=2.5)\n', (1504, 1531), False, 'from molml.crystal import GenerallizedCrystal\n'), ((1668, 1700), 'molml.molecule.Connectivity', 'Connectivity', ([], {'input_type': 'H_INPUT'}), '(input_type=H_INPUT)\n', (1680, 1700), False, 'from molml.molecule import Connectivity\n'), ((1903, 1919), 'molml.crystal.EwaldSumMatrix', 'EwaldSumMatrix', ([], {}), '()\n', (1917, 1919), False, 'from molml.crystal import EwaldSumMatrix, SineMatrix\n'), ((2042, 2076), 'molml.crystal.EwaldSumMatrix', 'EwaldSumMatrix', ([], {'input_type': 'H_INPUT'}), '(input_type=H_INPUT)\n', (2056, 2076), False, 'from molml.crystal import EwaldSumMatrix, SineMatrix\n'), ((2148, 2213), 'numpy.array', 'numpy.array', (['[[-1.68059225, 0.94480435, 0.94480435, -1.68059225]]'], {}), '([[-1.68059225, 0.94480435, 0.94480435, -1.68059225]])\n', (2159, 2213), False, 'import numpy\n'), ((2460, 2503), 'molml.crystal.EwaldSumMatrix', 'EwaldSumMatrix', ([], {'input_type': 'H_INPUT', 'G_max': '(2)'}), '(input_type=H_INPUT, G_max=2)\n', (2474, 2503), False, 'from molml.crystal import EwaldSumMatrix, SineMatrix\n'), ((2575, 2636), 'numpy.array', 'numpy.array', (['[[-1.68059225, 0.945167, 0.945167, -1.68059225]]'], {}), '([[-1.68059225, 0.945167, 0.945167, -1.68059225]])\n', (2586, 2636), False, 'import numpy\n'), ((2883, 2926), 'molml.crystal.EwaldSumMatrix', 'EwaldSumMatrix', ([], {'input_type': 'H_INPUT', 'L_max': '(2)'}), '(input_type=H_INPUT, L_max=2)\n', (2897, 2926), False, 'from molml.crystal import EwaldSumMatrix, SineMatrix\n'), ((2998, 3057), 'numpy.array', 'numpy.array', (['[[-1.68059225, 0.43748, 0.43748, -1.68059225]]'], {}), '([[-1.68059225, 0.43748, 0.43748, -1.68059225]])\n', (3009, 3057), False, 'import numpy\n'), ((3323, 3357), 'molml.crystal.EwaldSumMatrix', 'EwaldSumMatrix', ([], {'input_type': 'H_INPUT'}), '(input_type=H_INPUT)\n', (3337, 3357), False, 'from molml.crystal import EwaldSumMatrix, SineMatrix\n'), ((3509, 3543), 'molml.crystal.EwaldSumMatrix', 'EwaldSumMatrix', ([], {'input_type': 'H_INPUT'}), '(input_type=H_INPUT)\n', (3523, 3543), False, 'from molml.crystal import EwaldSumMatrix, SineMatrix\n'), ((3641, 3682), 'numpy.array', 'numpy.array', (['[[-1.944276, 0.0, 0.0, 0.0]]'], {}), '([[-1.944276, 0.0, 0.0, 0.0]])\n', (3652, 3682), False, 'import numpy\n'), ((3908, 3924), 'molml.crystal.EwaldSumMatrix', 'EwaldSumMatrix', ([], {}), '()\n', (3922, 3924), False, 'from molml.crystal import EwaldSumMatrix, SineMatrix\n'), ((4045, 4079), 'molml.crystal.EwaldSumMatrix', 'EwaldSumMatrix', ([], {'input_type': 'H_INPUT'}), '(input_type=H_INPUT)\n', (4059, 4079), False, 'from molml.crystal import EwaldSumMatrix, SineMatrix\n'), ((4135, 4200), 'numpy.array', 'numpy.array', (['[[-1.68059225, 0.94480435, 0.94480435, -1.68059225]]'], {}), '([[-1.68059225, 0.94480435, 0.94480435, -1.68059225]])\n', (4146, 4200), False, 'import numpy\n'), ((4446, 4491), 'molml.crystal.EwaldSumMatrix', 'EwaldSumMatrix', ([], {'input_type': 'H_INPUT', 'sort': '(True)'}), '(input_type=H_INPUT, sort=True)\n', (4460, 4491), False, 'from molml.crystal import EwaldSumMatrix, SineMatrix\n'), ((4547, 4612), 'numpy.array', 'numpy.array', (['[[-1.68059225, 0.94480435, 0.94480435, -1.68059225]]'], {}), '([[-1.68059225, 0.94480435, 0.94480435, -1.68059225]])\n', (4558, 4612), False, 'import numpy\n'), ((4859, 4905), 'molml.crystal.EwaldSumMatrix', 'EwaldSumMatrix', ([], {'input_type': 'H_INPUT', 'eigen': '(True)'}), '(input_type=H_INPUT, eigen=True)\n', (4873, 4905), False, 'from molml.crystal import EwaldSumMatrix, SineMatrix\n'), ((4961, 4998), 'numpy.array', 'numpy.array', (['[[-0.735788, -2.625397]]'], {}), '([[-0.735788, -2.625397]])\n', (4972, 4998), False, 'import numpy\n'), ((5252, 5264), 'molml.crystal.SineMatrix', 'SineMatrix', ([], {}), '()\n', (5262, 5264), False, 'from molml.crystal import EwaldSumMatrix, SineMatrix\n'), ((5387, 5417), 'molml.crystal.SineMatrix', 'SineMatrix', ([], {'input_type': 'H_INPUT'}), '(input_type=H_INPUT)\n', (5397, 5417), False, 'from molml.crystal import EwaldSumMatrix, SineMatrix\n'), ((5489, 5534), 'numpy.array', 'numpy.array', (['[[0.5, 0.475557, 0.475557, 0.5]]'], {}), '([[0.5, 0.475557, 0.475557, 0.5]])\n', (5500, 5534), False, 'import numpy\n'), ((5767, 5797), 'molml.crystal.SineMatrix', 'SineMatrix', ([], {'input_type': 'H_INPUT'}), '(input_type=H_INPUT)\n', (5777, 5797), False, 'from molml.crystal import EwaldSumMatrix, SineMatrix\n'), ((5949, 5979), 'molml.crystal.SineMatrix', 'SineMatrix', ([], {'input_type': 'H_INPUT'}), '(input_type=H_INPUT)\n', (5959, 5979), False, 'from molml.crystal import EwaldSumMatrix, SineMatrix\n'), ((6050, 6085), 'numpy.array', 'numpy.array', (['[[0.5, 0.0, 0.0, 0.0]]'], {}), '([[0.5, 0.0, 0.0, 0.0]])\n', (6061, 6085), False, 'import numpy\n'), ((6311, 6323), 'molml.crystal.SineMatrix', 'SineMatrix', ([], {}), '()\n', (6321, 6323), False, 'from molml.crystal import EwaldSumMatrix, SineMatrix\n'), ((6444, 6474), 'molml.crystal.SineMatrix', 'SineMatrix', ([], {'input_type': 'H_INPUT'}), '(input_type=H_INPUT)\n', (6454, 6474), False, 'from molml.crystal import EwaldSumMatrix, SineMatrix\n'), ((6530, 6575), 'numpy.array', 'numpy.array', (['[[0.5, 0.475557, 0.475557, 0.5]]'], {}), '([[0.5, 0.475557, 0.475557, 0.5]])\n', (6541, 6575), False, 'import numpy\n'), ((6788, 6829), 'molml.crystal.SineMatrix', 'SineMatrix', ([], {'input_type': 'H_INPUT', 'sort': '(True)'}), '(input_type=H_INPUT, sort=True)\n', (6798, 6829), False, 'from molml.crystal import EwaldSumMatrix, SineMatrix\n'), ((6885, 6930), 'numpy.array', 'numpy.array', (['[[0.5, 0.475557, 0.475557, 0.5]]'], {}), '([[0.5, 0.475557, 0.475557, 0.5]])\n', (6896, 6930), False, 'import numpy\n'), ((7144, 7186), 'molml.crystal.SineMatrix', 'SineMatrix', ([], {'input_type': 'H_INPUT', 'eigen': '(True)'}), '(input_type=H_INPUT, eigen=True)\n', (7154, 7186), False, 'from molml.crystal import EwaldSumMatrix, SineMatrix\n'), ((7242, 7277), 'numpy.array', 'numpy.array', (['[[0.975557, 0.024443]]'], {}), '([[0.975557, 0.024443]])\n', (7253, 7277), False, 'import numpy\n'), ((1153, 1172), 'numpy.array', 'numpy.array', (['[[37]]'], {}), '([[37]])\n', (1164, 1172), False, 'import numpy\n'), ((1597, 1616), 'numpy.array', 'numpy.array', (['[[37]]'], {}), '([[37]])\n', (1608, 1616), False, 'import numpy\n'), ((1757, 1812), 'molml.crystal.GenerallizedCrystal', 'GenerallizedCrystal', ([], {'transformer': 't', 'radius': '(2.5)', 'units': '(2)'}), '(transformer=t, radius=2.5, units=2)\n', (1776, 1812), False, 'from molml.crystal import GenerallizedCrystal\n'), ((2272, 2326), 'numpy.testing.assert_array_almost_equal', 'numpy.testing.assert_array_almost_equal', (['res', 'expected'], {}), '(res, expected)\n', (2311, 2326), False, 'import numpy\n'), ((2695, 2749), 'numpy.testing.assert_array_almost_equal', 'numpy.testing.assert_array_almost_equal', (['res', 'expected'], {}), '(res, expected)\n', (2734, 2749), False, 'import numpy\n'), ((3116, 3170), 'numpy.testing.assert_array_almost_equal', 'numpy.testing.assert_array_almost_equal', (['res', 'expected'], {}), '(res, expected)\n', (3155, 3170), False, 'import numpy\n'), ((3705, 3759), 'numpy.testing.assert_array_almost_equal', 'numpy.testing.assert_array_almost_equal', (['res', 'expected'], {}), '(res, expected)\n', (3744, 3759), False, 'import numpy\n'), ((4259, 4313), 'numpy.testing.assert_array_almost_equal', 'numpy.testing.assert_array_almost_equal', (['res', 'expected'], {}), '(res, expected)\n', (4298, 4313), False, 'import numpy\n'), ((4671, 4725), 'numpy.testing.assert_array_almost_equal', 'numpy.testing.assert_array_almost_equal', (['res', 'expected'], {}), '(res, expected)\n', (4710, 4725), False, 'import numpy\n'), ((5024, 5078), 'numpy.testing.assert_array_almost_equal', 'numpy.testing.assert_array_almost_equal', (['res', 'expected'], {}), '(res, expected)\n', (5063, 5078), False, 'import numpy\n'), ((5560, 5614), 'numpy.testing.assert_array_almost_equal', 'numpy.testing.assert_array_almost_equal', (['res', 'expected'], {}), '(res, expected)\n', (5599, 5614), False, 'import numpy\n'), ((6108, 6162), 'numpy.testing.assert_array_almost_equal', 'numpy.testing.assert_array_almost_equal', (['res', 'expected'], {}), '(res, expected)\n', (6147, 6162), False, 'import numpy\n'), ((6601, 6655), 'numpy.testing.assert_array_almost_equal', 'numpy.testing.assert_array_almost_equal', (['res', 'expected'], {}), '(res, expected)\n', (6640, 6655), False, 'import numpy\n'), ((6956, 7010), 'numpy.testing.assert_array_almost_equal', 'numpy.testing.assert_array_almost_equal', (['res', 'expected'], {}), '(res, expected)\n', (6995, 7010), False, 'import numpy\n'), ((7303, 7357), 'numpy.testing.assert_array_almost_equal', 'numpy.testing.assert_array_almost_equal', (['res', 'expected'], {}), '(res, expected)\n', (7342, 7357), False, 'import numpy\n')] |
import numpy as np
from multiphenotype_utils import (get_continuous_features_as_matrix, add_id, remove_id_and_get_mat,
partition_dataframe_into_binary_and_continuous, divide_idxs_into_batches)
import pandas as pd
import tensorflow as tf
from dimreducer import DimReducer
import time
from scipy.stats import pearsonr, linregress
from scipy.special import expit
import copy
import random
class GeneralAutoencoder(DimReducer):
"""
Base autoencoder class that other classes derive from.
Not intended to be run on its own.
Has code that's common to autoencoders in general,
e.g., default parameter settings, preprocessing functions, training procedure.
"""
def __init__(self,
learning_rate=0.01,
max_epochs=300,
random_seed=None,
binary_loss_weighting=1.0,
non_linearity='relu',
batch_size=128,
age_preprocessing_method='subtract_a_constant',
include_age_in_encoder_input=False,
uses_longitudinal_data=False,
can_calculate_Z_mu=True,
need_ages=False,
initialization_scaling=1,
regularization_weighting_schedule={'schedule_type':'constant', 'constant':1},
is_rate_of_aging_model=False):
self.need_ages = need_ages # whether ages are needed to compute loss or other quantities.
assert age_preprocessing_method in ['subtract_a_constant', 'divide_by_a_constant', 'subtract_about_40_and_divide_by_30']
self.age_preprocessing_method = age_preprocessing_method
self.include_age_in_encoder_input = include_age_in_encoder_input
# include_age_in_encoder_input is whether age is used to approximate the posterior over Z.
# Eg, we need this for rate-of-aging autoencoder.
# set random seed for reproducibility, but if it's None, the default,
# choose it randomly so we don't inadvertently test the same model over and over again in simulations.
if random_seed is None:
random_seed = random.randint(0, int(1e6))
print("Model random seed is %s" % random_seed)
self.can_calculate_Z_mu = can_calculate_Z_mu # does the variable Z_mu make any sense for the model.
self.uses_longitudinal_data = uses_longitudinal_data # does the model accomodate longitudinal data as well.
self.is_rate_of_aging_model = is_rate_of_aging_model # does the model compute a rate-of-aging.
# How many epochs should pass before we evaluate and print out
# the loss on the training/validation datasets?
self.num_epochs_before_eval = 10
# How many rounds of evaluation without validation improvement
# should pass before we quit training?
# Roughly,
# max_epochs_without_improving = num_epochs_before_eval * max_evals_without_improving
self.max_evals_without_improving = 500
self.max_epochs = max_epochs
# Set random seed
self.random_seed = random_seed
# binary loss weighting. This is used to make sure that the model doesn't just ignore binary features.
self.binary_loss_weighting = binary_loss_weighting
# save the regularization_weighting_schedule. This controls how heavily we weight the regularization loss
# as a function of epoch.
self.regularization_weighting_schedule = regularization_weighting_schedule
assert regularization_weighting_schedule['schedule_type'] in ['constant', 'logistic']
self.batch_size = batch_size
if non_linearity == 'sigmoid':
self.non_linearity = tf.nn.sigmoid
elif non_linearity == 'relu':
self.non_linearity = tf.nn.relu
elif non_linearity == 'identity':
self.non_linearity = tf.identity
else:
raise Exception("not a valid nonlinear activation")
self.learning_rate = learning_rate
self.optimization_method = tf.train.AdamOptimizer
self.initialization_function = self.glorot_init
self.initialization_scaling = initialization_scaling # how much should we scale the initialization by to keep from exploding.
self.all_losses_by_epoch = []
self.binary_feature_idxs = None
self.continuous_feature_idxs = None
self.feature_names = None
self.lon_loss_weighting_factor = None
def data_preprocessing_function(self, df):
# this function is used to process multiple dataframes so make sure that they are in the same format
old_binary_feature_idxs = copy.deepcopy(self.binary_feature_idxs)
old_continuous_feature_idxs = copy.deepcopy(self.continuous_feature_idxs)
old_feature_names = copy.deepcopy(self.feature_names)
X, self.binary_feature_idxs, self.continuous_feature_idxs, self.feature_names = \
partition_dataframe_into_binary_and_continuous(df)
#print("Number of continuous features: %i; binary features %i" % (
# len(self.continuous_feature_idxs),
# len(self.binary_feature_idxs)))
if old_binary_feature_idxs is not None:
assert list(self.binary_feature_idxs) == list(old_binary_feature_idxs)
if old_continuous_feature_idxs is not None:
assert list(self.continuous_feature_idxs) == list(old_continuous_feature_idxs)
if old_feature_names is not None:
assert list(self.feature_names) == list(old_feature_names)
return X
def get_projections(self, df, project_onto_mean, **projection_kwargs):
"""
use the fitted model to get projections for df.
if project_onto_mean=True, projects onto the mean value of Z (Z_mu). Otherwise, samples Z.
"""
#print("Getting projections using method %s." % self.__class__.__name__)
X = self.data_preprocessing_function(df)
ages = self.get_ages(df)
Z = self._get_projections_from_processed_data(X, ages, project_onto_mean, **projection_kwargs)
Z_df = add_id(Z, df) # Z_df and df will have the same id and individual_id.
Z_df.columns = ['individual_id'] + ['z%s' % i for i in range(Z.shape[1])]
return Z_df
def split_into_binary_and_continuous(self, X):
if len(self.binary_feature_idxs) > 0:
binary_features = tf.gather(X, indices=self.binary_feature_idxs, axis=1)
else:
binary_features = tf.zeros([tf.shape(X)[0], 0])
if len(self.continuous_feature_idxs) > 0:
continuous_features = tf.gather(X, indices=self.continuous_feature_idxs, axis=1)
else:
continuous_features = tf.zeros([tf.shape(X)[0], 0])
return binary_features, continuous_features
def glorot_init(self, shape):
if shape[0] == 0: # special case in case we have an empty state.
stddev = 2.
else:
stddev = tf.sqrt(2. / shape[0])
return self.initialization_scaling*tf.random_normal(shape=shape, stddev=stddev, seed=self.random_seed)
def init_network(self):
raise NotImplementedError
def get_setter_ops(self):
raise NotImplementedError
def encode(self, X):
raise NotImplementedError
def decode(self, Z):
raise NotImplementedError
def age_preprocessing_function(self, ages):
# three possibilities:
# 1. subtract a constant (to roughly zero-mean ages)
# 2. divide by a constant (to keep age roughly on the same-scale as the other features)
# 3. subtract about 40 and divide by 30 -- this is to make ages start at 0 and be on the same scale as other features,
# useful for rate of aging methods. We subtract 39.9 rather than 40 because otherwise we have 0/0 errors.
# this is hacky but should work.
# in all cases, we hard-code the constants in rather than deriving from data
# to avoid weird bugs if we train on people with young ages or something and then test on another group.
# the constant is chosen for UKBB data, which has most respondents 40 - 70.
if self.age_preprocessing_method == 'subtract_a_constant':
ages = ages - 55.
elif self.age_preprocessing_method == 'divide_by_a_constant':
ages = ages / 70.
elif self.age_preprocessing_method == 'subtract_about_40_and_divide_by_30':
ages = (ages - 39.9) / 30.
else:
raise Exception("Invalid age processing method")
return np.array(ages)
def get_ages(self, df):
ages = np.array(df['age_sex___age'].values, dtype=np.float32)
return self.age_preprocessing_function(ages)
def fit(self,
train_df,
valid_df,
train_lon_df0=None, # lon data at the first and second timepoint, respectively.
train_lon_df1=None,
verbose=True):
print("Fitting model using method %s." % self.__class__.__name__)
assert train_df.shape[1] == valid_df.shape[1]
assert np.all(train_df.columns == valid_df.columns)
train_data = self.data_preprocessing_function(train_df)
valid_data = self.data_preprocessing_function(valid_df)
train_ages = None
valid_ages = None
if self.need_ages:
train_ages = self.get_ages(train_df)
valid_ages = self.get_ages(valid_df)
# preprocess longitudinal data
train_lon_X0 = None
train_lon_X1 = None
train_lon_ages0 = None
train_lon_ages1 = None
if self.uses_longitudinal_data:
assert train_lon_df0 is not None
assert train_lon_df1 is not None
assert len(train_lon_df0) == len(train_lon_df1)
train_lon_X0 = self.data_preprocessing_function(train_lon_df0)
train_lon_X1 = self.data_preprocessing_function(train_lon_df1)
train_lon_ages0 = self.get_ages(train_lon_df0)
train_lon_ages1 = self.get_ages(train_lon_df1)
else:
assert train_lon_df0 is None
assert train_lon_df1 is None
self._fit_from_processed_data(train_data=train_data,
valid_data=valid_data,
train_ages=train_ages,
valid_ages=valid_ages,
train_lon_X0=train_lon_X0,
train_lon_X1=train_lon_X1,
train_lon_ages0=train_lon_ages0,
train_lon_ages1=train_lon_ages1,
verbose=verbose)
def get_regularization_weighting_for_epoch(self, epoch, verbose=True):
if self.regularization_weighting_schedule['schedule_type'] == 'constant':
weighting = self.regularization_weighting_schedule['constant']
elif self.regularization_weighting_schedule['schedule_type'] == 'logistic':
# scales the weighting up following a sigmoid
fraction_of_way_through_training = 1.0 * epoch / self.max_epochs
max_weight = self.regularization_weighting_schedule['max_weight']
slope = self.regularization_weighting_schedule['slope']
intercept = self.regularization_weighting_schedule['intercept']
weighting = max_weight * expit(fraction_of_way_through_training * slope + intercept)
else:
raise Exception("Invalid schedule type.")
assert (weighting <= 1) and (weighting >= 0)
if verbose:
print("Regularization weighting at epoch %i is %2.3e" % (epoch, weighting))
return weighting
def model_features_as_function_of_age(self, data, ages):
"""
given a processed data matrix, computes the age slope and intercept for each feature.
Returns a dictionary where feature names match to age slopes and intercepts.
"""
if len(ages) < 10000:
raise Exception("You are trying to compute age trends on data using very few datapoints. This seems bad.")
assert len(data) == len(ages)
features_to_age_slope_and_intercept = {}
for i, feature in enumerate(self.feature_names):
slope, intercept, _, _, _ = linregress(ages, data[:, i])
features_to_age_slope_and_intercept[feature] = {'slope':slope, 'intercept':intercept}
assert np.abs(pearsonr(data[:, i] - slope * ages - intercept, ages)[0]) < 1e-6
return features_to_age_slope_and_intercept
def decorrelate_data_with_age(self, data, ages):
"""
given a processed data matrix, uses the previously fitted age model to remove age trends from each feature.
Age trends are modeled linearly.
This relies on having previously fitted age_adjusted_models (ie, self.age_adjusted_models should not be None).
"""
decorrelated_data = copy.deepcopy(data)
for i, feature in enumerate(self.feature_names):
slope = self.age_adjusted_models[feature]['slope']
intercept = self.age_adjusted_models[feature]['intercept']
decorrelated_data[:, i] = decorrelated_data[:, i] - slope * ages - intercept
return decorrelated_data
def set_up_encoder_structure(self):
"""
This function sets up the basic encoder structure and return arguments.
Most basic: Z is just a function of X.
"""
self.Z = self.encode(self.X)
def set_up_regularization_loss_structure(self):
"""
This function sets up the basic loss structure. Should define self.reg_loss.
"""
self.reg_loss = tf.zeros(1)
def set_up_longitudinal_loss_and_optimization_structure(self):
"""
Sets up the graph structure for longitudinal loss. Only used if the autoencoder is trained on longitudinal data.
"""
raise NotImplementedError
def _fit_from_processed_data(self,
train_data,
valid_data,
train_ages=None,
valid_ages=None,
train_lon_X0=None,
train_lon_X1=None,
train_lon_ages0=None,
train_lon_ages1=None,
verbose=True):
"""
train_data and valid_data are data matrices
"""
if self.need_ages:
assert train_ages is not None
assert valid_ages is not None
# Compute models for removing age trends. Do this on the train set to avoid any data leakage.
self.age_adjusted_models = self.model_features_as_function_of_age(train_data, train_ages)
self.age_adjusted_train_data = self.decorrelate_data_with_age(train_data, train_ages)
self.age_adjusted_valid_data = self.decorrelate_data_with_age(valid_data, valid_ages)
else:
self.age_adjusted_models = None
self.age_adjusted_train_data = None
self.age_adjusted_valid_data = None
self.train_data = train_data
self.valid_data = valid_data
self.train_ages = train_ages
self.valid_ages = valid_ages
print("Train size %i; valid size %i" % (
self.train_data.shape[0], self.valid_data.shape[0]))
if self.uses_longitudinal_data:
self.train_lon_X0 = train_lon_X0
self.train_lon_X1 = train_lon_X1
self.train_lon_ages0 = train_lon_ages0
self.train_lon_ages1 = train_lon_ages1
print("LONGITUDINAL train data size %i" % self.train_lon_X0.shape[0])
self.graph = tf.Graph()
with self.graph.as_default():
tf.set_random_seed(self.random_seed)
np.random.seed(self.random_seed)
self.X = tf.placeholder(dtype="float32",
shape=[None, len(self.feature_names)],
name='X')
self.age_adjusted_X = tf.placeholder(dtype="float32",
shape=[None, len(self.feature_names)],
name='age_adjusted_X')
self.ages = tf.placeholder(dtype="float32",
shape=None,
name='ages')
self.regularization_weighting = tf.placeholder(dtype="float32", name='regularization_weighting')
self.init_network() # set up the networks that produce the encoder and decoder.
self.get_setter_ops() # set up ops that allow us to directly set network weights
self.set_up_encoder_structure() # set up the basic call signature and return values for the encoder.
self.set_up_regularization_loss_structure() # set up the basic call signature for the regularization loss.
self.Xr = self.decode(self.Z)
# set up losses. self.reg_loss has already been defined in self.set_up_regularization_loss_structure
self.binary_loss, self.continuous_loss = self.get_binary_and_continuous_loss(self.X, self.Xr)
self.combined_loss = (self.binary_loss
+ self.continuous_loss
+ self.regularization_weighting * self.reg_loss)
self.optimizer = self.optimization_method(learning_rate=self.learning_rate).minimize(self.combined_loss)
if self.uses_longitudinal_data:
self.set_up_longitudinal_loss_and_optimization_structure()
init = tf.global_variables_initializer()
# with tf.Session() as self.sess:
#config = tf.ConfigProto(gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=.4))
#self.sess = tf.Session(config=config)
# create a saver object so we can save the model if we want.
self.saver = tf.train.Saver()
self.sess = tf.Session()
self.sess.run(init)
min_valid_loss = np.nan
n_epochs_without_improvement = 0
params = self.sess.run(self.weights)
#print('Norm of params: %s' % np.linalg.norm(params['decoder_h0']))
if self.learn_aging_rate_scaling_factor_from_data:
aging_rate_scaling_factor = self.sess.run(self.aging_rate_scaling_factor)[0]
print("Aging rate scaling factor initialization is %2.3f" % aging_rate_scaling_factor)
for epoch in range(self.max_epochs):
t0 = time.time()
regularization_weighting_for_epoch = self.get_regularization_weighting_for_epoch(
epoch,
verbose=verbose)
self._train_epoch(regularization_weighting_for_epoch)
if (epoch % self.num_epochs_before_eval == 0) or (epoch == self.max_epochs - 1):
# regularization weighting is set to 1 just for the purpose of printing out
# the losses
train_mean_combined_loss, train_mean_binary_loss, \
train_mean_continuous_loss, train_mean_reg_loss = \
self.minibatch_mean_eval(self.train_data,
self.train_ages,
self.age_adjusted_train_data,
regularization_weighting=1.0)
valid_mean_combined_loss, valid_mean_binary_loss, \
valid_mean_continuous_loss, valid_mean_reg_loss = \
self.minibatch_mean_eval(self.valid_data,
self.valid_ages,
self.age_adjusted_valid_data,
regularization_weighting=1.0)
print('Epoch %i:\nTrain: mean loss %2.3f (%2.3f + %2.3f + %2.3f * %2.3f). '
'Valid: mean loss %2.3f (%2.3f + %2.3f + %2.3f * %2.3f)' % (
epoch,
train_mean_combined_loss,
train_mean_binary_loss,
train_mean_continuous_loss,
regularization_weighting_for_epoch,
train_mean_reg_loss,
valid_mean_combined_loss,
valid_mean_binary_loss,
valid_mean_continuous_loss,
regularization_weighting_for_epoch,
valid_mean_reg_loss
))
# log losses so that we can see if the model's training well.
self.all_losses_by_epoch.append({'epoch':epoch,
'train_mean_combined_loss':train_mean_combined_loss,
'train_mean_binary_loss':train_mean_binary_loss,
'train_mean_continuous_loss':train_mean_continuous_loss,
'train_mean_reg_loss':train_mean_reg_loss,
'valid_mean_combined_loss':valid_mean_combined_loss,
'valid_mean_binary_loss':valid_mean_binary_loss,
'valid_mean_continuous_loss':valid_mean_continuous_loss,
'valid_mean_reg_loss':valid_mean_reg_loss})
# print out various diagnostics so we can make sure the model isn't going haywire.
if self.learn_continuous_variance:
continuous_variance = np.exp(self.sess.run(self.log_continuous_variance)[0])
print("Continuous variance is %2.3f" % continuous_variance)
if self.learn_aging_rate_scaling_factor_from_data:
aging_rate_scaling_factor = self.sess.run(self.aging_rate_scaling_factor)[0]
print("Aging rate scaling factor is %2.3f" % aging_rate_scaling_factor)
if 'encoder_h0_sigma' in self.weights:
# make sure latent state for VAE looks ok by printing out diagnostics
if self.include_age_in_encoder_input:
sampled_Z, mu, sigma = self.sess.run([self.Z, self.Z_mu, self.Z_sigma], feed_dict = {self.X:self.train_data, self.ages:self.train_ages})
else:
sampled_Z, mu, sigma = self.sess.run([self.Z, self.Z_mu, self.Z_sigma], feed_dict = {self.X:self.train_data})
sampled_cov_matrix = np.cov(sampled_Z.transpose())
print('mean value of each Z component:')
print(sampled_Z.mean(axis = 0))
if self.need_ages:
print('correlation of each Z component with age:')
for i in range(sampled_Z.shape[1]):
print('%.2f' % pearsonr(sampled_Z[:, i], self.train_ages)[0], end=' ')
print('')
print("diagonal elements of Z covariance matrix:")
print(np.diag(sampled_cov_matrix))
upper_triangle = np.triu_indices(n = sampled_cov_matrix.shape[0], k = 1)
print("mean absolute value of off-diagonal covariance elements: %2.3f" %
(np.abs(sampled_cov_matrix[upper_triangle]).mean()))
if self.can_calculate_Z_mu:
print('mean value of Z_mu')
print(mu.mean(axis = 0))
print("standard deviation of Z_mu (if this is super-close to 0, that's bad)")
print(mu.std(axis = 0, ddof=1))
print('mean value of Z_sigma')
print(sigma.mean(axis = 0))
# fmin ignores nan's, so this handles the case when epoch=0
min_valid_loss = np.fmin(min_valid_loss, valid_mean_combined_loss)
if min_valid_loss < valid_mean_combined_loss:
print('Warning! valid loss not decreasing this epoch')
n_epochs_without_improvement += 1
if n_epochs_without_improvement > self.max_evals_without_improving:
print("No improvement for too long; quitting")
break
else:
n_epochs_without_improvement = 0
if verbose:
print("Total time to run epoch: %2.3f seconds" % (time.time() - t0))
def save_model(self, path_to_save_model):
print("Done training model; saving at path %s." % path_to_save_model)
self.saver.save(self.sess, save_path=path_to_save_model)
def fill_feed_dict(self, data, regularization_weighting, ages=None, idxs=None, age_adjusted_data=None):
"""
Returns a dictionary that has two keys:
self.ages: ages[idxs]
self.X: data[idxs, :]
and handles various parameters being set to None.
"""
if idxs is not None:
# if idxs is not None, we want to take subsets of the data using boolean indices
# if we pass in ages, subset appropriately; otherwise, just set to None to avoid an error.
if ages is not None:
ages_to_use = ages[idxs]
else:
ages_to_use = None
# similarly, if we pass in age_adjusted_data, subset appropriately
# otherwise, just set to None to avoid an error.
if age_adjusted_data is not None:
age_adjusted_data_to_use = age_adjusted_data[idxs, :]
else:
age_adjusted_data_to_use = None
# data will always be not None, so we can safely subset it.
data_to_use = data[idxs, :]
else:
# if we don't pass in indices, we just want to use all the data.
ages_to_use = ages
data_to_use = data
age_adjusted_data_to_use = age_adjusted_data
if self.need_ages:
feed_dict = {
self.ages:ages_to_use,
self.X:data_to_use,
self.age_adjusted_X:age_adjusted_data_to_use,
self.regularization_weighting:regularization_weighting}
else:
feed_dict = {self.X:data_to_use,
self.regularization_weighting:regularization_weighting}
return feed_dict
def minibatch_mean_eval(self, data, ages, age_adjusted_data, regularization_weighting):
"""
Takes in a data matrix and computes the average per-example loss on it.
Note: 'data' in this class is always a matrix.
"""
if self.need_ages:
assert ages is not None
batches = divide_idxs_into_batches(
np.arange(data.shape[0]),
self.batch_size)
mean_combined_loss = 0
mean_binary_loss = 0
mean_continuous_loss = 0
mean_reg_loss = 0
for idxs in batches:
feed_dict = self.fill_feed_dict(data,
regularization_weighting=regularization_weighting,
ages=ages,
idxs=idxs,
age_adjusted_data=age_adjusted_data)
combined_loss, binary_loss, continuous_loss, reg_loss = self.sess.run(
[self.combined_loss, self.binary_loss, self.continuous_loss, self.reg_loss],
feed_dict=feed_dict)
mean_combined_loss += combined_loss * len(idxs) / data.shape[0]
mean_binary_loss += binary_loss * len(idxs) / data.shape[0]
mean_continuous_loss += continuous_loss * len(idxs) / data.shape[0]
mean_reg_loss += reg_loss * len(idxs) / data.shape[0]
return mean_combined_loss, mean_binary_loss, mean_continuous_loss, mean_reg_loss
def _train_epoch(self, regularization_weighting):
# This function takes very few input arguments because we assume it just uses train data,
# which is already stored as fields of the object.
data = self.train_data
ages = self.train_ages
age_adjusted_data = self.age_adjusted_train_data
if self.need_ages:
assert ages is not None
perm = np.arange(data.shape[0])
np.random.shuffle(perm)
data = data[perm, :]
if ages is not None:
ages = ages[perm]
train_batches = divide_idxs_into_batches(
np.arange(data.shape[0]),
self.batch_size)
for idxs in train_batches:
feed_dict = self.fill_feed_dict(data,
regularization_weighting=regularization_weighting,
ages=ages,
idxs=idxs,
age_adjusted_data=age_adjusted_data)
self.sess.run([self.optimizer], feed_dict=feed_dict)
def reconstruct_data(self, Z_df):
"""
Input: n x (k+1) data frame with ID column and k latent components
Output: n x (d+1) data frame with ID column and data projected into the original (post-processed) space
"""
Z = remove_id_and_get_mat(Z_df)
X = self.sess.run(self.Xr, feed_dict={self.Z:Z})
df = add_id(Z=X, df_with_id=Z_df)
df.columns = ['individual_id'] + self.feature_names
return df
def _get_projections_from_processed_data(self, data, ages, project_onto_mean, rotation_matrix=None):
"""
if project_onto_mean=True, projects onto the mean value of Z. Otherwise, samples Z.
If rotation_matrix is passed in, rotates Z by multiplying by the rotation matrix after projecting it.
"""
if rotation_matrix is not None:
print("Rotating Z by the rotation matrix!")
chunk_size = 10000 # break into chunks so GPU doesn't run out of memory BOOO.
start = 0
Zs = []
while start < len(data):
data_i = data[start:(start + chunk_size),]
ages_i = ages[start:(start + chunk_size)]
start += chunk_size
if project_onto_mean:
if self.can_calculate_Z_mu:
# if we have a closed form for Z_mu, use this for Z.
Z = self.sess.run(self.Z_mu, feed_dict = {self.X:data_i, self.ages:ages_i})
else:
# otherwise, compute 100 replicates, take mean.
n_replicates = 100
print('number of replicates to compute Z_mu: %i' % n_replicates)
for replicate_idx in range(n_replicates):
replicate_Z = self.sess.run(self.Z, feed_dict = {self.X:data_i, self.ages:ages_i})
if replicate_idx == 0:
Z = replicate_Z
else:
Z += replicate_Z
Z = Z / n_replicates
else:
Z = self.sess.run(self.Z, feed_dict = {self.X:data_i, self.ages:ages_i})
if rotation_matrix is not None:
Z = np.dot(Z, rotation_matrix)
Zs.append(Z)
Z = np.vstack(Zs)
#print("Shape of autoencoder projections is", Z.shape)
return Z
| [
"multiphenotype_utils.partition_dataframe_into_binary_and_continuous",
"numpy.random.seed",
"numpy.abs",
"numpy.arange",
"numpy.diag",
"tensorflow.sqrt",
"tensorflow.gather",
"multiphenotype_utils.remove_id_and_get_mat",
"tensorflow.set_random_seed",
"tensorflow.placeholder",
"scipy.stats.linreg... | [((4661, 4700), 'copy.deepcopy', 'copy.deepcopy', (['self.binary_feature_idxs'], {}), '(self.binary_feature_idxs)\n', (4674, 4700), False, 'import copy\n'), ((4739, 4782), 'copy.deepcopy', 'copy.deepcopy', (['self.continuous_feature_idxs'], {}), '(self.continuous_feature_idxs)\n', (4752, 4782), False, 'import copy\n'), ((4811, 4844), 'copy.deepcopy', 'copy.deepcopy', (['self.feature_names'], {}), '(self.feature_names)\n', (4824, 4844), False, 'import copy\n'), ((4956, 5006), 'multiphenotype_utils.partition_dataframe_into_binary_and_continuous', 'partition_dataframe_into_binary_and_continuous', (['df'], {}), '(df)\n', (5002, 5006), False, 'from multiphenotype_utils import get_continuous_features_as_matrix, add_id, remove_id_and_get_mat, partition_dataframe_into_binary_and_continuous, divide_idxs_into_batches\n'), ((6134, 6147), 'multiphenotype_utils.add_id', 'add_id', (['Z', 'df'], {}), '(Z, df)\n', (6140, 6147), False, 'from multiphenotype_utils import get_continuous_features_as_matrix, add_id, remove_id_and_get_mat, partition_dataframe_into_binary_and_continuous, divide_idxs_into_batches\n'), ((8664, 8678), 'numpy.array', 'np.array', (['ages'], {}), '(ages)\n', (8672, 8678), True, 'import numpy as np\n'), ((8727, 8781), 'numpy.array', 'np.array', (["df['age_sex___age'].values"], {'dtype': 'np.float32'}), "(df['age_sex___age'].values, dtype=np.float32)\n", (8735, 8781), True, 'import numpy as np\n'), ((9218, 9262), 'numpy.all', 'np.all', (['(train_df.columns == valid_df.columns)'], {}), '(train_df.columns == valid_df.columns)\n', (9224, 9262), True, 'import numpy as np\n'), ((13228, 13247), 'copy.deepcopy', 'copy.deepcopy', (['data'], {}), '(data)\n', (13241, 13247), False, 'import copy\n'), ((13991, 14002), 'tensorflow.zeros', 'tf.zeros', (['(1)'], {}), '(1)\n', (13999, 14002), True, 'import tensorflow as tf\n'), ((16159, 16169), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (16167, 16169), True, 'import tensorflow as tf\n'), ((29633, 29657), 'numpy.arange', 'np.arange', (['data.shape[0]'], {}), '(data.shape[0])\n', (29642, 29657), True, 'import numpy as np\n'), ((29666, 29689), 'numpy.random.shuffle', 'np.random.shuffle', (['perm'], {}), '(perm)\n', (29683, 29689), True, 'import numpy as np\n'), ((30620, 30647), 'multiphenotype_utils.remove_id_and_get_mat', 'remove_id_and_get_mat', (['Z_df'], {}), '(Z_df)\n', (30641, 30647), False, 'from multiphenotype_utils import get_continuous_features_as_matrix, add_id, remove_id_and_get_mat, partition_dataframe_into_binary_and_continuous, divide_idxs_into_batches\n'), ((30719, 30747), 'multiphenotype_utils.add_id', 'add_id', ([], {'Z': 'X', 'df_with_id': 'Z_df'}), '(Z=X, df_with_id=Z_df)\n', (30725, 30747), False, 'from multiphenotype_utils import get_continuous_features_as_matrix, add_id, remove_id_and_get_mat, partition_dataframe_into_binary_and_continuous, divide_idxs_into_batches\n'), ((32676, 32689), 'numpy.vstack', 'np.vstack', (['Zs'], {}), '(Zs)\n', (32685, 32689), True, 'import numpy as np\n'), ((6455, 6509), 'tensorflow.gather', 'tf.gather', (['X'], {'indices': 'self.binary_feature_idxs', 'axis': '(1)'}), '(X, indices=self.binary_feature_idxs, axis=1)\n', (6464, 6509), True, 'import tensorflow as tf\n'), ((6669, 6727), 'tensorflow.gather', 'tf.gather', (['X'], {'indices': 'self.continuous_feature_idxs', 'axis': '(1)'}), '(X, indices=self.continuous_feature_idxs, axis=1)\n', (6678, 6727), True, 'import tensorflow as tf\n'), ((7034, 7057), 'tensorflow.sqrt', 'tf.sqrt', (['(2.0 / shape[0])'], {}), '(2.0 / shape[0])\n', (7041, 7057), True, 'import tensorflow as tf\n'), ((7100, 7167), 'tensorflow.random_normal', 'tf.random_normal', ([], {'shape': 'shape', 'stddev': 'stddev', 'seed': 'self.random_seed'}), '(shape=shape, stddev=stddev, seed=self.random_seed)\n', (7116, 7167), True, 'import tensorflow as tf\n'), ((12572, 12600), 'scipy.stats.linregress', 'linregress', (['ages', 'data[:, i]'], {}), '(ages, data[:, i])\n', (12582, 12600), False, 'from scipy.stats import pearsonr, linregress\n'), ((16220, 16256), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['self.random_seed'], {}), '(self.random_seed)\n', (16238, 16256), True, 'import tensorflow as tf\n'), ((16269, 16301), 'numpy.random.seed', 'np.random.seed', (['self.random_seed'], {}), '(self.random_seed)\n', (16283, 16301), True, 'import numpy as np\n'), ((16731, 16787), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': '"""float32"""', 'shape': 'None', 'name': '"""ages"""'}), "(dtype='float32', shape=None, name='ages')\n", (16745, 16787), True, 'import tensorflow as tf\n'), ((16912, 16976), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': '"""float32"""', 'name': '"""regularization_weighting"""'}), "(dtype='float32', name='regularization_weighting')\n", (16926, 16976), True, 'import tensorflow as tf\n'), ((18162, 18195), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (18193, 18195), True, 'import tensorflow as tf\n'), ((18522, 18538), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (18536, 18538), True, 'import tensorflow as tf\n'), ((18563, 18575), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (18573, 18575), True, 'import tensorflow as tf\n'), ((28054, 28078), 'numpy.arange', 'np.arange', (['data.shape[0]'], {}), '(data.shape[0])\n', (28063, 28078), True, 'import numpy as np\n'), ((29841, 29865), 'numpy.arange', 'np.arange', (['data.shape[0]'], {}), '(data.shape[0])\n', (29850, 29865), True, 'import numpy as np\n'), ((19167, 19178), 'time.time', 'time.time', ([], {}), '()\n', (19176, 19178), False, 'import time\n'), ((32608, 32634), 'numpy.dot', 'np.dot', (['Z', 'rotation_matrix'], {}), '(Z, rotation_matrix)\n', (32614, 32634), True, 'import numpy as np\n'), ((11654, 11713), 'scipy.special.expit', 'expit', (['(fraction_of_way_through_training * slope + intercept)'], {}), '(fraction_of_way_through_training * slope + intercept)\n', (11659, 11713), False, 'from scipy.special import expit\n'), ((25019, 25068), 'numpy.fmin', 'np.fmin', (['min_valid_loss', 'valid_mean_combined_loss'], {}), '(min_valid_loss, valid_mean_combined_loss)\n', (25026, 25068), True, 'import numpy as np\n'), ((6564, 6575), 'tensorflow.shape', 'tf.shape', (['X'], {}), '(X)\n', (6572, 6575), True, 'import tensorflow as tf\n'), ((6786, 6797), 'tensorflow.shape', 'tf.shape', (['X'], {}), '(X)\n', (6794, 6797), True, 'import tensorflow as tf\n'), ((12725, 12778), 'scipy.stats.pearsonr', 'pearsonr', (['(data[:, i] - slope * ages - intercept)', 'ages'], {}), '(data[:, i] - slope * ages - intercept, ages)\n', (12733, 12778), False, 'from scipy.stats import pearsonr, linregress\n'), ((24173, 24224), 'numpy.triu_indices', 'np.triu_indices', ([], {'n': 'sampled_cov_matrix.shape[0]', 'k': '(1)'}), '(n=sampled_cov_matrix.shape[0], k=1)\n', (24188, 24224), True, 'import numpy as np\n'), ((24103, 24130), 'numpy.diag', 'np.diag', (['sampled_cov_matrix'], {}), '(sampled_cov_matrix)\n', (24110, 24130), True, 'import numpy as np\n'), ((25662, 25673), 'time.time', 'time.time', ([], {}), '()\n', (25671, 25673), False, 'import time\n'), ((24358, 24400), 'numpy.abs', 'np.abs', (['sampled_cov_matrix[upper_triangle]'], {}), '(sampled_cov_matrix[upper_triangle])\n', (24364, 24400), True, 'import numpy as np\n'), ((23904, 23946), 'scipy.stats.pearsonr', 'pearsonr', (['sampled_Z[:, i]', 'self.train_ages'], {}), '(sampled_Z[:, i], self.train_ages)\n', (23912, 23946), False, 'from scipy.stats import pearsonr, linregress\n')] |
import cv2
import imutils
import numpy as np
import os
import concurrent.futures
MAX_MATCHS = 5000
GOOD_RATE = 0.3
def align_imgs(template_img, origin_img):
'''
Args:
template_img: template image
origin_img: origin image
Function:
align the template image to origin image
'''
template_gray = cv2.cvtColor(template_img, cv2.COLOR_BGR2GRAY)
origin_gray = cv2.cvtColor(origin_img, cv2.COLOR_BGR2GRAY)
orb = cv2.ORB_create(MAX_MATCHS)
kpsA = orb.detect(template_gray, None)
kpsB = orb.detect(origin_gray, None)
# (kpsA, descsA) = orb.detectAndCompute(template_gray, None)
# (kpsB, descsB) = orb.detectAndCompute(origin_gray, None)
descriptor = cv2.xfeatures2d.BEBLID_create(0.75)
kpsA, descsA = descriptor.compute(template_gray, kpsA)
kpsB, descsB = descriptor.compute(origin_gray, kpsB)
if len(kpsA) == 0 or len(kpsB) == 0:
return template_img.copy()
# match the features
method = cv2.DESCRIPTOR_MATCHER_BRUTEFORCE_HAMMING
matcher = cv2.DescriptorMatcher_create(method)
# matches = matcher.match(descsA, descsB, None)
# matches = sorted(matches, key=lambda x: x.distance)
nn_matches = matcher.knnMatch(descsA, descsB, 2)
matched1 = []
matched2 = []
nn_match_ratio = 0.8 # Nearest neighbor matching ratio
if len(nn_matches) < 4 or len(nn_matches[0]) == 1:
return template_img.copy()
for m, n in nn_matches:
if m.distance < nn_match_ratio * n.distance:
matched1.append(kpsA[m.queryIdx])
matched2.append(kpsB[m.trainIdx])
if len(matched1) < 4:
return template_img.copy()
ptsA = np.zeros((len(matched1), 2), dtype="float")
ptsB = np.zeros((len(matched1), 2), dtype="float")
for i in range(len(matched1)):
ptsA[i] = matched1[i].pt
ptsB[i] = matched2[i].pt
# keep only the top matches
# keep = int(len(matches) * GOOD_RATE)
# if keep < 4:
# return template_img.copy()
# matches = matches[:keep]
# ptsA = np.zeros((len(matches), 2), dtype="float")
# ptsB = np.zeros((len(matches), 2), dtype="float")
# # loop over the top matches
# for (i, m) in enumerate(matches):
# # indicate that the two keypoints in the respective images
# # map to each other
# ptsA[i] = kpsA[m.queryIdx].pt
# ptsB[i] = kpsB[m.trainIdx].pt
# compute the homography matrix between the two sets of matched
# points
(H, mask) = cv2.findHomography(ptsA, ptsB, method=cv2.RANSAC)
if H is None:
return template_img.copy()
# use the homography matrix to align the images
(h, w) = origin_img.shape[:2]
aligned = cv2.warpPerspective(template_img, H, (w, h))
# copy the black area background from origin image to aligned image
lower = np.array([0, 0, 0])
upper = np.array([10, 10, 10])
shapeMask = cv2.inRange(aligned, lower, upper)
mask = np.where(shapeMask == 255)
aligned[mask[0], mask[1], :] = origin_img[mask[0], mask[1], :]
# shapeMask = np.tile(shapeMask[:, :, None], [1, 1, 3])
# aligned = aligned + origin_img * shapeMask
return aligned
def process(img_name):
template_img_name = '{}_t.jpg'.format(img_name.split('.')[0])
origin_img = cv2.imread(os.path.join(train_folder, img_name))
template_img = cv2.imread(os.path.join(template_folder, template_img_name))
aligned_img = align_imgs(template_img, origin_img)
cv2.imwrite(os.path.join(saved_folder, template_img_name), aligned_img)
print('Finish {}'.format(img_name))
if __name__ == '__main__':
root_path = '/ssd/huangyifei/data_guangdong/tile_round2'
train_folder = os.path.join(root_path, 'train_imgs')
template_folder = os.path.join(root_path, 'train_template_imgs')
saved_folder = '/ssd/huangyifei/data_guangdong/tile_round2/template_aligned_v2'
if not os.path.exists(saved_folder):
os.mkdir(saved_folder)
img_names = os.listdir(train_folder)
data = cv2.imread(
'data/data_guangdong/tile_round2/train_imgs/272_97_t20201215160809596_CAM1_0.jpg'
)
data_t = cv2.imread(
'data/data_guangdong/tile_round2/train_template_imgs/272_97_t20201215160809596_CAM1_0_t.jpg'
)
aligned = align_imgs(data_t, data)
img = np.vstack([data, aligned])
cv2.imwrite('test.jpg', img)
# with concurrent.futures.ThreadPoolExecutor(max_workers=40) as executor:
# for img_name in img_names:
# executor.submit(process, img_name) | [
"os.mkdir",
"cv2.warpPerspective",
"cv2.xfeatures2d.BEBLID_create",
"os.path.join",
"cv2.cvtColor",
"cv2.imwrite",
"os.path.exists",
"cv2.inRange",
"cv2.imread",
"numpy.where",
"cv2.ORB_create",
"numpy.array",
"cv2.DescriptorMatcher_create",
"cv2.findHomography",
"os.listdir",
"numpy.v... | [((340, 386), 'cv2.cvtColor', 'cv2.cvtColor', (['template_img', 'cv2.COLOR_BGR2GRAY'], {}), '(template_img, cv2.COLOR_BGR2GRAY)\n', (352, 386), False, 'import cv2\n'), ((405, 449), 'cv2.cvtColor', 'cv2.cvtColor', (['origin_img', 'cv2.COLOR_BGR2GRAY'], {}), '(origin_img, cv2.COLOR_BGR2GRAY)\n', (417, 449), False, 'import cv2\n'), ((461, 487), 'cv2.ORB_create', 'cv2.ORB_create', (['MAX_MATCHS'], {}), '(MAX_MATCHS)\n', (475, 487), False, 'import cv2\n'), ((718, 753), 'cv2.xfeatures2d.BEBLID_create', 'cv2.xfeatures2d.BEBLID_create', (['(0.75)'], {}), '(0.75)\n', (747, 753), False, 'import cv2\n'), ((1042, 1078), 'cv2.DescriptorMatcher_create', 'cv2.DescriptorMatcher_create', (['method'], {}), '(method)\n', (1070, 1078), False, 'import cv2\n'), ((2508, 2557), 'cv2.findHomography', 'cv2.findHomography', (['ptsA', 'ptsB'], {'method': 'cv2.RANSAC'}), '(ptsA, ptsB, method=cv2.RANSAC)\n', (2526, 2557), False, 'import cv2\n'), ((2712, 2756), 'cv2.warpPerspective', 'cv2.warpPerspective', (['template_img', 'H', '(w, h)'], {}), '(template_img, H, (w, h))\n', (2731, 2756), False, 'import cv2\n'), ((2842, 2861), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (2850, 2861), True, 'import numpy as np\n'), ((2874, 2896), 'numpy.array', 'np.array', (['[10, 10, 10]'], {}), '([10, 10, 10])\n', (2882, 2896), True, 'import numpy as np\n'), ((2913, 2947), 'cv2.inRange', 'cv2.inRange', (['aligned', 'lower', 'upper'], {}), '(aligned, lower, upper)\n', (2924, 2947), False, 'import cv2\n'), ((2959, 2985), 'numpy.where', 'np.where', (['(shapeMask == 255)'], {}), '(shapeMask == 255)\n', (2967, 2985), True, 'import numpy as np\n'), ((3700, 3737), 'os.path.join', 'os.path.join', (['root_path', '"""train_imgs"""'], {}), "(root_path, 'train_imgs')\n", (3712, 3737), False, 'import os\n'), ((3760, 3806), 'os.path.join', 'os.path.join', (['root_path', '"""train_template_imgs"""'], {}), "(root_path, 'train_template_imgs')\n", (3772, 3806), False, 'import os\n'), ((3981, 4005), 'os.listdir', 'os.listdir', (['train_folder'], {}), '(train_folder)\n', (3991, 4005), False, 'import os\n'), ((4018, 4121), 'cv2.imread', 'cv2.imread', (['"""data/data_guangdong/tile_round2/train_imgs/272_97_t20201215160809596_CAM1_0.jpg"""'], {}), "(\n 'data/data_guangdong/tile_round2/train_imgs/272_97_t20201215160809596_CAM1_0.jpg'\n )\n", (4028, 4121), False, 'import cv2\n'), ((4139, 4253), 'cv2.imread', 'cv2.imread', (['"""data/data_guangdong/tile_round2/train_template_imgs/272_97_t20201215160809596_CAM1_0_t.jpg"""'], {}), "(\n 'data/data_guangdong/tile_round2/train_template_imgs/272_97_t20201215160809596_CAM1_0_t.jpg'\n )\n", (4149, 4253), False, 'import cv2\n'), ((4309, 4335), 'numpy.vstack', 'np.vstack', (['[data, aligned]'], {}), '([data, aligned])\n', (4318, 4335), True, 'import numpy as np\n'), ((4340, 4368), 'cv2.imwrite', 'cv2.imwrite', (['"""test.jpg"""', 'img'], {}), "('test.jpg', img)\n", (4351, 4368), False, 'import cv2\n'), ((3302, 3338), 'os.path.join', 'os.path.join', (['train_folder', 'img_name'], {}), '(train_folder, img_name)\n', (3314, 3338), False, 'import os\n'), ((3370, 3418), 'os.path.join', 'os.path.join', (['template_folder', 'template_img_name'], {}), '(template_folder, template_img_name)\n', (3382, 3418), False, 'import os\n'), ((3491, 3536), 'os.path.join', 'os.path.join', (['saved_folder', 'template_img_name'], {}), '(saved_folder, template_img_name)\n', (3503, 3536), False, 'import os\n'), ((3903, 3931), 'os.path.exists', 'os.path.exists', (['saved_folder'], {}), '(saved_folder)\n', (3917, 3931), False, 'import os\n'), ((3941, 3963), 'os.mkdir', 'os.mkdir', (['saved_folder'], {}), '(saved_folder)\n', (3949, 3963), False, 'import os\n')] |
from ..errors import logger
from ..stats._rolling_stats import rolling_stats
import numpy as np
def _nan_reshape(Xd, no_data):
Xd[np.isnan(Xd) | np.isinf(Xd)] = no_data
return Xd[:, np.newaxis]
def _mean(X, axis=1, no_data=0):
"""
Computes the mean
"""
X_ = X.mean(axis=axis)
return _nan_reshape(X_, no_data)
def _cv(X, axis=1, no_data=0):
"""
Computes the coefficient of variation
"""
X_ = X.std(axis=axis) / X.mean(axis=axis)
return _nan_reshape(X_, no_data)
def _five_cumulative(X, axis=1, no_data=0):
"""
Computes the value at the cumulative 5th percentile
"""
x_range = list(range(0, X.shape[1]+1))
# Cumulative sum
X_ = X.cumsum(axis=axis)
# Position at the nth percentile
pct_idx = int(np.ceil(np.percentile(x_range, 5)))
# Values at the nth percentile
X_ = X_[:, pct_idx]
return _nan_reshape(X_, no_data)
def _twenty_five_cumulative(X, axis=1, no_data=0):
"""
Computes the value at the cumulative 25th percentile
"""
x_range = list(range(0, X.shape[1]+1))
# Cumulative sum
X_ = X.cumsum(axis=axis)
# Position at the nth percentile
pct_idx = int(np.ceil(np.percentile(x_range, 25)))
# Values at the nth percentile
X_ = X_[:, pct_idx]
return _nan_reshape(X_, no_data)
def _fifty_cumulative(X, axis=1, no_data=0):
"""
Computes the value at the cumulative 50th percentile
"""
x_range = list(range(0, X.shape[1]+1))
# Cumulative sum
X_ = X.cumsum(axis=axis)
# Position at the nth percentile
pct_idx = int(np.ceil(np.percentile(x_range, 50)))
# Values at the nth percentile
X_ = X_[:, pct_idx]
return _nan_reshape(X_, no_data)
def _seventy_five_cumulative(X, axis=1, no_data=0):
"""
Computes the value at the cumulative 75th percentile
"""
x_range = list(range(0, X.shape[1]+1))
# Cumulative sum
X_ = X.cumsum(axis=axis)
# Position at the nth percentile
pct_idx = int(np.ceil(np.percentile(x_range, 75)))
# Values at the nth percentile
X_ = X_[:, pct_idx]
return _nan_reshape(X_, no_data)
def _ninety_five_cumulative(X, axis=1, no_data=0):
"""
Computes the value at the cumulative 95th percentile
"""
x_range = list(range(0, X.shape[1]+1))
# Cumulative sum
X_ = X.cumsum(axis=axis)
# Position at the nth percentile
pct_idx = int(np.ceil(np.percentile(x_range, 95)))
# Values at the nth percentile
X_ = X_[:, pct_idx]
return _nan_reshape(X_, no_data)
def _five(X, axis=1, no_data=0):
"""
Computes the 5th percentile
"""
X_ = np.percentile(X, 5, axis=axis)
return _nan_reshape(X_, no_data)
def _twenty_five(X, axis=1, no_data=0):
"""
Computes the 25th percentile
"""
X_ = np.percentile(X, 25, axis=axis)
return _nan_reshape(X_, no_data)
def _fifty(X, axis=1, no_data=0):
"""
Computes the 50th percentile (median)
"""
X_ = np.percentile(X, 50, axis=axis)
return _nan_reshape(X_, no_data)
def _seventy_five(X, axis=1, no_data=0):
"""
Computes the 75th percentile
"""
X_ = np.percentile(X, 75, axis=axis)
return _nan_reshape(X_, no_data)
def _ninety_five(X, axis=1, no_data=0):
"""
Computes the 95th percentile
"""
X_ = np.percentile(X, 95, axis=axis)
return _nan_reshape(X_, no_data)
def _slopes(X, axis=None, no_data=0):
"""
Computes min. and max. moving slope
"""
# Reshape to [dims x samples].
X_min, X_max = rolling_stats(X.T,
stat='slope',
window_size=15)
return np.hstack((_nan_reshape(X_min, no_data),
_nan_reshape(X_min, no_data)))
def _max_diff(X, axis=1, no_data=0):
"""
Computes the maximum difference
"""
X_ = np.abs(np.diff(X, n=2, axis=axis)).max(axis=axis)
return _nan_reshape(X_, no_data)
class TimeSeriesFeatures(object):
def __init__(self):
self.ts_funcs = None
self._func_dict = dict(mean=_mean,
cv=_cv,
five=_five,
twenty_five=_twenty_five,
fifty=_fifty,
seventy_five=_seventy_five,
ninety_five=_ninety_five,
five_cumulative=_five_cumulative,
twenty_five_cumulative=_twenty_five_cumulative,
fifty_cumulative=_fifty_cumulative,
seventy_five_cumulative=_seventy_five_cumulative,
ninety_five_cumulative=_ninety_five_cumulative,
slopes=_slopes)
def add_features(self, feature_list):
"""
Adds features
Args:
feature_list (str list): A list of features to add.
Choices are:
'cv'
'mean'
'five'
'twenty_five'
'fifty'
'seventy_five'
'ninety_five'
'five_cumulative'
'twenty_five_cumulative'
'fifty_cumulative'
'seventy_five_cumulative'
'ninety_five_cumulative'
'slopes'
"""
self.ts_funcs = [(feature_name, self._func_dict[feature_name]) for feature_name in feature_list
if feature_name in self._func_dict]
def apply_features(self, X=None, ts_indices=None, append_features=True, **kwargs):
"""
Applies features to an array
Args:
X (Optional[2d array]): The array to add features to.
ts_indices (Optional[1-d array like]): A list of indices to index the time series. Default is None.
append_features (Optional[bool]): Whether to append features to `X`. Default is True.
"""
if not isinstance(self.ts_funcs, list):
logger.error(' The features must be added with `add_features`.')
if not append_features:
Xnew = None
for ts_func in self.ts_funcs:
if isinstance(ts_indices, np.ndarray) or isinstance(ts_indices, list):
if append_features:
X = np.hstack((X,
ts_func[1](X[:, ts_indices],
**kwargs)))
else:
if isinstance(Xnew, np.ndarray):
Xnew = np.hstack((Xnew,
ts_func[1](X[:, ts_indices],
**kwargs)))
else:
Xnew = ts_func[1](X[:, ts_indices],
**kwargs)
else:
if append_features:
X = np.hstack((X,
ts_func[1](X,
**kwargs)))
else:
if isinstance(Xnew, np.ndarray):
Xnew = np.hstack((Xnew,
ts_func[1](X,
**kwargs)))
else:
Xnew = ts_func[1](X,
**kwargs)
if append_features:
return X
else:
return Xnew
| [
"numpy.percentile",
"numpy.diff",
"numpy.isinf",
"numpy.isnan"
] | [((2669, 2699), 'numpy.percentile', 'np.percentile', (['X', '(5)'], {'axis': 'axis'}), '(X, 5, axis=axis)\n', (2682, 2699), True, 'import numpy as np\n'), ((2840, 2871), 'numpy.percentile', 'np.percentile', (['X', '(25)'], {'axis': 'axis'}), '(X, 25, axis=axis)\n', (2853, 2871), True, 'import numpy as np\n'), ((3015, 3046), 'numpy.percentile', 'np.percentile', (['X', '(50)'], {'axis': 'axis'}), '(X, 50, axis=axis)\n', (3028, 3046), True, 'import numpy as np\n'), ((3188, 3219), 'numpy.percentile', 'np.percentile', (['X', '(75)'], {'axis': 'axis'}), '(X, 75, axis=axis)\n', (3201, 3219), True, 'import numpy as np\n'), ((3360, 3391), 'numpy.percentile', 'np.percentile', (['X', '(95)'], {'axis': 'axis'}), '(X, 95, axis=axis)\n', (3373, 3391), True, 'import numpy as np\n'), ((138, 150), 'numpy.isnan', 'np.isnan', (['Xd'], {}), '(Xd)\n', (146, 150), True, 'import numpy as np\n'), ((153, 165), 'numpy.isinf', 'np.isinf', (['Xd'], {}), '(Xd)\n', (161, 165), True, 'import numpy as np\n'), ((802, 827), 'numpy.percentile', 'np.percentile', (['x_range', '(5)'], {}), '(x_range, 5)\n', (815, 827), True, 'import numpy as np\n'), ((1214, 1240), 'numpy.percentile', 'np.percentile', (['x_range', '(25)'], {}), '(x_range, 25)\n', (1227, 1240), True, 'import numpy as np\n'), ((1621, 1647), 'numpy.percentile', 'np.percentile', (['x_range', '(50)'], {}), '(x_range, 50)\n', (1634, 1647), True, 'import numpy as np\n'), ((2035, 2061), 'numpy.percentile', 'np.percentile', (['x_range', '(75)'], {}), '(x_range, 75)\n', (2048, 2061), True, 'import numpy as np\n'), ((2448, 2474), 'numpy.percentile', 'np.percentile', (['x_range', '(95)'], {}), '(x_range, 95)\n', (2461, 2474), True, 'import numpy as np\n'), ((3912, 3938), 'numpy.diff', 'np.diff', (['X'], {'n': '(2)', 'axis': 'axis'}), '(X, n=2, axis=axis)\n', (3919, 3938), True, 'import numpy as np\n')] |
import os
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from model import Net
import json
from tqdm import tqdm
import numpy as np
import h5py
from data import get_extract_data
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
np.random.seed(1234)
import pickle
def save_dict(di_, filename_):
with open(filename_, 'wb') as f:
pickle.dump(di_, f)
def load_dict(filename_):
with open(filename_, 'rb') as f:
ret_dict = pickle.load(f)
return ret_dict
model = Net()
model = model.eval()
print(model)
GPU = True
if GPU:
gpus = '0,1,2,3,4,5,6,7'
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = gpus
device_ids = [i for i in range(torch.cuda.device_count())]
if torch.cuda.device_count() > 1:
print("\n\nLet's use", torch.cuda.device_count(), "GPUs!\n\n")
if len(device_ids)>1:
model = nn.DataParallel(model, device_ids = device_ids).cuda()
else:
model = model.cuda()
src = 'datasets/NUS-WIDE/features/'
jsons = ['81_only_full_nus_wide_train', '81_only_full_nus_wide_test']
# img_names = []
# for data_ in tqdm(data_loader):
# filenames = data_[0]
# for filename in filenames:
# img_names.append(filename.replace('/', '_'))
# dict_ = {'img_names':img_names}
# save_dict(dict_, os.path.join(src, 'test_img_names.pkl'))
for json_ in jsons:
if json_ == '81_only_full_nus_wide_train':
pickle_name='img_names_train_81.pkl'
else:
pickle_name='img_names_test_81.pkl'
type_ = 'Flickr'
dataset_ = get_extract_data(
dir_ = os.path.join('/home/ag1/akshita/multi-label-zsl','data/{}'.format(type_)),
json_file = os.path.join(src, json_+'.json'))
data_loader = DataLoader(dataset=dataset_, batch_size=128, shuffle=False, num_workers=32, drop_last=False)
img_names = []
fn = os.path.join(src, json_+'_CONV5_4_VGG_NO_CENTERCROP_compressed_gzip.h5')
with h5py.File(fn, mode='w') as h5f:
for data_ in tqdm(data_loader):
filename, img, lab = data_[0], data_[1], data_[2]
# filename, img, lab, lab_81, lab_925 = data_[0], data_[1], data_[2], data_[3], data_[4]
bs = img.size(0)
if GPU:
img = img.cuda()
with torch.no_grad():
out = model(img)
out = np.float32(out.cpu().numpy())
labels = np.int8(lab.numpy())
# labels_81 = np.int8(lab_81.numpy())
# labels_925 = np.int8(lab_925.numpy())
# import pdb;pdb.set_trace()
for i in range(bs):
if np.isnan(out[i].any()):
print(filename[i])
import pdb; pdb.set_trace()
img_names.append(filename[i].replace('/', '_'))
h5f.create_dataset(filename[i].replace('/', '_')+'-features', data=out[i], dtype=np.float32, compression="gzip")
h5f.create_dataset(filename[i].replace('/', '_')+'-labels', data=labels[i], dtype=np.int8, compression="gzip")
dict_ = {'img_names':img_names}
save_dict(dict_, os.path.join(src, pickle_name))
h5f.close() | [
"pickle.dump",
"h5py.File",
"numpy.random.seed",
"tqdm.tqdm",
"torch.utils.data.DataLoader",
"model.Net",
"torch.cuda.device_count",
"pickle.load",
"pdb.set_trace",
"torch.nn.DataParallel",
"torch.no_grad",
"os.path.join"
] | [((285, 305), 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), '(1234)\n', (299, 305), True, 'import numpy as np\n'), ((547, 552), 'model.Net', 'Net', ([], {}), '()\n', (550, 552), False, 'from model import Net\n'), ((1826, 1922), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'dataset_', 'batch_size': '(128)', 'shuffle': '(False)', 'num_workers': '(32)', 'drop_last': '(False)'}), '(dataset=dataset_, batch_size=128, shuffle=False, num_workers=32,\n drop_last=False)\n', (1836, 1922), False, 'from torch.utils.data import DataLoader\n'), ((1948, 2022), 'os.path.join', 'os.path.join', (['src', "(json_ + '_CONV5_4_VGG_NO_CENTERCROP_compressed_gzip.h5')"], {}), "(src, json_ + '_CONV5_4_VGG_NO_CENTERCROP_compressed_gzip.h5')\n", (1960, 2022), False, 'import os\n'), ((397, 416), 'pickle.dump', 'pickle.dump', (['di_', 'f'], {}), '(di_, f)\n', (408, 416), False, 'import pickle\n'), ((500, 514), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (511, 514), False, 'import pickle\n'), ((803, 828), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (826, 828), False, 'import torch\n'), ((2031, 2054), 'h5py.File', 'h5py.File', (['fn'], {'mode': '"""w"""'}), "(fn, mode='w')\n", (2040, 2054), False, 'import h5py\n'), ((2084, 2101), 'tqdm.tqdm', 'tqdm', (['data_loader'], {}), '(data_loader)\n', (2088, 2101), False, 'from tqdm import tqdm\n'), ((863, 888), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (886, 888), False, 'import torch\n'), ((1772, 1806), 'os.path.join', 'os.path.join', (['src', "(json_ + '.json')"], {}), "(src, json_ + '.json')\n", (1784, 1806), False, 'import os\n'), ((3198, 3228), 'os.path.join', 'os.path.join', (['src', 'pickle_name'], {}), '(src, pickle_name)\n', (3210, 3228), False, 'import os\n'), ((768, 793), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (791, 793), False, 'import torch\n'), ((946, 991), 'torch.nn.DataParallel', 'nn.DataParallel', (['model'], {'device_ids': 'device_ids'}), '(model, device_ids=device_ids)\n', (961, 991), True, 'import torch.nn as nn\n'), ((2365, 2380), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2378, 2380), False, 'import torch\n'), ((2796, 2811), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (2809, 2811), False, 'import pdb\n')] |
from abc import ABC
from dataclasses import dataclass
from enum import IntEnum
from functools import lru_cache
from typing import Any, Dict, List, Tuple, Type, Union
import numpy as np
import toolz
try:
from functools import cached_property
except:
from backports.cached_property import cached_property
from scipy.stats import rv_continuous
from colosseum.mdps import MDP
from colosseum.mdps.base_mdp import NextStateSampler
from colosseum.utils.random_vars import deterministic
@dataclass(frozen=True)
class CustomNode:
ID: int
def __str__(self):
return str(self.ID + 1)
class CustomMDP(MDP, ABC):
@staticmethod
def testing_parameters() -> Dict[str, List]:
t_params = MDP.testing_parameters()
num_states = 4
num_actions = 2
T = np.zeros((num_states, num_actions, num_states), dtype=np.float32)
T[0, 0, 1] = 1.0
T[0, 1, 2] = 1.0
T[1, 0, 2] = T[1, 0, 3] = 0.5
T[1, 1, 2] = T[1, 1, 3] = 0.1
T[1, 1, 1] = 0.8
T[2, 0, 1] = T[2, 0, 3] = 0.5
T[2, 1, 1] = T[2, 1, 3] = 0.1
T[2, 1, 2] = 0.8
T[3, 0, 0] = 0.5
T[3, 0, 1] = T[3, 0, 2] = 0.25
T[3, 1, 0] = 0.1
T[3, 1, 1] = T[3, 1, 2] = 0.1
T[3, 1, 3] = 0.7
np.random.seed(42)
R = np.random.rand(num_states, num_actions)
T_0 = {0: 1.0}
t_params["T_0"] = (T_0,)
t_params["T"] = (T,)
t_params["R"] = (R,)
return t_params
@staticmethod
def get_node_class() -> Type[CustomNode]:
return CustomNode
def __init__(
self,
seed: int,
T_0: Dict[int, float],
T: np.ndarray,
R: Union[np.ndarray, Dict[Tuple[int, int], rv_continuous]],
lazy: Union[None, float] = None,
randomize_actions: bool = True,
**kwargs,
):
"""
Parameters
----------
seed : int
the seed used for sampling rewards and next states.
randomize_actions : bool, optional
whether the effect of the actions changes for every node. It is particularly important to set this value to
true when doing experiments to avoid immediately reaching highly rewarding states in some MDPs by just
selecting the same action repeatedly. By default, it is set to true.
lazy : float
the probability of an action not producing any effect on the MDP.
T_0 : Dict[int, float]
the starting distribution. Note that the values of the dictionary should sum to one.
T : np.ndarray
the |S| x |A| x |S| transition distribution matrix.
R : Union[np.ndarray, Dict[Tuple[int, int], rv_continuous]]
the rewards can be either passed as a |S| x |A| array filled with deterministic values or with a dictionary of
state action pairs and rv_continuous objects.
"""
if type(R) == dict:
self.R = {(CustomNode(ID=s), a): d for (s, a), d in R.items()}
elif type(R) == np.ndarray:
self.R = R
else:
raise NotImplementedError(
f"The type of R, {type(R)}, is not accepted as input."
)
if type(T_0) == np.ndarray:
self.T_0 = {CustomNode(ID=i): p for i, p in enumerate(T_0) if T_0[i] > 0}
elif type(T_0) == dict:
self.T_0 = toolz.keymap(lambda x: CustomNode(ID=x), T_0)
else:
raise NotImplementedError(
f"The type of T_0, {type(T_0)}, is not accepted as input."
)
self.T = T
self._num_actions = self.T.shape[1]
super(CustomMDP, self).__init__(
seed=seed,
randomize_actions=randomize_actions,
lazy=lazy,
**kwargs,
)
@property
def parameters(self) -> Dict[str, Any]:
return super(CustomMDP, self).parameters
@property
def num_actions(self):
return self._num_actions
@cached_property
def possible_starting_nodes(self) -> List[CustomNode]:
return list(self.T_0.keys())
def _calculate_next_nodes_prms(
self, node: Any, action: int
) -> Tuple[Tuple[dict, float], ...]:
return tuple(
(dict(ID=next_node), self.T[node.ID, action, next_node])
for next_node in range(len(self.T))
if self.T[node.ID, action, next_node] > 0.0
)
def _calculate_reward_distribution(
self, node: Any, action: IntEnum, next_node: Any
) -> rv_continuous:
if type(self.R) == dict:
return self.R[node, action]
return deterministic(self.R[node.ID, action])
def _check_input_parameters(self):
super(CustomMDP, self)._check_input_parameters()
assert self.T.ndim == 3
assert type(self.R) in [dict, np.ndarray]
assert np.isclose(np.sum(list(self.T_0.values())), 1)
for s in range(len(self.T)):
for a in range(self.T.shape[1]):
assert np.isclose(self.T[s, a].sum(), 1), (
f"The transition kernel associated with state {s} and action {a} "
f"is not a well defined probability distribution."
)
def _instantiate_starting_node_sampler(self) -> NextStateSampler:
return NextStateSampler(
next_states=self.possible_starting_nodes,
probs=list(self.T_0.values()),
seed=self._next_seed(),
)
def merge_grid(self, grid, axis):
indices = np.where(
(grid == -1).sum(1 if axis == 0 else 0)
== grid.shape[1 if axis == 0 else 0] - 1
)[0][::2]
for ind in indices:
if axis == 1:
grid = grid.T
grid[ind + 1 : ind + 2][grid[ind : ind + 1] != -1] = grid[ind : ind + 1][
grid[ind : ind + 1] != -1
]
if axis == 1:
grid = grid.T
return np.delete(grid, indices, axis)
@cached_property
def grid(self) -> np.ndarray:
coo = np.array(list(self.graph_layout.values()))
X = sorted(coo[:, 0])
Y = sorted(coo[:, 1])
grid = np.zeros((len(coo), len(coo)), dtype=int) - 1
for ind, (x, y) in enumerate(coo):
grid[np.where(X == x)[0][0], np.where(Y == y)[0][0]] = ind
has_changed = True
while has_changed:
has_changed = False
if any((grid == -1).sum(0) == grid.shape[0] - 1):
grid = self.merge_grid(grid, 1)
has_changed = True
if any((grid == -1).sum(1) == grid.shape[1] - 1):
grid = self.merge_grid(grid, 0)
has_changed = True
return grid
@lru_cache()
def get_node_pos_in_grid(self, node) -> Tuple[int, int]:
x, y = np.where((self.str_grid_node_order[node] == self.grid))
return x[0], y[0]
@cached_property
def str_grid_node_order(self):
return dict(zip(self.graph_layout.keys(), range(self.num_states)))
def calc_grid_repr(self, node: Any) -> np.ndarray:
str_grid = np.zeros(self.grid.shape[:2], dtype=str)
str_grid[self.grid == -1] = "X"
str_grid[self.grid != -1] = " "
x, y = self.get_node_pos_in_grid(node)
str_grid[x, y] = "A"
return str_grid[::-1, :]
| [
"numpy.random.seed",
"numpy.zeros",
"colosseum.mdps.MDP.testing_parameters",
"numpy.where",
"colosseum.utils.random_vars.deterministic",
"numpy.random.rand",
"functools.lru_cache",
"numpy.delete",
"dataclasses.dataclass"
] | [((494, 516), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (503, 516), False, 'from dataclasses import dataclass\n'), ((6786, 6797), 'functools.lru_cache', 'lru_cache', ([], {}), '()\n', (6795, 6797), False, 'from functools import lru_cache\n'), ((718, 742), 'colosseum.mdps.MDP.testing_parameters', 'MDP.testing_parameters', ([], {}), '()\n', (740, 742), False, 'from colosseum.mdps import MDP\n'), ((804, 869), 'numpy.zeros', 'np.zeros', (['(num_states, num_actions, num_states)'], {'dtype': 'np.float32'}), '((num_states, num_actions, num_states), dtype=np.float32)\n', (812, 869), True, 'import numpy as np\n'), ((1285, 1303), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (1299, 1303), True, 'import numpy as np\n'), ((1316, 1355), 'numpy.random.rand', 'np.random.rand', (['num_states', 'num_actions'], {}), '(num_states, num_actions)\n', (1330, 1355), True, 'import numpy as np\n'), ((4666, 4704), 'colosseum.utils.random_vars.deterministic', 'deterministic', (['self.R[node.ID, action]'], {}), '(self.R[node.ID, action])\n', (4679, 4704), False, 'from colosseum.utils.random_vars import deterministic\n'), ((6000, 6030), 'numpy.delete', 'np.delete', (['grid', 'indices', 'axis'], {}), '(grid, indices, axis)\n', (6009, 6030), True, 'import numpy as np\n'), ((6874, 6927), 'numpy.where', 'np.where', (['(self.str_grid_node_order[node] == self.grid)'], {}), '(self.str_grid_node_order[node] == self.grid)\n', (6882, 6927), True, 'import numpy as np\n'), ((7163, 7203), 'numpy.zeros', 'np.zeros', (['self.grid.shape[:2]'], {'dtype': 'str'}), '(self.grid.shape[:2], dtype=str)\n', (7171, 7203), True, 'import numpy as np\n'), ((6328, 6344), 'numpy.where', 'np.where', (['(X == x)'], {}), '(X == x)\n', (6336, 6344), True, 'import numpy as np\n'), ((6352, 6368), 'numpy.where', 'np.where', (['(Y == y)'], {}), '(Y == y)\n', (6360, 6368), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Name : c10_16_straddle.py
Book : Python for Finance (2nd ed.)
Publisher: Packt Publishing Ltd.
Author : <NAME>
Date : 6/6/2017
email : <EMAIL>
<EMAIL>
"""
import matplotlib.pyplot as plt
import numpy as np
sT = np.arange(30,80,5)
x=50; c=2; p=1
straddle=(abs(sT-x)+sT-x)/2-c + (abs(x-sT)+x-sT)/2-p
y0=np.zeros(len(sT))
plt.ylim(-6,20)
plt.xlim(40,70)
plt.plot(sT,y0)
plt.plot(sT,straddle,'r')
plt.plot([x,x],[-6,4],'g-.')
plt.title("Profit-loss for a Straddle")
plt.xlabel('Stock price')
plt.ylabel('Profit (loss)')
plt.annotate('Point 1='+str(x-c-p), xy=(x-p-c,0), xytext=(x-p-c,10),
arrowprops=dict(facecolor='red',shrink=0.01),)
plt.annotate('Point 2='+str(x+c+p), xy=(x+p+c,0), xytext=(x+p+c,13),
arrowprops=dict(facecolor='blue',shrink=0.01),)
plt.annotate('exercise price', xy=(x+1,-5))
plt.annotate('Buy a call and buy a put with the same exercise price',xy=(45,16))
plt.show()
| [
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.annotate",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] | [((284, 304), 'numpy.arange', 'np.arange', (['(30)', '(80)', '(5)'], {}), '(30, 80, 5)\n', (293, 304), True, 'import numpy as np\n'), ((393, 409), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-6)', '(20)'], {}), '(-6, 20)\n', (401, 409), True, 'import matplotlib.pyplot as plt\n'), ((410, 426), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(40)', '(70)'], {}), '(40, 70)\n', (418, 426), True, 'import matplotlib.pyplot as plt\n'), ((427, 443), 'matplotlib.pyplot.plot', 'plt.plot', (['sT', 'y0'], {}), '(sT, y0)\n', (435, 443), True, 'import matplotlib.pyplot as plt\n'), ((444, 471), 'matplotlib.pyplot.plot', 'plt.plot', (['sT', 'straddle', '"""r"""'], {}), "(sT, straddle, 'r')\n", (452, 471), True, 'import matplotlib.pyplot as plt\n'), ((470, 502), 'matplotlib.pyplot.plot', 'plt.plot', (['[x, x]', '[-6, 4]', '"""g-."""'], {}), "([x, x], [-6, 4], 'g-.')\n", (478, 502), True, 'import matplotlib.pyplot as plt\n'), ((499, 538), 'matplotlib.pyplot.title', 'plt.title', (['"""Profit-loss for a Straddle"""'], {}), "('Profit-loss for a Straddle')\n", (508, 538), True, 'import matplotlib.pyplot as plt\n'), ((540, 565), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Stock price"""'], {}), "('Stock price')\n", (550, 565), True, 'import matplotlib.pyplot as plt\n'), ((567, 594), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Profit (loss)"""'], {}), "('Profit (loss)')\n", (577, 594), True, 'import matplotlib.pyplot as plt\n'), ((830, 876), 'matplotlib.pyplot.annotate', 'plt.annotate', (['"""exercise price"""'], {'xy': '(x + 1, -5)'}), "('exercise price', xy=(x + 1, -5))\n", (842, 876), True, 'import matplotlib.pyplot as plt\n'), ((874, 961), 'matplotlib.pyplot.annotate', 'plt.annotate', (['"""Buy a call and buy a put with the same exercise price"""'], {'xy': '(45, 16)'}), "('Buy a call and buy a put with the same exercise price', xy=(\n 45, 16))\n", (886, 961), True, 'import matplotlib.pyplot as plt\n'), ((955, 965), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (963, 965), True, 'import matplotlib.pyplot as plt\n')] |
#!/usr/bin/env python
import numpy as np
def convert_to_x4_q7_weights(weights):
[r, h, w, c] = weights.shape
weights = np.reshape(weights, (r, h*w*c))
num_of_rows = r
num_of_cols = h*w*c
new_weights = np.copy(weights)
new_weights = np.reshape(new_weights, (r*h*w*c))
counter = 0
for i in range(int(num_of_rows/4)):
# we only need to do the re-ordering for every 4 rows
row_base = 4*i
for j in range(int(num_of_cols/4)):
# for each 4 entries
column_base = 4*j
new_weights[counter] = weights[row_base ][column_base ]
new_weights[counter+1] = weights[row_base+1][column_base ]
new_weights[counter+2] = weights[row_base ][column_base+2]
new_weights[counter+3] = weights[row_base+1][column_base+2]
new_weights[counter+4] = weights[row_base+2][column_base ]
new_weights[counter+5] = weights[row_base+3][column_base ]
new_weights[counter+6] = weights[row_base+2][column_base+2]
new_weights[counter+7] = weights[row_base+3][column_base+2]
new_weights[counter+8] = weights[row_base ][column_base+1]
new_weights[counter+9] = weights[row_base+1][column_base+1]
new_weights[counter+10] = weights[row_base ][column_base+3]
new_weights[counter+11] = weights[row_base+1][column_base+3]
new_weights[counter+12] = weights[row_base+2][column_base+1]
new_weights[counter+13] = weights[row_base+3][column_base+1]
new_weights[counter+14] = weights[row_base+2][column_base+3]
new_weights[counter+15] = weights[row_base+3][column_base+3]
counter = counter + 16
# the remaining ones are in order
for j in range((int)(num_of_cols-num_of_cols%4), int(num_of_cols)):
new_weights[counter] = weights[row_base][j]
new_weights[counter+1] = weights[row_base+1][j]
new_weights[counter+2] = weights[row_base+2][j]
new_weights[counter+3] = weights[row_base+3][j]
counter = counter + 4
return new_weights.reshape(r, h)
def convert_to_x4_q15_weights(weights):
[r, h, w, c] = weights.shape
weights = np.reshape(weights, (r, h*w*c))
num_of_rows = r
num_of_cols = h*w*c
new_weights = np.copy(weights)
new_weights = np.reshape(new_weights, (r*h*w*c))
counter = 0
for i in range(int(num_of_rows/4)):
# we only need to do the re-ordering for every 4 rows
row_base = 4*i
for j in range(int(num_of_cols/4)):
# for each 2 entries
column_base = 2*j
new_weights[counter] = weights[row_base ][column_base ]
new_weights[counter+1] = weights[row_base ][column_base+1]
new_weights[counter+2] = weights[row_base+1][column_base ]
new_weights[counter+3] = weights[row_base+1][column_base+1]
new_weights[counter+4] = weights[row_base+2][column_base ]
new_weights[counter+5] = weights[row_base+2][column_base+1]
new_weights[counter+6] = weights[row_base+3][column_base ]
new_weights[counter+7] = weights[row_base+3][column_base+1]
counter = counter + 8
# the remaining ones are in order
for j in range((int)(num_of_cols-num_of_cols%2), int(num_of_cols)):
new_weights[counter] = weights[row_base][j]
new_weights[counter+1] = weights[row_base+1][j]
new_weights[counter+2] = weights[row_base+2][j]
new_weights[counter+3] = weights[row_base+3][j]
counter = counter + 4
return new_weights.reshape(r, h)
def convert_q7_q15_weights(weights):
[r, h, w, c] = weights.shape
weights = np.reshape(weights, (r, h*w*c))
num_of_rows = r
num_of_cols = h*w*c
new_weights = np.copy(weights)
new_weights = np.reshape(new_weights, (r*h*w*c))
counter = 0
for i in range(int(num_of_rows/4)):
# we only need to do the re-ordering for every 4 rows
row_base = 4*i
for j in range(int(num_of_cols/4)):
# for each 2 entries
column_base = 2*j
new_weights[counter] = weights[row_base ][column_base ]
new_weights[counter+1] = weights[row_base+1][column_base ]
new_weights[counter+2] = weights[row_base ][column_base+1]
new_weights[counter+3] = weights[row_base+1][column_base+1]
new_weights[counter+4] = weights[row_base+2][column_base ]
new_weights[counter+5] = weights[row_base+3][column_base ]
new_weights[counter+6] = weights[row_base+2][column_base+1]
new_weights[counter+7] = weights[row_base+3][column_base+1]
counter = counter + 8
# the remaining ones are in order
for j in range((int)(num_of_cols-num_of_cols%2), int(num_of_cols)):
new_weights[counter] = weights[row_base][j]
new_weights[counter+1] = weights[row_base+1][j]
new_weights[counter+2] = weights[row_base+2][j]
new_weights[counter+3] = weights[row_base+3][j]
counter = counter + 4
return new_weights.reshape(r, h)
if __name__ == "__main__":
# input dimensions
vec_dim = 127
row_dim = 127
weight = np.zeros((row_dim,vec_dim), dtype=int)
# generate random inputs
for i in range(row_dim):
for j in range(vec_dim):
weight[i][j] = np.random.randint(256)-128
weight = np.reshape(weight, (row_dim, vec_dim, 1, 1))
outfile = open("../Ref_Implementations/fully_connected_testing_weights.h", "w")
outfile.write("#define IP2_WEIGHT {")
weight.tofile(outfile,sep=",",format="%d")
outfile.write("}\n\n")
new_weight = convert_to_x4_q7_weights(weight)
outfile.write("#define IP4_WEIGHT {")
new_weight.tofile(outfile,sep=",",format="%d")
outfile.write("}\n\n")
new_weight = convert_q7_q15_weights(weight)
outfile.write("#define IP4_q7_q15_WEIGHT {")
new_weight.tofile(outfile,sep=",",format="%d")
outfile.write("}\n\n")
new_weight = convert_to_x4_q15_weights(weight)
outfile.write("#define IP4_WEIGHT_Q15 {")
new_weight.tofile(outfile,sep=",",format="%d")
outfile.write("}\n\n")
outfile.close()
| [
"numpy.random.randint",
"numpy.zeros",
"numpy.reshape",
"numpy.copy"
] | [((130, 165), 'numpy.reshape', 'np.reshape', (['weights', '(r, h * w * c)'], {}), '(weights, (r, h * w * c))\n', (140, 165), True, 'import numpy as np\n'), ((224, 240), 'numpy.copy', 'np.copy', (['weights'], {}), '(weights)\n', (231, 240), True, 'import numpy as np\n'), ((259, 297), 'numpy.reshape', 'np.reshape', (['new_weights', '(r * h * w * c)'], {}), '(new_weights, r * h * w * c)\n', (269, 297), True, 'import numpy as np\n'), ((2153, 2188), 'numpy.reshape', 'np.reshape', (['weights', '(r, h * w * c)'], {}), '(weights, (r, h * w * c))\n', (2163, 2188), True, 'import numpy as np\n'), ((2247, 2263), 'numpy.copy', 'np.copy', (['weights'], {}), '(weights)\n', (2254, 2263), True, 'import numpy as np\n'), ((2282, 2320), 'numpy.reshape', 'np.reshape', (['new_weights', '(r * h * w * c)'], {}), '(new_weights, r * h * w * c)\n', (2292, 2320), True, 'import numpy as np\n'), ((3620, 3655), 'numpy.reshape', 'np.reshape', (['weights', '(r, h * w * c)'], {}), '(weights, (r, h * w * c))\n', (3630, 3655), True, 'import numpy as np\n'), ((3714, 3730), 'numpy.copy', 'np.copy', (['weights'], {}), '(weights)\n', (3721, 3730), True, 'import numpy as np\n'), ((3749, 3787), 'numpy.reshape', 'np.reshape', (['new_weights', '(r * h * w * c)'], {}), '(new_weights, r * h * w * c)\n', (3759, 3787), True, 'import numpy as np\n'), ((5104, 5143), 'numpy.zeros', 'np.zeros', (['(row_dim, vec_dim)'], {'dtype': 'int'}), '((row_dim, vec_dim), dtype=int)\n', (5112, 5143), True, 'import numpy as np\n'), ((5297, 5341), 'numpy.reshape', 'np.reshape', (['weight', '(row_dim, vec_dim, 1, 1)'], {}), '(weight, (row_dim, vec_dim, 1, 1))\n', (5307, 5341), True, 'import numpy as np\n'), ((5256, 5278), 'numpy.random.randint', 'np.random.randint', (['(256)'], {}), '(256)\n', (5273, 5278), True, 'import numpy as np\n')] |
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.axes import Axes
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.lines import Line2D
from matplotlib.artist import *
from matplotlib.patches import *
from retina.core.py2 import *
from retina.core.calc_context import tracker_manager
class Layer2D(object):
"""
Class defining a Layer object. This class
should only be used in conjunction with a
valid Fovea axes.
"""
default_style = 'b-'
@classmethod
def set_default_style(cls, style):
"""
A class method for setting the default
style of a Layer. This applies to all
Layer instances.
"""
cls.default_style = style
def __init__(self, name, axes, **kwargs):
"""
Initializes the Layer class.
New attributes should be given default
values in self.default_attrs.
"""
default_attrs = {
'visible': True,
'style': Layer2D.default_style,
'lines': [],
'hlines': [],
'vlines': [],
'x_data': [],
'y_data': [],
'plots': [],
'patches': [],
'bounds': [],
'tracker': tracker_manager()
}
self.name = name
self.axes = axes
for attr in kwargs:
setattr(self, attr, kwargs[attr])
for attr in default_attrs:
if not hasattr(self, attr):
setattr(self, attr, default_attrs[attr])
def _try_method(self, val, method_name, *args, **kwargs):
try:
method_name(val, *args, **kwargs)
except:
pass
def _attr_try_method(self, val, method_name, *args, **kwargs):
"""
Private method which attempts to call the method
`method_name` from the potential object `val`.
"""
if not isinstance(val, Axes) and hasattr(val, method_name):
try:
method = getattr(val, method_name)
method(*args, **kwargs)
except:
pass
def _is_iterable(self, value):
"""
Returns True if value is iterable and not a string.
Otherwise returns False.
"""
return hasattr(value, "__iter__") and not isinstance(value, str)
def _method_loop(self, attr, method_name, iterable, *args, **kwargs):
"""
Recursively attempts to apply the method having `method_name`
to every item in the potential sequence `iterable`.
"""
for val in list(iterable):
if self._is_iterable(val):
self._method_loop(attr, method_name, val, *args, **kwargs)
else:
if attr:
self._attr_try_method(val, method_name, *args, **kwargs)
else:
self._try_method(val, method_name, *args, **kwargs)
def _set_visibility(self, boolean):
"""
Set the visibility of a Matplotlib artist. Accepts either True
or False.
"""
self._method_loop(True, "set_visible", self.__dict__.values(), boolean)
@py2plot
def show(self):
"""
Display a layer in the axes window.
"""
self._set_visibility(True)
self.visible = True
@py2plot
def hide(self):
"""
Hide a layer in the axes window.
"""
self._set_visibility(False)
self.visible = False
@py2plot
def toggle_display(self):
if self.visible:
self.hide()
else:
self.show()
def add_line(self, *args, **kwargs):
"""
Add a Matplotlib Line2D object to the layer.
"""
self.lines.append(Line2D(*args, **kwargs))
@py2plot
def add_vline(self, x):
"""
Add a vertical line specified by the equation
x = `x` to the layer.
"""
ymin, ymax = plt.ylim()
try:
vline = plt.vlines(x, ymin, ymax)
self.vlines.append(vline)
except:
print("Vertical lines are not supported by this Axes type.")
@py2plot
def add_hline(self, y):
"""
Add a horizontal line specified by the equation
y = `y` to the layer.
"""
xmin, xmax = plt.xlim()
try:
hline = plt.hlines(y, xmin, xmax)
self.hlines.append(hline)
except:
print("Horizontal lines are not supported by this Axes type.")
def set_style(self, style):
"""
Apply a style to all Matplotlib artists in the layer.
"""
self.style = style
def set_prop(self, *args, **kwargs):
"""
Sets property(ies) passed as *args and
**kwargs for each artist in the layer.
"""
self._method_loop(False, setp, self.__dict__.values(), *args, **kwargs)
def _set_linewidth(self, artist, linewidth=None, bold=True):
if linewidth:
setp(artist, 'linewidth')
else:
current_lw = getp(artist, 'linewidth')
if bold:
setp(artist, 'linewidth', 2 * current_lw)
else:
lw = max(current_lw / 2, 1)
setp(artist, 'linewidth', lw)
def bold(self, linewidth=None):
"""
Sets linewidth of layer artists to either the value of `linewidth`
or the default of twice the artist's current linewidth.
"""
self._method_loop(False, self._set_linewidth, self.__dict__.values(), linewidth)
def unbold(self):
"""
Reverts boldfacing of Matplotlib artists caused by calls to Layer.bold()
"""
self._method_loop(False, self._set_linewidth, self.__dict__.values(), bold=False)
def add_data(self, x_data, y_data):
"""
Add data to the layer.
First argument should be a list, tuple, or array of x data.
Second argument should be a list, tuple or array of y data.
Optional third argument should be a list, tuple, or array of z data.
"""
self.x_data.append(np.array(x_data))
self.y_data.append(np.array(y_data))
@py2plot
def bound(self, shape=Rectangle, **kwargs):
"""
Draws a boundary having specified `shape` around the data
contained in the layer. Shape should be a valid Matplotlib
patch class.
**kwargs should be Patch instantiation arguments.
"""
if self.bounds:
self._method_loop(True, "set_visible", self.bounds, True)
try:
x_min, x_max = np.amin(self.x_data[0]), np.amax(self.x_data[0])
y_min, y_max = np.amin(self.y_data[0]), np.amax(self.y_data[0])
except:
print("Bound cannot be calculated because data has not yet "
"been added to the plot.")
return
for x, y in zip(self.x_data, self.y_data):
x_lmax, x_lmin = np.amax(x), np.amin(x)
y_lmax, y_lmin = np.amax(y), np.amin(y)
if x_lmin < x_min:
x_min = x_lmin
if x_lmax > x_max:
x_max = x_lmax
if y_lmin < y_min:
y_min = y_lmin
if y_lmax > y_max:
y_max = y_lmax
if shape is Circle:
x_mid, y_mid = (x_min + x_max)/2, (y_min + y_max)/2
center = (x_mid, y_mid)
radius = np.sqrt((y_max - y_mid) ** 2 + (x_max - x_mid) ** 2)
self.patches.append(shape(center, radius, fill=False, **kwargs))
elif shape is Rectangle:
lower_left = (x_min, y_min)
width = x_max - x_min
height = y_max - y_min
self.patches.append(shape(lower_left, width, height, fill=False, **kwargs))
else:
raise ValueError("Unsupported shape")
self.axes.add_patch(self.patches[-1])
self.bounds.append(self.patches[-1])
@py2plot
def unbound(self):
self._method_loop(True, "set_visible", self.bounds, False)
def add_attrs(self, **kwargs):
"""
Add a custom attribute to the layer.
"""
for key, value in kwargs.items():
setattr(self, key, value)
def clear(self):
"""
Clear the layer, setting all attributes to either None
or their default values as specified in self.default_attrs.
"""
for key in self.__dict__.keys():
self.__dict__[key] = None
self.__dict__.update(self.default_attrs)
def delete(self):
attributes = [self.plots, self.hlines, self.vlines, self.bounds]
for attribute in attributes:
for artist in attribute:
try:
artist[0].remove()
except:
artist.remove()
del attribute[:]
self.x_data = []
self.y_data = []
class Layer3D(Layer2D):
def __init__(self, name, axes, **kwargs):
"""
Initializes the Layer class.
New attributes should be given default
values in self.default_attrs.
"""
self.default_attrs = {
'visible': True,
'style': Layer3D.default_style,
'lines': [],
'hlines': [],
'vlines': [],
'x_data': [],
'y_data': [],
'z_data': [],
'plots': [],
'planes': [],
'patches': [],
'bounds': []
}
self.name = name
self.axes = axes
for attr in kwargs:
setattr(self, attr, kwargs[attr])
for attr in self.default_attrs:
if not hasattr(self, attr):
setattr(self, attr, self.default_attrs[attr])
def add_data(self, x_data, y_data, z_data):
"""
Add data to the layer.
First argument should be a list, tuple, or array of x data.
Second argument should be a list, tuple or array of y data.
Optional third argument should be a list, tuple, or array of z data.
"""
self.x_data.append(np.array(x_data))
self.y_data.append(np.array(y_data))
self.z_data.append(np.array(z_data))
def add_plane(self, point, normal, **kwargs):
"""
normal -- Normal vector (a, b, c) to the plane
point -- point (x, y, z) on the plane
Adds a plane having the equation ax + by + cz = d.
"""
point = np.array(point)
normal = np.array(normal)
lims = [self.axes.get_xlim, self.axes.get_ylim, self.axes.get_zlim]
indices = np.argsort(normal)
point = point[indices]
normal = normal[indices]
lim_list = []
for sort in indices:
lim_list.append(lims[sort])
[l, r, u] = lim_list
d = point.dot(normal)
(l_min, l_max), (r_min, r_max) = l(), r()
l, r = np.meshgrid(np.linspace(l_min, l_max), np.linspace(r_min, r_max))
u = (d - normal[0] * l - normal[1] * r) * 1. / normal[2]
var_list = [l, r, u]
diff_ind = np.argsort(indices)
unsort = []
for ind in diff_ind:
unsort.append(var_list[ind])
self.planes.append(unsort)
self.axes.build_layer(self.name, **kwargs)
@py2plot
def bound(self, shape='cube', color='b', **kwargs):
if self.bounds:
self._method_loop(True, "set_visible", self.bounds, True)
return
try:
x_min, x_max = np.amin(self.x_data[0]), np.amax(self.x_data[0])
y_min, y_max = np.amin(self.y_data[0]), np.amax(self.y_data[0])
z_min, z_max = np.amin(self.z_data[0]), np.amax(self.z_data[0])
except:
print("Bound cannot be calculated because data has not yet "
"been added to the plot.")
return
for x, y, z in zip(self.x_data, self.y_data, self.z_data):
x_lmax, x_lmin = np.amax(x), np.amin(x)
y_lmax, y_lmin = np.amax(y), np.amin(y)
z_lmax, z_lmin = np.amax(z), np.amin(z)
if x_lmin < x_min:
x_min = x_lmin
if x_lmax > x_max:
x_max = x_lmax
if y_lmin < y_min:
y_min = y_lmin
if y_lmax > y_max:
y_max = y_lmax
if z_lmin < z_min:
z_min = z_lmin
if z_lmax > z_max:
z_max = z_lmax
self.bounds = []
if shape == 'cube':
x, y, z = [x_min, x_max], [y_min, y_max], [z_min, z_max]
from itertools import product, combinations
for s, e in combinations(np.array(list(product(x, y, z))), 2):
corner = np.sum(np.abs(s - e))
if corner == (x_max - x_min) or corner == (y_max - y_min) or corner == (z_max - z_min):
self.plots.append(self.axes.plot(*zip(s, e), color=color, **kwargs))
self.bounds.append(self.plots[-1])
else:
raise ValueError("Unsupported shape")
@py2plot
def unbound(self):
self._method_loop(True, "set_visible", self.bounds, False)
| [
"matplotlib.pyplot.xlim",
"numpy.abs",
"numpy.amin",
"matplotlib.lines.Line2D",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.vlines",
"numpy.argsort",
"numpy.amax",
"numpy.array",
"numpy.linspace",
"itertools.product",
"matplotlib.pyplot.hlines",
"retina.core.calc_context.tracker_manager",
... | [((4116, 4126), 'matplotlib.pyplot.ylim', 'plt.ylim', ([], {}), '()\n', (4124, 4126), True, 'import matplotlib.pyplot as plt\n'), ((4486, 4496), 'matplotlib.pyplot.xlim', 'plt.xlim', ([], {}), '()\n', (4494, 4496), True, 'import matplotlib.pyplot as plt\n'), ((10887, 10902), 'numpy.array', 'np.array', (['point'], {}), '(point)\n', (10895, 10902), True, 'import numpy as np\n'), ((10920, 10936), 'numpy.array', 'np.array', (['normal'], {}), '(normal)\n', (10928, 10936), True, 'import numpy as np\n'), ((11031, 11049), 'numpy.argsort', 'np.argsort', (['normal'], {}), '(normal)\n', (11041, 11049), True, 'import numpy as np\n'), ((11510, 11529), 'numpy.argsort', 'np.argsort', (['indices'], {}), '(indices)\n', (11520, 11529), True, 'import numpy as np\n'), ((1385, 1402), 'retina.core.calc_context.tracker_manager', 'tracker_manager', ([], {}), '()\n', (1400, 1402), False, 'from retina.core.calc_context import tracker_manager\n'), ((3920, 3943), 'matplotlib.lines.Line2D', 'Line2D', (['*args'], {}), '(*args, **kwargs)\n', (3926, 3943), False, 'from matplotlib.lines import Line2D\n'), ((4160, 4185), 'matplotlib.pyplot.vlines', 'plt.vlines', (['x', 'ymin', 'ymax'], {}), '(x, ymin, ymax)\n', (4170, 4185), True, 'import matplotlib.pyplot as plt\n'), ((4530, 4555), 'matplotlib.pyplot.hlines', 'plt.hlines', (['y', 'xmin', 'xmax'], {}), '(y, xmin, xmax)\n', (4540, 4555), True, 'import matplotlib.pyplot as plt\n'), ((6293, 6309), 'numpy.array', 'np.array', (['x_data'], {}), '(x_data)\n', (6301, 6309), True, 'import numpy as np\n'), ((6338, 6354), 'numpy.array', 'np.array', (['y_data'], {}), '(y_data)\n', (6346, 6354), True, 'import numpy as np\n'), ((7621, 7673), 'numpy.sqrt', 'np.sqrt', (['((y_max - y_mid) ** 2 + (x_max - x_mid) ** 2)'], {}), '((y_max - y_mid) ** 2 + (x_max - x_mid) ** 2)\n', (7628, 7673), True, 'import numpy as np\n'), ((10527, 10543), 'numpy.array', 'np.array', (['x_data'], {}), '(x_data)\n', (10535, 10543), True, 'import numpy as np\n'), ((10572, 10588), 'numpy.array', 'np.array', (['y_data'], {}), '(y_data)\n', (10580, 10588), True, 'import numpy as np\n'), ((10617, 10633), 'numpy.array', 'np.array', (['z_data'], {}), '(z_data)\n', (10625, 10633), True, 'import numpy as np\n'), ((11343, 11368), 'numpy.linspace', 'np.linspace', (['l_min', 'l_max'], {}), '(l_min, l_max)\n', (11354, 11368), True, 'import numpy as np\n'), ((11370, 11395), 'numpy.linspace', 'np.linspace', (['r_min', 'r_max'], {}), '(r_min, r_max)\n', (11381, 11395), True, 'import numpy as np\n'), ((6789, 6812), 'numpy.amin', 'np.amin', (['self.x_data[0]'], {}), '(self.x_data[0])\n', (6796, 6812), True, 'import numpy as np\n'), ((6814, 6837), 'numpy.amax', 'np.amax', (['self.x_data[0]'], {}), '(self.x_data[0])\n', (6821, 6837), True, 'import numpy as np\n'), ((6865, 6888), 'numpy.amin', 'np.amin', (['self.y_data[0]'], {}), '(self.y_data[0])\n', (6872, 6888), True, 'import numpy as np\n'), ((6890, 6913), 'numpy.amax', 'np.amax', (['self.y_data[0]'], {}), '(self.y_data[0])\n', (6897, 6913), True, 'import numpy as np\n'), ((7148, 7158), 'numpy.amax', 'np.amax', (['x'], {}), '(x)\n', (7155, 7158), True, 'import numpy as np\n'), ((7160, 7170), 'numpy.amin', 'np.amin', (['x'], {}), '(x)\n', (7167, 7170), True, 'import numpy as np\n'), ((7200, 7210), 'numpy.amax', 'np.amax', (['y'], {}), '(y)\n', (7207, 7210), True, 'import numpy as np\n'), ((7212, 7222), 'numpy.amin', 'np.amin', (['y'], {}), '(y)\n', (7219, 7222), True, 'import numpy as np\n'), ((11929, 11952), 'numpy.amin', 'np.amin', (['self.x_data[0]'], {}), '(self.x_data[0])\n', (11936, 11952), True, 'import numpy as np\n'), ((11954, 11977), 'numpy.amax', 'np.amax', (['self.x_data[0]'], {}), '(self.x_data[0])\n', (11961, 11977), True, 'import numpy as np\n'), ((12005, 12028), 'numpy.amin', 'np.amin', (['self.y_data[0]'], {}), '(self.y_data[0])\n', (12012, 12028), True, 'import numpy as np\n'), ((12030, 12053), 'numpy.amax', 'np.amax', (['self.y_data[0]'], {}), '(self.y_data[0])\n', (12037, 12053), True, 'import numpy as np\n'), ((12081, 12104), 'numpy.amin', 'np.amin', (['self.z_data[0]'], {}), '(self.z_data[0])\n', (12088, 12104), True, 'import numpy as np\n'), ((12106, 12129), 'numpy.amax', 'np.amax', (['self.z_data[0]'], {}), '(self.z_data[0])\n', (12113, 12129), True, 'import numpy as np\n'), ((12380, 12390), 'numpy.amax', 'np.amax', (['x'], {}), '(x)\n', (12387, 12390), True, 'import numpy as np\n'), ((12392, 12402), 'numpy.amin', 'np.amin', (['x'], {}), '(x)\n', (12399, 12402), True, 'import numpy as np\n'), ((12432, 12442), 'numpy.amax', 'np.amax', (['y'], {}), '(y)\n', (12439, 12442), True, 'import numpy as np\n'), ((12444, 12454), 'numpy.amin', 'np.amin', (['y'], {}), '(y)\n', (12451, 12454), True, 'import numpy as np\n'), ((12484, 12494), 'numpy.amax', 'np.amax', (['z'], {}), '(z)\n', (12491, 12494), True, 'import numpy as np\n'), ((12496, 12506), 'numpy.amin', 'np.amin', (['z'], {}), '(z)\n', (12503, 12506), True, 'import numpy as np\n'), ((13165, 13178), 'numpy.abs', 'np.abs', (['(s - e)'], {}), '(s - e)\n', (13171, 13178), True, 'import numpy as np\n'), ((13109, 13125), 'itertools.product', 'product', (['x', 'y', 'z'], {}), '(x, y, z)\n', (13116, 13125), False, 'from itertools import product, combinations\n')] |
"""
MIT License
Copyright (c) 2019 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import numpy as np
import pandas as pd
from sklearn.inspection import partial_dependence
from sklearn.neighbors import KNeighborsRegressor
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import r2_score
from sklearn import svm
from sklearn.datasets import load_boston
from articles.pd.support import load_rent, load_bulldozer, load_flights, \
toy_weather_data, toy_weight_data, \
df_cat_to_catcode, df_split_dates, \
df_string_to_cat, synthetic_interaction_data
from stratx import plot_stratpd, plot_catstratpd, \
plot_stratpd_gridsearch, plot_catstratpd_gridsearch
from stratx.partdep import partial_dependence
from stratx.plot import marginal_plot_, plot_ice, plot_catice
from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence
import inspect
import matplotlib.patches as mpatches
from collections import OrderedDict
import matplotlib.pyplot as plt
import os
import shap
import xgboost as xgb
from colour import rgb2hex, Color
from dtreeviz.trees import tree, ShadowDecTree
figsize = (2.5, 2)
figsize2 = (3.8, 3.2)
GREY = '#444443'
# This genfigs.py code is just demonstration code to generate figures for the paper.
# There are lots of programming sins committed here; to not take this to be
# our idea of good code. ;)
# For data sources, please see notebooks/examples.ipynb
def addnoise(df, n=1, c=0.5, prefix=''):
if n == 1:
df[f'{prefix}noise'] = np.random.random(len(df)) * c
return
for i in range(n):
df[f'{prefix}noise{i + 1}'] = np.random.random(len(df)) * c
def fix_missing_num(df, colname):
df[colname + '_na'] = pd.isnull(df[colname])
df[colname].fillna(df[colname].median(), inplace=True)
def savefig(filename, pad=0):
plt.tight_layout(pad=pad, w_pad=0, h_pad=0)
plt.savefig(f"images/{filename}.pdf", bbox_inches="tight", pad_inches=0)
# plt.savefig(f"images/{filename}.png", dpi=150)
plt.tight_layout()
plt.show()
plt.close()
def rent():
print(f"----------- {inspect.stack()[0][3]} -----------")
np.random.seed(1) # pick seed for reproducible article images
X,y = load_rent(n=10_000)
df_rent = X.copy()
df_rent['price'] = y
colname = 'bedrooms'
colname = 'bathrooms'
TUNE_RF = False
TUNE_XGB = False
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
if TUNE_RF:
rf, bestparams = tune_RF(X, y) # does CV on entire data set to tune
# bedrooms
# RF best: {'max_features': 0.3, 'min_samples_leaf': 1, 'n_estimators': 125}
# validation R^2 0.7873724127323822
# bathrooms
# RF best: {'max_features': 0.3, 'min_samples_leaf': 1, 'n_estimators': 200}
# validation R^2 0.8066593395345907
else:
rf = RandomForestRegressor(n_estimators=200, min_samples_leaf=1, max_features=.3,
oob_score=True, n_jobs=-1)
rf.fit(X_train, y_train) # Use training set for plotting
print("RF OOB R^2", rf.oob_score_)
rf_score = rf.score(X_test, y_test)
print("RF validation R^2", rf_score)
if TUNE_XGB:
tuned_parameters = {'n_estimators': [400, 450, 500, 600, 1000],
'learning_rate': [0.008, 0.01, 0.02, 0.05, 0.08, 0.1, 0.11],
'max_depth': [3, 4, 5, 6, 7, 8, 9]}
grid = GridSearchCV(
xgb.XGBRegressor(), tuned_parameters, scoring='r2',
cv=5,
n_jobs=-1,
verbose=2
)
grid.fit(X, y) # does CV on entire data set to tune
print("XGB best:", grid.best_params_)
b = grid.best_estimator_
# bedrooms
# XGB best: {'max_depth': 7, 'n_estimators': 250}
# XGB validation R^2 0.7945797751555217
# bathrooms
# XGB best: {'learning_rate': 0.11, 'max_depth': 6, 'n_estimators': 1000}
# XGB train R^2 0.9834399795800324
# XGB validation R^2 0.8244958014380593
else:
b = xgb.XGBRegressor(n_estimators=1000,
max_depth=6,
learning_rate=.11,
verbose=2,
n_jobs=8)
b.fit(X_train, y_train)
xgb_score = b.score(X_test, y_test)
print("XGB validation R^2", xgb_score)
lm = LinearRegression()
lm.fit(X_train, y_train)
lm_score = lm.score(X_test, y_test)
print("OLS validation R^2", lm_score)
lm.fit(X, y)
model, r2_keras = rent_deep_learning_model(X_train, y_train, X_test, y_test)
fig, axes = plt.subplots(1, 6, figsize=(10, 1.8),
gridspec_kw = {'wspace':0.15})
for i in range(len(axes)):
axes[i].set_xlim(0-.3,4+.3)
axes[i].set_xticks([0,1,2,3,4])
axes[i].set_ylim(1800, 9000)
axes[i].set_yticks([2000,4000,6000,8000])
axes[1].get_yaxis().set_visible(False)
axes[2].get_yaxis().set_visible(False)
axes[3].get_yaxis().set_visible(False)
axes[4].get_yaxis().set_visible(False)
axes[0].set_title("(a) Marginal", fontsize=10)
axes[1].set_title("(b) RF", fontsize=10)
axes[1].text(2,8000, f"$R^2=${rf_score:.3f}", horizontalalignment='center', fontsize=9)
axes[2].set_title("(c) XGBoost", fontsize=10)
axes[2].text(2,8000, f"$R^2=${xgb_score:.3f}", horizontalalignment='center', fontsize=9)
axes[3].set_title("(d) OLS", fontsize=10)
axes[3].text(2,8000, f"$R^2=${lm_score:.3f}", horizontalalignment='center', fontsize=9)
axes[4].set_title("(e) Keras", fontsize=10)
axes[4].text(2,8000, f"$R^2=${r2_keras:.3f}", horizontalalignment='center', fontsize=9)
axes[5].set_title("(f) StratPD", fontsize=10)
avg_per_baths = df_rent.groupby(colname).mean()['price']
axes[0].scatter(df_rent[colname], df_rent['price'], alpha=0.07, s=5)
axes[0].scatter(np.unique(df_rent[colname]), avg_per_baths, s=6, c='black',
label="average price/{colname}")
axes[0].set_ylabel("price") # , fontsize=12)
axes[0].set_xlabel("bathrooms")
axes[0].spines['right'].set_visible(False)
axes[0].spines['top'].set_visible(False)
ice = predict_ice(rf, X, colname, 'price', numx=30, nlines=100)
plot_ice(ice, colname, 'price', alpha=.3, ax=axes[1], show_xlabel=True,
show_ylabel=False)
ice = predict_ice(b, X, colname, 'price', numx=30, nlines=100)
plot_ice(ice, colname, 'price', alpha=.3, ax=axes[2], show_ylabel=False)
ice = predict_ice(lm, X, colname, 'price', numx=30, nlines=100)
plot_ice(ice, colname, 'price', alpha=.3, ax=axes[3], show_ylabel=False)
scaler = StandardScaler()
X_train_ = pd.DataFrame(scaler.fit_transform(X_train), columns=X_train.columns)
# y_pred = model.predict(X_)
# print("Keras training R^2", r2_score(y, y_pred)) # y_test in y
ice = predict_ice(model, X_train_, colname, 'price', numx=30, nlines=100)
# replace normalized unique X with unnormalized
ice.iloc[0, :] = np.linspace(np.min(X_train[colname]), np.max(X_train[colname]), 30, endpoint=True)
plot_ice(ice, colname, 'price', alpha=.3, ax=axes[4], show_ylabel=True)
pdpx, pdpy, ignored = \
plot_stratpd(X, y, colname, 'price', ax=axes[5],
pdp_marker_size=6,
show_x_counts=False,
hide_top_right_axes=False,
show_xlabel=True, show_ylabel=False)
print(f"StratPD ignored {ignored} records")
axes[5].yaxis.tick_right()
axes[5].yaxis.set_label_position('right')
axes[5].set_ylim(-250,2250)
axes[5].set_yticks([0,1000,2000])
axes[5].set_ylabel("price")
savefig(f"{colname}_vs_price")
def tune_RF(X, y, verbose=2):
tuned_parameters = {'n_estimators': [50, 100, 125, 150, 200],
'min_samples_leaf': [1, 3, 5, 7],
'max_features': [.1, .3, .5, .7, .9]}
grid = GridSearchCV(
RandomForestRegressor(), tuned_parameters, scoring='r2',
cv=5,
n_jobs=-1,
verbose=verbose
)
grid.fit(X, y) # does CV on entire data set
rf = grid.best_estimator_
print("RF best:", grid.best_params_)
#
# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# rf.fit(X_train, y_train)
# print("validation R^2", rf.score(X_test, y_test))
return rf, grid.best_params_
def plot_with_noise_col(df, colname):
features = ['bedrooms', 'bathrooms', 'latitude', 'longitude']
features_with_noise = ['bedrooms', 'bathrooms', 'latitude', 'longitude',
colname + '_noise']
type = "noise"
fig, axes = plt.subplots(2, 2, figsize=(5, 5), sharey=True, sharex=True)
df = df.copy()
addnoise(df, n=1, c=50, prefix=colname + '_')
X = df[features]
y = df['price']
# STRATPD ON ROW 1
X = df[features]
y = df['price']
plot_stratpd(X, y, colname, 'price', ax=axes[0, 0], slope_line_alpha=.15, show_xlabel=True,
show_ylabel=False)
axes[0, 0].set_ylim(-1000, 5000)
axes[0, 0].set_title(f"StratPD")
X = df[features_with_noise]
y = df['price']
plot_stratpd(X, y, colname, 'price', ax=axes[0, 1], slope_line_alpha=.15,
show_ylabel=False)
axes[0, 1].set_ylim(-1000, 5000)
axes[0, 1].set_title(f"StratPD w/{type} col")
# ICE ON ROW 2
X = df[features]
y = df['price']
rf = RandomForestRegressor(n_estimators=100, min_samples_leaf=1, oob_score=True,
n_jobs=-1)
rf.fit(X, y)
# do it w/o dup'd column
ice = predict_ice(rf, X, colname, 'price', nlines=1000)
uniq_x, pdp_curve = \
plot_ice(ice, colname, 'price', alpha=.05, ax=axes[1, 0], show_xlabel=True)
axes[1, 0].set_ylim(-1000, 5000)
axes[1, 0].set_title(f"FPD/ICE")
for i in range(2):
for j in range(2):
axes[i, j].set_xlim(0, 6)
X = df[features_with_noise]
y = df['price']
rf = RandomForestRegressor(n_estimators=100, min_samples_leaf=1, oob_score=True,
n_jobs=-1)
rf.fit(X, y)
ice = predict_ice(rf, X, colname, 'price', nlines=1000)
uniq_x_, pdp_curve_ = \
plot_ice(ice, colname, 'price', alpha=.05, ax=axes[1, 1], show_xlabel=True,
show_ylabel=False)
axes[1, 1].set_ylim(-1000, 5000)
axes[1, 1].set_title(f"FPD/ICE w/{type} col")
# print(f"max ICE curve {np.max(pdp_curve):.0f}, max curve with dup {np.max(pdp_curve_):.0f}")
axes[0, 0].get_xaxis().set_visible(False)
axes[0, 1].get_xaxis().set_visible(False)
def plot_with_dup_col(df, colname, min_samples_leaf):
features = ['bedrooms', 'bathrooms', 'latitude', 'longitude']
features_with_dup = ['bedrooms', 'bathrooms', 'latitude', 'longitude',
colname + '_dup']
fig, axes = plt.subplots(2, 3, figsize=(7.5, 5), sharey=True, sharex=True)
type = "dup"
verbose = False
df = df.copy()
df[colname + '_dup'] = df[colname]
# df_rent[colname+'_dupdup'] = df_rent[colname]
# STRATPD ON ROW 1
X = df[features]
y = df['price']
print(f"shape is {X.shape}")
plot_stratpd(X, y, colname, 'price', ax=axes[0, 0], slope_line_alpha=.15,
show_xlabel=True,
min_samples_leaf=min_samples_leaf,
show_ylabel=True,
verbose=verbose)
axes[0, 0].set_ylim(-1000, 5000)
axes[0, 0].set_title(f"StratPD")
X = df[features_with_dup]
y = df['price']
print(f"shape with dup is {X.shape}")
plot_stratpd(X, y, colname, 'price', ax=axes[0, 1], slope_line_alpha=.15, show_ylabel=False,
min_samples_leaf=min_samples_leaf,
verbose=verbose)
axes[0, 1].set_ylim(-1000, 5000)
axes[0, 1].set_title(f"StratPD w/{type} col")
plot_stratpd(X, y, colname, 'price', ax=axes[0, 2], slope_line_alpha=.15, show_xlabel=True,
min_samples_leaf=min_samples_leaf,
show_ylabel=False,
n_trees=15,
max_features=1,
bootstrap=False,
verbose=verbose
)
axes[0, 2].set_ylim(-1000, 5000)
axes[0, 2].set_title(f"StratPD w/{type} col")
axes[0, 2].text(.2, 4000, "ntrees=15")
axes[0, 2].text(.2, 3500, "max features per split=1")
# ICE ON ROW 2
X = df[features]
y = df['price']
rf = RandomForestRegressor(n_estimators=100, min_samples_leaf=1, oob_score=True,
n_jobs=-1)
rf.fit(X, y)
# do it w/o dup'd column
ice = predict_ice(rf, X, colname, 'price', nlines=1000)
plot_ice(ice, colname, 'price', alpha=.05, ax=axes[1, 0], show_xlabel=True)
axes[1, 0].set_ylim(-1000, 5000)
axes[1, 0].set_title(f"FPD/ICE")
for i in range(2):
for j in range(3):
axes[i, j].set_xlim(0, 6)
# with dup'd column
X = df[features_with_dup]
y = df['price']
rf = RandomForestRegressor(n_estimators=100, min_samples_leaf=1, oob_score=True,
n_jobs=-1)
rf.fit(X, y)
ice = predict_ice(rf, X, colname, 'price', nlines=1000)
plot_ice(ice, colname, 'price', alpha=.05, ax=axes[1, 1], show_xlabel=True, show_ylabel=False)
axes[1, 1].set_ylim(-1000, 5000)
axes[1, 1].set_title(f"FPD/ICE w/{type} col")
# print(f"max ICE curve {np.max(pdp_curve):.0f}, max curve with dup {np.max(pdp_curve_):.0f}")
axes[1, 2].set_title(f"FPD/ICE w/{type} col")
axes[1, 2].text(.2, 4000, "Cannot compensate")
axes[1, 2].set_xlabel(colname)
# print(f"max curve {np.max(curve):.0f}, max curve with dup {np.max(curve_):.0f}")
axes[0, 0].get_xaxis().set_visible(False)
axes[0, 1].get_xaxis().set_visible(False)
def rent_ntrees():
np.random.seed(1) # pick seed for reproducible article images
print(f"----------- {inspect.stack()[0][3]} -----------")
X, y = load_rent(n=10_000)
trees = [1, 5, 10, 30]
supervised = True
def onevar(colname, row, yrange=None):
alphas = [.1,.08,.05,.04]
for i, t in enumerate(trees):
plot_stratpd(X, y, colname, 'price', ax=axes[row, i], slope_line_alpha=alphas[i],
# min_samples_leaf=20,
yrange=yrange,
supervised=supervised,
show_ylabel=t == 1,
pdp_marker_size=2 if row==2 else 8,
n_trees=t,
max_features='auto',
bootstrap=True,
verbose=False)
fig, axes = plt.subplots(3, 4, figsize=(8, 6), sharey=True)
for i in range(1, 4):
axes[0, i].get_yaxis().set_visible(False)
axes[1, i].get_yaxis().set_visible(False)
axes[2, i].get_yaxis().set_visible(False)
for i in range(0, 4):
axes[0, i].set_title(f"{trees[i]} trees")
onevar('bedrooms', row=0, yrange=(-500, 4000))
onevar('bathrooms', row=1, yrange=(-500, 4000))
onevar('latitude', row=2, yrange=(-500, 4000))
savefig(f"rent_ntrees")
plt.close()
def meta_boston():
np.random.seed(1) # pick seed for reproducible article images
print(f"----------- {inspect.stack()[0][3]} -----------")
boston = load_boston()
print(len(boston.data))
df = pd.DataFrame(boston.data, columns=boston.feature_names)
df['MEDV'] = boston.target
X = df.drop('MEDV', axis=1)
y = df['MEDV']
plot_stratpd_gridsearch(X, y, 'AGE', 'MEDV',
show_slope_lines=True,
min_samples_leaf_values=[2,5,10,20,30],
yrange=(-10,10))
# yranges = [(-30, 0), (0, 30), (-8, 8), (-11, 0)]
# for nbins in range(6):
# plot_meta_multivar(X, y, colnames=['LSTAT', 'RM', 'CRIM', 'DIS'], targetname='MEDV',
# nbins=nbins,
# yranges=yranges)
savefig(f"meta_boston_age_medv")
def plot_meta_multivar(X, y, colnames, targetname, nbins, yranges=None):
np.random.seed(1) # pick seed for reproducible article images
min_samples_leaf_values = [2, 5, 10, 30, 50, 100, 200]
nrows = len(colnames)
ncols = len(min_samples_leaf_values)
fig, axes = plt.subplots(nrows, ncols + 2, figsize=((ncols + 2) * 2.5, nrows * 2.5))
if yranges is None:
yranges = [None] * len(colnames)
row = 0
for i, colname in enumerate(colnames):
marginal_plot_(X, y, colname, targetname, ax=axes[row, 0])
col = 2
for msl in min_samples_leaf_values:
print(
f"---------- min_samples_leaf={msl}, nbins={nbins:.2f} ----------- ")
plot_stratpd(X, y, colname, targetname, ax=axes[row, col],
min_samples_leaf=msl,
yrange=yranges[i],
n_trees=1)
axes[row, col].set_title(
f"leafsz={msl}, nbins={nbins:.2f}",
fontsize=9)
col += 1
row += 1
rf = RandomForestRegressor(n_estimators=100, min_samples_leaf=1, oob_score=True)
rf.fit(X, y)
row = 0
for i, colname in enumerate(colnames):
ice = predict_ice(rf, X, colname, targetname)
plot_ice(ice, colname, targetname, ax=axes[row, 1])
row += 1
def unsup_rent():
np.random.seed(1) # pick seed for reproducible article images
print(f"----------- {inspect.stack()[0][3]} -----------")
X, y = load_rent(n=10_000)
fig, axes = plt.subplots(4, 2, figsize=(4, 8))
plot_stratpd(X, y, 'bedrooms', 'price', ax=axes[0, 0], yrange=(-500,4000),
slope_line_alpha=.2, supervised=False)
plot_stratpd(X, y, 'bedrooms', 'price', ax=axes[0, 1], yrange=(-500,4000),
slope_line_alpha=.2, supervised=True)
plot_stratpd(X, y, 'bathrooms', 'price', ax=axes[1, 0], yrange=(-500,4000),
slope_line_alpha=.2, supervised=False)
plot_stratpd(X, y, 'bathrooms', 'price', ax=axes[1, 1], yrange=(-500,4000),
slope_line_alpha=.2, supervised=True)
plot_stratpd(X, y, 'latitude', 'price', ax=axes[2, 0], yrange=(-500,2000),
slope_line_alpha=.2, supervised=False, verbose=True)
plot_stratpd(X, y, 'latitude', 'price', ax=axes[2, 1], yrange=(-500,2000),
slope_line_alpha=.2, supervised=True, verbose=True)
plot_stratpd(X, y, 'longitude', 'price', ax=axes[3, 0], yrange=(-500,500),
slope_line_alpha=.2, supervised=False)
plot_stratpd(X, y, 'longitude', 'price', ax=axes[3, 1], yrange=(-500,500),
slope_line_alpha=.2, supervised=True)
axes[0, 0].set_title("Unsupervised")
axes[0, 1].set_title("Supervised")
for i in range(3):
axes[i, 1].get_yaxis().set_visible(False)
savefig(f"rent_unsup")
plt.close()
def weather():
np.random.seed(1) # pick seed for reproducible article images
print(f"----------- {inspect.stack()[0][3]} -----------")
TUNE_RF = False
df_raw = toy_weather_data()
df = df_raw.copy()
df_string_to_cat(df)
names = np.unique(df['state'])
catnames = OrderedDict()
for i,v in enumerate(names):
catnames[i+1] = v
df_cat_to_catcode(df)
X = df.drop('temperature', axis=1)
y = df['temperature']
# cats = catencoders['state'].values
# cats = np.insert(cats, 0, None) # prepend a None for catcode 0
if TUNE_RF:
rf, bestparams = tune_RF(X, y)
# RF best: {'max_features': 0.9, 'min_samples_leaf': 5, 'n_estimators': 150}
# validation R^2 0.9500072628270099
else:
rf = RandomForestRegressor(n_estimators=150, min_samples_leaf=5, max_features=0.9, oob_score=True)
rf.fit(X, y) # Use full data set for plotting
print("RF OOB R^2", rf.oob_score_)
fig, ax = plt.subplots(1, 1, figsize=figsize)
df = df_raw.copy()
avgtmp = df.groupby(['state', 'dayofyear'])[['temperature']].mean()
avgtmp = avgtmp.reset_index()
ca = avgtmp.query('state=="CA"')
co = avgtmp.query('state=="CO"')
az = avgtmp.query('state=="AZ"')
wa = avgtmp.query('state=="WA"')
nv = avgtmp.query('state=="NV"')
ax.plot(ca['dayofyear'], ca['temperature'], lw=.5, c='#fdae61', label="CA")
ax.plot(co['dayofyear'], co['temperature'], lw=.5, c='#225ea8', label="CO")
ax.plot(az['dayofyear'], az['temperature'], lw=.5, c='#41b6c4', label="AZ")
ax.plot(wa['dayofyear'], wa['temperature'], lw=.5, c='#a1dab4', label="WA")
ax.plot(nv['dayofyear'], nv['temperature'], lw=.5, c='#a1dab4', label="NV")
ax.legend(loc='upper left', borderpad=0, labelspacing=0)
ax.set_xlabel("dayofyear")
ax.set_ylabel("temperature")
ax.set_title("(a) State/day vs temp")
savefig(f"dayofyear_vs_temp")
fig, ax = plt.subplots(1, 1, figsize=figsize)
plot_stratpd(X, y, 'dayofyear', 'temperature', ax=ax,
show_x_counts=False,
yrange=(-10, 10),
pdp_marker_size=2, slope_line_alpha=.5, n_trials=1)
ax.set_title("(b) StratPD")
savefig(f"dayofyear_vs_temp_stratpd")
plt.close()
fig, ax = plt.subplots(1, 1, figsize=figsize)
plot_catstratpd(X, y, 'state', 'temperature', catnames=catnames,
show_x_counts=False,
# min_samples_leaf=30,
min_y_shifted_to_zero=True,
# alpha=.3,
ax=ax,
yrange=(-1, 55))
ax.set_yticks([0,10,20,30,40,50])
ax.set_title("(d) CatStratPD")
savefig(f"state_vs_temp_stratpd")
fig, ax = plt.subplots(1, 1, figsize=figsize)
ice = predict_ice(rf, X, 'dayofyear', 'temperature')
plot_ice(ice, 'dayofyear', 'temperature', ax=ax)
ax.set_title("(c) FPD/ICE")
savefig(f"dayofyear_vs_temp_pdp")
fig, ax = plt.subplots(1, 1, figsize=figsize)
ice = predict_catice(rf, X, 'state', 'temperature')
plot_catice(ice, 'state', 'temperature', catnames=catnames, ax=ax,
pdp_marker_size=15,
min_y_shifted_to_zero = True,
yrange=(-2, 50)
)
ax.set_yticks([0,10,20,30,40,50])
ax.set_title("(b) FPD/ICE")
savefig(f"state_vs_temp_pdp")
fig, ax = plt.subplots(1, 1, figsize=figsize)
ax.scatter(X['state'], y, alpha=.05, s=15)
ax.set_xticks(range(1,len(catnames)+1))
ax.set_xticklabels(catnames.values())
ax.set_xlabel("state")
ax.set_ylabel("temperature")
ax.set_title("(a) Marginal")
savefig(f"state_vs_temp")
plt.close()
def meta_weather():
np.random.seed(1) # pick seed for reproducible article images
print(f"----------- {inspect.stack()[0][3]} -----------")
# np.random.seed(66)
nyears = 5
years = []
for y in range(1980, 1980 + nyears):
df_ = toy_weather_data()
df_['year'] = y
years.append(df_)
df_raw = pd.concat(years, axis=0)
# df_raw.drop('year', axis=1, inplace=True)
df = df_raw.copy()
print(df.head(5))
names = {'CO': 5, 'CA': 10, 'AZ': 15, 'WA': 20}
df['state'] = df['state'].map(names)
catnames = {v:k for k,v in names.items()}
X = df.drop('temperature', axis=1)
y = df['temperature']
plot_catstratpd_gridsearch(X, y, 'state', 'temp',
min_samples_leaf_values=[2, 5, 20, 40, 60],
catnames=catnames,
yrange=(-5,60),
cellwidth=2
)
savefig(f"state_temp_meta")
plot_stratpd_gridsearch(X, y, 'dayofyear', 'temp',
show_slope_lines=True,
min_samples_leaf_values=[2,5,10,20,30],
yrange=(-10,10),
slope_line_alpha=.15)
savefig(f"dayofyear_temp_meta")
def weight():
np.random.seed(1) # pick seed for reproducible article images
print(f"----------- {inspect.stack()[0][3]} -----------")
X, y, df_raw, eqn = toy_weight_data(2000)
TUNE_RF = False
fig, ax = plt.subplots(1, 1, figsize=figsize)
plot_stratpd(X, y, 'education', 'weight', ax=ax,
show_x_counts=False,
pdp_marker_size=5,
yrange=(-12, 0.05), slope_line_alpha=.1, show_ylabel=True)
# ax.get_yaxis().set_visible(False)
ax.set_title("StratPD", fontsize=10)
ax.set_xlim(10,18)
ax.set_xticks([10,12,14,16,18])
savefig(f"education_vs_weight_stratpd")
fig, ax = plt.subplots(1, 1, figsize=figsize)
plot_stratpd(X, y, 'height', 'weight', ax=ax,
pdp_marker_size=.2,
show_x_counts=False,
yrange=(0, 160), show_ylabel=False)
# ax.get_yaxis().set_visible(False)
ax.set_title("StratPD", fontsize=10)
ax.set_xticks([60,65,70,75])
savefig(f"height_vs_weight_stratpd")
fig, ax = plt.subplots(1, 1, figsize=(1.3,2))
plot_catstratpd(X, y, 'sex', 'weight', ax=ax,
show_x_counts=False,
catnames={0:'M',1:'F'},
yrange=(-1, 35),
)
ax.set_title("CatStratPD", fontsize=10)
savefig(f"sex_vs_weight_stratpd")
fig, ax = plt.subplots(1, 1, figsize=(1.5,1.8))
plot_catstratpd(X, y, 'pregnant', 'weight', ax=ax,
show_x_counts=False,
catnames={0:False, 1:True},
yrange=(-1, 45),
)
ax.set_title("CatStratPD", fontsize=10)
savefig(f"pregnant_vs_weight_stratpd")
if TUNE_RF:
rf, bestparams = tune_RF(X, y)
# RF best: {'max_features': 0.9, 'min_samples_leaf': 1, 'n_estimators': 200}
# validation R^2 0.9996343699640691
else:
rf = RandomForestRegressor(n_estimators=200, min_samples_leaf=1, max_features=0.9, oob_score=True)
rf.fit(X, y) # Use full data set for plotting
print("RF OOB R^2", rf.oob_score_)
# show pregnant female at max range drops going taller
X_test = np.array([[1, 1, 70, 10]])
y_pred = rf.predict(X_test)
print("pregnant female at max range", X_test, "predicts", y_pred)
X_test = np.array([[1, 1, 72, 10]]) # make them taller
y_pred = rf.predict(X_test)
print("pregnant female in male height range", X_test, "predicts", y_pred)
fig, ax = plt.subplots(1, 1, figsize=figsize)
ice = predict_ice(rf, X, 'education', 'weight')
plot_ice(ice, 'education', 'weight', ax=ax, yrange=(-12, 0), min_y_shifted_to_zero=True)
ax.set_xlim(10,18)
ax.set_xticks([10,12,14,16,18])
ax.set_title("FPD/ICE", fontsize=10)
savefig(f"education_vs_weight_pdp")
fig, ax = plt.subplots(1, 1, figsize=(2.4, 2.2))
ice = predict_ice(rf, X, 'height', 'weight')
plot_ice(ice, 'height', 'weight', ax=ax, pdp_linewidth=2, yrange=(100, 250),
min_y_shifted_to_zero=False)
ax.set_xlabel("height\n(a)", fontsize=10)
ax.set_ylabel("weight", fontsize=10)
ax.set_title("FPD/ICE", fontsize=10)
ax.set_xticks([60,65,70,75])
savefig(f"height_vs_weight_pdp")
fig, ax = plt.subplots(1, 1, figsize=(1.3,2))
ice = predict_catice(rf, X, 'sex', 'weight')
plot_catice(ice, 'sex', 'weight', catnames={0:'M',1:'F'}, ax=ax, yrange=(0, 35),
pdp_marker_size=15)
ax.set_title("FPD/ICE", fontsize=10)
savefig(f"sex_vs_weight_pdp")
fig, ax = plt.subplots(1, 1, figsize=(1.3,1.8))
ice = predict_catice(rf, X, 'pregnant', 'weight', cats=df_raw['pregnant'].unique())
plot_catice(ice, 'pregnant', 'weight', catnames={0:'M',1:'F'}, ax=ax,
min_y_shifted_to_zero=True,
yrange=(-5, 45), pdp_marker_size=20)
ax.set_title("FPD/ICE", fontsize=10)
savefig(f"pregnant_vs_weight_pdp")
def shap_pregnant():
np.random.seed(1) # pick seed for reproducible article images
n = 2000
shap_test_size = 300
X, y, df_raw, eqn = toy_weight_data(n=n)
df = df_raw.copy()
df_string_to_cat(df)
df_cat_to_catcode(df)
df['pregnant'] = df['pregnant'].astype(int)
X = df.drop('weight', axis=1)
y = df['weight']
# parameters from tune_RF() called in weight()
rf = RandomForestRegressor(n_estimators=200, min_samples_leaf=1,
max_features=0.9,
oob_score=True)
rf.fit(X, y) # Use full data set for plotting
print("RF OOB R^2", rf.oob_score_)
explainer = shap.TreeExplainer(rf, data=shap.sample(X, 100),
feature_perturbation='interventional')
shap_sample = X.sample(shap_test_size, replace=False)
shap_values = explainer.shap_values(shap_sample, check_additivity=False)
GREY = '#444443'
fig, ax = plt.subplots(1, 1, figsize=(1.3,1.8))
preg_shap_values = shap_values[:, 1]
avg_not_preg_weight = np.mean(preg_shap_values[np.where(shap_sample['pregnant']==0)])
avg_preg_weight = np.mean(preg_shap_values[np.where(shap_sample['pregnant']==1)])
ax.bar([0, 1], [avg_not_preg_weight-avg_not_preg_weight, avg_preg_weight-avg_not_preg_weight],
color='#1E88E5')
ax.set_title("SHAP", fontsize=10)
ax.set_xlabel("pregnant")
ax.set_xticks([0,1])
ax.set_xticklabels(['False','True'])
ax.set_ylabel("weight")
ax.set_ylim(-1,45)
ax.set_yticks([0,10,20,30,40])
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
savefig('pregnant_vs_weight_shap')
def shap_weight(feature_perturbation, twin=False):
np.random.seed(1) # pick seed for reproducible article images
n = 2000
shap_test_size = 2000
X, y, df_raw, eqn = toy_weight_data(n=n)
df = df_raw.copy()
df_string_to_cat(df)
df_cat_to_catcode(df)
df['pregnant'] = df['pregnant'].astype(int)
X = df.drop('weight', axis=1)
y = df['weight']
# parameters from tune_RF() called in weight()
rf = RandomForestRegressor(n_estimators=200, min_samples_leaf=1,
max_features=0.9,
oob_score=True)
rf.fit(X, y) # Use full data set for plotting
print("RF OOB R^2", rf.oob_score_)
if feature_perturbation=='interventional':
explainer = shap.TreeExplainer(rf, data=shap.sample(X, 100), feature_perturbation='interventional')
xlabel = "height\n(c)"
ylabel = None
yticks = []
figsize = (2.2, 2.2)
else:
explainer = shap.TreeExplainer(rf, feature_perturbation='tree_path_dependent')
xlabel = "height\n(b)"
ylabel = "SHAP height"
yticks = [-75, -60, -40, -20, 0, 20, 40, 60, 75]
figsize = (2.6, 2.2)
shap_sample = X.sample(shap_test_size, replace=False)
shap_values = explainer.shap_values(shap_sample, check_additivity=False)
df_shap = pd.DataFrame()
df_shap['weight'] = shap_values[:, 2]
df_shap['height'] = shap_sample.iloc[:, 2]
# pdpy = df_shap.groupby('height').mean().reset_index()
# print("len pdpy", len(pdpy))
GREY = '#444443'
fig, ax = plt.subplots(1, 1, figsize=figsize)
shap.dependence_plot("height", shap_values, shap_sample,
interaction_index=None, ax=ax, dot_size=5,
show=False, alpha=1)
# ax.plot(pdpy['height'], pdpy['weight'], '.', c='k', markersize=.5, alpha=.5)
ax.spines['left'].set_linewidth(.5)
ax.spines['bottom'].set_linewidth(.5)
ax.spines['right'].set_linewidth(.5)
ax.spines['top'].set_linewidth(.5)
ax.set_ylabel(ylabel, fontsize=10, labelpad=0)
ax.set_xlabel(xlabel, fontsize=10)
ax.tick_params(axis='both', which='major', labelsize=10)
ax.plot([70,70], [-75,75], '--', lw=.6, color=GREY)
ax.text(69.8,60, "Max female", horizontalalignment='right',
fontsize=9)
leaf_xranges, leaf_slopes, slope_counts_at_x, dx, slope_at_x, pdpx, pdpy, ignored = \
partial_dependence(X=X, y=y, colname='height')
ax.set_ylim(-77,75)
# ax.set_xlim(min(pdpx), max(pdpx))
ax.set_xticks([60,65,70,75])
ax.set_yticks(yticks)
ax.set_title(f"SHAP {feature_perturbation}", fontsize=10)
# ax.set_ylim(-40,70)
print(min(pdpx), max(pdpx))
print(min(pdpy), max(pdpy))
rise = max(pdpy) - min(pdpy)
run = max(pdpx) - min(pdpx)
slope = rise/run
print(slope)
# ax.plot([min(pdpx),max(pdpyX['height'])], [0,]
if twin:
ax2 = ax.twinx()
# ax2.set_xlim(min(pdpx), max(pdpx))
ax2.set_ylim(min(pdpy)-5, max(pdpy)+5)
ax2.set_xticks([60,65,70,75])
ax2.set_yticks([0,20,40,60,80,100,120,140,150])
# ax2.set_ylabel("weight", fontsize=12)
ax2.plot(pdpx, pdpy, '.', markersize=1, c='k')
# ax2.text(65,25, f"StratPD slope = {slope:.1f}")
ax2.annotate(f"StratPD", (64.65,39), xytext=(66,18),
horizontalalignment='left',
arrowprops=dict(facecolor='black', width=.5, headwidth=5, headlength=5),
fontsize=9)
savefig(f"weight_{feature_perturbation}_shap")
def saledayofweek():
np.random.seed(1) # pick seed for reproducible article images
n = 10_000
shap_test_size = 1000
TUNE_RF = False
X, y = load_bulldozer(n=n)
avgprice = pd.concat([X,y], axis=1).groupby('saledayofweek')[['SalePrice']].mean()
avgprice = avgprice.reset_index()['SalePrice']
print(avgprice)
fig, ax = plt.subplots(1, 1, figsize=figsize2)
ax.scatter(range(0,7), avgprice, s=20, c='k')
ax.scatter(X['saledayofweek'], y, s=3, alpha=.1, c='#1E88E5')
# ax.set_xlim(1960,2010)
ax.set_xlabel("saledayofweek\n(a)", fontsize=11)
ax.set_ylabel("SalePrice ($)", fontsize=11)
ax.set_title("Marginal plot", fontsize=13)
ax.spines['left'].set_linewidth(.5)
ax.spines['bottom'].set_linewidth(.5)
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
savefig(f"bulldozer_saledayofweek_marginal")
if TUNE_RF:
rf, _ = tune_RF(X, y)
# RF best: {'max_features': 0.9, 'min_samples_leaf': 1, 'n_estimators': 150}
# validation R^2 0.8001628465688546
else:
rf = RandomForestRegressor(n_estimators=150, n_jobs=-1,
max_features=0.9,
min_samples_leaf=1, oob_score=True)
rf.fit(X, y)
print("RF OOB R^2", rf.oob_score_)
explainer = shap.TreeExplainer(rf, data=shap.sample(X, 100),
feature_perturbation='interventional')
shap_sample = X.sample(shap_test_size, replace=False)
shap_values = explainer.shap_values(shap_sample, check_additivity=False)
fig, ax = plt.subplots(1, 1, figsize=figsize2)
shap.dependence_plot("saledayofweek", shap_values, shap_sample,
interaction_index=None, ax=ax, dot_size=5,
show=False, alpha=.5)
ax.spines['left'].set_linewidth(.5)
ax.spines['bottom'].set_linewidth(.5)
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.set_title("SHAP", fontsize=13)
ax.set_ylabel("Impact on SalePrice\n(saledayofweek SHAP)", fontsize=11)
ax.set_xlabel("saledayofweek\n(b)", fontsize=11)
# ax.set_xlim(1960, 2010)
ax.tick_params(axis='both', which='major', labelsize=10)
savefig(f"bulldozer_saledayofweek_shap")
fig, ax = plt.subplots(1, 1, figsize=figsize2)
plot_catstratpd(X, y, colname='saledayofweek', targetname='SalePrice',
catnames={0:'M',1:'T',2:'W',3:'R',4:'F',5:'S',6:'S'},
n_trials=1,
bootstrap=True,
show_x_counts=True,
show_xlabel=False,
show_impact=False,
pdp_marker_size=4,
pdp_marker_alpha=1,
ax=ax
)
ax.set_title("StratPD", fontsize=13)
ax.set_xlabel("saledayofweek\n(d)", fontsize=11)
# ax.set_xlim(1960,2010)
# ax.set_ylim(-10000,30_000)
savefig(f"bulldozer_saledayofweek_stratpd")
fig, ax = plt.subplots(1, 1, figsize=figsize2)
ice = predict_ice(rf, X, "saledayofweek", 'SalePrice', numx=30, nlines=100)
plot_ice(ice, "saledayofweek", 'SalePrice', alpha=.3, ax=ax, show_ylabel=True,
# yrange=(-10000,30_000),
min_y_shifted_to_zero=True)
# ax.set_xlim(1960, 2010)
savefig(f"bulldozer_saledayofweek_pdp")
def productsize():
np.random.seed(1) # pick seed for reproducible article images
shap_test_size = 1000
TUNE_RF = False
# reuse same data generated by gencsv.py for bulldozer to
# make same comparison.
df = pd.read_csv("bulldozer20k.csv")
X = df.drop('SalePrice', axis=1)
y = df['SalePrice']
fig, ax = plt.subplots(1, 1, figsize=figsize2)
ax.scatter(X['ProductSize'], y, s=3, alpha=.1, c='#1E88E5')
# ax.set_xlim(1960,2010)
ax.set_xlabel("ProductSize\n(a)", fontsize=11)
ax.set_ylabel("SalePrice ($)", fontsize=11)
ax.set_title("Marginal plot", fontsize=13)
ax.spines['left'].set_linewidth(.5)
ax.spines['bottom'].set_linewidth(.5)
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
savefig(f"bulldozer_ProductSize_marginal")
if TUNE_RF:
rf, _ = tune_RF(X, y)
# RF best: {'max_features': 0.9, 'min_samples_leaf': 1, 'n_estimators': 150}
# validation R^2 0.8001628465688546
else:
rf = RandomForestRegressor(n_estimators=150, n_jobs=-1,
max_features=0.9,
min_samples_leaf=1, oob_score=True)
rf.fit(X, y)
print("RF OOB R^2", rf.oob_score_)
# SHAP
explainer = shap.TreeExplainer(rf, data=shap.sample(X, 100),
feature_perturbation='interventional')
shap_sample = X.sample(shap_test_size, replace=False)
shap_values = explainer.shap_values(shap_sample, check_additivity=False)
fig, ax = plt.subplots(1, 1, figsize=figsize2)
shap.dependence_plot("ProductSize", shap_values, shap_sample,
interaction_index=None, ax=ax, dot_size=5,
show=False, alpha=.5)
ax.spines['left'].set_linewidth(.5)
ax.spines['bottom'].set_linewidth(.5)
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.set_title("(b) SHAP", fontsize=13)
ax.set_ylabel("Impact on SalePrice\n(ProductSize SHAP)", fontsize=11)
ax.set_xlabel("ProductSize", fontsize=11)
# ax.set_xlim(1960, 2010)
ax.set_ylim(-15000,40_000)
ax.tick_params(axis='both', which='major', labelsize=10)
savefig(f"bulldozer_ProductSize_shap")
fig, ax = plt.subplots(1, 1, figsize=figsize2)
plot_stratpd(X, y, colname='ProductSize', targetname='SalePrice',
n_trials=10,
bootstrap=True,
show_slope_lines=False,
show_x_counts=False,
show_xlabel=False,
show_impact=False,
show_all_pdp=False,
pdp_marker_size=10,
pdp_marker_alpha=1,
ax=ax
)
ax.set_title("(d) StratPD", fontsize=13)
ax.set_xlabel("ProductSize", fontsize=11)
ax.set_xlim(0, 5)
ax.set_ylim(-15000,40_000)
savefig(f"bulldozer_ProductSize_stratpd")
fig, ax = plt.subplots(1, 1, figsize=figsize2)
ice = predict_ice(rf, X, "ProductSize", 'SalePrice', numx=30, nlines=100)
plot_ice(ice, "ProductSize", 'SalePrice', alpha=.3, ax=ax, show_ylabel=True,
# yrange=(-10000,30_000),
min_y_shifted_to_zero=True)
# ax.set_xlim(1960, 2010)
ax.set_ylim(-15000,40_000)
ax.set_title("(a) FPD/ICE plot", fontsize=13)
savefig(f"bulldozer_ProductSize_pdp")
def saledayofyear():
np.random.seed(1) # pick seed for reproducible article images
n = 10_000
shap_test_size = 1000
TUNE_RF = False
X, y = load_bulldozer(n=n)
fig, ax = plt.subplots(1, 1, figsize=figsize2)
ax.scatter(X['saledayofyear'], y, s=3, alpha=.1, c='#1E88E5')
# ax.set_xlim(1960,2010)
ax.set_xlabel("saledayofyear\n(a)", fontsize=11)
ax.set_ylabel("SalePrice ($)", fontsize=11)
ax.set_title("Marginal plot", fontsize=13)
ax.spines['left'].set_linewidth(.5)
ax.spines['bottom'].set_linewidth(.5)
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
savefig(f"bulldozer_saledayofyear_marginal")
if TUNE_RF:
rf, _ = tune_RF(X, y)
# RF best: {'max_features': 0.9, 'min_samples_leaf': 1, 'n_estimators': 150}
# validation R^2 0.8001628465688546
else:
rf = RandomForestRegressor(n_estimators=150, n_jobs=-1,
max_features=0.9,
min_samples_leaf=1, oob_score=True)
rf.fit(X, y)
print("RF OOB R^2", rf.oob_score_)
explainer = shap.TreeExplainer(rf, data=shap.sample(X, 100),
feature_perturbation='interventional')
shap_sample = X.sample(shap_test_size, replace=False)
shap_values = explainer.shap_values(shap_sample, check_additivity=False)
fig, ax = plt.subplots(1, 1, figsize=figsize2)
shap.dependence_plot("saledayofyear", shap_values, shap_sample,
interaction_index=None, ax=ax, dot_size=5,
show=False, alpha=.5)
ax.spines['left'].set_linewidth(.5)
ax.spines['bottom'].set_linewidth(.5)
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.set_title("SHAP", fontsize=13)
ax.set_ylabel("Impact on SalePrice\n(saledayofyear SHAP)", fontsize=11)
ax.set_xlabel("saledayofyear\n(b)", fontsize=11)
# ax.set_xlim(1960, 2010)
ax.tick_params(axis='both', which='major', labelsize=10)
savefig(f"bulldozer_saledayofyear_shap")
fig, ax = plt.subplots(1, 1, figsize=figsize2)
plot_stratpd(X, y, colname='saledayofyear', targetname='SalePrice',
n_trials=10,
bootstrap=True,
show_all_pdp=False,
show_slope_lines=False,
show_x_counts=True,
show_xlabel=False,
show_impact=False,
pdp_marker_size=4,
pdp_marker_alpha=1,
ax=ax
)
ax.set_title("StratPD", fontsize=13)
ax.set_xlabel("saledayofyear\n(d)", fontsize=11)
# ax.set_xlim(1960,2010)
# ax.set_ylim(-10000,30_000)
savefig(f"bulldozer_saledayofyear_stratpd")
fig, ax = plt.subplots(1, 1, figsize=figsize2)
ice = predict_ice(rf, X, "saledayofyear", 'SalePrice', numx=30, nlines=100)
plot_ice(ice, "saledayofyear", 'SalePrice', alpha=.3, ax=ax, show_ylabel=True,
# yrange=(-10000,30_000),
min_y_shifted_to_zero=True)
# ax.set_xlim(1960, 2010)
savefig(f"bulldozer_saledayofyear_pdp")
def yearmade():
np.random.seed(1) # pick seed for reproducible article images
n = 20_000
shap_test_size = 1000
TUNE_RF = False
# X, y = load_bulldozer(n=n)
# reuse same data generated by gencsv.py for bulldozer to
# make same comparison.
df = pd.read_csv("bulldozer20k.csv")
X = df.drop('SalePrice', axis=1)
y = df['SalePrice']
if TUNE_RF:
rf, _ = tune_RF(X, y)
# RF best: {'max_features': 0.9, 'min_samples_leaf': 1, 'n_estimators': 150}
# validation R^2 0.8001628465688546
else:
rf = RandomForestRegressor(n_estimators=150, n_jobs=-1,
max_features=0.9,
min_samples_leaf=1, oob_score=True)
rf.fit(X, y)
print("RF OOB R^2", rf.oob_score_)
fig, ax = plt.subplots(1, 1, figsize=figsize2)
ax.scatter(X['YearMade'], y, s=3, alpha=.1, c='#1E88E5')
ax.set_xlim(1960,2010)
ax.set_xlabel("YearMade", fontsize=11)
ax.set_ylabel("SalePrice ($)", fontsize=11)
ax.set_title("(a) Marginal plot", fontsize=13)
ax.spines['left'].set_linewidth(.5)
ax.spines['bottom'].set_linewidth(.5)
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
savefig(f"bulldozer_YearMade_marginal")
explainer = shap.TreeExplainer(rf, data=shap.sample(X, 100),
feature_perturbation='interventional')
shap_sample = X.sample(shap_test_size, replace=False)
shap_values = explainer.shap_values(shap_sample, check_additivity=False)
fig, ax = plt.subplots(1, 1, figsize=figsize2)
shap.dependence_plot("YearMade", shap_values, shap_sample,
interaction_index=None, ax=ax, dot_size=5,
show=False, alpha=.5)
ax.yaxis.label.set_visible(False)
ax.spines['left'].set_linewidth(.5)
ax.spines['bottom'].set_linewidth(.5)
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.set_title("(b) SHAP", fontsize=13)
ax.set_ylabel("Impact on SalePrice\n(YearMade SHAP)", fontsize=11)
ax.set_xlabel("YearMade", fontsize=11)
ax.set_xlim(1960, 2010)
ax.tick_params(axis='both', which='major', labelsize=10)
savefig(f"bulldozer_YearMade_shap")
fig, ax = plt.subplots(1, 1, figsize=figsize2)
plot_stratpd(X, y, colname='YearMade', targetname='SalePrice',
n_trials=10,
bootstrap=True,
show_slope_lines=False,
show_x_counts=True,
show_ylabel=False,
show_xlabel=False,
show_impact=False,
pdp_marker_size=4,
pdp_marker_alpha=1,
ax=ax
)
ax.set_title("(d) StratPD", fontsize=13)
ax.set_xlabel("YearMade", fontsize=11)
ax.set_xlim(1960,2010)
ax.set_ylim(-5000,30_000)
savefig(f"bulldozer_YearMade_stratpd")
fig, ax = plt.subplots(1, 1, figsize=figsize2)
ice = predict_ice(rf, X, "YearMade", 'SalePrice', numx=30, nlines=100)
plot_ice(ice, "YearMade", 'SalePrice', alpha=.3, ax=ax, show_ylabel=True,
yrange=(20_000,55_000))
ax.set_xlabel("YearMade", fontsize=11)
ax.set_xlim(1960, 2010)
ax.set_title("(a) FPD/ICE plot", fontsize=13)
savefig(f"bulldozer_YearMade_pdp")
def MachineHours():
np.random.seed(1) # pick seed for reproducible article images
shap_test_size = 1000
TUNE_RF = False
# reuse same data generated by gencsv.py for bulldozer to
# make same comparison.
df = pd.read_csv("bulldozer20k.csv")
# DROP RECORDS WITH MISSING MachineHours VALUES
# df = df[df['MachineHours']!=3138]
X = df.drop('SalePrice', axis=1)
y = df['SalePrice']
if TUNE_RF:
rf, _ = tune_RF(X, y)
# RF best: {'max_features': 0.9, 'min_samples_leaf': 1, 'n_estimators': 150}
# validation R^2 0.8001628465688546
else:
rf = RandomForestRegressor(n_estimators=150, n_jobs=-1,
max_features=0.9,
min_samples_leaf=1, oob_score=True)
rf.fit(X, y)
print("RF OOB R^2", rf.oob_score_)
fig, ax = plt.subplots(1, 1, figsize=figsize2)
ax.scatter(X['MachineHours'], y, s=3, alpha=.1, c='#1E88E5')
ax.set_xlim(0,30_000)
ax.set_xlabel("MachineHours\n(a)", fontsize=11)
ax.set_ylabel("SalePrice ($)", fontsize=11)
ax.set_title("Marginal plot", fontsize=13)
ax.spines['left'].set_linewidth(.5)
ax.spines['bottom'].set_linewidth(.5)
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
savefig(f"bulldozer_MachineHours_marginal")
# SHAP
explainer = shap.TreeExplainer(rf, data=shap.sample(X, 100),
feature_perturbation='interventional')
shap_sample = X.sample(shap_test_size, replace=False)
shap_values = explainer.shap_values(shap_sample, check_additivity=False)
fig, ax = plt.subplots(1, 1, figsize=figsize2)
shap.dependence_plot("MachineHours", shap_values, shap_sample,
interaction_index=None, ax=ax, dot_size=5,
show=False, alpha=.5)
ax.yaxis.label.set_visible(False)
ax.spines['left'].set_linewidth(.5)
ax.spines['bottom'].set_linewidth(.5)
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.set_title("SHAP", fontsize=13)
ax.set_ylabel("SHAP MachineHours)", fontsize=11)
ax.set_xlabel("MachineHours\n(b)", fontsize=11)
ax.set_xlim(0,30_000)
ax.set_ylim(-3000,5000)
ax.tick_params(axis='both', which='major', labelsize=10)
savefig(f"bulldozer_MachineHours_shap")
# STRATPD
fig, ax = plt.subplots(1, 1, figsize=figsize2)
plot_stratpd(X, y, colname='MachineHours', targetname='SalePrice',
n_trials=10,
bootstrap=True,
show_all_pdp=False,
show_slope_lines=False,
show_x_counts=True,
barchar_alpha=1.0,
barchar_color='k',
show_ylabel=False,
show_xlabel=False,
show_impact=False,
pdp_marker_size=1,
pdp_marker_alpha=.3,
ax=ax
)
# ax.annotate("Imputed median value", xytext=(10000,-5300),
# xy=(3138,-5200), fontsize=9,
# arrowprops={'arrowstyle':"->"})
ax.yaxis.label.set_visible(False)
ax.set_title("StratPD", fontsize=13)
ax.set_xlim(0,30_000)
ax.set_xlabel("MachineHours\n(d)", fontsize=11)
ax.set_ylim(-6500,2_000)
savefig(f"bulldozer_MachineHours_stratpd")
fig, ax = plt.subplots(1, 1, figsize=figsize2)
ice = predict_ice(rf, X, "MachineHours", 'SalePrice', numx=300, nlines=200)
plot_ice(ice, "MachineHours", 'SalePrice', alpha=.5, ax=ax,
show_ylabel=True,
yrange=(33_000,38_000)
)
ax.set_xlabel("MachineHours\n(a)", fontsize=11)
ax.set_title("FPD/ICE plot", fontsize=13)
ax.set_xlim(0,30_000)
savefig(f"bulldozer_MachineHours_pdp")
def unsup_yearmade():
np.random.seed(1) # pick seed for reproducible article images
n = 10_000
X, y = load_bulldozer(n=n)
fig, ax = plt.subplots(1, 1, figsize=figsize2)
plot_stratpd(X, y, colname='YearMade', targetname='SalePrice',
n_trials=1,
bootstrap=True,
show_slope_lines=False,
show_x_counts=True,
show_xlabel=False,
show_impact=False,
pdp_marker_size=4,
pdp_marker_alpha=1,
ax=ax,
supervised=False
)
ax.set_title("Unsupervised StratPD", fontsize=13)
ax.set_xlabel("YearMade", fontsize=11)
ax.set_xlim(1960,2010)
ax.set_ylim(-10000,30_000)
savefig(f"bulldozer_YearMade_stratpd_unsup")
def unsup_weight():
np.random.seed(1) # pick seed for reproducible article images
print(f"----------- {inspect.stack()[0][3]} -----------")
X, y, df_raw, eqn = toy_weight_data(2000)
df = df_raw.copy()
catencoders = df_string_to_cat(df)
df_cat_to_catcode(df)
df['pregnant'] = df['pregnant'].astype(int)
X = df.drop('weight', axis=1)
y = df['weight']
fig, axes = plt.subplots(2, 2, figsize=(4, 4))
plot_stratpd(X, y, 'education', 'weight', ax=axes[0, 0],
show_x_counts=False,
yrange=(-13, 0), slope_line_alpha=.1, supervised=False)
plot_stratpd(X, y, 'education', 'weight', ax=axes[0, 1],
show_x_counts=False,
yrange=(-13, 0), slope_line_alpha=.1, supervised=True)
plot_catstratpd(X, y, 'pregnant', 'weight', ax=axes[1, 0],
show_x_counts=False,
catnames=df_raw['pregnant'].unique(),
yrange=(-5, 45))
plot_catstratpd(X, y, 'pregnant', 'weight', ax=axes[1, 1],
show_x_counts=False,
catnames=df_raw['pregnant'].unique(),
yrange=(-5, 45))
axes[0, 0].set_title("Unsupervised")
axes[0, 1].set_title("Supervised")
axes[0, 1].get_yaxis().set_visible(False)
axes[1, 1].get_yaxis().set_visible(False)
savefig(f"weight_unsup")
plt.close()
def weight_ntrees():
np.random.seed(1) # pick seed for reproducible article images
print(f"----------- {inspect.stack()[0][3]} -----------")
X, y, df_raw, eqn = toy_weight_data(1000)
df = df_raw.copy()
catencoders = df_string_to_cat(df)
df_cat_to_catcode(df)
df['pregnant'] = df['pregnant'].astype(int)
X = df.drop('weight', axis=1)
y = df['weight']
trees = [1, 5, 10, 30]
fig, axes = plt.subplots(2, 4, figsize=(8, 4))
for i in range(1, 4):
axes[0, i].get_yaxis().set_visible(False)
axes[1, i].get_yaxis().set_visible(False)
for i in range(0, 4):
axes[0, i].set_title(f"{trees[i]} trees")
plot_stratpd(X, y, 'education', 'weight', ax=axes[0, 0],
min_samples_leaf=5,
yrange=(-12, 0), slope_line_alpha=.1, pdp_marker_size=10, show_ylabel=True,
n_trees=1, max_features=1.0, bootstrap=False)
plot_stratpd(X, y, 'education', 'weight', ax=axes[0, 1],
min_samples_leaf=5,
yrange=(-12, 0), slope_line_alpha=.1, pdp_marker_size=10, show_ylabel=False,
n_trees=5, max_features='auto', bootstrap=True)
plot_stratpd(X, y, 'education', 'weight', ax=axes[0, 2],
min_samples_leaf=5,
yrange=(-12, 0), slope_line_alpha=.08, pdp_marker_size=10, show_ylabel=False,
n_trees=10, max_features='auto', bootstrap=True)
plot_stratpd(X, y, 'education', 'weight', ax=axes[0, 3],
min_samples_leaf=5,
yrange=(-12, 0), slope_line_alpha=.05, pdp_marker_size=10, show_ylabel=False,
n_trees=30, max_features='auto', bootstrap=True)
plot_catstratpd(X, y, 'pregnant', 'weight', ax=axes[1, 0],
catnames={0:False, 1:True}, show_ylabel=True,
yrange=(0, 35),
n_trees=1, max_features=1.0, bootstrap=False)
plot_catstratpd(X, y, 'pregnant', 'weight', ax=axes[1, 1],
catnames={0:False, 1:True}, show_ylabel=False,
yrange=(0, 35),
n_trees=5, max_features='auto', bootstrap=True)
plot_catstratpd(X, y, 'pregnant', 'weight', ax=axes[1, 2],
catnames={0:False, 1:True}, show_ylabel=False,
yrange=(0, 35),
n_trees=10, max_features='auto', bootstrap=True)
plot_catstratpd(X, y, 'pregnant', 'weight', ax=axes[1, 3],
catnames={0:False, 1:True}, show_ylabel=False,
yrange=(0, 35),
n_trees=30, max_features='auto', bootstrap=True)
savefig(f"education_pregnant_vs_weight_ntrees")
plt.close()
def meta_weight():
np.random.seed(1) # pick seed for reproducible article images
print(f"----------- {inspect.stack()[0][3]} -----------")
X, y, df_raw, eqn = toy_weight_data(1000)
df = df_raw.copy()
catencoders = df_string_to_cat(df)
df_cat_to_catcode(df)
df['pregnant'] = df['pregnant'].astype(int)
X = df.drop('weight', axis=1)
y = df['weight']
plot_stratpd_gridsearch(X, y, colname='education', targetname='weight',
show_slope_lines=True,
xrange=(10,18),
yrange=(-12,0))
savefig("education_weight_meta")
plot_stratpd_gridsearch(X, y, colname='height', targetname='weight', yrange=(0,150),
show_slope_lines=True)
savefig("height_weight_meta")
def noisy_poly_data(n, sd=1.0):
x1 = np.random.uniform(-2, 2, size=n)
x2 = np.random.uniform(-2, 2, size=n)
y = x1 ** 2 + x2 + 10 + np.random.normal(0, sd, size=n)
df = pd.DataFrame()
df['x1'] = x1
df['x2'] = x2
df['y'] = y
return df
def noise():
np.random.seed(1) # pick seed for reproducible article images
print(f"----------- {inspect.stack()[0][3]} -----------")
n = 1000
fig, axes = plt.subplots(1, 4, figsize=(8, 2), sharey=True)
sds = [0,.5,1,2]
for i,sd in enumerate(sds):
df = noisy_poly_data(n=n, sd=sd)
X = df.drop('y', axis=1)
y = df['y']
plot_stratpd(X, y, 'x1', 'y',
show_ylabel=False,
pdp_marker_size=1,
show_x_counts=False,
ax=axes[i], yrange=(-4, .5))
axes[0].set_ylabel("y", fontsize=12)
for i,(ax,which) in enumerate(zip(axes,['(a)','(b)','(c)','(d)'])):
ax.text(0, -1, f"{which}\n$\sigma = {sds[i]}$", horizontalalignment='center')
ax.set_xlabel('$x_1$', fontsize=12)
ax.set_xticks([-2,-1,0,1,2])
savefig(f"noise")
def meta_noise():
np.random.seed(1) # pick seed for reproducible article images
print(f"----------- {inspect.stack()[0][3]} -----------")
n = 1000
noises = [0, .5, .8, 1.0]
sizes = [2, 10, 30, 50]
fig, axes = plt.subplots(len(noises), len(sizes), figsize=(7, 6), sharey=True,
sharex=True)
row = 0
for sd in noises:
df = noisy_poly_data(n=n, sd=sd)
X = df.drop('y', axis=1)
y = df['y']
col = 0
for s in sizes:
if row == 3:
show_xlabel = True
else:
show_xlabel = False
print(f"------------------- noise {sd}, SIZE {s} --------------------")
if col > 1: axes[row, col].get_yaxis().set_visible(False)
plot_stratpd(X, y, 'x1', 'y', ax=axes[row, col],
show_x_counts=False,
min_samples_leaf=s,
yrange=(-3.5, .5),
pdp_marker_size=1,
show_ylabel=False,
show_xlabel=show_xlabel)
if col == 0:
axes[row, col].set_ylabel(f'$y, \epsilon \sim N(0,{sd:.2f})$')
if row == 0:
axes[row, col].set_title("Min $x_{\\overline{c}}$ leaf " + f"{s}",
fontsize=12)
col += 1
row += 1
lastrow = len(noises)
# row = 0
# for sd in noises:
# axes[row, 0].scatter(X['x1'], y, slope_line_alpha=.12, label=None)
# axes[row, 0].set_xlabel("x1")
# axes[row, 0].set_ylabel("y")
# axes[row, 0].set_ylim(-5, 5)
# axes[row, 0].set_title(f"$y = x_1^2 + x_2 + \epsilon$, $\epsilon \sim N(0,{sd:.2f})$")
# row += 1
# axes[lastrow, 0].set_ylabel(f'$y$ vs $x_c$ partition')
# col = 0
# for s in sizes:
# rtreeviz_univar(axes[lastrow, col],
# X['x2'], y,
# min_samples_leaf=s,
# feature_name='x2',
# target_name='y',
# fontsize=10, show={'splits'},
# split_linewidth=.5,
# markersize=5)
# axes[lastrow, col].set_xlabel("x2")
# col += 1
savefig(f"meta_additivity_noise")
def bigX_data(n):
x1 = np.random.uniform(-1, 1, size=n)
x2 = np.random.uniform(-1, 1, size=n)
x3 = np.random.uniform(-1, 1, size=n)
y = 0.2 * x1 - 5 * x2 + 10 * x2 * np.where(x3 >= 0, 1, 0) + np.random.normal(0, 1,
size=n)
df = pd.DataFrame()
df['x1'] = x1
df['x2'] = x2
df['x3'] = x3
df['y'] = y
return df
def bigX():
np.random.seed(1) # pick seed for reproducible article images
print(f"----------- {inspect.stack()[0][3]} -----------")
n = 1000
df = bigX_data(n=n)
X = df.drop('y', axis=1)
y = df['y']
# plot_stratpd_gridsearch(X, y, 'x2', 'y',
# min_samples_leaf_values=[2,5,10,20,30],
# # nbins_values=[1,3,5,6,10],
# yrange=(-4,4))
#
# plt.tight_layout()
# plt.show()
# return
# Partial deriv is just 0.2 so this is correct. flat deriv curve, net effect line at slope .2
# ICE is way too shallow and not line at n=1000 even
fig, axes = plt.subplots(2, 2, figsize=(4, 4), sharey=True)
# Partial deriv wrt x2 is -5 plus 10 about half the time so about 0
# Should not expect a criss-cross like ICE since deriv of 1_x3>=0 is 0 everywhere
# wrt to any x, even x3. x2 *is* affecting y BUT the net effect at any spot
# is what we care about and that's 0. Just because marginal x2 vs y shows non-
# random plot doesn't mean that x2's net effect is nonzero. We are trying to
# strip away x1/x3's effect upon y. When we do, x2 has no effect on y.
# Ask what is net effect at every x2? 0.
plot_stratpd(X, y, 'x2', 'y', ax=axes[0, 0], yrange=(-4, 4),
min_samples_leaf=5,
pdp_marker_size=2)
# Partial deriv wrt x3 of 1_x3>=0 is 0 everywhere so result must be 0
plot_stratpd(X, y, 'x3', 'y', ax=axes[1, 0], yrange=(-4, 4),
min_samples_leaf=5,
pdp_marker_size=2)
rf = RandomForestRegressor(n_estimators=100, min_samples_leaf=1, oob_score=True)
rf.fit(X, y)
print(f"RF OOB {rf.oob_score_}")
ice = predict_ice(rf, X, 'x2', 'y', numx=100)
plot_ice(ice, 'x2', 'y', ax=axes[0, 1], yrange=(-4, 4))
ice = predict_ice(rf, X, 'x3', 'y', numx=100)
plot_ice(ice, 'x3', 'y', ax=axes[1, 1], yrange=(-4, 4))
axes[0, 1].get_yaxis().set_visible(False)
axes[1, 1].get_yaxis().set_visible(False)
axes[0, 0].set_title("StratPD", fontsize=10)
axes[0, 1].set_title("FPD/ICE", fontsize=10)
savefig(f"bigx")
plt.close()
def unsup_boston():
np.random.seed(1) # pick seed for reproducible article images
# np.random.seed(42)
print(f"----------- {inspect.stack()[0][3]} -----------")
boston = load_boston()
print(len(boston.data))
df = pd.DataFrame(boston.data, columns=boston.feature_names)
df['MEDV'] = boston.target
X = df.drop('MEDV', axis=1)
y = df['MEDV']
fig, axes = plt.subplots(1, 4, figsize=(9, 2))
axes[0].scatter(df['AGE'], y, s=5, alpha=.7)
axes[0].set_ylabel('MEDV')
axes[0].set_xlabel('AGE')
axes[0].set_title("Marginal")
axes[1].set_title("Unsupervised StratPD")
axes[2].set_title("Supervised StratPD")
axes[3].set_title("FPD/ICE")
plot_stratpd(X, y, 'AGE', 'MEDV', ax=axes[1], yrange=(-20, 20),
n_trees=20,
bootstrap=True,
# min_samples_leaf=10,
max_features='auto',
supervised=False, show_ylabel=False,
verbose=True,
slope_line_alpha=.1)
plot_stratpd(X, y, 'AGE', 'MEDV', ax=axes[2], yrange=(-20, 20),
min_samples_leaf=5,
n_trees=1,
supervised=True, show_ylabel=False)
axes[1].text(5, 15, f"20 trees, bootstrap")
axes[2].text(5, 15, f"1 tree, no bootstrap")
rf = RandomForestRegressor(n_estimators=100, oob_score=True)
rf.fit(X, y)
print(f"RF OOB {rf.oob_score_}")
ice = predict_ice(rf, X, 'AGE', 'MEDV', numx=10)
plot_ice(ice, 'AGE', 'MEDV', ax=axes[3], yrange=(-20, 20), show_ylabel=False)
# axes[0,1].get_yaxis().set_visible(False)
# axes[1,1].get_yaxis().set_visible(False)
savefig(f"boston_unsup")
# plt.tight_layout()
# plt.show()
def lm_plot(X, y, colname, targetname, ax=None):
ax.scatter(X[colname], y, alpha=.12, label=None)
ax.set_xlabel(colname)
ax.set_ylabel(targetname)
col = X[colname]
# y_pred_hp = r_col.predict(col.values.reshape(-1, 1))
# ax.plot(col, y_pred_hp, ":", linewidth=1, c='red', label='y ~ horsepower')
r = LinearRegression()
r.fit(X[['horsepower', 'weight']], y)
xcol = np.linspace(np.min(col), np.max(col), num=100)
ci = 0 if colname == 'horsepower' else 1
# use beta from y ~ hp + weight
# ax.plot(xcol, xcol * r.coef_[ci] + r.intercept_, linewidth=1, c='orange')
# ax.text(min(xcol)*1.02, max(y)*.95, f"$\\beta_{{{colname}}}$={r.coef_[ci]:.3f}")
# r = LinearRegression()
# r.fit(X[['horsepower','weight']], y)
# xcol = np.linspace(np.min(col), np.max(col), num=100)
# ci = X.columns.get_loc(colname)
# # ax.plot(xcol, xcol * r.coef_[ci] + r_col.intercept_, linewidth=1, c='orange', label=f"$\\beta_{{{colname}}}$")
# left40 = xcol[int(len(xcol) * .4)]
# ax.text(min(xcol), max(y)*.94, f"$\hat{{y}} = \\beta_0 + \\beta_1 x_{{horsepower}} + \\beta_2 x_{{weight}}$")
# i = 1 if colname=='horsepower' else 2
# # ax.text(left40, left40*r.coef_[ci] + r_col.intercept_, f"$\\beta_{i}$={r.coef_[ci]:.3f}")
def cars():
np.random.seed(1) # pick seed for reproducible article images
print(f"----------- {inspect.stack()[0][3]} -----------")
df_cars = pd.read_csv("../notebooks/data/auto-mpg.csv")
df_cars = df_cars[df_cars['horsepower'] != '?'] # drop the few missing values
df_cars['horsepower'] = df_cars['horsepower'].astype(float)
X = df_cars[['horsepower', 'weight']]
y = df_cars['mpg']
fig, axes = plt.subplots(2, 3, figsize=(9, 4))
lm_plot(X, y, 'horsepower', 'mpg', ax=axes[0, 0])
lm_plot(X, y, 'weight', 'mpg', ax=axes[1, 0])
plot_stratpd(X, y, 'horsepower', 'mpg', ax=axes[0, 1],
min_samples_leaf=10,
xrange=(45, 235), yrange=(-20, 20), show_ylabel=False)
plot_stratpd(X, y, 'weight', 'mpg', ax=axes[1, 1],
min_samples_leaf=10,
xrange=(1600, 5200), yrange=(-20, 20), show_ylabel=False)
rf = RandomForestRegressor(n_estimators=100, min_samples_leaf=1, oob_score=True)
rf.fit(X, y)
ice = predict_ice(rf, X, 'horsepower', 'mpg', numx=100)
plot_ice(ice, 'horsepower', 'mpg', ax=axes[0, 2], yrange=(-20, 20), show_ylabel=False)
ice = predict_ice(rf, X, 'weight', 'mpg', numx=100)
plot_ice(ice, 'weight', 'mpg', ax=axes[1, 2], yrange=(-20, 20), show_ylabel=False)
# draw regr line for horsepower
r = LinearRegression()
r.fit(X, y)
colname = 'horsepower'
col = X[colname]
xcol = np.linspace(np.min(col), np.max(col), num=100)
ci = X.columns.get_loc(colname)
beta0 = -r.coef_[ci] * min(col) # solved for beta0 to get y-intercept
# axes[0,1].plot(xcol, xcol * r.coef_[ci], linewidth=1, c='orange', label=f"$\\beta_{{{colname}}}$")
# axes[0,2].plot(xcol, xcol * r.coef_[ci], linewidth=1, c='orange', label=f"$\\beta_{{{colname}}}$")
# draw regr line for weight
colname = 'weight'
col = X[colname]
xcol = np.linspace(np.min(col), np.max(col), num=100)
ci = X.columns.get_loc(colname)
beta0 = -r.coef_[ci] * min(col) # solved for beta0 to get y-intercept
# axes[1,1].plot(xcol, xcol * r.coef_[ci]+11, linewidth=1, c='orange', label=f"$\\beta_{{{colname}}}$")
# axes[1,2].plot(xcol, xcol * r.coef_[ci]+13, linewidth=1, c='orange', label=f"$\\beta_{{{colname}}}$")
axes[1, 2].set_xlim(1600, 5200)
savefig("cars")
def meta_cars():
np.random.seed(1) # pick seed for reproducible article images
print(f"----------- {inspect.stack()[0][3]} -----------")
df_cars = pd.read_csv("../notebooks/data/auto-mpg.csv")
df_cars = df_cars[df_cars['horsepower'] != '?'] # drop the few missing values
df_cars['horsepower'] = df_cars['horsepower'].astype(float)
X = df_cars[['horsepower', 'weight']]
y = df_cars['mpg']
plot_stratpd_gridsearch(X, y, colname='horsepower', targetname='mpg',
show_slope_lines=True,
min_samples_leaf_values=[2,5,10,20,30],
nbins_values=[1,2,3,4,5],
yrange=(-20, 20))
savefig("horsepower_meta")
plot_stratpd_gridsearch(X, y, colname='weight', targetname='mpg',
show_slope_lines=True,
min_samples_leaf_values=[2,5,10,20,30],
nbins_values=[1,2,3,4,5],
yrange=(-20, 20))
savefig("weight_meta")
def multi_joint_distr():
np.random.seed(1) # pick seed for reproducible article images
print(f"----------- {inspect.stack()[0][3]} -----------")
# np.random.seed(42)
n = 1000
min_samples_leaf = 30
nbins = 2
df = pd.DataFrame(np.random.multivariate_normal([6, 6, 6, 6],
[
[1, 5, .7, 3],
[5, 1, 2, .5],
[.7, 2, 1, 1.5],
[3, .5, 1.5, 1]
],
n),
columns=['x1', 'x2', 'x3', 'x4'])
df['y'] = df['x1'] + df['x2'] + df['x3'] + df['x4']
X = df.drop('y', axis=1)
y = df['y']
r = LinearRegression()
r.fit(X, y)
print(r.coef_) # should be all 1s
yrange = (-2, 15)
fig, axes = plt.subplots(6, 4, figsize=(7.5, 8.5), sharey=False) # , sharex=True)
axes[0, 0].scatter(X['x1'], y, s=5, alpha=.08)
axes[0, 0].set_xlim(0, 13)
axes[0, 0].set_ylim(0, 45)
axes[0, 1].scatter(X['x2'], y, s=5, alpha=.08)
axes[0, 1].set_xlim(0, 13)
axes[0, 1].set_ylim(3, 45)
axes[0, 2].scatter(X['x3'], y, s=5, alpha=.08)
axes[0, 2].set_xlim(0, 13)
axes[0, 2].set_ylim(3, 45)
axes[0, 3].scatter(X['x4'], y, s=5, alpha=.08)
axes[0, 3].set_xlim(0, 13)
axes[0, 3].set_ylim(3, 45)
axes[0, 0].text(1, 38, 'Marginal', horizontalalignment='left')
axes[0, 1].text(1, 38, 'Marginal', horizontalalignment='left')
axes[0, 2].text(1, 38, 'Marginal', horizontalalignment='left')
axes[0, 3].text(1, 38, 'Marginal', horizontalalignment='left')
axes[0, 0].set_ylabel("y")
for i in range(6):
for j in range(1, 4):
axes[i, j].get_yaxis().set_visible(False)
for i in range(6):
for j in range(4):
axes[i, j].set_xlim(0, 15)
pdpx, pdpy, ignored = \
plot_stratpd(X, y, 'x1', 'y', ax=axes[1, 0], xrange=(0, 13),
min_samples_leaf=min_samples_leaf,
yrange=yrange, show_xlabel=False, show_ylabel=True)
r = LinearRegression()
r.fit(pdpx.reshape(-1, 1), pdpy)
axes[1, 0].text(1, 10, f"Slope={r.coef_[0]:.2f}")
pdpx, pdpy, ignored = \
plot_stratpd(X, y, 'x2', 'y', ax=axes[1, 1], xrange=(0, 13),
# show_dx_line=True,
min_samples_leaf=min_samples_leaf,
yrange=yrange, show_xlabel=False, show_ylabel=False)
r = LinearRegression()
r.fit(pdpx.reshape(-1, 1), pdpy)
axes[1, 1].text(1, 10, f"Slope={r.coef_[0]:.2f}")
pdpx, pdpy, ignored = \
plot_stratpd(X, y, 'x3', 'y', ax=axes[1, 2], xrange=(0, 13),
# show_dx_line=True,
min_samples_leaf=min_samples_leaf,
yrange=yrange, show_xlabel=False, show_ylabel=False)
r = LinearRegression()
r.fit(pdpx.reshape(-1, 1), pdpy)
axes[1, 2].text(1, 10, f"Slope={r.coef_[0]:.2f}")
pdpx, pdpy, ignored = \
plot_stratpd(X, y, 'x4', 'y', ax=axes[1, 3], xrange=(0, 13),
# show_dx_line=True,
min_samples_leaf=min_samples_leaf,
yrange=yrange, show_xlabel=False, show_ylabel=False)
r = LinearRegression()
r.fit(pdpx.reshape(-1, 1), pdpy)
axes[1, 3].text(1, 10, f"Slope={r.coef_[0]:.2f}")
axes[1, 0].text(1, 12, 'StratPD', horizontalalignment='left')
axes[1, 1].text(1, 12, 'StratPD', horizontalalignment='left')
axes[1, 2].text(1, 12, 'StratPD', horizontalalignment='left')
axes[1, 3].text(1, 12, 'StratPD', horizontalalignment='left')
# plt.show()
# return
nfeatures = 4
regrs = [
RandomForestRegressor(n_estimators=100, min_samples_leaf=1, oob_score=True),
svm.SVR(gamma=1 / nfeatures), # gamma='scale'),
LinearRegression(),
KNeighborsRegressor(n_neighbors=5)]
row = 2
for regr in regrs:
regr.fit(X, y)
rname = regr.__class__.__name__
if rname == 'SVR':
rname = "SVM FPD/ICE"
if rname == 'RandomForestRegressor':
rname = "RF FPD/ICE"
if rname == 'LinearRegression':
rname = 'Linear FPD/ICE'
if rname == 'KNeighborsRegressor':
rname = 'kNN FPD/ICE'
show_xlabel = True if row == 5 else False
axes[row, 0].text(.5, 11, rname, horizontalalignment='left')
axes[row, 1].text(.5, 11, rname, horizontalalignment='left')
axes[row, 2].text(.5, 11, rname, horizontalalignment='left')
axes[row, 3].text(.5, 11, rname, horizontalalignment='left')
ice = predict_ice(regr, X, 'x1', 'y')
plot_ice(ice, 'x1', 'y', ax=axes[row, 0], xrange=(0, 13), yrange=yrange,
alpha=.08,
show_xlabel=show_xlabel, show_ylabel=True)
ice = predict_ice(regr, X, 'x2', 'y')
plot_ice(ice, 'x2', 'y', ax=axes[row, 1], xrange=(0, 13), yrange=yrange,
alpha=.08,
show_xlabel=show_xlabel, show_ylabel=False)
ice = predict_ice(regr, X, 'x3', 'y')
plot_ice(ice, 'x3', 'y', ax=axes[row, 2], xrange=(0, 13), yrange=yrange,
alpha=.08,
show_xlabel=show_xlabel, show_ylabel=False)
ice = predict_ice(regr, X, 'x4', 'y')
plot_ice(ice, 'x4', 'y', ax=axes[row, 3], xrange=(0, 13), yrange=yrange,
alpha=.08,
show_xlabel=show_xlabel, show_ylabel=False)
row += 1
# plt.tight_layout()
# plt.show()
savefig("multivar_multimodel_normal")
def interactions():
np.random.seed(1) # pick seed for reproducible article images
n = 2000
df = synthetic_interaction_data(n)
X, y = df[['x1', 'x2', 'x3']].copy(), df['y'].copy()
X1 = X.iloc[:, 0]
X2 = X.iloc[:, 1]
X3 = X.iloc[:, 2] # UNUSED in y
rf = RandomForestRegressor(n_estimators=10, oob_score=True)
rf.fit(X, y)
print("R^2 training", rf.score(X, y))
print("R^2 OOB", rf.oob_score_)
print("mean(y) =", np.mean(y))
print("mean(X_1), mean(X_2) =", np.mean(X1), np.mean(X2))
pdp_x1 = friedman_partial_dependence(rf, X, 'x1', numx=None, mean_centered=False)
pdp_x2 = friedman_partial_dependence(rf, X, 'x2', numx=None, mean_centered=False)
pdp_x3 = friedman_partial_dependence(rf, X, 'x3', numx=None, mean_centered=False)
m1 = np.mean(pdp_x1[1])
m2 = np.mean(pdp_x2[1])
m3 = np.mean(pdp_x3[1])
print("mean(PDP_1) =", np.mean(pdp_x1[1]))
print("mean(PDP_2) =", np.mean(pdp_x2[1]))
print("mean(PDP_2) =", np.mean(pdp_x3[1]))
print("mean abs PDP_1-ybar", np.mean(np.abs(pdp_x1[1] - m1)))
print("mean abs PDP_2-ybar", np.mean(np.abs(pdp_x2[1] - m2)))
print("mean abs PDP_3-ybar", np.mean(np.abs(pdp_x3[1] - m3)))
explainer = shap.TreeExplainer(rf, data=X,
feature_perturbation='interventional')
shap_values = explainer.shap_values(X, check_additivity=False)
shapavg = np.mean(shap_values, axis=0)
print("SHAP avg x1,x2,x3 =", shapavg)
shapimp = np.mean(np.abs(shap_values), axis=0)
print("SHAP avg |x1|,|x2|,|x3| =", shapimp)
fig, axes = plt.subplots(1,4,figsize=(11.33,2.8))
x1_color = '#1E88E5'
x2_color = 'orange'
x3_color = '#A22396'
axes[0].plot(pdp_x1[0], pdp_x1[1], '.', markersize=1, c=x1_color, label='$FPD_1$', alpha=1)
axes[0].plot(pdp_x2[0], pdp_x2[1], '.', markersize=1, c=x2_color, label='$FPD_2$', alpha=1)
axes[0].plot(pdp_x3[0], pdp_x3[1], '.', markersize=1, c=x3_color, label='$FPD_3$', alpha=1)
axes[0].text(0, 75, f"$\\bar{{y}}={np.mean(y):.1f}$", fontsize=13)
axes[0].set_xticks([0,2,4,6,8,10])
axes[0].set_xlabel("$x_1, x_2, x_3$", fontsize=10)
axes[0].set_ylabel("y")
axes[0].set_yticks([0, 25, 50, 75, 100, 125, 150])
axes[0].set_ylim(-10,160)
axes[0].set_title(f"(a) Friedman FPD")
axes[0].spines['top'].set_linewidth(.5)
axes[0].spines['right'].set_linewidth(.5)
axes[0].spines['left'].set_linewidth(.5)
axes[0].spines['bottom'].set_linewidth(.5)
axes[0].spines['top'].set_color('none')
axes[0].spines['right'].set_color('none')
x1_patch = mpatches.Patch(color=x1_color, label='$x_1$')
x2_patch = mpatches.Patch(color=x2_color, label='$x_2$')
x3_patch = mpatches.Patch(color=x3_color, label='$x_3$')
axes[0].legend(handles=[x1_patch,x2_patch,x3_patch], fontsize=10)
# axes[0].legend(fontsize=10)
#axes[1].plot(shap_values)
shap.dependence_plot("x1", shap_values, X,
interaction_index=None, ax=axes[1], dot_size=4,
show=False, alpha=.5, color=x1_color)
shap.dependence_plot("x2", shap_values, X,
interaction_index=None, ax=axes[1], dot_size=4,
show=False, alpha=.5, color=x2_color)
shap.dependence_plot("x3", shap_values, X,
interaction_index=None, ax=axes[1], dot_size=4,
show=False, alpha=.5, color=x3_color)
axes[1].set_xticks([0,2,4,6,8,10])
axes[1].set_xlabel("$x_1, x_2, x_3$", fontsize=12)
axes[1].set_ylim(-95,110)
axes[1].set_title("(b) SHAP")
axes[1].set_ylabel("SHAP values", fontsize=11)
x1_patch = mpatches.Patch(color=x1_color, label='$x_1$')
x2_patch = mpatches.Patch(color=x2_color, label='$x_2$')
x3_patch = mpatches.Patch(color=x3_color, label='$x_3$')
axes[1].legend(handles=[x1_patch,x2_patch,x3_patch], fontsize=12)
df_x1 = pd.read_csv("images/x1_ale.csv")
df_x2 = pd.read_csv("images/x2_ale.csv")
df_x3 = pd.read_csv("images/x3_ale.csv")
axes[2].plot(df_x1['x.values'],df_x1['f.values'],'.',color=x1_color,markersize=2)
axes[2].plot(df_x2['x.values'],df_x2['f.values'],'.',color=x2_color,markersize=2)
axes[2].plot(df_x3['x.values'],df_x3['f.values'],'.',color=x3_color,markersize=2)
axes[2].set_title("(c) ALE")
# axes[2].set_ylabel("y", fontsize=12)
axes[2].set_xlabel("$x_1, x_2, x_3$", fontsize=12)
axes[2].set_ylim(-95,110)
# axes[2].tick_params(axis='both', which='major', labelsize=10)
axes[2].set_xticks([0,2,4,6,8,10])
axes[2].spines['top'].set_linewidth(.5)
axes[2].spines['right'].set_linewidth(.5)
axes[2].spines['left'].set_linewidth(.5)
axes[2].spines['bottom'].set_linewidth(.5)
axes[2].spines['top'].set_color('none')
axes[2].spines['right'].set_color('none')
x1_patch = mpatches.Patch(color=x1_color, label='$x_1$')
x2_patch = mpatches.Patch(color=x2_color, label='$x_2$')
x3_patch = mpatches.Patch(color=x3_color, label='$x_3$')
axes[2].legend(handles=[x1_patch,x2_patch,x3_patch], fontsize=12)
plot_stratpd(X, y, "x1", "y", ax=axes[3], pdp_marker_size=1,
pdp_marker_color=x1_color,
show_x_counts=False, n_trials=1, show_slope_lines=False)
plot_stratpd(X, y, "x2", "y", ax=axes[3], pdp_marker_size=1,
pdp_marker_color=x2_color,
show_x_counts=False, n_trials=1, show_slope_lines=False)
plot_stratpd(X, y, "x3", "y", ax=axes[3], pdp_marker_size=1,
pdp_marker_color=x3_color,
show_x_counts=False, n_trials=1, show_slope_lines=False)
axes[3].set_xticks([0,2,4,6,8,10])
axes[3].set_ylim(-20,160)
axes[3].set_yticks([0, 25, 50, 75, 100, 125, 150])
axes[3].set_xlabel("$x_1, x_2, x_3$", fontsize=12)
# axes[3].set_ylabel("y", fontsize=12)
axes[3].set_title("(d) StratPD")
axes[3].spines['top'].set_linewidth(.5)
axes[3].spines['right'].set_linewidth(.5)
axes[3].spines['left'].set_linewidth(.5)
axes[3].spines['bottom'].set_linewidth(.5)
axes[3].spines['top'].set_color('none')
axes[3].spines['right'].set_color('none')
x1_patch = mpatches.Patch(color=x1_color, label='$x_1$')
x2_patch = mpatches.Patch(color=x2_color, label='$x_2$')
x3_patch = mpatches.Patch(color=x3_color, label='$x_3$')
axes[3].legend(handles=[x1_patch,x2_patch,x3_patch], fontsize=12)
savefig("interactions")
def gen_ale_plot_data_in_R():
"Exec R and generate images/*.csv files. Then plot with Python"
os.system("R CMD BATCH ale_plots_bulldozer.R")
os.system("R CMD BATCH ale_plots_rent.R")
os.system("R CMD BATCH ale_plots_weather.R")
os.system("R CMD BATCH ale_plots_weight.R")
def ale_yearmade():
df = pd.read_csv("images/YearMade_ale.csv")
# df['f.values'] -= np.min(df['f.values'])
print(df)
fig, ax = plt.subplots(1, 1, figsize=figsize2)
ax.plot(df['x.values'],df['f.values'],'.',color='k',markersize=4)
ax.set_title("(c) ALE", fontsize=13)
ax.set_xlabel("YearMade", fontsize=11)
ax.set_xlim(1960, 2010)
ax.set_ylim(-25000,30000)
ax.tick_params(axis='both', which='major', labelsize=10)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
savefig('bulldozer_YearMade_ale')
def ale_MachineHours():
df = pd.read_csv("images/MachineHours_ale.csv")
# df['f.values'] -= np.min(df['f.values'])
print(df)
fig, ax = plt.subplots(1, 1, figsize=figsize2)
ax.plot(df['x.values'],df['f.values'],'.',color='k',markersize=4)
ax.set_title("ALE", fontsize=13)
# ax.set_ylabel("SalePrice", fontsize=11)
ax.set_xlabel("(c) MachineHours", fontsize=11)
ax.set_xlim(0, 30_000)
ax.set_ylim(-3000,5000)
ax.tick_params(axis='both', which='major', labelsize=10)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
savefig('bulldozer_MachineHours_ale')
def ale_productsize():
df = pd.read_csv("images/ProductSize_ale.csv")
print(df)
fig, ax = plt.subplots(1, 1, figsize=figsize2)
ax.plot(df['x.values'],df['f.values'],'.',color='k',markersize=10)
ax.set_title("(c) ALE", fontsize=13)
# ax.set_ylabel("SalePrice", fontsize=11)
ax.set_xlabel("ProductSize", fontsize=11)
# ax.set_xlim(0, 30_000)
ax.set_ylim(-15000,40000)
ax.tick_params(axis='both', which='major', labelsize=10)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
savefig('bulldozer_ProductSize_ale')
def ale_height():
df = pd.read_csv("images/height_ale.csv")
# df['f.values'] -= np.min(df['f.values'])
print(df)
fig, ax = plt.subplots(1, 1, figsize=(2.4, 2.2))
ax.plot(df['x.values'],df['f.values'],'.',color='k',markersize=1)
# ax.set_ylim(-5,150)
ax.set_ylim(-65,90)
# ax.set_yticks([0,20,40,60,80,100,120,140,150])
ax.set_title("ALE", fontsize=10)
ax.set_ylabel("Weight", fontsize=10, labelpad=0)
ax.set_xlabel("Height\n(d)", fontsize=10)
ax.set_xticks([60,65,70,75])
ax.set_yticks([-75, -60, -40, -20, 0, 20, 40, 60, 75])
ax.tick_params(axis='both', which='major', labelsize=10)
# ax.spines['right'].set_visible(False)
# ax.spines['top'].set_visible(False)
savefig('height_ale')
def ale_state():
df = pd.read_csv("images/state_ale.csv")
df = df.sort_values(by="x.values")
df['f.values'] -= np.min(df['f.values'])
print(df)
fig, ax = plt.subplots(1, 1, figsize=figsize)
ax.bar(df['x.values'],df['f.values'],color='#BEBEBE')
ax.set_title("ALE", fontsize=13)
ax.set_xlabel("state")
ax.set_ylabel("temperature")
ax.set_title("(c) ALE")
ax.set_ylim(0,55)
ax.set_yticks([0,10,20,30,40,50])
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
savefig('state_ale')
def ale_pregnant():
df = pd.read_csv("images/pregnant_ale.csv")
df['x.values'] = df['x.values'].map({0:"False",1:"True"})
df['f.values'] -= np.min(df['f.values'])
print(df)
fig, ax = plt.subplots(1, 1, figsize=(1.3,1.8))
ax.bar(df['x.values'],df['f.values'],color='#BEBEBE')
ax.set_title("ALE", fontsize=10)
ax.set_xlabel("pregnant")
ax.set_ylabel("weight")
ax.set_title("ALE")
ax.set_ylim(-1,45)
ax.set_yticks([0,10,20,30,40])
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
savefig('pregnant_2_ale')
def rent_deep_learning_model(X_train, y_train, X_test, y_test):
np.random.seed(1) # pick seed for reproducible article images
from tensorflow.keras import models, layers, callbacks, optimizers
# Normalize data
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.fit_transform(X_test)
# for colname in X.columns:
# m = np.mean(X[colname])
# sd = np.std(X[colname])
# X[colname] = (X[colname]-m)/sd
#y = (y - np.mean(y))/np.std(y)
model = models.Sequential()
layer1 = 100
batch_size = 1000
dropout = 0.3
model.add(layers.Dense(layer1, input_dim=X_train.shape[1], activation='relu'))
model.add(layers.BatchNormalization())
model.add(layers.Dropout(dropout))
model.add(layers.Dense(1, activation='linear'))
# learning_rate=1e-2 #DEFAULT
opt = optimizers.SGD() # SGB gets NaNs?
# opt = optimizers.RMSprop(lr=0.1)
opt = optimizers.Adam(lr=0.3)
model.compile(loss='mean_squared_error', optimizer=opt, metrics=['mae'])
callback = callbacks.EarlyStopping(monitor='val_loss', patience=10)
history = model.fit(X_train, y_train,
# epochs=1000,
epochs=500,
# validation_split=0.2,
validation_data=(X_test, y_test),
batch_size=batch_size,
# callbacks=[tensorboard_callback],
verbose=1
)
y_pred = model.predict(X_train)
# y_pred *= np.std(y_raw) # undo normalization on y
# y_pred += np.mean(y_raw)
r2 = r2_score(y_train, y_pred)
print("Keras training R^2", r2)
y_pred = model.predict(X_test)
r2 = r2_score(y_test, y_pred)
print("Keras validation R^2", r2)
if False: # Show training results
y_pred = model.predict(X)
y_pred *= np.std(y_raw) # undo normalization on y
y_pred += np.mean(y_raw)
r2 = r2_score(y_raw, y_pred)
print("Keras training R^2", r2)
plt.ylabel("MAE")
plt.xlabel("epochs")
plt.plot(history.history['val_mae'], label='val_mae')
plt.plot(history.history['mae'], label='train_mae')
plt.title(f"batch_size {batch_size}, Layer1 {layer1}, Layer2 {layer2}, R^2 {r2:.3f}")
plt.legend()
plt.show()
return model, r2
def partitioning():
np.random.seed(1) # pick seed for reproducible article images
# np.random.seed(2)
n = 200
x = np.random.uniform(0, 1, size=n)
x1 = x + np.random.normal(0, 0.1, n)
# x2 = x + np.random.normal(0, 0.03, n)
x2 = (x*4).astype(int) + np.random.randint(0, 5, n)
X = np.vstack([x1, x2]).T
y = X[:, 0] + X[:, 1] ** 2
regr = tree.DecisionTreeRegressor(max_leaf_nodes=8,
min_samples_leaf=1) # limit depth of tree
regr.fit(X[:,1].reshape(-1,1), y)
shadow_tree = ShadowDecTree(regr, X[:,1].reshape(-1,1), y, feature_names=['x1', 'x2'])
splits = []
print("splits")
for node in shadow_tree.internal:
splits.append(node.split())
print("\t",node.split())
splits = sorted(splits)
fig, ax = plt.subplots(1, 1, figsize=(3,2.5))
color_map_min = '#c7e9b4'
color_map_max = '#081d58'
y_lim = np.min(y), np.max(y)
y_range = y_lim[1] - y_lim[0]
n_colors_in_map = 100
markersize = 5
scatter_edge=GREY
color_map = [rgb2hex(c.rgb, force_long=True)
for c in Color(color_map_min).range_to(Color(color_map_max), n_colors_in_map)]
color_map = [color_map[int(((y_-y_lim[0])/y_range)*(n_colors_in_map-1))] for y_ in y]
# ax.scatter(x, y, marker='o', c=color_map, edgecolor=scatter_edge, lw=.3, s=markersize)
ax.scatter(X[:,0], X[:,1], marker='o', c=color_map, alpha=.7, edgecolor=scatter_edge, lw=.3, s=markersize)
ax.set_xlabel("$x_1$", fontsize=12)
ax.set_ylabel("$x_2$", fontsize=12)
a = -.08
b = 1.05
ax.set_xlim(a, b)
# ax.set_ylim(a, b+0.02)
ax.spines['left'].set_linewidth(.5)
ax.spines['bottom'].set_linewidth(.5)
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
for s in splits:
ax.plot([a,b], [s,s], '-', c='grey', lw=.5)
# savefig("partitioning_background")
plt.tight_layout(pad=0, w_pad=0, h_pad=0)
plt.savefig(f"images/partitioning_background.svg", bbox_inches="tight", pad_inches=0)
plt.show()
if __name__ == '__main__':
# productsize()
# interactions()
# yearmade()
# rent()
# rent_ntrees()
# weight()
# shap_pregnant()
# shap_weight(feature_perturbation='tree_path_dependent', twin=True) # more biased but faster
# shap_weight(feature_perturbation='interventional', twin=True) # takes 04:45 minutes
# weather()
noise()
# Invoke R to generate csv files then load with python to plot
gen_ale_plot_data_in_R()
ale_MachineHours()
ale_yearmade()
ale_height()
ale_pregnant()
ale_state()
ale_productsize()
| [
"matplotlib.pyplot.title",
"numpy.random.seed",
"sklearn.preprocessing.StandardScaler",
"numpy.abs",
"tensorflow.keras.layers.Dense",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"stratx.plot.plot_ice",
"stratx.plot_stratpd_gridsearch",
"stratx.plot.plot_catice",
"tensorflow.ke... | [((3016, 3038), 'pandas.isnull', 'pd.isnull', (['df[colname]'], {}), '(df[colname])\n', (3025, 3038), True, 'import pandas as pd\n'), ((3134, 3177), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {'pad': 'pad', 'w_pad': '(0)', 'h_pad': '(0)'}), '(pad=pad, w_pad=0, h_pad=0)\n', (3150, 3177), True, 'import matplotlib.pyplot as plt\n'), ((3182, 3254), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""images/{filename}.pdf"""'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0)'}), "(f'images/{filename}.pdf', bbox_inches='tight', pad_inches=0)\n", (3193, 3254), True, 'import matplotlib.pyplot as plt\n'), ((3313, 3331), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3329, 3331), True, 'import matplotlib.pyplot as plt\n'), ((3336, 3346), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3344, 3346), True, 'import matplotlib.pyplot as plt\n'), ((3352, 3363), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (3361, 3363), True, 'import matplotlib.pyplot as plt\n'), ((3444, 3461), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (3458, 3461), True, 'import numpy as np\n'), ((3517, 3535), 'articles.pd.support.load_rent', 'load_rent', ([], {'n': '(10000)'}), '(n=10000)\n', (3526, 3535), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((3718, 3755), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)'}), '(X, y, test_size=0.2)\n', (3734, 3755), False, 'from sklearn.model_selection import train_test_split\n'), ((5707, 5725), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (5723, 5725), False, 'from sklearn.linear_model import LinearRegression\n'), ((5953, 6020), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(6)'], {'figsize': '(10, 1.8)', 'gridspec_kw': "{'wspace': 0.15}"}), "(1, 6, figsize=(10, 1.8), gridspec_kw={'wspace': 0.15})\n", (5965, 6020), True, 'import matplotlib.pyplot as plt\n'), ((7544, 7601), 'stratx.ice.predict_ice', 'predict_ice', (['rf', 'X', 'colname', '"""price"""'], {'numx': '(30)', 'nlines': '(100)'}), "(rf, X, colname, 'price', numx=30, nlines=100)\n", (7555, 7601), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((7606, 7701), 'stratx.plot.plot_ice', 'plot_ice', (['ice', 'colname', '"""price"""'], {'alpha': '(0.3)', 'ax': 'axes[1]', 'show_xlabel': '(True)', 'show_ylabel': '(False)'}), "(ice, colname, 'price', alpha=0.3, ax=axes[1], show_xlabel=True,\n show_ylabel=False)\n", (7614, 7701), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((7721, 7777), 'stratx.ice.predict_ice', 'predict_ice', (['b', 'X', 'colname', '"""price"""'], {'numx': '(30)', 'nlines': '(100)'}), "(b, X, colname, 'price', numx=30, nlines=100)\n", (7732, 7777), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((7782, 7855), 'stratx.plot.plot_ice', 'plot_ice', (['ice', 'colname', '"""price"""'], {'alpha': '(0.3)', 'ax': 'axes[2]', 'show_ylabel': '(False)'}), "(ice, colname, 'price', alpha=0.3, ax=axes[2], show_ylabel=False)\n", (7790, 7855), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((7866, 7923), 'stratx.ice.predict_ice', 'predict_ice', (['lm', 'X', 'colname', '"""price"""'], {'numx': '(30)', 'nlines': '(100)'}), "(lm, X, colname, 'price', numx=30, nlines=100)\n", (7877, 7923), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((7928, 8001), 'stratx.plot.plot_ice', 'plot_ice', (['ice', 'colname', '"""price"""'], {'alpha': '(0.3)', 'ax': 'axes[3]', 'show_ylabel': '(False)'}), "(ice, colname, 'price', alpha=0.3, ax=axes[3], show_ylabel=False)\n", (7936, 8001), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((8015, 8031), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (8029, 8031), False, 'from sklearn.preprocessing import StandardScaler\n'), ((8228, 8295), 'stratx.ice.predict_ice', 'predict_ice', (['model', 'X_train_', 'colname', '"""price"""'], {'numx': '(30)', 'nlines': '(100)'}), "(model, X_train_, colname, 'price', numx=30, nlines=100)\n", (8239, 8295), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((8456, 8528), 'stratx.plot.plot_ice', 'plot_ice', (['ice', 'colname', '"""price"""'], {'alpha': '(0.3)', 'ax': 'axes[4]', 'show_ylabel': '(True)'}), "(ice, colname, 'price', alpha=0.3, ax=axes[4], show_ylabel=True)\n", (8464, 8528), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((8565, 8725), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', 'colname', '"""price"""'], {'ax': 'axes[5]', 'pdp_marker_size': '(6)', 'show_x_counts': '(False)', 'hide_top_right_axes': '(False)', 'show_xlabel': '(True)', 'show_ylabel': '(False)'}), "(X, y, colname, 'price', ax=axes[5], pdp_marker_size=6,\n show_x_counts=False, hide_top_right_axes=False, show_xlabel=True,\n show_ylabel=False)\n", (8577, 8725), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((10028, 10088), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {'figsize': '(5, 5)', 'sharey': '(True)', 'sharex': '(True)'}), '(2, 2, figsize=(5, 5), sharey=True, sharex=True)\n', (10040, 10088), True, 'import matplotlib.pyplot as plt\n'), ((10270, 10385), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', 'colname', '"""price"""'], {'ax': 'axes[0, 0]', 'slope_line_alpha': '(0.15)', 'show_xlabel': '(True)', 'show_ylabel': '(False)'}), "(X, y, colname, 'price', ax=axes[0, 0], slope_line_alpha=0.15,\n show_xlabel=True, show_ylabel=False)\n", (10282, 10385), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((10529, 10626), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', 'colname', '"""price"""'], {'ax': 'axes[0, 1]', 'slope_line_alpha': '(0.15)', 'show_ylabel': '(False)'}), "(X, y, colname, 'price', ax=axes[0, 1], slope_line_alpha=0.15,\n show_ylabel=False)\n", (10541, 10626), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((10796, 10886), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(100)', 'min_samples_leaf': '(1)', 'oob_score': '(True)', 'n_jobs': '(-1)'}), '(n_estimators=100, min_samples_leaf=1, oob_score=True,\n n_jobs=-1)\n', (10817, 10886), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((10970, 11019), 'stratx.ice.predict_ice', 'predict_ice', (['rf', 'X', 'colname', '"""price"""'], {'nlines': '(1000)'}), "(rf, X, colname, 'price', nlines=1000)\n", (10981, 11019), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((11054, 11130), 'stratx.plot.plot_ice', 'plot_ice', (['ice', 'colname', '"""price"""'], {'alpha': '(0.05)', 'ax': 'axes[1, 0]', 'show_xlabel': '(True)'}), "(ice, colname, 'price', alpha=0.05, ax=axes[1, 0], show_xlabel=True)\n", (11062, 11130), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((11355, 11445), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(100)', 'min_samples_leaf': '(1)', 'oob_score': '(True)', 'n_jobs': '(-1)'}), '(n_estimators=100, min_samples_leaf=1, oob_score=True,\n n_jobs=-1)\n', (11376, 11445), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((11500, 11549), 'stratx.ice.predict_ice', 'predict_ice', (['rf', 'X', 'colname', '"""price"""'], {'nlines': '(1000)'}), "(rf, X, colname, 'price', nlines=1000)\n", (11511, 11549), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((11586, 11685), 'stratx.plot.plot_ice', 'plot_ice', (['ice', 'colname', '"""price"""'], {'alpha': '(0.05)', 'ax': 'axes[1, 1]', 'show_xlabel': '(True)', 'show_ylabel': '(False)'}), "(ice, colname, 'price', alpha=0.05, ax=axes[1, 1], show_xlabel=True,\n show_ylabel=False)\n", (11594, 11685), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((12234, 12296), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(3)'], {'figsize': '(7.5, 5)', 'sharey': '(True)', 'sharex': '(True)'}), '(2, 3, figsize=(7.5, 5), sharey=True, sharex=True)\n', (12246, 12296), True, 'import matplotlib.pyplot as plt\n'), ((12548, 12718), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', 'colname', '"""price"""'], {'ax': 'axes[0, 0]', 'slope_line_alpha': '(0.15)', 'show_xlabel': '(True)', 'min_samples_leaf': 'min_samples_leaf', 'show_ylabel': '(True)', 'verbose': 'verbose'}), "(X, y, colname, 'price', ax=axes[0, 0], slope_line_alpha=0.15,\n show_xlabel=True, min_samples_leaf=min_samples_leaf, show_ylabel=True,\n verbose=verbose)\n", (12560, 12718), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((12949, 13098), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', 'colname', '"""price"""'], {'ax': 'axes[0, 1]', 'slope_line_alpha': '(0.15)', 'show_ylabel': '(False)', 'min_samples_leaf': 'min_samples_leaf', 'verbose': 'verbose'}), "(X, y, colname, 'price', ax=axes[0, 1], slope_line_alpha=0.15,\n show_ylabel=False, min_samples_leaf=min_samples_leaf, verbose=verbose)\n", (12961, 13098), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((13220, 13436), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', 'colname', '"""price"""'], {'ax': 'axes[0, 2]', 'slope_line_alpha': '(0.15)', 'show_xlabel': '(True)', 'min_samples_leaf': 'min_samples_leaf', 'show_ylabel': '(False)', 'n_trees': '(15)', 'max_features': '(1)', 'bootstrap': '(False)', 'verbose': 'verbose'}), "(X, y, colname, 'price', ax=axes[0, 2], slope_line_alpha=0.15,\n show_xlabel=True, min_samples_leaf=min_samples_leaf, show_ylabel=False,\n n_trees=15, max_features=1, bootstrap=False, verbose=verbose)\n", (13232, 13436), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((13806, 13896), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(100)', 'min_samples_leaf': '(1)', 'oob_score': '(True)', 'n_jobs': '(-1)'}), '(n_estimators=100, min_samples_leaf=1, oob_score=True,\n n_jobs=-1)\n', (13827, 13896), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((13981, 14030), 'stratx.ice.predict_ice', 'predict_ice', (['rf', 'X', 'colname', '"""price"""'], {'nlines': '(1000)'}), "(rf, X, colname, 'price', nlines=1000)\n", (13992, 14030), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((14035, 14111), 'stratx.plot.plot_ice', 'plot_ice', (['ice', 'colname', '"""price"""'], {'alpha': '(0.05)', 'ax': 'axes[1, 0]', 'show_xlabel': '(True)'}), "(ice, colname, 'price', alpha=0.05, ax=axes[1, 0], show_xlabel=True)\n", (14043, 14111), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((14358, 14448), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(100)', 'min_samples_leaf': '(1)', 'oob_score': '(True)', 'n_jobs': '(-1)'}), '(n_estimators=100, min_samples_leaf=1, oob_score=True,\n n_jobs=-1)\n', (14379, 14448), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((14503, 14552), 'stratx.ice.predict_ice', 'predict_ice', (['rf', 'X', 'colname', '"""price"""'], {'nlines': '(1000)'}), "(rf, X, colname, 'price', nlines=1000)\n", (14514, 14552), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((14557, 14656), 'stratx.plot.plot_ice', 'plot_ice', (['ice', 'colname', '"""price"""'], {'alpha': '(0.05)', 'ax': 'axes[1, 1]', 'show_xlabel': '(True)', 'show_ylabel': '(False)'}), "(ice, colname, 'price', alpha=0.05, ax=axes[1, 1], show_xlabel=True,\n show_ylabel=False)\n", (14565, 14656), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((15181, 15198), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (15195, 15198), True, 'import numpy as np\n'), ((15317, 15335), 'articles.pd.support.load_rent', 'load_rent', ([], {'n': '(10000)'}), '(n=10000)\n', (15326, 15335), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((16020, 16067), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)', '(4)'], {'figsize': '(8, 6)', 'sharey': '(True)'}), '(3, 4, figsize=(8, 6), sharey=True)\n', (16032, 16067), True, 'import matplotlib.pyplot as plt\n'), ((16509, 16520), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (16518, 16520), True, 'import matplotlib.pyplot as plt\n'), ((16546, 16563), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (16560, 16563), True, 'import numpy as np\n'), ((16684, 16697), 'sklearn.datasets.load_boston', 'load_boston', ([], {}), '()\n', (16695, 16697), False, 'from sklearn.datasets import load_boston\n'), ((16735, 16790), 'pandas.DataFrame', 'pd.DataFrame', (['boston.data'], {'columns': 'boston.feature_names'}), '(boston.data, columns=boston.feature_names)\n', (16747, 16790), True, 'import pandas as pd\n'), ((16880, 17013), 'stratx.plot_stratpd_gridsearch', 'plot_stratpd_gridsearch', (['X', 'y', '"""AGE"""', '"""MEDV"""'], {'show_slope_lines': '(True)', 'min_samples_leaf_values': '[2, 5, 10, 20, 30]', 'yrange': '(-10, 10)'}), "(X, y, 'AGE', 'MEDV', show_slope_lines=True,\n min_samples_leaf_values=[2, 5, 10, 20, 30], yrange=(-10, 10))\n", (16903, 17013), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((17474, 17491), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (17488, 17491), True, 'import numpy as np\n'), ((17680, 17752), 'matplotlib.pyplot.subplots', 'plt.subplots', (['nrows', '(ncols + 2)'], {'figsize': '((ncols + 2) * 2.5, nrows * 2.5)'}), '(nrows, ncols + 2, figsize=((ncols + 2) * 2.5, nrows * 2.5))\n', (17692, 17752), True, 'import matplotlib.pyplot as plt\n'), ((18471, 18546), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(100)', 'min_samples_leaf': '(1)', 'oob_score': '(True)'}), '(n_estimators=100, min_samples_leaf=1, oob_score=True)\n', (18492, 18546), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((18774, 18791), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (18788, 18791), True, 'import numpy as np\n'), ((18910, 18928), 'articles.pd.support.load_rent', 'load_rent', ([], {'n': '(10000)'}), '(n=10000)\n', (18919, 18928), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((18947, 18981), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(4)', '(2)'], {'figsize': '(4, 8)'}), '(4, 2, figsize=(4, 8))\n', (18959, 18981), True, 'import matplotlib.pyplot as plt\n'), ((18987, 19106), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""bedrooms"""', '"""price"""'], {'ax': 'axes[0, 0]', 'yrange': '(-500, 4000)', 'slope_line_alpha': '(0.2)', 'supervised': '(False)'}), "(X, y, 'bedrooms', 'price', ax=axes[0, 0], yrange=(-500, 4000),\n slope_line_alpha=0.2, supervised=False)\n", (18999, 19106), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((19122, 19240), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""bedrooms"""', '"""price"""'], {'ax': 'axes[0, 1]', 'yrange': '(-500, 4000)', 'slope_line_alpha': '(0.2)', 'supervised': '(True)'}), "(X, y, 'bedrooms', 'price', ax=axes[0, 1], yrange=(-500, 4000),\n slope_line_alpha=0.2, supervised=True)\n", (19134, 19240), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((19257, 19377), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""bathrooms"""', '"""price"""'], {'ax': 'axes[1, 0]', 'yrange': '(-500, 4000)', 'slope_line_alpha': '(0.2)', 'supervised': '(False)'}), "(X, y, 'bathrooms', 'price', ax=axes[1, 0], yrange=(-500, 4000),\n slope_line_alpha=0.2, supervised=False)\n", (19269, 19377), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((19393, 19512), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""bathrooms"""', '"""price"""'], {'ax': 'axes[1, 1]', 'yrange': '(-500, 4000)', 'slope_line_alpha': '(0.2)', 'supervised': '(True)'}), "(X, y, 'bathrooms', 'price', ax=axes[1, 1], yrange=(-500, 4000),\n slope_line_alpha=0.2, supervised=True)\n", (19405, 19512), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((19529, 19662), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""latitude"""', '"""price"""'], {'ax': 'axes[2, 0]', 'yrange': '(-500, 2000)', 'slope_line_alpha': '(0.2)', 'supervised': '(False)', 'verbose': '(True)'}), "(X, y, 'latitude', 'price', ax=axes[2, 0], yrange=(-500, 2000),\n slope_line_alpha=0.2, supervised=False, verbose=True)\n", (19541, 19662), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((19678, 19810), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""latitude"""', '"""price"""'], {'ax': 'axes[2, 1]', 'yrange': '(-500, 2000)', 'slope_line_alpha': '(0.2)', 'supervised': '(True)', 'verbose': '(True)'}), "(X, y, 'latitude', 'price', ax=axes[2, 1], yrange=(-500, 2000),\n slope_line_alpha=0.2, supervised=True, verbose=True)\n", (19690, 19810), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((19827, 19946), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""longitude"""', '"""price"""'], {'ax': 'axes[3, 0]', 'yrange': '(-500, 500)', 'slope_line_alpha': '(0.2)', 'supervised': '(False)'}), "(X, y, 'longitude', 'price', ax=axes[3, 0], yrange=(-500, 500),\n slope_line_alpha=0.2, supervised=False)\n", (19839, 19946), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((19962, 20080), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""longitude"""', '"""price"""'], {'ax': 'axes[3, 1]', 'yrange': '(-500, 500)', 'slope_line_alpha': '(0.2)', 'supervised': '(True)'}), "(X, y, 'longitude', 'price', ax=axes[3, 1], yrange=(-500, 500),\n slope_line_alpha=0.2, supervised=True)\n", (19974, 20080), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((20279, 20290), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (20288, 20290), True, 'import matplotlib.pyplot as plt\n'), ((20312, 20329), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (20326, 20329), True, 'import numpy as np\n'), ((20470, 20488), 'articles.pd.support.toy_weather_data', 'toy_weather_data', ([], {}), '()\n', (20486, 20488), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((20517, 20537), 'articles.pd.support.df_string_to_cat', 'df_string_to_cat', (['df'], {}), '(df)\n', (20533, 20537), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((20550, 20572), 'numpy.unique', 'np.unique', (["df['state']"], {}), "(df['state'])\n", (20559, 20572), True, 'import numpy as np\n'), ((20588, 20601), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (20599, 20601), False, 'from collections import OrderedDict\n'), ((20665, 20686), 'articles.pd.support.df_cat_to_catcode', 'df_cat_to_catcode', (['df'], {}), '(df)\n', (20682, 20686), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((21277, 21312), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize'}), '(1, 1, figsize=figsize)\n', (21289, 21312), True, 'import matplotlib.pyplot as plt\n'), ((22243, 22278), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize'}), '(1, 1, figsize=figsize)\n', (22255, 22278), True, 'import matplotlib.pyplot as plt\n'), ((22283, 22432), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""dayofyear"""', '"""temperature"""'], {'ax': 'ax', 'show_x_counts': '(False)', 'yrange': '(-10, 10)', 'pdp_marker_size': '(2)', 'slope_line_alpha': '(0.5)', 'n_trials': '(1)'}), "(X, y, 'dayofyear', 'temperature', ax=ax, show_x_counts=False,\n yrange=(-10, 10), pdp_marker_size=2, slope_line_alpha=0.5, n_trials=1)\n", (22295, 22432), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((22558, 22569), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (22567, 22569), True, 'import matplotlib.pyplot as plt\n'), ((22585, 22620), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize'}), '(1, 1, figsize=figsize)\n', (22597, 22620), True, 'import matplotlib.pyplot as plt\n'), ((22625, 22766), 'stratx.plot_catstratpd', 'plot_catstratpd', (['X', 'y', '"""state"""', '"""temperature"""'], {'catnames': 'catnames', 'show_x_counts': '(False)', 'min_y_shifted_to_zero': '(True)', 'ax': 'ax', 'yrange': '(-1, 55)'}), "(X, y, 'state', 'temperature', catnames=catnames,\n show_x_counts=False, min_y_shifted_to_zero=True, ax=ax, yrange=(-1, 55))\n", (22640, 22766), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((23045, 23080), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize'}), '(1, 1, figsize=figsize)\n', (23057, 23080), True, 'import matplotlib.pyplot as plt\n'), ((23091, 23137), 'stratx.ice.predict_ice', 'predict_ice', (['rf', 'X', '"""dayofyear"""', '"""temperature"""'], {}), "(rf, X, 'dayofyear', 'temperature')\n", (23102, 23137), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((23142, 23190), 'stratx.plot.plot_ice', 'plot_ice', (['ice', '"""dayofyear"""', '"""temperature"""'], {'ax': 'ax'}), "(ice, 'dayofyear', 'temperature', ax=ax)\n", (23150, 23190), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((23276, 23311), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize'}), '(1, 1, figsize=figsize)\n', (23288, 23311), True, 'import matplotlib.pyplot as plt\n'), ((23322, 23367), 'stratx.ice.predict_catice', 'predict_catice', (['rf', 'X', '"""state"""', '"""temperature"""'], {}), "(rf, X, 'state', 'temperature')\n", (23336, 23367), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((23372, 23507), 'stratx.plot.plot_catice', 'plot_catice', (['ice', '"""state"""', '"""temperature"""'], {'catnames': 'catnames', 'ax': 'ax', 'pdp_marker_size': '(15)', 'min_y_shifted_to_zero': '(True)', 'yrange': '(-2, 50)'}), "(ice, 'state', 'temperature', catnames=catnames, ax=ax,\n pdp_marker_size=15, min_y_shifted_to_zero=True, yrange=(-2, 50))\n", (23383, 23507), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((23690, 23725), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize'}), '(1, 1, figsize=figsize)\n', (23702, 23725), True, 'import matplotlib.pyplot as plt\n'), ((23987, 23998), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (23996, 23998), True, 'import matplotlib.pyplot as plt\n'), ((24025, 24042), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (24039, 24042), True, 'import numpy as np\n'), ((24344, 24368), 'pandas.concat', 'pd.concat', (['years'], {'axis': '(0)'}), '(years, axis=0)\n', (24353, 24368), True, 'import pandas as pd\n'), ((24674, 24821), 'stratx.plot_catstratpd_gridsearch', 'plot_catstratpd_gridsearch', (['X', 'y', '"""state"""', '"""temp"""'], {'min_samples_leaf_values': '[2, 5, 20, 40, 60]', 'catnames': 'catnames', 'yrange': '(-5, 60)', 'cellwidth': '(2)'}), "(X, y, 'state', 'temp', min_samples_leaf_values=[\n 2, 5, 20, 40, 60], catnames=catnames, yrange=(-5, 60), cellwidth=2)\n", (24700, 24821), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((25009, 25175), 'stratx.plot_stratpd_gridsearch', 'plot_stratpd_gridsearch', (['X', 'y', '"""dayofyear"""', '"""temp"""'], {'show_slope_lines': '(True)', 'min_samples_leaf_values': '[2, 5, 10, 20, 30]', 'yrange': '(-10, 10)', 'slope_line_alpha': '(0.15)'}), "(X, y, 'dayofyear', 'temp', show_slope_lines=True,\n min_samples_leaf_values=[2, 5, 10, 20, 30], yrange=(-10, 10),\n slope_line_alpha=0.15)\n", (25032, 25175), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((25330, 25347), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (25344, 25347), True, 'import numpy as np\n'), ((25479, 25500), 'articles.pd.support.toy_weight_data', 'toy_weight_data', (['(2000)'], {}), '(2000)\n', (25494, 25500), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((25537, 25572), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize'}), '(1, 1, figsize=figsize)\n', (25549, 25572), True, 'import matplotlib.pyplot as plt\n'), ((25577, 25733), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""education"""', '"""weight"""'], {'ax': 'ax', 'show_x_counts': '(False)', 'pdp_marker_size': '(5)', 'yrange': '(-12, 0.05)', 'slope_line_alpha': '(0.1)', 'show_ylabel': '(True)'}), "(X, y, 'education', 'weight', ax=ax, show_x_counts=False,\n pdp_marker_size=5, yrange=(-12, 0.05), slope_line_alpha=0.1,\n show_ylabel=True)\n", (25589, 25733), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((25978, 26013), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize'}), '(1, 1, figsize=figsize)\n', (25990, 26013), True, 'import matplotlib.pyplot as plt\n'), ((26018, 26145), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""height"""', '"""weight"""'], {'ax': 'ax', 'pdp_marker_size': '(0.2)', 'show_x_counts': '(False)', 'yrange': '(0, 160)', 'show_ylabel': '(False)'}), "(X, y, 'height', 'weight', ax=ax, pdp_marker_size=0.2,\n show_x_counts=False, yrange=(0, 160), show_ylabel=False)\n", (26030, 26145), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((26365, 26401), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(1.3, 2)'}), '(1, 1, figsize=(1.3, 2))\n', (26377, 26401), True, 'import matplotlib.pyplot as plt\n'), ((26405, 26524), 'stratx.plot_catstratpd', 'plot_catstratpd', (['X', 'y', '"""sex"""', '"""weight"""'], {'ax': 'ax', 'show_x_counts': '(False)', 'catnames': "{(0): 'M', (1): 'F'}", 'yrange': '(-1, 35)'}), "(X, y, 'sex', 'weight', ax=ax, show_x_counts=False, catnames\n ={(0): 'M', (1): 'F'}, yrange=(-1, 35))\n", (26420, 26524), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((26692, 26730), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(1.5, 1.8)'}), '(1, 1, figsize=(1.5, 1.8))\n', (26704, 26730), True, 'import matplotlib.pyplot as plt\n'), ((26734, 26860), 'stratx.plot_catstratpd', 'plot_catstratpd', (['X', 'y', '"""pregnant"""', '"""weight"""'], {'ax': 'ax', 'show_x_counts': '(False)', 'catnames': '{(0): False, (1): True}', 'yrange': '(-1, 45)'}), "(X, y, 'pregnant', 'weight', ax=ax, show_x_counts=False,\n catnames={(0): False, (1): True}, yrange=(-1, 45))\n", (26749, 26860), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((27492, 27518), 'numpy.array', 'np.array', (['[[1, 1, 70, 10]]'], {}), '([[1, 1, 70, 10]])\n', (27500, 27518), True, 'import numpy as np\n'), ((27634, 27660), 'numpy.array', 'np.array', (['[[1, 1, 72, 10]]'], {}), '([[1, 1, 72, 10]])\n', (27642, 27660), True, 'import numpy as np\n'), ((27805, 27840), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize'}), '(1, 1, figsize=figsize)\n', (27817, 27840), True, 'import matplotlib.pyplot as plt\n'), ((27851, 27892), 'stratx.ice.predict_ice', 'predict_ice', (['rf', 'X', '"""education"""', '"""weight"""'], {}), "(rf, X, 'education', 'weight')\n", (27862, 27892), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((27897, 27989), 'stratx.plot.plot_ice', 'plot_ice', (['ice', '"""education"""', '"""weight"""'], {'ax': 'ax', 'yrange': '(-12, 0)', 'min_y_shifted_to_zero': '(True)'}), "(ice, 'education', 'weight', ax=ax, yrange=(-12, 0),\n min_y_shifted_to_zero=True)\n", (27905, 27989), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((28141, 28179), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(2.4, 2.2)'}), '(1, 1, figsize=(2.4, 2.2))\n', (28153, 28179), True, 'import matplotlib.pyplot as plt\n'), ((28190, 28228), 'stratx.ice.predict_ice', 'predict_ice', (['rf', 'X', '"""height"""', '"""weight"""'], {}), "(rf, X, 'height', 'weight')\n", (28201, 28228), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((28233, 28342), 'stratx.plot.plot_ice', 'plot_ice', (['ice', '"""height"""', '"""weight"""'], {'ax': 'ax', 'pdp_linewidth': '(2)', 'yrange': '(100, 250)', 'min_y_shifted_to_zero': '(False)'}), "(ice, 'height', 'weight', ax=ax, pdp_linewidth=2, yrange=(100, 250),\n min_y_shifted_to_zero=False)\n", (28241, 28342), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((28565, 28601), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(1.3, 2)'}), '(1, 1, figsize=(1.3, 2))\n', (28577, 28601), True, 'import matplotlib.pyplot as plt\n'), ((28611, 28649), 'stratx.ice.predict_catice', 'predict_catice', (['rf', 'X', '"""sex"""', '"""weight"""'], {}), "(rf, X, 'sex', 'weight')\n", (28625, 28649), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((28654, 28765), 'stratx.plot.plot_catice', 'plot_catice', (['ice', '"""sex"""', '"""weight"""'], {'catnames': "{(0): 'M', (1): 'F'}", 'ax': 'ax', 'yrange': '(0, 35)', 'pdp_marker_size': '(15)'}), "(ice, 'sex', 'weight', catnames={(0): 'M', (1): 'F'}, ax=ax,\n yrange=(0, 35), pdp_marker_size=15)\n", (28665, 28765), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((28861, 28899), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(1.3, 1.8)'}), '(1, 1, figsize=(1.3, 1.8))\n', (28873, 28899), True, 'import matplotlib.pyplot as plt\n'), ((28991, 29136), 'stratx.plot.plot_catice', 'plot_catice', (['ice', '"""pregnant"""', '"""weight"""'], {'catnames': "{(0): 'M', (1): 'F'}", 'ax': 'ax', 'min_y_shifted_to_zero': '(True)', 'yrange': '(-5, 45)', 'pdp_marker_size': '(20)'}), "(ice, 'pregnant', 'weight', catnames={(0): 'M', (1): 'F'}, ax=ax,\n min_y_shifted_to_zero=True, yrange=(-5, 45), pdp_marker_size=20)\n", (29002, 29136), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((29265, 29282), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (29279, 29282), True, 'import numpy as np\n'), ((29390, 29410), 'articles.pd.support.toy_weight_data', 'toy_weight_data', ([], {'n': 'n'}), '(n=n)\n', (29405, 29410), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((29438, 29458), 'articles.pd.support.df_string_to_cat', 'df_string_to_cat', (['df'], {}), '(df)\n', (29454, 29458), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((29463, 29484), 'articles.pd.support.df_cat_to_catcode', 'df_cat_to_catcode', (['df'], {}), '(df)\n', (29480, 29484), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((29649, 29747), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(200)', 'min_samples_leaf': '(1)', 'max_features': '(0.9)', 'oob_score': '(True)'}), '(n_estimators=200, min_samples_leaf=1, max_features=\n 0.9, oob_score=True)\n', (29670, 29747), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((30206, 30244), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(1.3, 1.8)'}), '(1, 1, figsize=(1.3, 1.8))\n', (30218, 30244), True, 'import matplotlib.pyplot as plt\n'), ((30987, 31004), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (31001, 31004), True, 'import numpy as np\n'), ((31113, 31133), 'articles.pd.support.toy_weight_data', 'toy_weight_data', ([], {'n': 'n'}), '(n=n)\n', (31128, 31133), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((31161, 31181), 'articles.pd.support.df_string_to_cat', 'df_string_to_cat', (['df'], {}), '(df)\n', (31177, 31181), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((31186, 31207), 'articles.pd.support.df_cat_to_catcode', 'df_cat_to_catcode', (['df'], {}), '(df)\n', (31203, 31207), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((31372, 31470), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(200)', 'min_samples_leaf': '(1)', 'max_features': '(0.9)', 'oob_score': '(True)'}), '(n_estimators=200, min_samples_leaf=1, max_features=\n 0.9, oob_score=True)\n', (31393, 31470), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((32271, 32285), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (32283, 32285), True, 'import pandas as pd\n'), ((32507, 32542), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize'}), '(1, 1, figsize=figsize)\n', (32519, 32542), True, 'import matplotlib.pyplot as plt\n'), ((32548, 32673), 'shap.dependence_plot', 'shap.dependence_plot', (['"""height"""', 'shap_values', 'shap_sample'], {'interaction_index': 'None', 'ax': 'ax', 'dot_size': '(5)', 'show': '(False)', 'alpha': '(1)'}), "('height', shap_values, shap_sample, interaction_index=\n None, ax=ax, dot_size=5, show=False, alpha=1)\n", (32568, 32673), False, 'import shap\n'), ((33361, 33407), 'stratx.partdep.partial_dependence', 'partial_dependence', ([], {'X': 'X', 'y': 'y', 'colname': '"""height"""'}), "(X=X, y=y, colname='height')\n", (33379, 33407), False, 'from stratx.partdep import partial_dependence\n'), ((34545, 34562), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (34559, 34562), True, 'import numpy as np\n'), ((34680, 34699), 'articles.pd.support.load_bulldozer', 'load_bulldozer', ([], {'n': 'n'}), '(n=n)\n', (34694, 34699), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((34874, 34910), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (34886, 34910), True, 'import matplotlib.pyplot as plt\n'), ((36235, 36271), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (36247, 36271), True, 'import matplotlib.pyplot as plt\n'), ((36276, 36409), 'shap.dependence_plot', 'shap.dependence_plot', (['"""saledayofweek"""', 'shap_values', 'shap_sample'], {'interaction_index': 'None', 'ax': 'ax', 'dot_size': '(5)', 'show': '(False)', 'alpha': '(0.5)'}), "('saledayofweek', shap_values, shap_sample,\n interaction_index=None, ax=ax, dot_size=5, show=False, alpha=0.5)\n", (36296, 36409), False, 'import shap\n'), ((37030, 37066), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (37042, 37066), True, 'import matplotlib.pyplot as plt\n'), ((37071, 37368), 'stratx.plot_catstratpd', 'plot_catstratpd', (['X', 'y'], {'colname': '"""saledayofweek"""', 'targetname': '"""SalePrice"""', 'catnames': "{(0): 'M', (1): 'T', (2): 'W', (3): 'R', (4): 'F', (5): 'S', (6): 'S'}", 'n_trials': '(1)', 'bootstrap': '(True)', 'show_x_counts': '(True)', 'show_xlabel': '(False)', 'show_impact': '(False)', 'pdp_marker_size': '(4)', 'pdp_marker_alpha': '(1)', 'ax': 'ax'}), "(X, y, colname='saledayofweek', targetname='SalePrice',\n catnames={(0): 'M', (1): 'T', (2): 'W', (3): 'R', (4): 'F', (5): 'S', (\n 6): 'S'}, n_trials=1, bootstrap=True, show_x_counts=True, show_xlabel=\n False, show_impact=False, pdp_marker_size=4, pdp_marker_alpha=1, ax=ax)\n", (37086, 37368), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((37721, 37757), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (37733, 37757), True, 'import matplotlib.pyplot as plt\n'), ((37768, 37837), 'stratx.ice.predict_ice', 'predict_ice', (['rf', 'X', '"""saledayofweek"""', '"""SalePrice"""'], {'numx': '(30)', 'nlines': '(100)'}), "(rf, X, 'saledayofweek', 'SalePrice', numx=30, nlines=100)\n", (37779, 37837), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((37842, 37954), 'stratx.plot.plot_ice', 'plot_ice', (['ice', '"""saledayofweek"""', '"""SalePrice"""'], {'alpha': '(0.3)', 'ax': 'ax', 'show_ylabel': '(True)', 'min_y_shifted_to_zero': '(True)'}), "(ice, 'saledayofweek', 'SalePrice', alpha=0.3, ax=ax, show_ylabel=\n True, min_y_shifted_to_zero=True)\n", (37850, 37954), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((38099, 38116), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (38113, 38116), True, 'import numpy as np\n'), ((38308, 38339), 'pandas.read_csv', 'pd.read_csv', (['"""bulldozer20k.csv"""'], {}), "('bulldozer20k.csv')\n", (38319, 38339), True, 'import pandas as pd\n'), ((38416, 38452), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (38428, 38452), True, 'import matplotlib.pyplot as plt\n'), ((39732, 39768), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (39744, 39768), True, 'import matplotlib.pyplot as plt\n'), ((39773, 39904), 'shap.dependence_plot', 'shap.dependence_plot', (['"""ProductSize"""', 'shap_values', 'shap_sample'], {'interaction_index': 'None', 'ax': 'ax', 'dot_size': '(5)', 'show': '(False)', 'alpha': '(0.5)'}), "('ProductSize', shap_values, shap_sample,\n interaction_index=None, ax=ax, dot_size=5, show=False, alpha=0.5)\n", (39793, 39904), False, 'import shap\n'), ((40546, 40582), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (40558, 40582), True, 'import matplotlib.pyplot as plt\n'), ((40587, 40844), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y'], {'colname': '"""ProductSize"""', 'targetname': '"""SalePrice"""', 'n_trials': '(10)', 'bootstrap': '(True)', 'show_slope_lines': '(False)', 'show_x_counts': '(False)', 'show_xlabel': '(False)', 'show_impact': '(False)', 'show_all_pdp': '(False)', 'pdp_marker_size': '(10)', 'pdp_marker_alpha': '(1)', 'ax': 'ax'}), "(X, y, colname='ProductSize', targetname='SalePrice', n_trials=\n 10, bootstrap=True, show_slope_lines=False, show_x_counts=False,\n show_xlabel=False, show_impact=False, show_all_pdp=False,\n pdp_marker_size=10, pdp_marker_alpha=1, ax=ax)\n", (40599, 40844), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((41225, 41261), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (41237, 41261), True, 'import matplotlib.pyplot as plt\n'), ((41272, 41339), 'stratx.ice.predict_ice', 'predict_ice', (['rf', 'X', '"""ProductSize"""', '"""SalePrice"""'], {'numx': '(30)', 'nlines': '(100)'}), "(rf, X, 'ProductSize', 'SalePrice', numx=30, nlines=100)\n", (41283, 41339), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((41344, 41454), 'stratx.plot.plot_ice', 'plot_ice', (['ice', '"""ProductSize"""', '"""SalePrice"""'], {'alpha': '(0.3)', 'ax': 'ax', 'show_ylabel': '(True)', 'min_y_shifted_to_zero': '(True)'}), "(ice, 'ProductSize', 'SalePrice', alpha=0.3, ax=ax, show_ylabel=\n True, min_y_shifted_to_zero=True)\n", (41352, 41454), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((41680, 41697), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (41694, 41697), True, 'import numpy as np\n'), ((41815, 41834), 'articles.pd.support.load_bulldozer', 'load_bulldozer', ([], {'n': 'n'}), '(n=n)\n', (41829, 41834), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((41850, 41886), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (41862, 41886), True, 'import matplotlib.pyplot as plt\n'), ((43161, 43197), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (43173, 43197), True, 'import matplotlib.pyplot as plt\n'), ((43202, 43335), 'shap.dependence_plot', 'shap.dependence_plot', (['"""saledayofyear"""', 'shap_values', 'shap_sample'], {'interaction_index': 'None', 'ax': 'ax', 'dot_size': '(5)', 'show': '(False)', 'alpha': '(0.5)'}), "('saledayofyear', shap_values, shap_sample,\n interaction_index=None, ax=ax, dot_size=5, show=False, alpha=0.5)\n", (43222, 43335), False, 'import shap\n'), ((43956, 43992), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (43968, 43992), True, 'import matplotlib.pyplot as plt\n'), ((43997, 44253), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y'], {'colname': '"""saledayofyear"""', 'targetname': '"""SalePrice"""', 'n_trials': '(10)', 'bootstrap': '(True)', 'show_all_pdp': '(False)', 'show_slope_lines': '(False)', 'show_x_counts': '(True)', 'show_xlabel': '(False)', 'show_impact': '(False)', 'pdp_marker_size': '(4)', 'pdp_marker_alpha': '(1)', 'ax': 'ax'}), "(X, y, colname='saledayofyear', targetname='SalePrice',\n n_trials=10, bootstrap=True, show_all_pdp=False, show_slope_lines=False,\n show_x_counts=True, show_xlabel=False, show_impact=False,\n pdp_marker_size=4, pdp_marker_alpha=1, ax=ax)\n", (44009, 44253), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((44649, 44685), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (44661, 44685), True, 'import matplotlib.pyplot as plt\n'), ((44696, 44765), 'stratx.ice.predict_ice', 'predict_ice', (['rf', 'X', '"""saledayofyear"""', '"""SalePrice"""'], {'numx': '(30)', 'nlines': '(100)'}), "(rf, X, 'saledayofyear', 'SalePrice', numx=30, nlines=100)\n", (44707, 44765), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((44770, 44882), 'stratx.plot.plot_ice', 'plot_ice', (['ice', '"""saledayofyear"""', '"""SalePrice"""'], {'alpha': '(0.3)', 'ax': 'ax', 'show_ylabel': '(True)', 'min_y_shifted_to_zero': '(True)'}), "(ice, 'saledayofyear', 'SalePrice', alpha=0.3, ax=ax, show_ylabel=\n True, min_y_shifted_to_zero=True)\n", (44778, 44882), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((45024, 45041), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (45038, 45041), True, 'import numpy as np\n'), ((45282, 45313), 'pandas.read_csv', 'pd.read_csv', (['"""bulldozer20k.csv"""'], {}), "('bulldozer20k.csv')\n", (45293, 45313), True, 'import pandas as pd\n'), ((45828, 45864), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (45840, 45864), True, 'import matplotlib.pyplot as plt\n'), ((46683, 46719), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (46695, 46719), True, 'import matplotlib.pyplot as plt\n'), ((46724, 46852), 'shap.dependence_plot', 'shap.dependence_plot', (['"""YearMade"""', 'shap_values', 'shap_sample'], {'interaction_index': 'None', 'ax': 'ax', 'dot_size': '(5)', 'show': '(False)', 'alpha': '(0.5)'}), "('YearMade', shap_values, shap_sample,\n interaction_index=None, ax=ax, dot_size=5, show=False, alpha=0.5)\n", (46744, 46852), False, 'import shap\n'), ((47492, 47528), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (47504, 47528), True, 'import matplotlib.pyplot as plt\n'), ((47533, 47784), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y'], {'colname': '"""YearMade"""', 'targetname': '"""SalePrice"""', 'n_trials': '(10)', 'bootstrap': '(True)', 'show_slope_lines': '(False)', 'show_x_counts': '(True)', 'show_ylabel': '(False)', 'show_xlabel': '(False)', 'show_impact': '(False)', 'pdp_marker_size': '(4)', 'pdp_marker_alpha': '(1)', 'ax': 'ax'}), "(X, y, colname='YearMade', targetname='SalePrice', n_trials=10,\n bootstrap=True, show_slope_lines=False, show_x_counts=True, show_ylabel\n =False, show_xlabel=False, show_impact=False, pdp_marker_size=4,\n pdp_marker_alpha=1, ax=ax)\n", (47545, 47784), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((48163, 48199), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (48175, 48199), True, 'import matplotlib.pyplot as plt\n'), ((48210, 48274), 'stratx.ice.predict_ice', 'predict_ice', (['rf', 'X', '"""YearMade"""', '"""SalePrice"""'], {'numx': '(30)', 'nlines': '(100)'}), "(rf, X, 'YearMade', 'SalePrice', numx=30, nlines=100)\n", (48221, 48274), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((48279, 48380), 'stratx.plot.plot_ice', 'plot_ice', (['ice', '"""YearMade"""', '"""SalePrice"""'], {'alpha': '(0.3)', 'ax': 'ax', 'show_ylabel': '(True)', 'yrange': '(20000, 55000)'}), "(ice, 'YearMade', 'SalePrice', alpha=0.3, ax=ax, show_ylabel=True,\n yrange=(20000, 55000))\n", (48287, 48380), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((48576, 48593), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (48590, 48593), True, 'import numpy as np\n'), ((48785, 48816), 'pandas.read_csv', 'pd.read_csv', (['"""bulldozer20k.csv"""'], {}), "('bulldozer20k.csv')\n", (48796, 48816), True, 'import pandas as pd\n'), ((49425, 49461), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (49437, 49461), True, 'import matplotlib.pyplot as plt\n'), ((50303, 50339), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (50315, 50339), True, 'import matplotlib.pyplot as plt\n'), ((50344, 50476), 'shap.dependence_plot', 'shap.dependence_plot', (['"""MachineHours"""', 'shap_values', 'shap_sample'], {'interaction_index': 'None', 'ax': 'ax', 'dot_size': '(5)', 'show': '(False)', 'alpha': '(0.5)'}), "('MachineHours', shap_values, shap_sample,\n interaction_index=None, ax=ax, dot_size=5, show=False, alpha=0.5)\n", (50364, 50476), False, 'import shap\n'), ((51146, 51182), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (51158, 51182), True, 'import matplotlib.pyplot as plt\n'), ((51187, 51507), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y'], {'colname': '"""MachineHours"""', 'targetname': '"""SalePrice"""', 'n_trials': '(10)', 'bootstrap': '(True)', 'show_all_pdp': '(False)', 'show_slope_lines': '(False)', 'show_x_counts': '(True)', 'barchar_alpha': '(1.0)', 'barchar_color': '"""k"""', 'show_ylabel': '(False)', 'show_xlabel': '(False)', 'show_impact': '(False)', 'pdp_marker_size': '(1)', 'pdp_marker_alpha': '(0.3)', 'ax': 'ax'}), "(X, y, colname='MachineHours', targetname='SalePrice', n_trials\n =10, bootstrap=True, show_all_pdp=False, show_slope_lines=False,\n show_x_counts=True, barchar_alpha=1.0, barchar_color='k', show_ylabel=\n False, show_xlabel=False, show_impact=False, pdp_marker_size=1,\n pdp_marker_alpha=0.3, ax=ax)\n", (51199, 51507), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((52137, 52173), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (52149, 52173), True, 'import matplotlib.pyplot as plt\n'), ((52184, 52253), 'stratx.ice.predict_ice', 'predict_ice', (['rf', 'X', '"""MachineHours"""', '"""SalePrice"""'], {'numx': '(300)', 'nlines': '(200)'}), "(rf, X, 'MachineHours', 'SalePrice', numx=300, nlines=200)\n", (52195, 52253), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((52258, 52364), 'stratx.plot.plot_ice', 'plot_ice', (['ice', '"""MachineHours"""', '"""SalePrice"""'], {'alpha': '(0.5)', 'ax': 'ax', 'show_ylabel': '(True)', 'yrange': '(33000, 38000)'}), "(ice, 'MachineHours', 'SalePrice', alpha=0.5, ax=ax, show_ylabel=\n True, yrange=(33000, 38000))\n", (52266, 52364), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((52595, 52612), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (52609, 52612), True, 'import numpy as np\n'), ((52684, 52703), 'articles.pd.support.load_bulldozer', 'load_bulldozer', ([], {'n': 'n'}), '(n=n)\n', (52698, 52703), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((52719, 52755), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (52731, 52755), True, 'import matplotlib.pyplot as plt\n'), ((52760, 53009), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y'], {'colname': '"""YearMade"""', 'targetname': '"""SalePrice"""', 'n_trials': '(1)', 'bootstrap': '(True)', 'show_slope_lines': '(False)', 'show_x_counts': '(True)', 'show_xlabel': '(False)', 'show_impact': '(False)', 'pdp_marker_size': '(4)', 'pdp_marker_alpha': '(1)', 'ax': 'ax', 'supervised': '(False)'}), "(X, y, colname='YearMade', targetname='SalePrice', n_trials=1,\n bootstrap=True, show_slope_lines=False, show_x_counts=True, show_xlabel\n =False, show_impact=False, pdp_marker_size=4, pdp_marker_alpha=1, ax=ax,\n supervised=False)\n", (52772, 53009), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((53415, 53432), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (53429, 53432), True, 'import numpy as np\n'), ((53564, 53585), 'articles.pd.support.toy_weight_data', 'toy_weight_data', (['(2000)'], {}), '(2000)\n', (53579, 53585), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((53627, 53647), 'articles.pd.support.df_string_to_cat', 'df_string_to_cat', (['df'], {}), '(df)\n', (53643, 53647), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((53652, 53673), 'articles.pd.support.df_cat_to_catcode', 'df_cat_to_catcode', (['df'], {}), '(df)\n', (53669, 53673), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((53794, 53828), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {'figsize': '(4, 4)'}), '(2, 2, figsize=(4, 4))\n', (53806, 53828), True, 'import matplotlib.pyplot as plt\n'), ((53833, 53972), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""education"""', '"""weight"""'], {'ax': 'axes[0, 0]', 'show_x_counts': '(False)', 'yrange': '(-13, 0)', 'slope_line_alpha': '(0.1)', 'supervised': '(False)'}), "(X, y, 'education', 'weight', ax=axes[0, 0], show_x_counts=\n False, yrange=(-13, 0), slope_line_alpha=0.1, supervised=False)\n", (53845, 53972), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((54005, 54143), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""education"""', '"""weight"""'], {'ax': 'axes[0, 1]', 'show_x_counts': '(False)', 'yrange': '(-13, 0)', 'slope_line_alpha': '(0.1)', 'supervised': '(True)'}), "(X, y, 'education', 'weight', ax=axes[0, 1], show_x_counts=\n False, yrange=(-13, 0), slope_line_alpha=0.1, supervised=True)\n", (54017, 54143), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((54779, 54790), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (54788, 54790), True, 'import matplotlib.pyplot as plt\n'), ((54818, 54835), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (54832, 54835), True, 'import numpy as np\n'), ((54967, 54988), 'articles.pd.support.toy_weight_data', 'toy_weight_data', (['(1000)'], {}), '(1000)\n', (54982, 54988), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((55030, 55050), 'articles.pd.support.df_string_to_cat', 'df_string_to_cat', (['df'], {}), '(df)\n', (55046, 55050), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((55055, 55076), 'articles.pd.support.df_cat_to_catcode', 'df_cat_to_catcode', (['df'], {}), '(df)\n', (55072, 55076), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((55225, 55259), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(4)'], {'figsize': '(8, 4)'}), '(2, 4, figsize=(8, 4))\n', (55237, 55259), True, 'import matplotlib.pyplot as plt\n'), ((55468, 55676), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""education"""', '"""weight"""'], {'ax': 'axes[0, 0]', 'min_samples_leaf': '(5)', 'yrange': '(-12, 0)', 'slope_line_alpha': '(0.1)', 'pdp_marker_size': '(10)', 'show_ylabel': '(True)', 'n_trees': '(1)', 'max_features': '(1.0)', 'bootstrap': '(False)'}), "(X, y, 'education', 'weight', ax=axes[0, 0], min_samples_leaf=5,\n yrange=(-12, 0), slope_line_alpha=0.1, pdp_marker_size=10, show_ylabel=\n True, n_trees=1, max_features=1.0, bootstrap=False)\n", (55480, 55676), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((55722, 55933), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""education"""', '"""weight"""'], {'ax': 'axes[0, 1]', 'min_samples_leaf': '(5)', 'yrange': '(-12, 0)', 'slope_line_alpha': '(0.1)', 'pdp_marker_size': '(10)', 'show_ylabel': '(False)', 'n_trees': '(5)', 'max_features': '"""auto"""', 'bootstrap': '(True)'}), "(X, y, 'education', 'weight', ax=axes[0, 1], min_samples_leaf=5,\n yrange=(-12, 0), slope_line_alpha=0.1, pdp_marker_size=10, show_ylabel=\n False, n_trees=5, max_features='auto', bootstrap=True)\n", (55734, 55933), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((55979, 56192), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""education"""', '"""weight"""'], {'ax': 'axes[0, 2]', 'min_samples_leaf': '(5)', 'yrange': '(-12, 0)', 'slope_line_alpha': '(0.08)', 'pdp_marker_size': '(10)', 'show_ylabel': '(False)', 'n_trees': '(10)', 'max_features': '"""auto"""', 'bootstrap': '(True)'}), "(X, y, 'education', 'weight', ax=axes[0, 2], min_samples_leaf=5,\n yrange=(-12, 0), slope_line_alpha=0.08, pdp_marker_size=10, show_ylabel\n =False, n_trees=10, max_features='auto', bootstrap=True)\n", (55991, 56192), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((56238, 56451), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""education"""', '"""weight"""'], {'ax': 'axes[0, 3]', 'min_samples_leaf': '(5)', 'yrange': '(-12, 0)', 'slope_line_alpha': '(0.05)', 'pdp_marker_size': '(10)', 'show_ylabel': '(False)', 'n_trees': '(30)', 'max_features': '"""auto"""', 'bootstrap': '(True)'}), "(X, y, 'education', 'weight', ax=axes[0, 3], min_samples_leaf=5,\n yrange=(-12, 0), slope_line_alpha=0.05, pdp_marker_size=10, show_ylabel\n =False, n_trees=30, max_features='auto', bootstrap=True)\n", (56250, 56451), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((56498, 56679), 'stratx.plot_catstratpd', 'plot_catstratpd', (['X', 'y', '"""pregnant"""', '"""weight"""'], {'ax': 'axes[1, 0]', 'catnames': '{(0): False, (1): True}', 'show_ylabel': '(True)', 'yrange': '(0, 35)', 'n_trees': '(1)', 'max_features': '(1.0)', 'bootstrap': '(False)'}), "(X, y, 'pregnant', 'weight', ax=axes[1, 0], catnames={(0): \n False, (1): True}, show_ylabel=True, yrange=(0, 35), n_trees=1,\n max_features=1.0, bootstrap=False)\n", (56513, 56679), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((56729, 56913), 'stratx.plot_catstratpd', 'plot_catstratpd', (['X', 'y', '"""pregnant"""', '"""weight"""'], {'ax': 'axes[1, 1]', 'catnames': '{(0): False, (1): True}', 'show_ylabel': '(False)', 'yrange': '(0, 35)', 'n_trees': '(5)', 'max_features': '"""auto"""', 'bootstrap': '(True)'}), "(X, y, 'pregnant', 'weight', ax=axes[1, 1], catnames={(0): \n False, (1): True}, show_ylabel=False, yrange=(0, 35), n_trees=5,\n max_features='auto', bootstrap=True)\n", (56744, 56913), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((56963, 57148), 'stratx.plot_catstratpd', 'plot_catstratpd', (['X', 'y', '"""pregnant"""', '"""weight"""'], {'ax': 'axes[1, 2]', 'catnames': '{(0): False, (1): True}', 'show_ylabel': '(False)', 'yrange': '(0, 35)', 'n_trees': '(10)', 'max_features': '"""auto"""', 'bootstrap': '(True)'}), "(X, y, 'pregnant', 'weight', ax=axes[1, 2], catnames={(0): \n False, (1): True}, show_ylabel=False, yrange=(0, 35), n_trees=10,\n max_features='auto', bootstrap=True)\n", (56978, 57148), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((57198, 57383), 'stratx.plot_catstratpd', 'plot_catstratpd', (['X', 'y', '"""pregnant"""', '"""weight"""'], {'ax': 'axes[1, 3]', 'catnames': '{(0): False, (1): True}', 'show_ylabel': '(False)', 'yrange': '(0, 35)', 'n_trees': '(30)', 'max_features': '"""auto"""', 'bootstrap': '(True)'}), "(X, y, 'pregnant', 'weight', ax=axes[1, 3], catnames={(0): \n False, (1): True}, show_ylabel=False, yrange=(0, 35), n_trees=30,\n max_features='auto', bootstrap=True)\n", (57213, 57383), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((57486, 57497), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (57495, 57497), True, 'import matplotlib.pyplot as plt\n'), ((57523, 57540), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (57537, 57540), True, 'import numpy as np\n'), ((57672, 57693), 'articles.pd.support.toy_weight_data', 'toy_weight_data', (['(1000)'], {}), '(1000)\n', (57687, 57693), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((57735, 57755), 'articles.pd.support.df_string_to_cat', 'df_string_to_cat', (['df'], {}), '(df)\n', (57751, 57755), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((57760, 57781), 'articles.pd.support.df_cat_to_catcode', 'df_cat_to_catcode', (['df'], {}), '(df)\n', (57777, 57781), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((57890, 58022), 'stratx.plot_stratpd_gridsearch', 'plot_stratpd_gridsearch', (['X', 'y'], {'colname': '"""education"""', 'targetname': '"""weight"""', 'show_slope_lines': '(True)', 'xrange': '(10, 18)', 'yrange': '(-12, 0)'}), "(X, y, colname='education', targetname='weight',\n show_slope_lines=True, xrange=(10, 18), yrange=(-12, 0))\n", (57913, 58022), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((58143, 58256), 'stratx.plot_stratpd_gridsearch', 'plot_stratpd_gridsearch', (['X', 'y'], {'colname': '"""height"""', 'targetname': '"""weight"""', 'yrange': '(0, 150)', 'show_slope_lines': '(True)'}), "(X, y, colname='height', targetname='weight', yrange\n =(0, 150), show_slope_lines=True)\n", (58166, 58256), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((58356, 58388), 'numpy.random.uniform', 'np.random.uniform', (['(-2)', '(2)'], {'size': 'n'}), '(-2, 2, size=n)\n', (58373, 58388), True, 'import numpy as np\n'), ((58398, 58430), 'numpy.random.uniform', 'np.random.uniform', (['(-2)', '(2)'], {'size': 'n'}), '(-2, 2, size=n)\n', (58415, 58430), True, 'import numpy as np\n'), ((58501, 58515), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (58513, 58515), True, 'import pandas as pd\n'), ((58601, 58618), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (58615, 58618), True, 'import numpy as np\n'), ((58756, 58803), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(4)'], {'figsize': '(8, 2)', 'sharey': '(True)'}), '(1, 4, figsize=(8, 2), sharey=True)\n', (58768, 58803), True, 'import matplotlib.pyplot as plt\n'), ((59491, 59508), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (59505, 59508), True, 'import numpy as np\n'), ((61857, 61889), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': 'n'}), '(-1, 1, size=n)\n', (61874, 61889), True, 'import numpy as np\n'), ((61899, 61931), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': 'n'}), '(-1, 1, size=n)\n', (61916, 61931), True, 'import numpy as np\n'), ((61941, 61973), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': 'n'}), '(-1, 1, size=n)\n', (61958, 61973), True, 'import numpy as np\n'), ((62160, 62174), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (62172, 62174), True, 'import pandas as pd\n'), ((62277, 62294), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (62291, 62294), True, 'import numpy as np\n'), ((62966, 63013), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {'figsize': '(4, 4)', 'sharey': '(True)'}), '(2, 2, figsize=(4, 4), sharey=True)\n', (62978, 63013), True, 'import matplotlib.pyplot as plt\n'), ((63541, 63644), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""x2"""', '"""y"""'], {'ax': 'axes[0, 0]', 'yrange': '(-4, 4)', 'min_samples_leaf': '(5)', 'pdp_marker_size': '(2)'}), "(X, y, 'x2', 'y', ax=axes[0, 0], yrange=(-4, 4),\n min_samples_leaf=5, pdp_marker_size=2)\n", (63553, 63644), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((63754, 63857), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""x3"""', '"""y"""'], {'ax': 'axes[1, 0]', 'yrange': '(-4, 4)', 'min_samples_leaf': '(5)', 'pdp_marker_size': '(2)'}), "(X, y, 'x3', 'y', ax=axes[1, 0], yrange=(-4, 4),\n min_samples_leaf=5, pdp_marker_size=2)\n", (63766, 63857), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((63898, 63973), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(100)', 'min_samples_leaf': '(1)', 'oob_score': '(True)'}), '(n_estimators=100, min_samples_leaf=1, oob_score=True)\n', (63919, 63973), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((64039, 64078), 'stratx.ice.predict_ice', 'predict_ice', (['rf', 'X', '"""x2"""', '"""y"""'], {'numx': '(100)'}), "(rf, X, 'x2', 'y', numx=100)\n", (64050, 64078), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((64083, 64138), 'stratx.plot.plot_ice', 'plot_ice', (['ice', '"""x2"""', '"""y"""'], {'ax': 'axes[0, 1]', 'yrange': '(-4, 4)'}), "(ice, 'x2', 'y', ax=axes[0, 1], yrange=(-4, 4))\n", (64091, 64138), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((64150, 64189), 'stratx.ice.predict_ice', 'predict_ice', (['rf', 'X', '"""x3"""', '"""y"""'], {'numx': '(100)'}), "(rf, X, 'x3', 'y', numx=100)\n", (64161, 64189), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((64194, 64249), 'stratx.plot.plot_ice', 'plot_ice', (['ice', '"""x3"""', '"""y"""'], {'ax': 'axes[1, 1]', 'yrange': '(-4, 4)'}), "(ice, 'x3', 'y', ax=axes[1, 1], yrange=(-4, 4))\n", (64202, 64249), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((64468, 64479), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (64477, 64479), True, 'import matplotlib.pyplot as plt\n'), ((64506, 64523), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (64520, 64523), True, 'import numpy as np\n'), ((64670, 64683), 'sklearn.datasets.load_boston', 'load_boston', ([], {}), '()\n', (64681, 64683), False, 'from sklearn.datasets import load_boston\n'), ((64721, 64776), 'pandas.DataFrame', 'pd.DataFrame', (['boston.data'], {'columns': 'boston.feature_names'}), '(boston.data, columns=boston.feature_names)\n', (64733, 64776), True, 'import pandas as pd\n'), ((64877, 64911), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(4)'], {'figsize': '(9, 2)'}), '(1, 4, figsize=(9, 2))\n', (64889, 64911), True, 'import matplotlib.pyplot as plt\n'), ((65186, 65380), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""AGE"""', '"""MEDV"""'], {'ax': 'axes[1]', 'yrange': '(-20, 20)', 'n_trees': '(20)', 'bootstrap': '(True)', 'max_features': '"""auto"""', 'supervised': '(False)', 'show_ylabel': '(False)', 'verbose': '(True)', 'slope_line_alpha': '(0.1)'}), "(X, y, 'AGE', 'MEDV', ax=axes[1], yrange=(-20, 20), n_trees=20,\n bootstrap=True, max_features='auto', supervised=False, show_ylabel=\n False, verbose=True, slope_line_alpha=0.1)\n", (65198, 65380), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((65517, 65651), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""AGE"""', '"""MEDV"""'], {'ax': 'axes[2]', 'yrange': '(-20, 20)', 'min_samples_leaf': '(5)', 'n_trees': '(1)', 'supervised': '(True)', 'show_ylabel': '(False)'}), "(X, y, 'AGE', 'MEDV', ax=axes[2], yrange=(-20, 20),\n min_samples_leaf=5, n_trees=1, supervised=True, show_ylabel=False)\n", (65529, 65651), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((65807, 65862), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(100)', 'oob_score': '(True)'}), '(n_estimators=100, oob_score=True)\n', (65828, 65862), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((65928, 65970), 'stratx.ice.predict_ice', 'predict_ice', (['rf', 'X', '"""AGE"""', '"""MEDV"""'], {'numx': '(10)'}), "(rf, X, 'AGE', 'MEDV', numx=10)\n", (65939, 65970), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((65975, 66052), 'stratx.plot.plot_ice', 'plot_ice', (['ice', '"""AGE"""', '"""MEDV"""'], {'ax': 'axes[3]', 'yrange': '(-20, 20)', 'show_ylabel': '(False)'}), "(ice, 'AGE', 'MEDV', ax=axes[3], yrange=(-20, 20), show_ylabel=False)\n", (65983, 66052), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((66551, 66569), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (66567, 66569), False, 'from sklearn.linear_model import LinearRegression\n'), ((67526, 67543), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (67540, 67543), True, 'import numpy as np\n'), ((67665, 67710), 'pandas.read_csv', 'pd.read_csv', (['"""../notebooks/data/auto-mpg.csv"""'], {}), "('../notebooks/data/auto-mpg.csv')\n", (67676, 67710), True, 'import pandas as pd\n'), ((67941, 67975), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(3)'], {'figsize': '(9, 4)'}), '(2, 3, figsize=(9, 4))\n', (67953, 67975), True, 'import matplotlib.pyplot as plt\n'), ((68086, 68220), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""horsepower"""', '"""mpg"""'], {'ax': 'axes[0, 1]', 'min_samples_leaf': '(10)', 'xrange': '(45, 235)', 'yrange': '(-20, 20)', 'show_ylabel': '(False)'}), "(X, y, 'horsepower', 'mpg', ax=axes[0, 1], min_samples_leaf=10,\n xrange=(45, 235), yrange=(-20, 20), show_ylabel=False)\n", (68098, 68220), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((68255, 68388), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""weight"""', '"""mpg"""'], {'ax': 'axes[1, 1]', 'min_samples_leaf': '(10)', 'xrange': '(1600, 5200)', 'yrange': '(-20, 20)', 'show_ylabel': '(False)'}), "(X, y, 'weight', 'mpg', ax=axes[1, 1], min_samples_leaf=10,\n xrange=(1600, 5200), yrange=(-20, 20), show_ylabel=False)\n", (68267, 68388), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((68429, 68504), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(100)', 'min_samples_leaf': '(1)', 'oob_score': '(True)'}), '(n_estimators=100, min_samples_leaf=1, oob_score=True)\n', (68450, 68504), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((68532, 68581), 'stratx.ice.predict_ice', 'predict_ice', (['rf', 'X', '"""horsepower"""', '"""mpg"""'], {'numx': '(100)'}), "(rf, X, 'horsepower', 'mpg', numx=100)\n", (68543, 68581), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((68586, 68676), 'stratx.plot.plot_ice', 'plot_ice', (['ice', '"""horsepower"""', '"""mpg"""'], {'ax': 'axes[0, 2]', 'yrange': '(-20, 20)', 'show_ylabel': '(False)'}), "(ice, 'horsepower', 'mpg', ax=axes[0, 2], yrange=(-20, 20),\n show_ylabel=False)\n", (68594, 68676), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((68683, 68728), 'stratx.ice.predict_ice', 'predict_ice', (['rf', 'X', '"""weight"""', '"""mpg"""'], {'numx': '(100)'}), "(rf, X, 'weight', 'mpg', numx=100)\n", (68694, 68728), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((68733, 68820), 'stratx.plot.plot_ice', 'plot_ice', (['ice', '"""weight"""', '"""mpg"""'], {'ax': 'axes[1, 2]', 'yrange': '(-20, 20)', 'show_ylabel': '(False)'}), "(ice, 'weight', 'mpg', ax=axes[1, 2], yrange=(-20, 20), show_ylabel\n =False)\n", (68741, 68820), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((68861, 68879), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (68877, 68879), False, 'from sklearn.linear_model import LinearRegression\n'), ((69864, 69881), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (69878, 69881), True, 'import numpy as np\n'), ((70003, 70048), 'pandas.read_csv', 'pd.read_csv', (['"""../notebooks/data/auto-mpg.csv"""'], {}), "('../notebooks/data/auto-mpg.csv')\n", (70014, 70048), True, 'import pandas as pd\n'), ((70267, 70459), 'stratx.plot_stratpd_gridsearch', 'plot_stratpd_gridsearch', (['X', 'y'], {'colname': '"""horsepower"""', 'targetname': '"""mpg"""', 'show_slope_lines': '(True)', 'min_samples_leaf_values': '[2, 5, 10, 20, 30]', 'nbins_values': '[1, 2, 3, 4, 5]', 'yrange': '(-20, 20)'}), "(X, y, colname='horsepower', targetname='mpg',\n show_slope_lines=True, min_samples_leaf_values=[2, 5, 10, 20, 30],\n nbins_values=[1, 2, 3, 4, 5], yrange=(-20, 20))\n", (70290, 70459), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((70593, 70781), 'stratx.plot_stratpd_gridsearch', 'plot_stratpd_gridsearch', (['X', 'y'], {'colname': '"""weight"""', 'targetname': '"""mpg"""', 'show_slope_lines': '(True)', 'min_samples_leaf_values': '[2, 5, 10, 20, 30]', 'nbins_values': '[1, 2, 3, 4, 5]', 'yrange': '(-20, 20)'}), "(X, y, colname='weight', targetname='mpg',\n show_slope_lines=True, min_samples_leaf_values=[2, 5, 10, 20, 30],\n nbins_values=[1, 2, 3, 4, 5], yrange=(-20, 20))\n", (70616, 70781), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((70937, 70954), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (70951, 70954), True, 'import numpy as np\n'), ((71824, 71842), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (71840, 71842), False, 'from sklearn.linear_model import LinearRegression\n'), ((71938, 71990), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(6)', '(4)'], {'figsize': '(7.5, 8.5)', 'sharey': '(False)'}), '(6, 4, figsize=(7.5, 8.5), sharey=False)\n', (71950, 71990), True, 'import matplotlib.pyplot as plt\n'), ((72998, 73153), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""x1"""', '"""y"""'], {'ax': 'axes[1, 0]', 'xrange': '(0, 13)', 'min_samples_leaf': 'min_samples_leaf', 'yrange': 'yrange', 'show_xlabel': '(False)', 'show_ylabel': '(True)'}), "(X, y, 'x1', 'y', ax=axes[1, 0], xrange=(0, 13),\n min_samples_leaf=min_samples_leaf, yrange=yrange, show_xlabel=False,\n show_ylabel=True)\n", (73010, 73153), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((73198, 73216), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (73214, 73216), False, 'from sklearn.linear_model import LinearRegression\n'), ((73345, 73501), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""x2"""', '"""y"""'], {'ax': 'axes[1, 1]', 'xrange': '(0, 13)', 'min_samples_leaf': 'min_samples_leaf', 'yrange': 'yrange', 'show_xlabel': '(False)', 'show_ylabel': '(False)'}), "(X, y, 'x2', 'y', ax=axes[1, 1], xrange=(0, 13),\n min_samples_leaf=min_samples_leaf, yrange=yrange, show_xlabel=False,\n show_ylabel=False)\n", (73357, 73501), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((73586, 73604), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (73602, 73604), False, 'from sklearn.linear_model import LinearRegression\n'), ((73733, 73889), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""x3"""', '"""y"""'], {'ax': 'axes[1, 2]', 'xrange': '(0, 13)', 'min_samples_leaf': 'min_samples_leaf', 'yrange': 'yrange', 'show_xlabel': '(False)', 'show_ylabel': '(False)'}), "(X, y, 'x3', 'y', ax=axes[1, 2], xrange=(0, 13),\n min_samples_leaf=min_samples_leaf, yrange=yrange, show_xlabel=False,\n show_ylabel=False)\n", (73745, 73889), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((73974, 73992), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (73990, 73992), False, 'from sklearn.linear_model import LinearRegression\n'), ((74121, 74277), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""x4"""', '"""y"""'], {'ax': 'axes[1, 3]', 'xrange': '(0, 13)', 'min_samples_leaf': 'min_samples_leaf', 'yrange': 'yrange', 'show_xlabel': '(False)', 'show_ylabel': '(False)'}), "(X, y, 'x4', 'y', ax=axes[1, 3], xrange=(0, 13),\n min_samples_leaf=min_samples_leaf, yrange=yrange, show_xlabel=False,\n show_ylabel=False)\n", (74133, 74277), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((74362, 74380), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (74378, 74380), False, 'from sklearn.linear_model import LinearRegression\n'), ((76725, 76742), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (76739, 76742), True, 'import numpy as np\n'), ((76810, 76839), 'articles.pd.support.synthetic_interaction_data', 'synthetic_interaction_data', (['n'], {}), '(n)\n', (76836, 76839), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((76988, 77042), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(10)', 'oob_score': '(True)'}), '(n_estimators=10, oob_score=True)\n', (77009, 77042), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((77250, 77322), 'stratx.ice.friedman_partial_dependence', 'friedman_partial_dependence', (['rf', 'X', '"""x1"""'], {'numx': 'None', 'mean_centered': '(False)'}), "(rf, X, 'x1', numx=None, mean_centered=False)\n", (77277, 77322), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((77336, 77408), 'stratx.ice.friedman_partial_dependence', 'friedman_partial_dependence', (['rf', 'X', '"""x2"""'], {'numx': 'None', 'mean_centered': '(False)'}), "(rf, X, 'x2', numx=None, mean_centered=False)\n", (77363, 77408), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((77422, 77494), 'stratx.ice.friedman_partial_dependence', 'friedman_partial_dependence', (['rf', 'X', '"""x3"""'], {'numx': 'None', 'mean_centered': '(False)'}), "(rf, X, 'x3', numx=None, mean_centered=False)\n", (77449, 77494), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((77504, 77522), 'numpy.mean', 'np.mean', (['pdp_x1[1]'], {}), '(pdp_x1[1])\n', (77511, 77522), True, 'import numpy as np\n'), ((77532, 77550), 'numpy.mean', 'np.mean', (['pdp_x2[1]'], {}), '(pdp_x2[1])\n', (77539, 77550), True, 'import numpy as np\n'), ((77560, 77578), 'numpy.mean', 'np.mean', (['pdp_x3[1]'], {}), '(pdp_x3[1])\n', (77567, 77578), True, 'import numpy as np\n'), ((77936, 78005), 'shap.TreeExplainer', 'shap.TreeExplainer', (['rf'], {'data': 'X', 'feature_perturbation': '"""interventional"""'}), "(rf, data=X, feature_perturbation='interventional')\n", (77954, 78005), False, 'import shap\n'), ((78122, 78150), 'numpy.mean', 'np.mean', (['shap_values'], {'axis': '(0)'}), '(shap_values, axis=0)\n', (78129, 78150), True, 'import numpy as np\n'), ((78309, 78349), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(4)'], {'figsize': '(11.33, 2.8)'}), '(1, 4, figsize=(11.33, 2.8))\n', (78321, 78349), True, 'import matplotlib.pyplot as plt\n'), ((79322, 79367), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': 'x1_color', 'label': '"""$x_1$"""'}), "(color=x1_color, label='$x_1$')\n", (79336, 79367), True, 'import matplotlib.patches as mpatches\n'), ((79383, 79428), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': 'x2_color', 'label': '"""$x_2$"""'}), "(color=x2_color, label='$x_2$')\n", (79397, 79428), True, 'import matplotlib.patches as mpatches\n'), ((79444, 79489), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': 'x3_color', 'label': '"""$x_3$"""'}), "(color=x3_color, label='$x_3$')\n", (79458, 79489), True, 'import matplotlib.patches as mpatches\n'), ((79631, 79765), 'shap.dependence_plot', 'shap.dependence_plot', (['"""x1"""', 'shap_values', 'X'], {'interaction_index': 'None', 'ax': 'axes[1]', 'dot_size': '(4)', 'show': '(False)', 'alpha': '(0.5)', 'color': 'x1_color'}), "('x1', shap_values, X, interaction_index=None, ax=axes[\n 1], dot_size=4, show=False, alpha=0.5, color=x1_color)\n", (79651, 79765), False, 'import shap\n'), ((79814, 79948), 'shap.dependence_plot', 'shap.dependence_plot', (['"""x2"""', 'shap_values', 'X'], {'interaction_index': 'None', 'ax': 'axes[1]', 'dot_size': '(4)', 'show': '(False)', 'alpha': '(0.5)', 'color': 'x2_color'}), "('x2', shap_values, X, interaction_index=None, ax=axes[\n 1], dot_size=4, show=False, alpha=0.5, color=x2_color)\n", (79834, 79948), False, 'import shap\n'), ((79997, 80131), 'shap.dependence_plot', 'shap.dependence_plot', (['"""x3"""', 'shap_values', 'X'], {'interaction_index': 'None', 'ax': 'axes[1]', 'dot_size': '(4)', 'show': '(False)', 'alpha': '(0.5)', 'color': 'x3_color'}), "('x3', shap_values, X, interaction_index=None, ax=axes[\n 1], dot_size=4, show=False, alpha=0.5, color=x3_color)\n", (80017, 80131), False, 'import shap\n'), ((80400, 80445), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': 'x1_color', 'label': '"""$x_1$"""'}), "(color=x1_color, label='$x_1$')\n", (80414, 80445), True, 'import matplotlib.patches as mpatches\n'), ((80461, 80506), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': 'x2_color', 'label': '"""$x_2$"""'}), "(color=x2_color, label='$x_2$')\n", (80475, 80506), True, 'import matplotlib.patches as mpatches\n'), ((80522, 80567), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': 'x3_color', 'label': '"""$x_3$"""'}), "(color=x3_color, label='$x_3$')\n", (80536, 80567), True, 'import matplotlib.patches as mpatches\n'), ((80651, 80683), 'pandas.read_csv', 'pd.read_csv', (['"""images/x1_ale.csv"""'], {}), "('images/x1_ale.csv')\n", (80662, 80683), True, 'import pandas as pd\n'), ((80696, 80728), 'pandas.read_csv', 'pd.read_csv', (['"""images/x2_ale.csv"""'], {}), "('images/x2_ale.csv')\n", (80707, 80728), True, 'import pandas as pd\n'), ((80741, 80773), 'pandas.read_csv', 'pd.read_csv', (['"""images/x3_ale.csv"""'], {}), "('images/x3_ale.csv')\n", (80752, 80773), True, 'import pandas as pd\n'), ((81587, 81632), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': 'x1_color', 'label': '"""$x_1$"""'}), "(color=x1_color, label='$x_1$')\n", (81601, 81632), True, 'import matplotlib.patches as mpatches\n'), ((81648, 81693), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': 'x2_color', 'label': '"""$x_2$"""'}), "(color=x2_color, label='$x_2$')\n", (81662, 81693), True, 'import matplotlib.patches as mpatches\n'), ((81709, 81754), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': 'x3_color', 'label': '"""$x_3$"""'}), "(color=x3_color, label='$x_3$')\n", (81723, 81754), True, 'import matplotlib.patches as mpatches\n'), ((81830, 81982), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""x1"""', '"""y"""'], {'ax': 'axes[3]', 'pdp_marker_size': '(1)', 'pdp_marker_color': 'x1_color', 'show_x_counts': '(False)', 'n_trials': '(1)', 'show_slope_lines': '(False)'}), "(X, y, 'x1', 'y', ax=axes[3], pdp_marker_size=1,\n pdp_marker_color=x1_color, show_x_counts=False, n_trials=1,\n show_slope_lines=False)\n", (81842, 81982), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((82013, 82165), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""x2"""', '"""y"""'], {'ax': 'axes[3]', 'pdp_marker_size': '(1)', 'pdp_marker_color': 'x2_color', 'show_x_counts': '(False)', 'n_trials': '(1)', 'show_slope_lines': '(False)'}), "(X, y, 'x2', 'y', ax=axes[3], pdp_marker_size=1,\n pdp_marker_color=x2_color, show_x_counts=False, n_trials=1,\n show_slope_lines=False)\n", (82025, 82165), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((82196, 82348), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""x3"""', '"""y"""'], {'ax': 'axes[3]', 'pdp_marker_size': '(1)', 'pdp_marker_color': 'x3_color', 'show_x_counts': '(False)', 'n_trials': '(1)', 'show_slope_lines': '(False)'}), "(X, y, 'x3', 'y', ax=axes[3], pdp_marker_size=1,\n pdp_marker_color=x3_color, show_x_counts=False, n_trials=1,\n show_slope_lines=False)\n", (82208, 82348), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((82921, 82966), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': 'x1_color', 'label': '"""$x_1$"""'}), "(color=x1_color, label='$x_1$')\n", (82935, 82966), True, 'import matplotlib.patches as mpatches\n'), ((82982, 83027), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': 'x2_color', 'label': '"""$x_2$"""'}), "(color=x2_color, label='$x_2$')\n", (82996, 83027), True, 'import matplotlib.patches as mpatches\n'), ((83043, 83088), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': 'x3_color', 'label': '"""$x_3$"""'}), "(color=x3_color, label='$x_3$')\n", (83057, 83088), True, 'import matplotlib.patches as mpatches\n'), ((83293, 83339), 'os.system', 'os.system', (['"""R CMD BATCH ale_plots_bulldozer.R"""'], {}), "('R CMD BATCH ale_plots_bulldozer.R')\n", (83302, 83339), False, 'import os\n'), ((83344, 83385), 'os.system', 'os.system', (['"""R CMD BATCH ale_plots_rent.R"""'], {}), "('R CMD BATCH ale_plots_rent.R')\n", (83353, 83385), False, 'import os\n'), ((83390, 83434), 'os.system', 'os.system', (['"""R CMD BATCH ale_plots_weather.R"""'], {}), "('R CMD BATCH ale_plots_weather.R')\n", (83399, 83434), False, 'import os\n'), ((83439, 83482), 'os.system', 'os.system', (['"""R CMD BATCH ale_plots_weight.R"""'], {}), "('R CMD BATCH ale_plots_weight.R')\n", (83448, 83482), False, 'import os\n'), ((83514, 83552), 'pandas.read_csv', 'pd.read_csv', (['"""images/YearMade_ale.csv"""'], {}), "('images/YearMade_ale.csv')\n", (83525, 83552), True, 'import pandas as pd\n'), ((83629, 83665), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (83641, 83665), True, 'import matplotlib.pyplot as plt\n'), ((84094, 84136), 'pandas.read_csv', 'pd.read_csv', (['"""images/MachineHours_ale.csv"""'], {}), "('images/MachineHours_ale.csv')\n", (84105, 84136), True, 'import pandas as pd\n'), ((84213, 84249), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (84225, 84249), True, 'import matplotlib.pyplot as plt\n'), ((84728, 84769), 'pandas.read_csv', 'pd.read_csv', (['"""images/ProductSize_ale.csv"""'], {}), "('images/ProductSize_ale.csv')\n", (84739, 84769), True, 'import pandas as pd\n'), ((84799, 84835), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize2'}), '(1, 1, figsize=figsize2)\n', (84811, 84835), True, 'import matplotlib.pyplot as plt\n'), ((85312, 85348), 'pandas.read_csv', 'pd.read_csv', (['"""images/height_ale.csv"""'], {}), "('images/height_ale.csv')\n", (85323, 85348), True, 'import pandas as pd\n'), ((85425, 85463), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(2.4, 2.2)'}), '(1, 1, figsize=(2.4, 2.2))\n', (85437, 85463), True, 'import matplotlib.pyplot as plt\n'), ((86067, 86102), 'pandas.read_csv', 'pd.read_csv', (['"""images/state_ale.csv"""'], {}), "('images/state_ale.csv')\n", (86078, 86102), True, 'import pandas as pd\n'), ((86164, 86186), 'numpy.min', 'np.min', (["df['f.values']"], {}), "(df['f.values'])\n", (86170, 86186), True, 'import numpy as np\n'), ((86216, 86251), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': 'figsize'}), '(1, 1, figsize=figsize)\n', (86228, 86251), True, 'import matplotlib.pyplot as plt\n'), ((86633, 86671), 'pandas.read_csv', 'pd.read_csv', (['"""images/pregnant_ale.csv"""'], {}), "('images/pregnant_ale.csv')\n", (86644, 86671), True, 'import pandas as pd\n'), ((86756, 86778), 'numpy.min', 'np.min', (["df['f.values']"], {}), "(df['f.values'])\n", (86762, 86778), True, 'import numpy as np\n'), ((86808, 86846), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(1.3, 1.8)'}), '(1, 1, figsize=(1.3, 1.8))\n', (86820, 86846), True, 'import matplotlib.pyplot as plt\n'), ((87263, 87280), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (87277, 87280), True, 'import numpy as np\n'), ((87432, 87448), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (87446, 87448), False, 'from sklearn.preprocessing import StandardScaler\n'), ((87726, 87745), 'tensorflow.keras.models.Sequential', 'models.Sequential', ([], {}), '()\n', (87743, 87745), False, 'from tensorflow.keras import models, layers, callbacks, optimizers\n'), ((88065, 88081), 'tensorflow.keras.optimizers.SGD', 'optimizers.SGD', ([], {}), '()\n', (88079, 88081), False, 'from tensorflow.keras import models, layers, callbacks, optimizers\n'), ((88149, 88172), 'tensorflow.keras.optimizers.Adam', 'optimizers.Adam', ([], {'lr': '(0.3)'}), '(lr=0.3)\n', (88164, 88172), False, 'from tensorflow.keras import models, layers, callbacks, optimizers\n'), ((88267, 88323), 'tensorflow.keras.callbacks.EarlyStopping', 'callbacks.EarlyStopping', ([], {'monitor': '"""val_loss"""', 'patience': '(10)'}), "(monitor='val_loss', patience=10)\n", (88290, 88323), False, 'from tensorflow.keras import models, layers, callbacks, optimizers\n'), ((88848, 88873), 'sklearn.metrics.r2_score', 'r2_score', (['y_train', 'y_pred'], {}), '(y_train, y_pred)\n', (88856, 88873), False, 'from sklearn.metrics import r2_score\n'), ((88955, 88979), 'sklearn.metrics.r2_score', 'r2_score', (['y_test', 'y_pred'], {}), '(y_test, y_pred)\n', (88963, 88979), False, 'from sklearn.metrics import r2_score\n'), ((89623, 89640), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (89637, 89640), True, 'import numpy as np\n'), ((89730, 89761), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)'], {'size': 'n'}), '(0, 1, size=n)\n', (89747, 89761), True, 'import numpy as np\n'), ((89977, 90041), 'dtreeviz.trees.tree.DecisionTreeRegressor', 'tree.DecisionTreeRegressor', ([], {'max_leaf_nodes': '(8)', 'min_samples_leaf': '(1)'}), '(max_leaf_nodes=8, min_samples_leaf=1)\n', (90003, 90041), False, 'from dtreeviz.trees import tree, ShadowDecTree\n'), ((90419, 90455), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(3, 2.5)'}), '(1, 1, figsize=(3, 2.5))\n', (90431, 90455), True, 'import matplotlib.pyplot as plt\n'), ((91621, 91662), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {'pad': '(0)', 'w_pad': '(0)', 'h_pad': '(0)'}), '(pad=0, w_pad=0, h_pad=0)\n', (91637, 91662), True, 'import matplotlib.pyplot as plt\n'), ((91667, 91756), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""images/partitioning_background.svg"""'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0)'}), "(f'images/partitioning_background.svg', bbox_inches='tight',\n pad_inches=0)\n", (91678, 91756), True, 'import matplotlib.pyplot as plt\n'), ((91757, 91767), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (91765, 91767), True, 'import matplotlib.pyplot as plt\n'), ((4171, 4280), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(200)', 'min_samples_leaf': '(1)', 'max_features': '(0.3)', 'oob_score': '(True)', 'n_jobs': '(-1)'}), '(n_estimators=200, min_samples_leaf=1, max_features=\n 0.3, oob_score=True, n_jobs=-1)\n', (4192, 4280), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((5380, 5473), 'xgboost.XGBRegressor', 'xgb.XGBRegressor', ([], {'n_estimators': '(1000)', 'max_depth': '(6)', 'learning_rate': '(0.11)', 'verbose': '(2)', 'n_jobs': '(8)'}), '(n_estimators=1000, max_depth=6, learning_rate=0.11,\n verbose=2, n_jobs=8)\n', (5396, 5473), True, 'import xgboost as xgb\n'), ((7239, 7266), 'numpy.unique', 'np.unique', (['df_rent[colname]'], {}), '(df_rent[colname])\n', (7248, 7266), True, 'import numpy as np\n'), ((8381, 8405), 'numpy.min', 'np.min', (['X_train[colname]'], {}), '(X_train[colname])\n', (8387, 8405), True, 'import numpy as np\n'), ((8407, 8431), 'numpy.max', 'np.max', (['X_train[colname]'], {}), '(X_train[colname])\n', (8413, 8431), True, 'import numpy as np\n'), ((9316, 9339), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {}), '()\n', (9337, 9339), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((17883, 17941), 'stratx.plot.marginal_plot_', 'marginal_plot_', (['X', 'y', 'colname', 'targetname'], {'ax': 'axes[row, 0]'}), '(X, y, colname, targetname, ax=axes[row, 0])\n', (17897, 17941), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((18633, 18672), 'stratx.ice.predict_ice', 'predict_ice', (['rf', 'X', 'colname', 'targetname'], {}), '(rf, X, colname, targetname)\n', (18644, 18672), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((18681, 18732), 'stratx.plot.plot_ice', 'plot_ice', (['ice', 'colname', 'targetname'], {'ax': 'axes[row, 1]'}), '(ice, colname, targetname, ax=axes[row, 1])\n', (18689, 18732), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((21071, 21169), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(150)', 'min_samples_leaf': '(5)', 'max_features': '(0.9)', 'oob_score': '(True)'}), '(n_estimators=150, min_samples_leaf=5, max_features=\n 0.9, oob_score=True)\n', (21092, 21169), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((24261, 24279), 'articles.pd.support.toy_weather_data', 'toy_weather_data', ([], {}), '()\n', (24277, 24279), False, 'from articles.pd.support import load_rent, load_bulldozer, load_flights, toy_weather_data, toy_weight_data, df_cat_to_catcode, df_split_dates, df_string_to_cat, synthetic_interaction_data\n'), ((27228, 27326), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(200)', 'min_samples_leaf': '(1)', 'max_features': '(0.9)', 'oob_score': '(True)'}), '(n_estimators=200, min_samples_leaf=1, max_features=\n 0.9, oob_score=True)\n', (27249, 27326), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((31906, 31972), 'shap.TreeExplainer', 'shap.TreeExplainer', (['rf'], {'feature_perturbation': '"""tree_path_dependent"""'}), "(rf, feature_perturbation='tree_path_dependent')\n", (31924, 31972), False, 'import shap\n'), ((35706, 35814), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(150)', 'n_jobs': '(-1)', 'max_features': '(0.9)', 'min_samples_leaf': '(1)', 'oob_score': '(True)'}), '(n_estimators=150, n_jobs=-1, max_features=0.9,\n min_samples_leaf=1, oob_score=True)\n', (35727, 35814), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((39192, 39300), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(150)', 'n_jobs': '(-1)', 'max_features': '(0.9)', 'min_samples_leaf': '(1)', 'oob_score': '(True)'}), '(n_estimators=150, n_jobs=-1, max_features=0.9,\n min_samples_leaf=1, oob_score=True)\n', (39213, 39300), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((42632, 42740), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(150)', 'n_jobs': '(-1)', 'max_features': '(0.9)', 'min_samples_leaf': '(1)', 'oob_score': '(True)'}), '(n_estimators=150, n_jobs=-1, max_features=0.9,\n min_samples_leaf=1, oob_score=True)\n', (42653, 42740), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((45574, 45682), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(150)', 'n_jobs': '(-1)', 'max_features': '(0.9)', 'min_samples_leaf': '(1)', 'oob_score': '(True)'}), '(n_estimators=150, n_jobs=-1, max_features=0.9,\n min_samples_leaf=1, oob_score=True)\n', (45595, 45682), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((49171, 49279), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(150)', 'n_jobs': '(-1)', 'max_features': '(0.9)', 'min_samples_leaf': '(1)', 'oob_score': '(True)'}), '(n_estimators=150, n_jobs=-1, max_features=0.9,\n min_samples_leaf=1, oob_score=True)\n', (49192, 49279), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((58460, 58491), 'numpy.random.normal', 'np.random.normal', (['(0)', 'sd'], {'size': 'n'}), '(0, sd, size=n)\n', (58476, 58491), True, 'import numpy as np\n'), ((58961, 59083), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""x1"""', '"""y"""'], {'show_ylabel': '(False)', 'pdp_marker_size': '(1)', 'show_x_counts': '(False)', 'ax': 'axes[i]', 'yrange': '(-4, 0.5)'}), "(X, y, 'x1', 'y', show_ylabel=False, pdp_marker_size=1,\n show_x_counts=False, ax=axes[i], yrange=(-4, 0.5))\n", (58973, 59083), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((62039, 62069), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)'], {'size': 'n'}), '(0, 1, size=n)\n', (62055, 62069), True, 'import numpy as np\n'), ((66636, 66647), 'numpy.min', 'np.min', (['col'], {}), '(col)\n', (66642, 66647), True, 'import numpy as np\n'), ((66649, 66660), 'numpy.max', 'np.max', (['col'], {}), '(col)\n', (66655, 66660), True, 'import numpy as np\n'), ((68967, 68978), 'numpy.min', 'np.min', (['col'], {}), '(col)\n', (68973, 68978), True, 'import numpy as np\n'), ((68980, 68991), 'numpy.max', 'np.max', (['col'], {}), '(col)\n', (68986, 68991), True, 'import numpy as np\n'), ((69423, 69434), 'numpy.min', 'np.min', (['col'], {}), '(col)\n', (69429, 69434), True, 'import numpy as np\n'), ((69436, 69447), 'numpy.max', 'np.max', (['col'], {}), '(col)\n', (69442, 69447), True, 'import numpy as np\n'), ((71162, 71282), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['[6, 6, 6, 6]', '[[1, 5, 0.7, 3], [5, 1, 2, 0.5], [0.7, 2, 1, 1.5], [3, 0.5, 1.5, 1]]', 'n'], {}), '([6, 6, 6, 6], [[1, 5, 0.7, 3], [5, 1, 2, 0.5],\n [0.7, 2, 1, 1.5], [3, 0.5, 1.5, 1]], n)\n', (71191, 71282), True, 'import numpy as np\n'), ((74809, 74884), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(100)', 'min_samples_leaf': '(1)', 'oob_score': '(True)'}), '(n_estimators=100, min_samples_leaf=1, oob_score=True)\n', (74830, 74884), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((74894, 74922), 'sklearn.svm.SVR', 'svm.SVR', ([], {'gamma': '(1 / nfeatures)'}), '(gamma=1 / nfeatures)\n', (74901, 74922), False, 'from sklearn import svm\n'), ((74951, 74969), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (74967, 74969), False, 'from sklearn.linear_model import LinearRegression\n'), ((74979, 75013), 'sklearn.neighbors.KNeighborsRegressor', 'KNeighborsRegressor', ([], {'n_neighbors': '(5)'}), '(n_neighbors=5)\n', (74998, 75013), False, 'from sklearn.neighbors import KNeighborsRegressor\n'), ((75748, 75779), 'stratx.ice.predict_ice', 'predict_ice', (['regr', 'X', '"""x1"""', '"""y"""'], {}), "(regr, X, 'x1', 'y')\n", (75759, 75779), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((75788, 75919), 'stratx.plot.plot_ice', 'plot_ice', (['ice', '"""x1"""', '"""y"""'], {'ax': 'axes[row, 0]', 'xrange': '(0, 13)', 'yrange': 'yrange', 'alpha': '(0.08)', 'show_xlabel': 'show_xlabel', 'show_ylabel': '(True)'}), "(ice, 'x1', 'y', ax=axes[row, 0], xrange=(0, 13), yrange=yrange,\n alpha=0.08, show_xlabel=show_xlabel, show_ylabel=True)\n", (75796, 75919), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((75963, 75994), 'stratx.ice.predict_ice', 'predict_ice', (['regr', 'X', '"""x2"""', '"""y"""'], {}), "(regr, X, 'x2', 'y')\n", (75974, 75994), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((76003, 76135), 'stratx.plot.plot_ice', 'plot_ice', (['ice', '"""x2"""', '"""y"""'], {'ax': 'axes[row, 1]', 'xrange': '(0, 13)', 'yrange': 'yrange', 'alpha': '(0.08)', 'show_xlabel': 'show_xlabel', 'show_ylabel': '(False)'}), "(ice, 'x2', 'y', ax=axes[row, 1], xrange=(0, 13), yrange=yrange,\n alpha=0.08, show_xlabel=show_xlabel, show_ylabel=False)\n", (76011, 76135), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((76179, 76210), 'stratx.ice.predict_ice', 'predict_ice', (['regr', 'X', '"""x3"""', '"""y"""'], {}), "(regr, X, 'x3', 'y')\n", (76190, 76210), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((76219, 76351), 'stratx.plot.plot_ice', 'plot_ice', (['ice', '"""x3"""', '"""y"""'], {'ax': 'axes[row, 2]', 'xrange': '(0, 13)', 'yrange': 'yrange', 'alpha': '(0.08)', 'show_xlabel': 'show_xlabel', 'show_ylabel': '(False)'}), "(ice, 'x3', 'y', ax=axes[row, 2], xrange=(0, 13), yrange=yrange,\n alpha=0.08, show_xlabel=show_xlabel, show_ylabel=False)\n", (76227, 76351), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((76395, 76426), 'stratx.ice.predict_ice', 'predict_ice', (['regr', 'X', '"""x4"""', '"""y"""'], {}), "(regr, X, 'x4', 'y')\n", (76406, 76426), False, 'from stratx.ice import predict_ice, predict_catice, friedman_partial_dependence\n'), ((76435, 76567), 'stratx.plot.plot_ice', 'plot_ice', (['ice', '"""x4"""', '"""y"""'], {'ax': 'axes[row, 3]', 'xrange': '(0, 13)', 'yrange': 'yrange', 'alpha': '(0.08)', 'show_xlabel': 'show_xlabel', 'show_ylabel': '(False)'}), "(ice, 'x4', 'y', ax=axes[row, 3], xrange=(0, 13), yrange=yrange,\n alpha=0.08, show_xlabel=show_xlabel, show_ylabel=False)\n", (76443, 76567), False, 'from stratx.plot import marginal_plot_, plot_ice, plot_catice\n'), ((77162, 77172), 'numpy.mean', 'np.mean', (['y'], {}), '(y)\n', (77169, 77172), True, 'import numpy as np\n'), ((77210, 77221), 'numpy.mean', 'np.mean', (['X1'], {}), '(X1)\n', (77217, 77221), True, 'import numpy as np\n'), ((77223, 77234), 'numpy.mean', 'np.mean', (['X2'], {}), '(X2)\n', (77230, 77234), True, 'import numpy as np\n'), ((77606, 77624), 'numpy.mean', 'np.mean', (['pdp_x1[1]'], {}), '(pdp_x1[1])\n', (77613, 77624), True, 'import numpy as np\n'), ((77653, 77671), 'numpy.mean', 'np.mean', (['pdp_x2[1]'], {}), '(pdp_x2[1])\n', (77660, 77671), True, 'import numpy as np\n'), ((77700, 77718), 'numpy.mean', 'np.mean', (['pdp_x3[1]'], {}), '(pdp_x3[1])\n', (77707, 77718), True, 'import numpy as np\n'), ((78215, 78234), 'numpy.abs', 'np.abs', (['shap_values'], {}), '(shap_values)\n', (78221, 78234), True, 'import numpy as np\n'), ((87817, 87884), 'tensorflow.keras.layers.Dense', 'layers.Dense', (['layer1'], {'input_dim': 'X_train.shape[1]', 'activation': '"""relu"""'}), "(layer1, input_dim=X_train.shape[1], activation='relu')\n", (87829, 87884), False, 'from tensorflow.keras import models, layers, callbacks, optimizers\n'), ((87900, 87927), 'tensorflow.keras.layers.BatchNormalization', 'layers.BatchNormalization', ([], {}), '()\n', (87925, 87927), False, 'from tensorflow.keras import models, layers, callbacks, optimizers\n'), ((87943, 87966), 'tensorflow.keras.layers.Dropout', 'layers.Dropout', (['dropout'], {}), '(dropout)\n', (87957, 87966), False, 'from tensorflow.keras import models, layers, callbacks, optimizers\n'), ((87982, 88018), 'tensorflow.keras.layers.Dense', 'layers.Dense', (['(1)'], {'activation': '"""linear"""'}), "(1, activation='linear')\n", (87994, 88018), False, 'from tensorflow.keras import models, layers, callbacks, optimizers\n'), ((89109, 89122), 'numpy.std', 'np.std', (['y_raw'], {}), '(y_raw)\n', (89115, 89122), True, 'import numpy as np\n'), ((89171, 89185), 'numpy.mean', 'np.mean', (['y_raw'], {}), '(y_raw)\n', (89178, 89185), True, 'import numpy as np\n'), ((89199, 89222), 'sklearn.metrics.r2_score', 'r2_score', (['y_raw', 'y_pred'], {}), '(y_raw, y_pred)\n', (89207, 89222), False, 'from sklearn.metrics import r2_score\n'), ((89271, 89288), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""MAE"""'], {}), "('MAE')\n", (89281, 89288), True, 'import matplotlib.pyplot as plt\n'), ((89297, 89317), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""epochs"""'], {}), "('epochs')\n", (89307, 89317), True, 'import matplotlib.pyplot as plt\n'), ((89327, 89380), 'matplotlib.pyplot.plot', 'plt.plot', (["history.history['val_mae']"], {'label': '"""val_mae"""'}), "(history.history['val_mae'], label='val_mae')\n", (89335, 89380), True, 'import matplotlib.pyplot as plt\n'), ((89389, 89440), 'matplotlib.pyplot.plot', 'plt.plot', (["history.history['mae']"], {'label': '"""train_mae"""'}), "(history.history['mae'], label='train_mae')\n", (89397, 89440), True, 'import matplotlib.pyplot as plt\n'), ((89449, 89539), 'matplotlib.pyplot.title', 'plt.title', (['f"""batch_size {batch_size}, Layer1 {layer1}, Layer2 {layer2}, R^2 {r2:.3f}"""'], {}), "(\n f'batch_size {batch_size}, Layer1 {layer1}, Layer2 {layer2}, R^2 {r2:.3f}')\n", (89458, 89539), True, 'import matplotlib.pyplot as plt\n'), ((89543, 89555), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (89553, 89555), True, 'import matplotlib.pyplot as plt\n'), ((89564, 89574), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (89572, 89574), True, 'import matplotlib.pyplot as plt\n'), ((89775, 89802), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.1)', 'n'], {}), '(0, 0.1, n)\n', (89791, 89802), True, 'import numpy as np\n'), ((89876, 89902), 'numpy.random.randint', 'np.random.randint', (['(0)', '(5)', 'n'], {}), '(0, 5, n)\n', (89893, 89902), True, 'import numpy as np\n'), ((89911, 89930), 'numpy.vstack', 'np.vstack', (['[x1, x2]'], {}), '([x1, x2])\n', (89920, 89930), True, 'import numpy as np\n'), ((90529, 90538), 'numpy.min', 'np.min', (['y'], {}), '(y)\n', (90535, 90538), True, 'import numpy as np\n'), ((90540, 90549), 'numpy.max', 'np.max', (['y'], {}), '(y)\n', (90546, 90549), True, 'import numpy as np\n'), ((90668, 90699), 'colour.rgb2hex', 'rgb2hex', (['c.rgb'], {'force_long': '(True)'}), '(c.rgb, force_long=True)\n', (90675, 90699), False, 'from colour import rgb2hex, Color\n'), ((4775, 4793), 'xgboost.XGBRegressor', 'xgb.XGBRegressor', ([], {}), '()\n', (4791, 4793), True, 'import xgboost as xgb\n'), ((15516, 15769), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', 'colname', '"""price"""'], {'ax': 'axes[row, i]', 'slope_line_alpha': 'alphas[i]', 'yrange': 'yrange', 'supervised': 'supervised', 'show_ylabel': '(t == 1)', 'pdp_marker_size': '(2 if row == 2 else 8)', 'n_trees': 't', 'max_features': '"""auto"""', 'bootstrap': '(True)', 'verbose': '(False)'}), "(X, y, colname, 'price', ax=axes[row, i], slope_line_alpha=\n alphas[i], yrange=yrange, supervised=supervised, show_ylabel=t == 1,\n pdp_marker_size=2 if row == 2 else 8, n_trees=t, max_features='auto',\n bootstrap=True, verbose=False)\n", (15528, 15769), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((18119, 18234), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', 'colname', 'targetname'], {'ax': 'axes[row, col]', 'min_samples_leaf': 'msl', 'yrange': 'yranges[i]', 'n_trees': '(1)'}), '(X, y, colname, targetname, ax=axes[row, col], min_samples_leaf\n =msl, yrange=yranges[i], n_trees=1)\n', (18131, 18234), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((29940, 29959), 'shap.sample', 'shap.sample', (['X', '(100)'], {}), '(X, 100)\n', (29951, 29959), False, 'import shap\n'), ((30337, 30375), 'numpy.where', 'np.where', (["(shap_sample['pregnant'] == 0)"], {}), "(shap_sample['pregnant'] == 0)\n", (30345, 30375), True, 'import numpy as np\n'), ((30423, 30461), 'numpy.where', 'np.where', (["(shap_sample['pregnant'] == 1)"], {}), "(shap_sample['pregnant'] == 1)\n", (30431, 30461), True, 'import numpy as np\n'), ((35990, 36009), 'shap.sample', 'shap.sample', (['X', '(100)'], {}), '(X, 100)\n', (36001, 36009), False, 'import shap\n'), ((39487, 39506), 'shap.sample', 'shap.sample', (['X', '(100)'], {}), '(X, 100)\n', (39498, 39506), False, 'import shap\n'), ((42916, 42935), 'shap.sample', 'shap.sample', (['X', '(100)'], {}), '(X, 100)\n', (42927, 42935), False, 'import shap\n'), ((46438, 46457), 'shap.sample', 'shap.sample', (['X', '(100)'], {}), '(X, 100)\n', (46449, 46457), False, 'import shap\n'), ((50058, 50077), 'shap.sample', 'shap.sample', (['X', '(100)'], {}), '(X, 100)\n', (50069, 50077), False, 'import shap\n'), ((60262, 60443), 'stratx.plot_stratpd', 'plot_stratpd', (['X', 'y', '"""x1"""', '"""y"""'], {'ax': 'axes[row, col]', 'show_x_counts': '(False)', 'min_samples_leaf': 's', 'yrange': '(-3.5, 0.5)', 'pdp_marker_size': '(1)', 'show_ylabel': '(False)', 'show_xlabel': 'show_xlabel'}), "(X, y, 'x1', 'y', ax=axes[row, col], show_x_counts=False,\n min_samples_leaf=s, yrange=(-3.5, 0.5), pdp_marker_size=1, show_ylabel=\n False, show_xlabel=show_xlabel)\n", (60274, 60443), False, 'from stratx import plot_stratpd, plot_catstratpd, plot_stratpd_gridsearch, plot_catstratpd_gridsearch\n'), ((77762, 77784), 'numpy.abs', 'np.abs', (['(pdp_x1[1] - m1)'], {}), '(pdp_x1[1] - m1)\n', (77768, 77784), True, 'import numpy as np\n'), ((77828, 77850), 'numpy.abs', 'np.abs', (['(pdp_x2[1] - m2)'], {}), '(pdp_x2[1] - m2)\n', (77834, 77850), True, 'import numpy as np\n'), ((77894, 77916), 'numpy.abs', 'np.abs', (['(pdp_x3[1] - m3)'], {}), '(pdp_x3[1] - m3)\n', (77900, 77916), True, 'import numpy as np\n'), ((31714, 31733), 'shap.sample', 'shap.sample', (['X', '(100)'], {}), '(X, 100)\n', (31725, 31733), False, 'import shap\n'), ((62013, 62036), 'numpy.where', 'np.where', (['(x3 >= 0)', '(1)', '(0)'], {}), '(x3 >= 0, 1, 0)\n', (62021, 62036), True, 'import numpy as np\n'), ((78751, 78761), 'numpy.mean', 'np.mean', (['y'], {}), '(y)\n', (78758, 78761), True, 'import numpy as np\n'), ((90756, 90776), 'colour.Color', 'Color', (['color_map_max'], {}), '(color_map_max)\n', (90761, 90776), False, 'from colour import rgb2hex, Color\n'), ((90726, 90746), 'colour.Color', 'Color', (['color_map_min'], {}), '(color_map_min)\n', (90731, 90746), False, 'from colour import rgb2hex, Color\n'), ((3403, 3418), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (3416, 3418), False, 'import inspect\n'), ((15269, 15284), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (15282, 15284), False, 'import inspect\n'), ((16634, 16649), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (16647, 16649), False, 'import inspect\n'), ((18862, 18877), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (18875, 18877), False, 'import inspect\n'), ((20400, 20415), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (20413, 20415), False, 'import inspect\n'), ((24113, 24128), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (24126, 24128), False, 'import inspect\n'), ((25418, 25433), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (25431, 25433), False, 'import inspect\n'), ((34716, 34741), 'pandas.concat', 'pd.concat', (['[X, y]'], {'axis': '(1)'}), '([X, y], axis=1)\n', (34725, 34741), True, 'import pandas as pd\n'), ((53503, 53518), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (53516, 53518), False, 'import inspect\n'), ((54906, 54921), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (54919, 54921), False, 'import inspect\n'), ((57611, 57626), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (57624, 57626), False, 'import inspect\n'), ((58689, 58704), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (58702, 58704), False, 'import inspect\n'), ((59579, 59594), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (59592, 59594), False, 'import inspect\n'), ((62365, 62380), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (62378, 62380), False, 'import inspect\n'), ((64620, 64635), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (64633, 64635), False, 'import inspect\n'), ((67614, 67629), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (67627, 67629), False, 'import inspect\n'), ((69952, 69967), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (69965, 69967), False, 'import inspect\n'), ((71025, 71040), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (71038, 71040), False, 'import inspect\n')] |
"""
This is a template script - an example of how a CEA script should be set up.
NOTE: ADD YOUR SCRIPT'S DOCUMENTATION HERE (what, why, include literature references)
"""
import math
import os
from typing import Union
import numpy as np
import osmnx.footprints
from geopandas import GeoDataFrame as Gdf
import pandas as pd
import cea.config
import cea.inputlocator
from cea.datamanagement.databases_verification import COLUMNS_ZONE_TYPOLOGY
from cea.demand import constants
from cea.datamanagement.constants import OSM_BUILDING_CATEGORIES, OTHER_OSM_CATEGORIES_UNCONDITIONED
from cea.utilities.dbf import dataframe_to_dbf
from cea.utilities.standardize_coordinates import get_projected_coordinate_system, get_geographic_coordinate_system
__author__ = "<NAME>"
__copyright__ = "Copyright 2019, Architecture and Building Systems - ETH Zurich"
__credits__ = ["<NAME>", "<NAME>"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Production"
def parse_building_floors(floors):
"""
Tries to parse string of `building:levels` from OSM data to get the number of floors as a float.
If the string is a list of numerical values separated by commas or semicolons, it will return the maximum value.
It returns NaN if it is unable to parse the value.
:param str floors: String representation of number of floors from OSM
:return: Number of floors as a float or NaN
"""
import re
try:
parsed_floors = float(floors) # Try casting string to float
except ValueError:
separators = [',', ';'] # Try matching with different separators
separated_values = r'^(?:\d+(?:\.\d+)?(?:{separator}\s?)?)+$'
for separator in separators:
match = re.match(separated_values.format(separator=separator), floors)
if match:
return max([float(x.strip() or 0) for x in floors.split(separator)])
return np.nan
else:
return parsed_floors
def clean_attributes(shapefile, buildings_height, buildings_floors, buildings_height_below_ground,
buildings_floors_below_ground, key):
# local variables
no_buildings = shapefile.shape[0]
list_of_columns = shapefile.columns
if buildings_height is None and buildings_floors is None:
print('Warning! you have not indicated a height or number of floors above ground for the buildings, '
'we are reverting to data stored in Open Street Maps (It might not be accurate at all),'
'if we do not find data in OSM for a particular building, we get the median in the surroundings, '
'if we do not get any data we assume 4 floors per building')
# Check which attributes the OSM has, Sometimes it does not have any and indicate the data source
if 'building:levels' not in list_of_columns:
shapefile['building:levels'] = [3] * no_buildings
shapefile['REFERENCE'] = "CEA - assumption"
elif pd.isnull(shapefile['building:levels']).all():
shapefile['building:levels'] = [3] * no_buildings
shapefile['REFERENCE'] = "CEA - assumption"
else:
shapefile['REFERENCE'] = ["OSM - median values of all buildings" if x is np.nan else "OSM - as it is" for x
in shapefile['building:levels']]
if 'roof:levels' not in list_of_columns:
shapefile['roof:levels'] = 0
# get the median from the area:
data_osm_floors1 = shapefile['building:levels'].fillna(0)
data_osm_floors2 = shapefile['roof:levels'].fillna(0)
data_floors_sum = [x + y for x, y in zip([parse_building_floors(x) for x in data_osm_floors1],
[parse_building_floors(x) for x in data_osm_floors2])]
data_floors_sum_with_nan = [np.nan if x < 1.0 else x for x in data_floors_sum]
data_osm_floors_joined = math.ceil(
np.nanmedian(data_floors_sum_with_nan)) # median so we get close to the worse case
shapefile["floors_ag"] = [int(x) if not np.isnan(x) else data_osm_floors_joined for x in
data_floors_sum_with_nan]
shapefile["height_ag"] = shapefile["floors_ag"] * constants.H_F
else:
shapefile['REFERENCE'] = "User - assumption"
if buildings_height is None and buildings_floors is not None:
shapefile["floors_ag"] = [buildings_floors] * no_buildings
shapefile["height_ag"] = shapefile["floors_ag"] * constants.H_F
elif buildings_height is not None and buildings_floors is None:
shapefile["height_ag"] = [buildings_height] * no_buildings
shapefile["floors_ag"] = [int(math.floor(x)) for x in shapefile["height_ag"] / constants.H_F]
else: # both are not none
shapefile["height_ag"] = [buildings_height] * no_buildings
shapefile["floors_ag"] = [buildings_floors] * no_buildings
# add fields for floorsa and height below ground
shapefile["height_bg"] = [buildings_height_below_ground] * no_buildings
shapefile["floors_bg"] = [buildings_floors_below_ground] * no_buildings
# add description
if "description" in list_of_columns:
shapefile["description"] = shapefile['description']
elif 'addr:housename' in list_of_columns:
shapefile["description"] = shapefile['addr:housename']
elif 'amenity' in list_of_columns:
shapefile["description"] = shapefile['amenity']
else:
shapefile["description"] = [np.nan] * no_buildings
shapefile["category"] = shapefile['building']
if 'amenity' in list_of_columns:
# in OSM, "amenities" (where available) supersede "building" categories
in_categories = shapefile['amenity'].isin(OSM_BUILDING_CATEGORIES.keys())
shapefile.loc[in_categories, '1ST_USE'] = shapefile[in_categories]['amenity'].map(OSM_BUILDING_CATEGORIES)
shapefile["Name"] = [key + str(x + 1000) for x in
range(no_buildings)] # start in a big number to avoid potential confusion
cleaned_shapefile = shapefile[
["Name", "height_ag", "floors_ag", "height_bg", "floors_bg", "description", "category", "geometry",
"REFERENCE"]]
cleaned_shapefile.reset_index(inplace=True, drop=True)
shapefile.reset_index(inplace=True, drop=True)
return cleaned_shapefile, shapefile
def zone_helper(locator, config):
"""
This script gets a polygon and calculates the zone.shp and the occupancy.dbf and age.dbf inputs files for CEA
:param locator:
:param config:
:return:
"""
# local variables:
poly = Gdf.from_file(locator.get_site_polygon())
buildings_height = config.zone_helper.height_ag
buildings_floors = config.zone_helper.floors_ag
buildings_height_below_ground = config.zone_helper.height_bg
buildings_floors_below_ground = config.zone_helper.floors_bg
occupancy_type = config.zone_helper.occupancy_type
year_construction = config.zone_helper.year_construction
zone_output_path = locator.get_zone_geometry()
typology_output_path = locator.get_building_typology()
# ensure folders exist
locator.ensure_parent_folder_exists(zone_output_path)
locator.ensure_parent_folder_exists(typology_output_path)
# get zone.shp file and save in folder location
zone_df = polygon_to_zone(buildings_floors, buildings_floors_below_ground, buildings_height,
buildings_height_below_ground,
poly, zone_output_path)
# USE_A zone.shp file contents to get the contents of occupancy.dbf and age.dbf
calculate_typology_file(locator, zone_df, year_construction, occupancy_type, typology_output_path)
def calc_category(standard_db, year_array):
def category_assignment(year):
within_year = (standard_db['YEAR_START'] <= year) & (standard_db['YEAR_END'] >= year)
standards = standard_db.STANDARD.values
# Filter standards if found
if within_year.any():
standards = standards[within_year]
# Just return first value
return standards[0]
category = np.array([category_assignment(y) for y in year_array])
return category
def calculate_typology_file(locator, zone_df, year_construction, occupancy_type, occupancy_output_path):
"""
This script fills in the occupancy.dbf file with one occupancy type
:param zone_df:
:param occupancy_type:
:param occupancy_output_path:
:return:
"""
# calculate construction year
typology_df = calculate_age(zone_df, year_construction)
# calculate the most likely construction standard
standard_database = pd.read_excel(locator.get_database_construction_standards(), sheet_name='STANDARD_DEFINITION')
typology_df['STANDARD'] = calc_category(standard_database, typology_df['YEAR'].values)
# Calculate the most likely use type
typology_df['1ST_USE'] = 'MULTI_RES'
typology_df['1ST_USE_R'] = 1.0
typology_df['2ND_USE'] = "NONE"
typology_df['2ND_USE_R'] = 0.0
typology_df['3RD_USE'] = "NONE"
typology_df['3RD_USE_R'] = 0.0
if occupancy_type == "Get it from open street maps":
# for OSM building/amenity types with a clear CEA use type, this use type is assigned
in_categories = zone_df['category'].isin(OSM_BUILDING_CATEGORIES.keys())
zone_df.loc[in_categories, '1ST_USE'] = zone_df[in_categories]['category'].map(OSM_BUILDING_CATEGORIES)
# for un-conditioned OSM building categories without a clear CEA use type, "PARKING" is assigned
if 'amenity' in zone_df.columns:
in_unconditioned_categories = zone_df['category'].isin(OTHER_OSM_CATEGORIES_UNCONDITIONED) | zone_df['amenity'].isin(OTHER_OSM_CATEGORIES_UNCONDITIONED)
else:
in_unconditioned_categories = zone_df['category'].isin(OTHER_OSM_CATEGORIES_UNCONDITIONED)
zone_df.loc[in_unconditioned_categories, '1ST_USE'] = "PARKING"
fields = COLUMNS_ZONE_TYPOLOGY
dataframe_to_dbf(typology_df[fields + ['REFERENCE']], occupancy_output_path)
def parse_year(year: Union[str, int]) -> int:
import re
# `start-date` formats can be found here https://wiki.openstreetmap.org/wiki/Key:start_date#Formatting
if type(year) == str:
# For year in "century" format e.g. `C19`
century_year = re.search(r'C(\d{2})', year)
if century_year:
return int(f"{century_year.group(1)}00")
# For any four digits in a string e.g. `1860s` or `late 1920s`
four_digit = re.search(r'\d{4}', year)
if four_digit:
return int(four_digit.group(0))
# Finally try to cast string to int
try:
return int(year)
except ValueError:
# Raise error later
pass
raise ValueError(f"Invalid year format found `{year}`")
else:
return year
def calculate_age(zone_df, year_construction):
"""
This script fills in the age.dbf file with one year of construction
:param zone_df:
:param year_construction:
:param age_output_path:
:return:
"""
if year_construction is None:
print('Warning! you have not indicated a year of construction for the buildings, '
'we are reverting to data stored in Open Street Maps (It might not be accurate at all),'
'if we do not find data in OSM for a particular building, we get the median in the surroundings, '
'if we do not get any data we assume all buildings being constructed in the year 2000')
list_of_columns = zone_df.columns
if "start_date" not in list_of_columns: # this field describes the construction year of buildings
zone_df["start_date"] = 2000
zone_df['REFERENCE'] = "CEA - assumption"
else:
zone_df['REFERENCE'] = ["OSM - median" if x is np.nan else "OSM - as it is" for x in zone_df['start_date']]
data_age = [np.nan if x is np.nan else parse_year(x) for x in zone_df['start_date']]
data_osm_floors_joined = int(math.ceil(np.nanmedian(data_age))) # median so we get close to the worse case
zone_df["YEAR"] = [int(x) if x is not np.nan else data_osm_floors_joined for x in data_age]
else:
zone_df['YEAR'] = year_construction
zone_df['REFERENCE'] = "CEA - assumption"
return zone_df
def polygon_to_zone(buildings_floors, buildings_floors_below_ground, buildings_height, buildings_height_below_ground,
poly, zone_out_path):
poly = poly.to_crs(get_geographic_coordinate_system())
lon = poly.geometry[0].centroid.coords.xy[0][0]
lat = poly.geometry[0].centroid.coords.xy[1][0]
# get footprints of all the district
poly = osmnx.footprints.footprints_from_polygon(polygon=poly['geometry'].values[0])
# clean geometries
poly = clean_geometries(poly)
# clean attributes of height, name and number of floors
cleaned_shapefile, shapefile = clean_attributes(poly, buildings_height, buildings_floors,
buildings_height_below_ground,
buildings_floors_below_ground, key="B")
cleaned_shapefile = cleaned_shapefile.to_crs(get_projected_coordinate_system(float(lat), float(lon)))
# save shapefile to zone.shp
cleaned_shapefile.to_file(zone_out_path)
return shapefile
def clean_geometries(gdf):
"""
Takes in a GeoPandas DataFrame and making sure all geometries are of type 'Polygon' and remove any entries that do
not have any geometries
:param gdf: GeoPandas DataFrame containing geometries
:return:
"""
def flatten_geometries(geometry):
"""
Flatten polygon collections into a single polygon by using their union
:param geometry: Type of Shapely geometry
:return:
"""
from shapely.ops import unary_union
if geometry.type == 'Polygon': # ignore Polygons
return geometry
elif geometry.type in ['Point', 'LineString']:
print(f'Discarding geometry of type: {geometry.type}')
return None # discard geometry if it is a Point or LineString
else:
joined = unary_union(list(geometry))
if joined.type == 'MultiPolygon': # some Multipolygons could not be combined
return joined[0] # just return first polygon
elif joined.type != 'Polygon': # discard geometry if it is still not a Polygon
print(f'Discarding geometry of type: {joined.type}')
return None
else:
return joined
gdf.geometry = gdf.geometry.map(flatten_geometries)
gdf = gdf[gdf.geometry.notnull()] # remove None geometries
return gdf
def main(config):
"""
This script gets a polygon and calculates the zone.shp and the occupancy.dbf and age.dbf inputs files for CEA
"""
assert os.path.exists(config.scenario), 'Scenario not found: %s' % config.scenario
locator = cea.inputlocator.InputLocator(config.scenario)
zone_helper(locator, config)
if __name__ == '__main__':
main(cea.config.Configuration())
| [
"numpy.nanmedian",
"os.path.exists",
"math.floor",
"pandas.isnull",
"numpy.isnan",
"cea.datamanagement.constants.OSM_BUILDING_CATEGORIES.keys",
"cea.utilities.dbf.dataframe_to_dbf",
"cea.utilities.standardize_coordinates.get_geographic_coordinate_system",
"re.search"
] | [((10086, 10162), 'cea.utilities.dbf.dataframe_to_dbf', 'dataframe_to_dbf', (["typology_df[fields + ['REFERENCE']]", 'occupancy_output_path'], {}), "(typology_df[fields + ['REFERENCE']], occupancy_output_path)\n", (10102, 10162), False, 'from cea.utilities.dbf import dataframe_to_dbf\n'), ((15059, 15090), 'os.path.exists', 'os.path.exists', (['config.scenario'], {}), '(config.scenario)\n', (15073, 15090), False, 'import os\n'), ((10431, 10459), 're.search', 're.search', (['"""C(\\\\d{2})"""', 'year'], {}), "('C(\\\\d{2})', year)\n", (10440, 10459), False, 'import re\n'), ((10631, 10656), 're.search', 're.search', (['"""\\\\d{4}"""', 'year'], {}), "('\\\\d{4}', year)\n", (10640, 10656), False, 'import re\n'), ((12650, 12684), 'cea.utilities.standardize_coordinates.get_geographic_coordinate_system', 'get_geographic_coordinate_system', ([], {}), '()\n', (12682, 12684), False, 'from cea.utilities.standardize_coordinates import get_projected_coordinate_system, get_geographic_coordinate_system\n'), ((3983, 4021), 'numpy.nanmedian', 'np.nanmedian', (['data_floors_sum_with_nan'], {}), '(data_floors_sum_with_nan)\n', (3995, 4021), True, 'import numpy as np\n'), ((5823, 5853), 'cea.datamanagement.constants.OSM_BUILDING_CATEGORIES.keys', 'OSM_BUILDING_CATEGORIES.keys', ([], {}), '()\n', (5851, 5853), False, 'from cea.datamanagement.constants import OSM_BUILDING_CATEGORIES, OTHER_OSM_CATEGORIES_UNCONDITIONED\n'), ((9401, 9431), 'cea.datamanagement.constants.OSM_BUILDING_CATEGORIES.keys', 'OSM_BUILDING_CATEGORIES.keys', ([], {}), '()\n', (9429, 9431), False, 'from cea.datamanagement.constants import OSM_BUILDING_CATEGORIES, OTHER_OSM_CATEGORIES_UNCONDITIONED\n'), ((12172, 12194), 'numpy.nanmedian', 'np.nanmedian', (['data_age'], {}), '(data_age)\n', (12184, 12194), True, 'import numpy as np\n'), ((3004, 3043), 'pandas.isnull', 'pd.isnull', (["shapefile['building:levels']"], {}), "(shapefile['building:levels'])\n", (3013, 3043), True, 'import pandas as pd\n'), ((4115, 4126), 'numpy.isnan', 'np.isnan', (['x'], {}), '(x)\n', (4123, 4126), True, 'import numpy as np\n'), ((4761, 4774), 'math.floor', 'math.floor', (['x'], {}), '(x)\n', (4771, 4774), False, 'import math\n')] |
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics.classification import accuracy_score
from dbn.tensorflow import SupervisedDBNClassification
from keras.preprocessing.image import ImageDataGenerator
train_dir = 'E:\\Datasets\\bangla\\train'
test_dir = 'E:\\Datasets\\bangla\\test'
train_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size = (64, 64),
batch_size=12000
)
validation_generator = test_datagen.flow_from_directory(
test_dir,
target_size = (64, 64),
batch_size=3000
)
for X_train, Y_train in train_generator:
X_train = X_train.reshape(-1, 64*64*3)
Y_train = np.argmax(Y_train, axis=1)
break
for X_test, Y_test in validation_generator:
X_train = X_train.reshape(-1, 64*64*3)
Y_test = np.argmax(Y_test, axis=1)
break
# Training
classifier = SupervisedDBNClassification(hidden_layers_structure=[256, 256],
learning_rate_rbm=0.05,
learning_rate=0.1,
n_epochs_rbm=10,
n_iter_backprop=100,
batch_size=32,
activation_function='relu',
dropout_p=0.2)
classifier.fit(X_train, Y_train)
classifier.save('model.pkl')
# Test
Y_pred = classifier.predict(X_test)
print('Done.\nAccuracy: %f' % accuracy_score(Y_test, Y_pred))
| [
"sklearn.metrics.classification.accuracy_score",
"keras.preprocessing.image.ImageDataGenerator",
"dbn.tensorflow.SupervisedDBNClassification",
"numpy.argmax"
] | [((344, 381), 'keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {'rescale': '(1.0 / 255)'}), '(rescale=1.0 / 255)\n', (362, 381), False, 'from keras.preprocessing.image import ImageDataGenerator\n'), ((394, 431), 'keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {'rescale': '(1.0 / 255)'}), '(rescale=1.0 / 255)\n', (412, 431), False, 'from keras.preprocessing.image import ImageDataGenerator\n'), ((969, 1183), 'dbn.tensorflow.SupervisedDBNClassification', 'SupervisedDBNClassification', ([], {'hidden_layers_structure': '[256, 256]', 'learning_rate_rbm': '(0.05)', 'learning_rate': '(0.1)', 'n_epochs_rbm': '(10)', 'n_iter_backprop': '(100)', 'batch_size': '(32)', 'activation_function': '"""relu"""', 'dropout_p': '(0.2)'}), "(hidden_layers_structure=[256, 256],\n learning_rate_rbm=0.05, learning_rate=0.1, n_epochs_rbm=10,\n n_iter_backprop=100, batch_size=32, activation_function='relu',\n dropout_p=0.2)\n", (996, 1183), False, 'from dbn.tensorflow import SupervisedDBNClassification\n'), ((770, 796), 'numpy.argmax', 'np.argmax', (['Y_train'], {'axis': '(1)'}), '(Y_train, axis=1)\n', (779, 796), True, 'import numpy as np\n'), ((908, 933), 'numpy.argmax', 'np.argmax', (['Y_test'], {'axis': '(1)'}), '(Y_test, axis=1)\n', (917, 933), True, 'import numpy as np\n'), ((1595, 1625), 'sklearn.metrics.classification.accuracy_score', 'accuracy_score', (['Y_test', 'Y_pred'], {}), '(Y_test, Y_pred)\n', (1609, 1625), False, 'from sklearn.metrics.classification import accuracy_score\n')] |
import boto3
import numpy as np
import time
import matplotlib.pyplot as plt
# docker run -p 8000:8000 -v $(pwd)/local/dynamodb:/data/ amazon/dynamodb-local -jar DynamoDBLocal.jar -sharedDb -dbPath /data
def main():
dynamodb=boto3.client(
'dynamodb',
endpoint_url='http://localhost:8000',
aws_access_key_id='foo',
aws_secret_access_key='bar',
verify=False
)
try:
dynamodb.delete_table(TableName='values')
except dynamodb.exceptions.ResourceNotFoundException:
print("Table does not exist yet, creating...")
resource = boto3.resource(
'dynamodb',
endpoint_url='http://localhost:8000',
aws_access_key_id='foo',
aws_secret_access_key='bar',
verify=False
)
t = resource.Table('values')
dynamodb.create_table(
TableName='values',
KeySchema=[
{
'AttributeName': 'key',
'KeyType': 'HASH'
}
],
AttributeDefinitions=[
{
'AttributeName': 'key',
'AttributeType': 'S'
}
],
ProvisionedThroughput={
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
}
)
# # Test job size vs job time
N = 1000
memory_set = {}
memory_get = {}
time_table_set = {}
time_table_get = {}
time_complete_set = {}
time_complete_get = {}
# memory issues around size 256 ...
# 9
array_sizes = 2**np.arange(9)
for size in array_sizes:
print("size {}".format(size**2 * 8))
t_set = []
t_get = []
t_set_complete = []
t_get_complete =[]
# store values
for i in range(N):
#t_start = r.time()
t_start = time.time_ns()
key = "{0:015b}".format(i)
x = np.random.uniform(0,1,size=(size,size))
#r.set(key,x.tobytes())
t.put_item(Item={'key': key})
#t_end = r.time()
t_end = time.time_ns()
#job_time = (t_end[0] + t_end[1]*1e-6)-(t_start[0] + t_start[1]*1e-6)
job_time = t_end - t_start
t_set.append(job_time)
#t_set_complete.append(t_end[0] + t_end[1]*1e-6)
t_set_complete.append(t_end)
# get values
for i in range(N):
#t_start = r.time()
t_start = time.time_ns()
key = "{0:015b}".format(i)
#r.get(key)
t.get_item(Key={'key': key})
#t_end = r.time()
t_end = time.time_ns()
#job_time = (t_end[0] + t_end[1]*1e-6)-(t_start[0] + t_start[1]*1e-6)
job_time = t_end - t_start
t_get.append(job_time)
#t_get_complete.append(t_end[0] + t_end[1]*1e-6)
t_set_complete.append(t_end)
#breakpoint()
# clear keys
for i in range(N):
#r.delete("{0:015b}".format(i))
t.delete_item(Key={'key': "{0:015b}".format(i)})
memory_set[str(size**2 * 8)] = np.mean(t_set)
time_table_set[str(size**2 * 8)] = t_set
memory_get[str(size**2 * 8)] = np.mean(t_get)
time_table_get[str(size**2 * 8)] = t_get
time_complete_set[str(size**2 * 8)] = time_complete_set
time_complete_get[str(size**2 * 8)] = time_complete_get
plt.plot(np.array(list(memory_set.keys())),np.array(list(memory_set.values())))
plt.plot(np.array(list(memory_get.keys())),np.array(list(memory_get.values())))
plt.xlabel("Memory (bytes)")
plt.ylabel("Average Time")
plt.legend(["Set","Get"])
plt.plot(np.array(list(memory_get.keys())),np.array(list(memory_get.values()))-np.array(list(memory_set.values())))
plt.xlabel("Memory (bytes)")
plt.ylabel("Average Time")
plt.title("Set - Get as memory increased")
plt.show()
plt.figure(figsize=(10,5))
for size in array_sizes:
key = size**2 * 8
t = time_table_set[str(key)]
num_bins = int(np.sqrt(len(t)))#int(np.floor(5/3 * (len(t)**(1/3))))
counts, bin_edges = np.histogram (t, bins=num_bins, normed=True)
cdf = np.cumsum (counts)
plt.plot (np.hstack((np.zeros((1,)),bin_edges[1:])), np.hstack((np.zeros(1,),cdf/cdf[-1])))
plt.xlabel("t"); plt.ylabel("f(t)");
plt.xlim([0,0.005])
plt.legend(array_sizes**2 * 8)
plt.show()
plt.figure(figsize=(10,5))
for size in array_sizes:
key = size**2 * 8
ti = time_table_get[str(key)]
num_bins = int(np.sqrt(len(ti)))#int(np.floor(5/3 * (len(t)**(1/3))))
counts, bin_edges = np.histogram (ti, bins=num_bins, normed=True)
cdf = np.cumsum (counts)
plt.plot (np.hstack((np.zeros((1,)),bin_edges[1:])), np.hstack((np.zeros(1,),cdf/cdf[-1])))
plt.xlabel("t"); plt.ylabel("f(t)");
plt.xlim([0,0.0015])
plt.legend(array_sizes**2 * 8)
plt.show()
# clear keys
for i in range(N):
#r.delete("{0:015b}".format(i))
t.delete_item(Key={'key': "{0:015b}".format(i)})
"""
## job vs total time
N = 100
memory_set = {}
memory_get = {}
time_table_set = {}
time_table_get = {}
time_complete_set = {}
time_complete_get = {}
#pipeline = r.pipeline(transaction=True)
batcher = boto3.client('batch')
job_size = np.array([1,10,100,1000,10000,100000])
for size in job_size:
print("N jobs {}".format(size))
t_set = []
t_get = []
t_set_complete = []
t_get_complete =[]
# store values
for _ in range(N):
for i in range(size):
key = "{0:015b}".format(i)
x = np.random.uniform(0,1,size=(8,8))
pipeline.set(key,x.tobytes())
t_start = r.time()
pipeline.execute()
t_end = r.time()
job_time = (t_end[0] + t_end[1]*1e-6)-(t_start[0] + t_start[1]*1e-6)
t_set.append(job_time)
t_set_complete.append(t_end[0] + t_end[1]*1e-6)
# get values
for _ in range(N):
for i in range(size):
key = "{0:015b}".format(i)
pipeline.get(key)
t_start = r.time()
pipeline.execute()
t_end = r.time()
job_time = (t_end[0] + t_end[1]*1e-6)-(t_start[0] + t_start[1]*1e-6)
t_get.append(job_time)
t_get_complete.append(t_end[0] + t_end[1]*1e-6)
# clear keys
for i in range(N):
r.delete("{0:015b}".format(i))
memory_set[str(size)] = np.mean(t_set)
time_table_set[str(size)] = t_set
memory_get[str(size)] = np.mean(t_get)
time_table_get[str(size)] = t_get
plt.plot(np.array(list(memory_set.keys())),np.array(list(memory_set.values())))
plt.plot(np.array(list(memory_get.keys())),np.array(list(memory_get.values())))
plt.xlabel("Memory (bytes)")
plt.ylabel("Average Time")
plt.legend(["Set","Get"])
plt.show()
plt.plot(np.array(list(memory_get.keys())),np.array(list(memory_get.values()))-np.array(list(memory_set.values())))
plt.xlabel("Memory (bytes)")
plt.ylabel("Average Time")
plt.title("Set - Get as memory increased")
plt.show()
plt.figure(figsize=(10,5))
for size in job_size:
key = size
t = time_table_set[str(key)]
num_bins = int(np.sqrt(len(t))) #int(np.floor(5/3 * (len(t)**(1/3))))
counts, bin_edges = np.histogram (t, bins=num_bins, normed=True)
cdf = np.cumsum (counts)
plt.plot (np.hstack((np.zeros((1,)),bin_edges[1:])), np.hstack((np.zeros(1,),cdf/cdf[-1])))
plt.xlabel("t"); plt.ylabel("f(t)");
plt.xlim([0,5])
plt.legend(job_size)
plt.show()
plt.figure(figsize=(10,5))
for size in job_size:
key = size
t = time_table_get[str(key)]
num_bins = int(np.sqrt(len(t)))#int(np.floor(5/3 * (len(t)**(1/3))))
counts, bin_edges = np.histogram (t, bins=num_bins, normed=True)
cdf = np.cumsum (counts)
plt.plot (np.hstack((np.zeros((1,)),bin_edges[1:])), np.hstack((np.zeros(1,),cdf/cdf[-1])))
plt.xlabel("t"); plt.ylabel("f(t)");
plt.xlim()
plt.legend(job_size)
plt.show()
# clear keys
for i in range(N):
r.delete("{0:015b}".format(i))
"""
if __name__ == "__main__":
main() | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlim",
"numpy.random.uniform",
"matplotlib.pyplot.show",
"boto3.client",
"matplotlib.pyplot.legend",
"numpy.zeros",
"numpy.cumsum",
"matplotlib.pyplot.figure",
"boto3.resource",
"numpy.arange",
"numpy.mean",
"numpy.histogram",
"time.time_ns",
... | [((229, 363), 'boto3.client', 'boto3.client', (['"""dynamodb"""'], {'endpoint_url': '"""http://localhost:8000"""', 'aws_access_key_id': '"""foo"""', 'aws_secret_access_key': '"""bar"""', 'verify': '(False)'}), "('dynamodb', endpoint_url='http://localhost:8000',\n aws_access_key_id='foo', aws_secret_access_key='bar', verify=False)\n", (241, 363), False, 'import boto3\n'), ((595, 731), 'boto3.resource', 'boto3.resource', (['"""dynamodb"""'], {'endpoint_url': '"""http://localhost:8000"""', 'aws_access_key_id': '"""foo"""', 'aws_secret_access_key': '"""bar"""', 'verify': '(False)'}), "('dynamodb', endpoint_url='http://localhost:8000',\n aws_access_key_id='foo', aws_secret_access_key='bar', verify=False)\n", (609, 731), False, 'import boto3\n'), ((3756, 3784), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Memory (bytes)"""'], {}), "('Memory (bytes)')\n", (3766, 3784), True, 'import matplotlib.pyplot as plt\n'), ((3789, 3815), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Average Time"""'], {}), "('Average Time')\n", (3799, 3815), True, 'import matplotlib.pyplot as plt\n'), ((3820, 3846), 'matplotlib.pyplot.legend', 'plt.legend', (["['Set', 'Get']"], {}), "(['Set', 'Get'])\n", (3830, 3846), True, 'import matplotlib.pyplot as plt\n'), ((3972, 4000), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Memory (bytes)"""'], {}), "('Memory (bytes)')\n", (3982, 4000), True, 'import matplotlib.pyplot as plt\n'), ((4005, 4031), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Average Time"""'], {}), "('Average Time')\n", (4015, 4031), True, 'import matplotlib.pyplot as plt\n'), ((4036, 4078), 'matplotlib.pyplot.title', 'plt.title', (['"""Set - Get as memory increased"""'], {}), "('Set - Get as memory increased')\n", (4045, 4078), True, 'import matplotlib.pyplot as plt\n'), ((4083, 4093), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4091, 4093), True, 'import matplotlib.pyplot as plt\n'), ((4098, 4125), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 5)'}), '(figsize=(10, 5))\n', (4108, 4125), True, 'import matplotlib.pyplot as plt\n'), ((4580, 4600), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0, 0.005]'], {}), '([0, 0.005])\n', (4588, 4600), True, 'import matplotlib.pyplot as plt\n'), ((4604, 4636), 'matplotlib.pyplot.legend', 'plt.legend', (['(array_sizes ** 2 * 8)'], {}), '(array_sizes ** 2 * 8)\n', (4614, 4636), True, 'import matplotlib.pyplot as plt\n'), ((4639, 4649), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4647, 4649), True, 'import matplotlib.pyplot as plt\n'), ((4654, 4681), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 5)'}), '(figsize=(10, 5))\n', (4664, 4681), True, 'import matplotlib.pyplot as plt\n'), ((5139, 5160), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0, 0.0015]'], {}), '([0, 0.0015])\n', (5147, 5160), True, 'import matplotlib.pyplot as plt\n'), ((5164, 5196), 'matplotlib.pyplot.legend', 'plt.legend', (['(array_sizes ** 2 * 8)'], {}), '(array_sizes ** 2 * 8)\n', (5174, 5196), True, 'import matplotlib.pyplot as plt\n'), ((5199, 5209), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5207, 5209), True, 'import matplotlib.pyplot as plt\n'), ((1535, 1547), 'numpy.arange', 'np.arange', (['(9)'], {}), '(9)\n', (1544, 1547), True, 'import numpy as np\n'), ((3268, 3282), 'numpy.mean', 'np.mean', (['t_set'], {}), '(t_set)\n', (3275, 3282), True, 'import numpy as np\n'), ((3380, 3394), 'numpy.mean', 'np.mean', (['t_get'], {}), '(t_get)\n', (3387, 3394), True, 'import numpy as np\n'), ((4334, 4377), 'numpy.histogram', 'np.histogram', (['t'], {'bins': 'num_bins', 'normed': '(True)'}), '(t, bins=num_bins, normed=True)\n', (4346, 4377), True, 'import numpy as np\n'), ((4393, 4410), 'numpy.cumsum', 'np.cumsum', (['counts'], {}), '(counts)\n', (4402, 4410), True, 'import numpy as np\n'), ((4520, 4535), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""t"""'], {}), "('t')\n", (4530, 4535), True, 'import matplotlib.pyplot as plt\n'), ((4537, 4555), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""f(t)"""'], {}), "('f(t)')\n", (4547, 4555), True, 'import matplotlib.pyplot as plt\n'), ((4892, 4936), 'numpy.histogram', 'np.histogram', (['ti'], {'bins': 'num_bins', 'normed': '(True)'}), '(ti, bins=num_bins, normed=True)\n', (4904, 4936), True, 'import numpy as np\n'), ((4952, 4969), 'numpy.cumsum', 'np.cumsum', (['counts'], {}), '(counts)\n', (4961, 4969), True, 'import numpy as np\n'), ((5079, 5094), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""t"""'], {}), "('t')\n", (5089, 5094), True, 'import matplotlib.pyplot as plt\n'), ((5096, 5114), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""f(t)"""'], {}), "('f(t)')\n", (5106, 5114), True, 'import matplotlib.pyplot as plt\n'), ((1856, 1870), 'time.time_ns', 'time.time_ns', ([], {}), '()\n', (1868, 1870), False, 'import time\n'), ((1939, 1981), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)'], {'size': '(size, size)'}), '(0, 1, size=(size, size))\n', (1956, 1981), True, 'import numpy as np\n'), ((2108, 2122), 'time.time_ns', 'time.time_ns', ([], {}), '()\n', (2120, 2122), False, 'import time\n'), ((2537, 2551), 'time.time_ns', 'time.time_ns', ([], {}), '()\n', (2549, 2551), False, 'import time\n'), ((2733, 2747), 'time.time_ns', 'time.time_ns', ([], {}), '()\n', (2745, 2747), False, 'import time\n'), ((4441, 4455), 'numpy.zeros', 'np.zeros', (['(1,)'], {}), '((1,))\n', (4449, 4455), True, 'import numpy as np\n'), ((4484, 4495), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (4492, 4495), True, 'import numpy as np\n'), ((5000, 5014), 'numpy.zeros', 'np.zeros', (['(1,)'], {}), '((1,))\n', (5008, 5014), True, 'import numpy as np\n'), ((5043, 5054), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (5051, 5054), True, 'import numpy as np\n')] |
""" Class Scenario
Creation date: 2018 11 05
Author(s): <NAME>
To do:
Move falls_into method to ScenarioCategory and rename it to "comprises".
Modifications:
2018 11 22: Make is possible to instantiate a Scenario from JSON code.
2018 12 06: Add functionality to return the derived Tags.
2018 12 06: Make it possible to return full JSON code (incl. attributes' JSON code).
2018 12 06: to_openscenario function added.
2018 12 07: fall_into method for checking if Scenario falls into ScenarioCategory.
2019 05 22: Make use of type_checking.py to shorten the initialization.
2019 10 13: Update of terminology.
2019 11 04: Add options to automatically assign unique ids to actor/activities.
2020 08 23: Remove the update_uid options because uid is automatically generated by ScenarioElement.
2020 08 24: Make Scenario a subclass of TimeInterval.
2020 08 24: Enable instantiation of Scenario from json without needing full json code.
2020 08 25: Add functionality to evaluate the state variables (+derivatives) at given times.
2020 10 05: Change way of creating object from JSON code.
2020 10 12: Remove Dynamic/StaticPhysicalThing and use PhysicalElement instead.
2020 10 15: Add function get_actor_by_name.
"""
from typing import Callable, List, Tuple, Union
import numpy as np
from .activity import Activity, _activity_from_json
from .actor import Actor, _actor_from_json
from .physical_element import PhysicalElement, _physical_element_from_json
from .scenario_category import derive_actor_tags, _check_acts, _print_tags, _get_acts
from .scenario_element import DMObjects, _attributes_from_json, _object_from_json
from .state_variable import StateVariable
from .time_interval import TimeInterval, _time_interval_props_from_json
from .type_checking import check_for_list, check_for_tuple
class Scenario(TimeInterval):
""" Scenario - either a real-world scenario or a test case.
A scenario is a quantitative description of the ego vehicle, its activities
and/or goals, its dynamic environment (consisting of traffic environment and
conditions) and its static environment. From the perspective of the ego
vehicle, a scenario contains all relevant events.
When instantiating the Scenario object, the name, start event, end event,
unique id (uid), and tags are passed. To set the activities, actors, dynamic
physical things, acts, and static physical things, use the corresponding
methods, i.e., set_activities(), set_actors(),
set_dynamic_physical_things(), set_acts(), and set_static_physical_things(),
respectively.
Attributes:
physical_elements (List[PhysicalElement]): All the things that make up
the static environment and part of the dynamic environment.
actors (List[Actor]): Actors that are participating in this scenario.
This list should always include the ego vehicle.
activities (List[Activity]): Activities that are relevant for this
scenario.
acts (List[tuple[Actor, Activity]]): The acts describe which actors
perform which activities.
name (str): A name that serves as a short description of the scenario.
uid (int): A unique ID.
tags (List[Tag]): A list of tags that formally defines the scenario
category. These tags determine whether a scenario category comprises
this scenario or not.
start (Event): The starting event.
end (Event): The end event.
"""
def __init__(self, **kwargs):
# Assign the attributes
TimeInterval.__init__(self, **kwargs)
self.physical_elements = [] # Type: List[PhysicalElement]
self.actors = [] # Type: List[Actor]
self.activities = [] # Type: List[Activity]
self.acts = [] # Type: List[Tuple(Actor, Activity)]
# Set attributes if provided by kwargs.
if "physical_elements" in kwargs:
self.set_physical_elements(kwargs["physical_elements"])
if "actors" in kwargs:
self.set_actors(kwargs["actors"])
if "activities" in kwargs:
self.set_activities(kwargs["activities"])
if "acts" in kwargs:
self.set_acts(kwargs["acts"])
def set_physical_elements(self, physical_elements: List[PhysicalElement]) -> None:
""" Set the physical things.
Check whether the physical elements are correctly defined.
:param physical_elements: List of physical elements.
"""
# Check whether the physical elements are correctly defined.
check_for_list("physical_elements", physical_elements, PhysicalElement, can_be_none=False)
# Assign physical elements to an attribute.
self.physical_elements = physical_elements
def set_activities(self, activities: List[Activity]) -> None:
""" Set the activities.
Check whether the activities are correctly defined. Activities should be
a list with instantiations of Activity.
:param activities: List of activities that are used for this Scenario.
"""
# Check whether the activities are correctly defined.
check_for_list("activities", activities, Activity, can_be_none=False)
# Assign actitivies to an attribute.
self.activities = activities # Type: List[Activity]
def set_actors(self, actors: List[Actor]) -> None:
""" Set the actors.
Check whether the actors are correctly defined. Actors should be a list
with instantiations of Actor.
:param actors: List of actors that participate in the Scenario.
"""
# Check whether the actors are correctly defined.
check_for_list("actors", actors, Actor, can_be_none=False)
# Assign actors to an attribute.
self.actors = actors # Type: List[Actor]
def set_acts(self, acts_scenario: List[Tuple[Actor, Activity]], verbose: bool = True) -> None:
""" Set the acts
Check whether the acts are correctly defined. Each act should be a tuple
with an actor and an activity, i.e., (Actor, Activity). Acts is a list
containing multiple tuples (Actor, Activity).
:param acts_scenario: The acts describe which actors perform which
activities and a certain time. The actors and activities that are
used in acts should also be passed with the actors and activities
arguments. If not, a warning will be shown and the corresponding
actor/activity will be added to the list of actors/activities.
:param verbose: Set to False if warning should be surpressed.
"""
check_for_list("acts", acts_scenario, tuple)
for act in acts_scenario:
check_for_tuple("act", act, (Actor, Activity))
# Set the acts.
self.acts = acts_scenario
# Check whether the actors/activities defined with the acts are already listed. If not,
# the corresponding actor/activity will be added and a warning will be shown.
_check_acts(self.acts, self.actors, self.activities, verbose=verbose)
def derived_tags(self) -> dict:
""" Return all tags, including the tags of the attributes.
The Scenario has tags, but also its attributes can have tags. More
specifically, each PhysicalElement, each Actor, and each Activity might
have tags. A dictionary will be returned. Each item of the dictionary
contains a list of tags corresponding to either the own object (i.e.,
Scenario), an Actor, or an PhysicalElement.
The tags that might be associated with the Activity are returned with
the Actor if the corresponding Actor is performing that Activity
according to the defined acts.
:return: List of tags.
"""
# Instantiate the dictionary.
tags = {}
# Provide the tags of the very own object (Scenario).
if self.tags:
tags["{:s}::Scenario".format(self.name)] = self.tags
# Provide the tags for each Actor.
tags = derive_actor_tags(self.actors, self.acts, tags=tags)
# Provide the tags for each PhysicalElement.
for physical_element in self.physical_elements:
if physical_element.get_tags():
tags["{:s}::PhysicalElement".format(physical_element.name)] = \
physical_element.get_tags()
# Return the tags.
return tags
def print_tags(self) -> None:
""" Print the derived tags. """
print(_print_tags(self.derived_tags()))
def get_state(self, actor: Actor, state: StateVariable, time: Union[float, List, np.ndarray]) \
-> Union[None, float, np.ndarray]:
""" Obtain the values of the state variable at the given time instants.
:param actor: The actor of which the state variable is to be retrieved.
:param state: The state variable that is to be retrieved.
:param time: The time instance(s).
:return: The value of the state variable at the given time instants.
"""
return self._get_state(actor, state, time)
def get_state_dot(self, actor: Actor, state: StateVariable,
time: Union[float, List, np.ndarray]) -> Union[None, float, np.ndarray]:
""" Obtain the derivative of the values of the state variable at the given time instants.
:param actor: The actor of which the state variable derivative is to be
retrieved.
:param state: The state variable that is to be retrieved.
:param time: The time instance(s).
:return: The value of the state variable at the given time instants.
"""
return self._get_state(actor, state, time, derivative=True)
def _get_state(self, actor: Actor, state: StateVariable, time: Union[float, List, np.ndarray],
derivative=False) -> Union[None, float, np.ndarray]:
vec_time = self._time2vec(time)
is_valid = False
# Loop through the acts.
for my_actor, my_activity in self.acts:
# Only continue with right actor and activity.
if my_actor == actor and my_activity.category.state == state:
tstart = my_activity.get_tstart()
tend = my_activity.get_tend()
if tstart is None or tend is None:
continue
# Check if the time span contains time instances that we want to evaluate.
mask = np.logical_and(vec_time >= tstart, vec_time <= tend)
if np.any(mask):
if not derivative:
tmp_values = my_activity.get_state(time=vec_time[mask])
else:
tmp_values = my_activity.get_state_dot(time=vec_time[mask])
if not is_valid:
if len(tmp_values.shape) == 1:
values = np.ones(len(vec_time)) * np.nan
else:
values = np.ones((len(vec_time), tmp_values.shape[0])) * np.nan
is_valid = True
values[mask] = tmp_values.T
if not is_valid:
return None
if isinstance(time, (float, int)):
return values[0]
return values
@staticmethod
def _time2vec(time: Union[float, List, np.ndarray]) -> np.ndarray:
if isinstance(time, (float, int)):
vec_time = np.array([time])
elif isinstance(time, List):
vec_time = np.array(time)
elif isinstance(time, np.ndarray):
vec_time = time
else:
raise TypeError("<time> needs to be of type <float>, <List>, or <np.ndarray>.")
return vec_time
def get_actor_by_name(self, name: str) -> Union[Actor, None]:
""" Get the actor with the provided name.
If there is no actor with the given name, None is returned. Note that
as soon as an actor is found with the given name, this actor is retuned.
Therefore, this function might fail if there are multiple actors with
the same name.
:param name: The name of the actor that is to be returned.
:return: The actor with the given name.
"""
for actor in self.actors:
if actor.name == name:
return actor
return None
def to_json(self) -> dict:
scenario = TimeInterval.to_json(self)
scenario["physical_elements"] = [dict(name=thing.name, uid=thing.uid)
for thing in self.physical_elements]
scenario["actors"] = [dict(name=actor.name, uid=actor.uid) for actor in self.actors]
scenario["activities"] = [dict(name=activity.name, uid=activity.uid)
for activity in self.activities]
scenario["acts"] = []
for actor, activity in self.acts:
scenario["acts"].append({"actor": actor.uid, "activity": activity.uid})
scenario["derived_tags"] = self.derived_tags()
for key, tags in scenario["derived_tags"].items():
scenario["derived_tags"][key] = [tag.to_json() for tag in tags]
return scenario
def to_json_full(self) -> dict:
scenario = self.to_json()
scenario.update(TimeInterval.to_json_full(self))
scenario["physical_elements"] = [element.to_json_full()
for element in self.physical_elements]
scenario["actors"] = [actor.to_json_full() for actor in self.actors]
scenario["activities"] = [activity.to_json_full() for activity in self.activities]
return scenario
def _scenario_props_from_json(json: dict, attribute_objects: DMObjects, **kwargs) -> dict:
props = _time_interval_props_from_json(json, attribute_objects,
start=None if "start" not in kwargs else kwargs["start"],
end=None if "end" not in kwargs else kwargs["end"])
props.update(_attributes_from_json(
json, attribute_objects,
dict(physical_elements=(_physical_element_from_json, "physical_element"),
actors=(_actor_from_json, "actor"),
activities=(_activity_from_json, "activity")),
**kwargs))
props["acts"] = _get_acts(json, props["actors"], props["activities"])
return props
def _scenario_from_json(json: dict, attribute_objects: DMObjects, **kwargs) -> Scenario:
return Scenario(**_scenario_props_from_json(json, attribute_objects, **kwargs))
def scenario_from_json(json: dict, attribute_objects: DMObjects = None, **kwargs) -> Scenario:
""" Get Scenario object from JSON code
It is assumed that all the attributes are fully defined. Alternatively,
the attributes can be passed via optional arguments. The following optional
arguments are allowed:
- start: The start event.
- end: The end event.
- physical_elements: The physical elements that define the static
environment.
- actors: The physical elements that are dynamic.
- activities: The activities that describe the evolution of the dynamic
environment.
:param json: JSON code of Scenario.
:param attribute_objects: A structure for storing all objects (optional).
:return: Scenario object.
"""
return _object_from_json(json, _scenario_from_json, "scenario", attribute_objects, **kwargs)
def _create_scenario_attributes(json: dict, class_name: str, func_from_json: Callable) -> List:
""" Create list of objects of the class `class_name`.
:param json: The dictionary with the JSON code.
:param class_name: The name of the class for which the objects are to be
instantiated.
:param func_from_json: Function to instantiate an object.
:return: List of objects that are member of the class `class_name`.
"""
# Create the actor categories (ActorCategory) and actors (Actor).
categories = []
categories_ids = []
objects = []
for json_object in json[class_name]:
if json_object["category"]["id"] in categories_ids:
# Category object is already defined.
category = categories[categories_ids.index(json_object["category"]["id"])]
objects.append(func_from_json(json_object, category=category))
else:
objects.append(func_from_json(json_object))
categories.append(objects[-1].category) # This category has just been created
categories_ids.append(categories[-1].uid)
return objects
| [
"numpy.any",
"numpy.array",
"numpy.logical_and"
] | [((11534, 11550), 'numpy.array', 'np.array', (['[time]'], {}), '([time])\n', (11542, 11550), True, 'import numpy as np\n'), ((10548, 10600), 'numpy.logical_and', 'np.logical_and', (['(vec_time >= tstart)', '(vec_time <= tend)'], {}), '(vec_time >= tstart, vec_time <= tend)\n', (10562, 10600), True, 'import numpy as np\n'), ((10620, 10632), 'numpy.any', 'np.any', (['mask'], {}), '(mask)\n', (10626, 10632), True, 'import numpy as np\n'), ((11611, 11625), 'numpy.array', 'np.array', (['time'], {}), '(time)\n', (11619, 11625), True, 'import numpy as np\n')] |
# library of small functions
import json
import logging
import traceback
from pathlib import Path
import numpy as np
from ibllib.misc import version
_logger = logging.getLogger('ibllib')
def pprint(my_dict):
print(json.dumps(my_dict, indent=4))
def _parametrized(dec):
def layer(*args, **kwargs):
def repl(f):
return dec(f, *args, **kwargs)
return repl
return layer
@_parametrized
def log2session_static(func, log_file_name):
""" Decorator that will fork the log output of any function that takes a session path as
first argument to a {session_path}/logs/yyyy-mm-dd_{log_filename}_ibllib_v1.2.3.log"""
def func_wrapper(session_path, *args, **kwargs):
fh = log2sessions_set(session_path, log_file_name)
try:
f = func(session_path, *args, **kwargs)
except Exception as e:
log2sessions_catch(e, session_path, log_file_name)
f = None
log2sessions_unset(log_file_name, fh)
return f
return func_wrapper
@_parametrized
def log2session(func, log_file_name):
""" Decorator that will fork the log output of any method that takes a session path as
first argument to a {session_path}/logs/yyyy-mm-dd_{log_filename}_ibllib_v1.2.3.log"""
def func_wrapper(self, session_path, *args, **kwargs):
fh = log2sessions_set(session_path, log_file_name)
try:
f = func(self, session_path, *args, **kwargs)
except Exception as e:
log2sessions_catch(e, session_path, log_file_name)
f = None
log2sessions_unset(log_file_name, fh)
return f
return func_wrapper
def log2sessions_set(session_path, log_type):
log_file = Path(session_path).joinpath(
'logs', f'_ibl_log.info.{log_type}_v{version.ibllib()}.log')
log_file.parent.mkdir(exist_ok=True)
fh = logging.FileHandler(log_file)
str_format = '%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s'
fh.setFormatter(logging.Formatter(str_format))
_logger.addHandler(fh)
return fh
def log2sessions_unset(log_type, fh=None):
for hdlr in _logger.handlers:
if '_ibl_log.' in str(hdlr):
_logger.removeHandler(hdlr)
if fh:
fh.close()
def log2sessions_catch(e, sessionpath, log_type):
error_message = f'{sessionpath} failed extraction \n {str(e)} \n' \
f'{traceback.format_exc()}'
err_file = Path(sessionpath).joinpath(
'logs', f'_ibl_log.error.{log_type}_v{version.ibllib()}.log')
with open(err_file, 'w+') as fid:
fid.write(error_message)
_logger.error(error_message)
def structarr(names, shape=None, formats=None):
if not formats:
formats = ['f8'] * len(names)
dtyp = np.dtype({'names': names, 'formats': formats})
return np.zeros(shape, dtype=dtyp)
def logger_config(name=None):
import logging
import colorlog
"""
Setup the logging environment
"""
if not name:
log = logging.getLogger() # root logger
else:
log = logging.getLogger(name)
log.setLevel(logging.INFO)
format_str = '%(asctime)s.%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s'
date_format = '%Y-%m-%d %H:%M:%S'
cformat = '%(log_color)s' + format_str
colors = {'DEBUG': 'green',
'INFO': 'cyan',
'WARNING': 'bold_yellow',
'ERROR': 'bold_red',
'CRITICAL': 'bold_purple'}
formatter = colorlog.ColoredFormatter(cformat, date_format,
log_colors=colors)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
log.addHandler(stream_handler)
return log
def print_progress(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'):
"""
Call in a loop to create terminal progress bar
:param iteration: Required : current iteration (Int)
:param total: Required : total iterations (Int)
:param prefix: Optional : prefix string (Str)
:param suffix: Optional: suffix string (Str)
:param decimals: Optional: positive number of decimals in percent complete (Int)
:param length: Optional: character length of bar (Int)
:param fill: Optional: bar fill character (Str)
:return: None
"""
iteration += 1
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end='\r')
# Print New Line on Complete
if iteration == total:
print()
| [
"logging.FileHandler",
"numpy.dtype",
"numpy.zeros",
"logging.StreamHandler",
"json.dumps",
"ibllib.misc.version.ibllib",
"logging.Formatter",
"pathlib.Path",
"traceback.format_exc",
"colorlog.ColoredFormatter",
"logging.getLogger"
] | [((161, 188), 'logging.getLogger', 'logging.getLogger', (['"""ibllib"""'], {}), "('ibllib')\n", (178, 188), False, 'import logging\n'), ((1876, 1905), 'logging.FileHandler', 'logging.FileHandler', (['log_file'], {}), '(log_file)\n', (1895, 1905), False, 'import logging\n'), ((2788, 2834), 'numpy.dtype', 'np.dtype', (["{'names': names, 'formats': formats}"], {}), "({'names': names, 'formats': formats})\n", (2796, 2834), True, 'import numpy as np\n'), ((2846, 2873), 'numpy.zeros', 'np.zeros', (['shape'], {'dtype': 'dtyp'}), '(shape, dtype=dtyp)\n', (2854, 2873), True, 'import numpy as np\n'), ((3514, 3580), 'colorlog.ColoredFormatter', 'colorlog.ColoredFormatter', (['cformat', 'date_format'], {'log_colors': 'colors'}), '(cformat, date_format, log_colors=colors)\n', (3539, 3580), False, 'import colorlog\n'), ((3644, 3667), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (3665, 3667), False, 'import logging\n'), ((222, 251), 'json.dumps', 'json.dumps', (['my_dict'], {'indent': '(4)'}), '(my_dict, indent=4)\n', (232, 251), False, 'import json\n'), ((2021, 2050), 'logging.Formatter', 'logging.Formatter', (['str_format'], {}), '(str_format)\n', (2038, 2050), False, 'import logging\n'), ((3030, 3049), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (3047, 3049), False, 'import logging\n'), ((3089, 3112), 'logging.getLogger', 'logging.getLogger', (['name'], {}), '(name)\n', (3106, 3112), False, 'import logging\n'), ((1728, 1746), 'pathlib.Path', 'Path', (['session_path'], {}), '(session_path)\n', (1732, 1746), False, 'from pathlib import Path\n'), ((2427, 2449), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (2447, 2449), False, 'import traceback\n'), ((2467, 2484), 'pathlib.Path', 'Path', (['sessionpath'], {}), '(sessionpath)\n', (2471, 2484), False, 'from pathlib import Path\n'), ((1802, 1818), 'ibllib.misc.version.ibllib', 'version.ibllib', ([], {}), '()\n', (1816, 1818), False, 'from ibllib.misc import version\n'), ((2541, 2557), 'ibllib.misc.version.ibllib', 'version.ibllib', ([], {}), '()\n', (2555, 2557), False, 'from ibllib.misc import version\n')] |
import os.path as osp
import glob
from datetime import datetime
from os import mkdir
from os import path
from sys import exit
import cv2
import numpy as np
import torch
from model.unet.model import UNet
from utils.image import show_images_side2side
import matplotlib.image as mpimg
def save_predictions_as_imgs(model, device, epoch, datetime_dir, image_folder='data/inputs/Set5/*', plot_images=True):
idx = 0
save_dir = f'data/saved/models/superresolution/{datetime_dir}'
if not path.exists(save_dir):
mkdir(save_dir)
model.eval()
for image_path in glob.glob(image_folder):
idx += 1
base = osp.splitext(osp.basename(image_path))[0]
# read images
img = cv2.imread(image_path, cv2.IMREAD_COLOR)
test_file_path = f'{save_dir}/checkpoint-epoch{epoch}_test_{base}.png'
cv2.imwrite(test_file_path, img)
img_norm = img * 1.0 / 255
img_norm = torch.from_numpy(np.transpose(img_norm[:, :, [2, 1, 0]], (2, 0, 1))).float()
img_LR = img_norm.unsqueeze(0)
img_LR = img_LR.to(device)
with torch.no_grad():
output = model(img_LR).data.squeeze().float().cpu().clamp_(0, 1).numpy()
output = np.transpose(output[[2, 1, 0], :, :], (1, 2, 0))
output = (output * 255.0).round()
test_output_path = f'{save_dir}/checkpoint-epoch{epoch}_output_{base}.png'
cv2.imwrite(test_output_path, output)
print(f'Saving {idx}.) filename={base}, test_image={test_file_path}, output_image={test_output_path}')
if plot_images:
img1 = mpimg.imread(test_file_path)
img2 = mpimg.imread(test_output_path)
show_images_side2side(img1, img2)
if __name__ == '__main__':
use_best_model = True
model_date_dir = '0625_153809'
dev = 'cuda' if torch.cuda.is_available() else 'cpu'
default_model = UNet().to(dev)
if use_best_model:
model_path = f'data/saved/models/superresolution/{model_date_dir}/model_best.pth'
print('Model path {:s}. \nTesting...'.format(model_path))
saved_model = torch.load(model_path)
default_model.load_state_dict(saved_model['state_dict'])
save_predictions_as_imgs(default_model, dev, 'best', model_date_dir)
else:
model_paths = glob.glob(f'data/saved/models/superresolution/{model_date_dir}/*')
checkpoints = list(filter(lambda path: 'checkpoint' in path, model_paths))
checkpoints.sort()
for model_path in checkpoints:
filename_idx = osp.splitext(osp.basename(model_path))[0][-3:]
saved_model = torch.load(model_path)
default_model.load_state_dict(saved_model['state_dict'])
save_predictions_as_imgs(default_model, dev, filename_idx, model_date_dir)
| [
"os.mkdir",
"matplotlib.image.imread",
"utils.image.show_images_side2side",
"os.path.basename",
"cv2.imwrite",
"torch.load",
"os.path.exists",
"numpy.transpose",
"cv2.imread",
"torch.cuda.is_available",
"glob.glob",
"model.unet.model.UNet",
"torch.no_grad"
] | [((581, 604), 'glob.glob', 'glob.glob', (['image_folder'], {}), '(image_folder)\n', (590, 604), False, 'import glob\n'), ((494, 515), 'os.path.exists', 'path.exists', (['save_dir'], {}), '(save_dir)\n', (505, 515), False, 'from os import path\n'), ((525, 540), 'os.mkdir', 'mkdir', (['save_dir'], {}), '(save_dir)\n', (530, 540), False, 'from os import mkdir\n'), ((716, 756), 'cv2.imread', 'cv2.imread', (['image_path', 'cv2.IMREAD_COLOR'], {}), '(image_path, cv2.IMREAD_COLOR)\n', (726, 756), False, 'import cv2\n'), ((844, 876), 'cv2.imwrite', 'cv2.imwrite', (['test_file_path', 'img'], {}), '(test_file_path, img)\n', (855, 876), False, 'import cv2\n'), ((1215, 1263), 'numpy.transpose', 'np.transpose', (['output[[2, 1, 0], :, :]', '(1, 2, 0)'], {}), '(output[[2, 1, 0], :, :], (1, 2, 0))\n', (1227, 1263), True, 'import numpy as np\n'), ((1397, 1434), 'cv2.imwrite', 'cv2.imwrite', (['test_output_path', 'output'], {}), '(test_output_path, output)\n', (1408, 1434), False, 'import cv2\n'), ((1825, 1850), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1848, 1850), False, 'import torch\n'), ((2099, 2121), 'torch.load', 'torch.load', (['model_path'], {}), '(model_path)\n', (2109, 2121), False, 'import torch\n'), ((2296, 2362), 'glob.glob', 'glob.glob', (['f"""data/saved/models/superresolution/{model_date_dir}/*"""'], {}), "(f'data/saved/models/superresolution/{model_date_dir}/*')\n", (2305, 2362), False, 'import glob\n'), ((1096, 1111), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1109, 1111), False, 'import torch\n'), ((1590, 1618), 'matplotlib.image.imread', 'mpimg.imread', (['test_file_path'], {}), '(test_file_path)\n', (1602, 1618), True, 'import matplotlib.image as mpimg\n'), ((1638, 1668), 'matplotlib.image.imread', 'mpimg.imread', (['test_output_path'], {}), '(test_output_path)\n', (1650, 1668), True, 'import matplotlib.image as mpimg\n'), ((1681, 1714), 'utils.image.show_images_side2side', 'show_images_side2side', (['img1', 'img2'], {}), '(img1, img2)\n', (1702, 1714), False, 'from utils.image import show_images_side2side\n'), ((1882, 1888), 'model.unet.model.UNet', 'UNet', ([], {}), '()\n', (1886, 1888), False, 'from model.unet.model import UNet\n'), ((2612, 2634), 'torch.load', 'torch.load', (['model_path'], {}), '(model_path)\n', (2622, 2634), False, 'import torch\n'), ((651, 675), 'os.path.basename', 'osp.basename', (['image_path'], {}), '(image_path)\n', (663, 675), True, 'import os.path as osp\n'), ((948, 998), 'numpy.transpose', 'np.transpose', (['img_norm[:, :, [2, 1, 0]]', '(2, 0, 1)'], {}), '(img_norm[:, :, [2, 1, 0]], (2, 0, 1))\n', (960, 998), True, 'import numpy as np\n'), ((2552, 2576), 'os.path.basename', 'osp.basename', (['model_path'], {}), '(model_path)\n', (2564, 2576), True, 'import os.path as osp\n')] |
#####################################################################
# Sampling from a Biased Population #
# In this tutorial we will go over some code that recreates the #
# visualizations in the Interactive Sampling Distribution Demo. #
# This demo looks at a hypothetical problem that illustrates what #
# happens when we sample from a biased population and not the entire#
# population we are interested in. This tutorial assumes that you #
# have seen that demo, for context, and understand the statistics #
# behind the graphs. #
#####################################################################
# Import the packages that we will be using for the tutorial
import numpy as np # for sampling for the distributions
import matplotlib.pyplot as plt # for basic plotting
import seaborn as sns; sns.set() # for plotting of the histograms
# Recreate the simulations from the video
mean_uofm = 155
sd_uofm = 5
mean_gym = 185
sd_gym = 5
gymperc = .3
totalPopSize = 40000
# Create the two subgroups
uofm_students = np.random.normal(mean_uofm, sd_uofm, int(totalPopSize * (1 - gymperc)))
students_at_gym = np.random.normal(mean_gym, sd_gym, int(totalPopSize * (gymperc)))
# Create the population from the subgroups
population = np.append(uofm_students, students_at_gym)
# Set up the figure for plotting
plt.figure(figsize=(10,12))
# Plot the UofM students only
plt.subplot(3,1,1)
sns.histplot(uofm_students, kde=True)
plt.title("UofM Students Only")
plt.xlim([140,200])
# Plot the Gym Goers only
plt.subplot(3,1,2)
sns.histplot(students_at_gym,kde=True)
plt.title("Gym Goers Only")
plt.xlim([140,200])
# Plot both groups together
plt.subplot(3,1,3)
sns.histplot(population,kde=True)
plt.title("Full Population of UofM Students")
plt.axvline(x = np.mean(population))
plt.xlim([140,200])
#########################################################
# What Happens if We Sample from the Entire Population? #
# We will sample randomly from all students at the #
# University of Michigan. #
#########################################################
# Simulation parameters
numberSamps = 5000
sampSize = 50
# Get the sampling distribution of the mean from only the gym
mean_distribution = np.empty(numberSamps)
for i in np.arange(numberSamps):
random_students = np.random.choice(population, sampSize)
mean_distribution[i] = np.mean(random_students)
# Plot the population and the biased sampling distribution
plt.figure(figsize=(10, 8))
# Plotting the population again
plt.subplot(2, 1, 1)
sns.histplot(population,kde=True)
plt.title("Full Population of UofM Students")
plt.axvline(x=np.mean(population))
plt.xlim([140, 200])
# Plotting the sampling distribution
plt.subplot(2, 1, 2)
sns.histplot(mean_distribution,kde=True)
plt.title("Sampling Distribution of the Mean Weight of All UofM Students")
plt.axvline(x=np.mean(population))
plt.axvline(x=np.mean(mean_distribution), color="black")
plt.xlim([140, 200])
##########################################################
# What Happens if We take a Non-Representative Sample? #
# What happens if I only go to the gym to get the weight #
# of individuals, and I don't sample randomly from all #
# students at the University of Michigan? #
##########################################################
# Simulation parameters
numberSamps = 5000
sampSize = 3
# Get the sampling distribution of the mean from only the gym
mean_distribution = np.empty(numberSamps)
for i in np.arange(numberSamps):
random_students = np.random.choice(students_at_gym, sampSize)
mean_distribution[i] = np.mean(random_students)
# Plot the population and the biased sampling distribution
plt.figure(figsize=(10, 8))
# Plotting the population again
plt.subplot(2, 1, 1)
sns.histplot(population,kde=True)
plt.title("Full Population of UofM Students")
plt.axvline(x=np.mean(population))
plt.xlim([140, 200])
# Plotting the sampling distribution
plt.subplot(2, 1, 2)
sns.histplot(mean_distribution,kde=True)
plt.title("Sampling Distribution of the Mean Weight of Gym Goers")
plt.axvline(x=np.mean(population))
plt.axvline(x=np.mean(students_at_gym), color="black")
plt.xlim([140, 200])
plt.show()
np.random.seed() | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.xlim",
"seaborn.histplot",
"matplotlib.pyplot.show",
"numpy.random.seed",
"numpy.empty",
"numpy.append",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.arange",
"numpy.random.choice",
"seaborn.set"
] | [((894, 903), 'seaborn.set', 'sns.set', ([], {}), '()\n', (901, 903), True, 'import seaborn as sns\n'), ((1325, 1366), 'numpy.append', 'np.append', (['uofm_students', 'students_at_gym'], {}), '(uofm_students, students_at_gym)\n', (1334, 1366), True, 'import numpy as np\n'), ((1401, 1429), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 12)'}), '(figsize=(10, 12))\n', (1411, 1429), True, 'import matplotlib.pyplot as plt\n'), ((1460, 1480), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(1)', '(1)'], {}), '(3, 1, 1)\n', (1471, 1480), True, 'import matplotlib.pyplot as plt\n'), ((1479, 1516), 'seaborn.histplot', 'sns.histplot', (['uofm_students'], {'kde': '(True)'}), '(uofm_students, kde=True)\n', (1491, 1516), True, 'import seaborn as sns\n'), ((1517, 1548), 'matplotlib.pyplot.title', 'plt.title', (['"""UofM Students Only"""'], {}), "('UofM Students Only')\n", (1526, 1548), True, 'import matplotlib.pyplot as plt\n'), ((1549, 1569), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[140, 200]'], {}), '([140, 200])\n', (1557, 1569), True, 'import matplotlib.pyplot as plt\n'), ((1596, 1616), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(1)', '(2)'], {}), '(3, 1, 2)\n', (1607, 1616), True, 'import matplotlib.pyplot as plt\n'), ((1615, 1654), 'seaborn.histplot', 'sns.histplot', (['students_at_gym'], {'kde': '(True)'}), '(students_at_gym, kde=True)\n', (1627, 1654), True, 'import seaborn as sns\n'), ((1654, 1681), 'matplotlib.pyplot.title', 'plt.title', (['"""Gym Goers Only"""'], {}), "('Gym Goers Only')\n", (1663, 1681), True, 'import matplotlib.pyplot as plt\n'), ((1682, 1702), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[140, 200]'], {}), '([140, 200])\n', (1690, 1702), True, 'import matplotlib.pyplot as plt\n'), ((1731, 1751), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(1)', '(3)'], {}), '(3, 1, 3)\n', (1742, 1751), True, 'import matplotlib.pyplot as plt\n'), ((1750, 1784), 'seaborn.histplot', 'sns.histplot', (['population'], {'kde': '(True)'}), '(population, kde=True)\n', (1762, 1784), True, 'import seaborn as sns\n'), ((1784, 1829), 'matplotlib.pyplot.title', 'plt.title', (['"""Full Population of UofM Students"""'], {}), "('Full Population of UofM Students')\n", (1793, 1829), True, 'import matplotlib.pyplot as plt\n'), ((1867, 1887), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[140, 200]'], {}), '([140, 200])\n', (1875, 1887), True, 'import matplotlib.pyplot as plt\n'), ((2319, 2340), 'numpy.empty', 'np.empty', (['numberSamps'], {}), '(numberSamps)\n', (2327, 2340), True, 'import numpy as np\n'), ((2350, 2372), 'numpy.arange', 'np.arange', (['numberSamps'], {}), '(numberSamps)\n', (2359, 2372), True, 'import numpy as np\n'), ((2547, 2574), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 8)'}), '(figsize=(10, 8))\n', (2557, 2574), True, 'import matplotlib.pyplot as plt\n'), ((2608, 2628), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(1)'], {}), '(2, 1, 1)\n', (2619, 2628), True, 'import matplotlib.pyplot as plt\n'), ((2629, 2663), 'seaborn.histplot', 'sns.histplot', (['population'], {'kde': '(True)'}), '(population, kde=True)\n', (2641, 2663), True, 'import seaborn as sns\n'), ((2663, 2708), 'matplotlib.pyplot.title', 'plt.title', (['"""Full Population of UofM Students"""'], {}), "('Full Population of UofM Students')\n", (2672, 2708), True, 'import matplotlib.pyplot as plt\n'), ((2744, 2764), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[140, 200]'], {}), '([140, 200])\n', (2752, 2764), True, 'import matplotlib.pyplot as plt\n'), ((2803, 2823), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(2)'], {}), '(2, 1, 2)\n', (2814, 2823), True, 'import matplotlib.pyplot as plt\n'), ((2824, 2865), 'seaborn.histplot', 'sns.histplot', (['mean_distribution'], {'kde': '(True)'}), '(mean_distribution, kde=True)\n', (2836, 2865), True, 'import seaborn as sns\n'), ((2865, 2939), 'matplotlib.pyplot.title', 'plt.title', (['"""Sampling Distribution of the Mean Weight of All UofM Students"""'], {}), "('Sampling Distribution of the Mean Weight of All UofM Students')\n", (2874, 2939), True, 'import matplotlib.pyplot as plt\n'), ((3032, 3052), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[140, 200]'], {}), '([140, 200])\n', (3040, 3052), True, 'import matplotlib.pyplot as plt\n'), ((3549, 3570), 'numpy.empty', 'np.empty', (['numberSamps'], {}), '(numberSamps)\n', (3557, 3570), True, 'import numpy as np\n'), ((3580, 3602), 'numpy.arange', 'np.arange', (['numberSamps'], {}), '(numberSamps)\n', (3589, 3602), True, 'import numpy as np\n'), ((3782, 3809), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 8)'}), '(figsize=(10, 8))\n', (3792, 3809), True, 'import matplotlib.pyplot as plt\n'), ((3843, 3863), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(1)'], {}), '(2, 1, 1)\n', (3854, 3863), True, 'import matplotlib.pyplot as plt\n'), ((3864, 3898), 'seaborn.histplot', 'sns.histplot', (['population'], {'kde': '(True)'}), '(population, kde=True)\n', (3876, 3898), True, 'import seaborn as sns\n'), ((3898, 3943), 'matplotlib.pyplot.title', 'plt.title', (['"""Full Population of UofM Students"""'], {}), "('Full Population of UofM Students')\n", (3907, 3943), True, 'import matplotlib.pyplot as plt\n'), ((3979, 3999), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[140, 200]'], {}), '([140, 200])\n', (3987, 3999), True, 'import matplotlib.pyplot as plt\n'), ((4038, 4058), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(2)'], {}), '(2, 1, 2)\n', (4049, 4058), True, 'import matplotlib.pyplot as plt\n'), ((4059, 4100), 'seaborn.histplot', 'sns.histplot', (['mean_distribution'], {'kde': '(True)'}), '(mean_distribution, kde=True)\n', (4071, 4100), True, 'import seaborn as sns\n'), ((4100, 4166), 'matplotlib.pyplot.title', 'plt.title', (['"""Sampling Distribution of the Mean Weight of Gym Goers"""'], {}), "('Sampling Distribution of the Mean Weight of Gym Goers')\n", (4109, 4166), True, 'import matplotlib.pyplot as plt\n'), ((4257, 4277), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[140, 200]'], {}), '([140, 200])\n', (4265, 4277), True, 'import matplotlib.pyplot as plt\n'), ((4279, 4289), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4287, 4289), True, 'import matplotlib.pyplot as plt\n'), ((4291, 4307), 'numpy.random.seed', 'np.random.seed', ([], {}), '()\n', (4305, 4307), True, 'import numpy as np\n'), ((2396, 2434), 'numpy.random.choice', 'np.random.choice', (['population', 'sampSize'], {}), '(population, sampSize)\n', (2412, 2434), True, 'import numpy as np\n'), ((2462, 2486), 'numpy.mean', 'np.mean', (['random_students'], {}), '(random_students)\n', (2469, 2486), True, 'import numpy as np\n'), ((3626, 3669), 'numpy.random.choice', 'np.random.choice', (['students_at_gym', 'sampSize'], {}), '(students_at_gym, sampSize)\n', (3642, 3669), True, 'import numpy as np\n'), ((3697, 3721), 'numpy.mean', 'np.mean', (['random_students'], {}), '(random_students)\n', (3704, 3721), True, 'import numpy as np\n'), ((1846, 1865), 'numpy.mean', 'np.mean', (['population'], {}), '(population)\n', (1853, 1865), True, 'import numpy as np\n'), ((2723, 2742), 'numpy.mean', 'np.mean', (['population'], {}), '(population)\n', (2730, 2742), True, 'import numpy as np\n'), ((2954, 2973), 'numpy.mean', 'np.mean', (['population'], {}), '(population)\n', (2961, 2973), True, 'import numpy as np\n'), ((2989, 3015), 'numpy.mean', 'np.mean', (['mean_distribution'], {}), '(mean_distribution)\n', (2996, 3015), True, 'import numpy as np\n'), ((3958, 3977), 'numpy.mean', 'np.mean', (['population'], {}), '(population)\n', (3965, 3977), True, 'import numpy as np\n'), ((4181, 4200), 'numpy.mean', 'np.mean', (['population'], {}), '(population)\n', (4188, 4200), True, 'import numpy as np\n'), ((4216, 4240), 'numpy.mean', 'np.mean', (['students_at_gym'], {}), '(students_at_gym)\n', (4223, 4240), True, 'import numpy as np\n')] |
"""
Common test functions for optimizers.
Also see: https://en.wikipedia.org/wiki/Test_functions_for_optimization
"""
def rosenbrock(x, y):
"""
Rosenbrock function. Minimum: f(1, 1) = 0.
https://en.wikipedia.org/wiki/Rosenbrock_function
"""
return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2
rosenbrock.errordef = 1
def rosenbrock_grad(x, y):
"""Gradient of Rosenbrock function."""
return (-400 * x * (-(x ** 2) + y) + 2 * x - 2, -200 * x ** 2 + 200 * y)
def ackley(x, y):
"""
Ackley function. Minimum: f(0, 0) = 0.
https://en.wikipedia.org/wiki/Ackley_function
"""
from math import sqrt, exp, cos, pi, e
term1 = -20 * exp(-0.2 * sqrt(0.5 * (x ** 2 + y ** 2)))
term2 = -exp(0.5 * (cos(2 * pi * x) + cos(2 * pi * y)))
return term1 + term2 + 20 + e
ackley.errordef = 1
def beale(x, y):
"""
Beale function. Minimum: f(3, 0.5) = 0.
https://en.wikipedia.org/wiki/Test_functions_for_optimization
"""
term1 = 1.5 - x + x * y
term2 = 2.25 - x + x * y ** 2
term3 = 2.625 - x + x * y ** 3
return term1 * term1 + term2 * term2 + term3 * term3
beale.errordef = 1
def matyas(x, y):
"""
Matyas function. Minimum: f(0, 0) = 0.
https://en.wikipedia.org/wiki/Test_functions_for_optimization
"""
return 0.26 * (x ** 2 + y ** 2) - 0.48 * x * y
matyas.errordef = 1
def sphere_np(x):
"""
Sphere function for variable number of arguments. Minimum: f(0, ..., 0) = 0.
https://en.wikipedia.org/wiki/Test_functions_for_optimization
"""
import numpy as np
return np.sum(x ** 2)
sphere_np.errordef = 1
| [
"numpy.sum",
"math.cos",
"math.sqrt"
] | [((1595, 1609), 'numpy.sum', 'np.sum', (['(x ** 2)'], {}), '(x ** 2)\n', (1601, 1609), True, 'import numpy as np\n'), ((689, 718), 'math.sqrt', 'sqrt', (['(0.5 * (x ** 2 + y ** 2))'], {}), '(0.5 * (x ** 2 + y ** 2))\n', (693, 718), False, 'from math import sqrt, exp, cos, pi, e\n'), ((744, 759), 'math.cos', 'cos', (['(2 * pi * x)'], {}), '(2 * pi * x)\n', (747, 759), False, 'from math import sqrt, exp, cos, pi, e\n'), ((762, 777), 'math.cos', 'cos', (['(2 * pi * y)'], {}), '(2 * pi * y)\n', (765, 777), False, 'from math import sqrt, exp, cos, pi, e\n')] |
from collections import defaultdict
import numpy as np
from irec.offline_experiments.metrics.base import Metric
class TopItemsMembership(Metric):
def __init__(self, items_feature_values, top_size, *args, **kwargs):
super().__init__(*args, **kwargs)
self.users_num_items_recommended = defaultdict(int)
self.users_membership_count_cumulated = defaultdict(float)
self.items_feature_values = items_feature_values
self.top_size = top_size
self.top_items = set(np.argsort(items_feature_values)[::-1][: self.top_size])
def compute(self, uid):
return (
self.users_membership_count_cumulated[uid]
/ self.users_num_items_recommended[uid]
)
def update_recommendation(self, uid, item, reward):
self.users_num_items_recommended[uid] += 1
if item in self.top_items:
self.users_membership_count_cumulated[uid] += 1
| [
"collections.defaultdict",
"numpy.argsort"
] | [((306, 322), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (317, 322), False, 'from collections import defaultdict\n'), ((371, 389), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (382, 389), False, 'from collections import defaultdict\n'), ((509, 541), 'numpy.argsort', 'np.argsort', (['items_feature_values'], {}), '(items_feature_values)\n', (519, 541), True, 'import numpy as np\n')] |
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.models import load_model
import numpy as np
import cv2
import os
# Load the face detector model
print("[INFO] Loading faces detector model...")
prototxtPath = os.path.sep.join(["trainer-model/face/deploy.prototxt"])
weightsPath = os.path.sep.join(["trainer-model/face/res10_300x300_ssd_iter_140000.caffemodel"])
net = cv2.dnn.readNet(prototxtPath, weightsPath)
# Load the face mask detector model from disk
print("[INFO] Loading mask detector model...")
model = load_model("trainer-model/mask/mask_detector.model")
# Load image and get spacial dimensions
imageExamplePath = 'examples/1.png'
print("[INFO] Loading image from " + imageExamplePath)
image = cv2.imread(imageExamplePath)
orige = image.copy()
(h, w) = image.shape[:2]
# constructor a blob by image
blob = cv2.dnn.blobFromImage(image, 1.0, (300, 300), (104.0, 177.0, 123.0))
# Pass the blob from network and get the faces detected
print("[INFO] Computing face detector...")
net.setInput(blob)
detecteds = net.forward()
# Text to bounding box
strWithMask = "With Mask"
strWithoutMask = "Without Mask"
# Loop in all faces detected
for i in range(0, detecteds.shape[2]):
# Extract the confidence (probability) associated with the face detected
probability = detecteds[0, 0, i, 2]
# Filters out the low chance of hit detections. They pass only with more than 50% chance of success
if probability > 0.5:
# Calculate the coordinates (x, y) around the detected object
box = detecteds[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
# Checking that the bounding boxes are within the dimensions of the frame
(startX, startY) = (max(0, startX), max(0, startY))
(endX, endY) = (min(w - 1, endX), min(h - 1, endY))
# Extracts the ROI from the face and converts the image from BGR to RGB
face = image[startY:endY, startX:endX]
face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
# Resize to 224x224 and pre process
face = cv2.resize(face, (224, 224))
face = img_to_array(face)
face = preprocess_input(face)
face = np.expand_dims(face, axis=0)
# Pass the detected face in mask detector model
(mask, withoutMask) = model.predict(face)[0]
# Set color and text to paint in bounding box
label = strWithMask if mask < withoutMask else strWithoutMask
color = (0, 255, 0) if label == strWithMask else (0, 0, 255)
# Set the propability in the label
label = "{}: {:.2f}%".format(label, max(mask, withoutMask) * 100)
# show the label and the rectangle in the output image
cv2.putText(image, label, (startX, startY - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)
cv2.rectangle(image, (startX, startY), (endX, endY), color, 2)
# Show final image
print("[INFO] Opening image in new window")
cv2.imshow("Mask detector -> github/hconcessa", image)
cv2.waitKey(0) | [
"tensorflow.keras.models.load_model",
"cv2.putText",
"cv2.waitKey",
"cv2.cvtColor",
"tensorflow.keras.preprocessing.image.img_to_array",
"cv2.dnn.blobFromImage",
"numpy.expand_dims",
"cv2.dnn.readNet",
"cv2.imread",
"tensorflow.keras.applications.mobilenet_v2.preprocess_input",
"numpy.array",
... | [((317, 373), 'os.path.sep.join', 'os.path.sep.join', (["['trainer-model/face/deploy.prototxt']"], {}), "(['trainer-model/face/deploy.prototxt'])\n", (333, 373), False, 'import os\n'), ((388, 474), 'os.path.sep.join', 'os.path.sep.join', (["['trainer-model/face/res10_300x300_ssd_iter_140000.caffemodel']"], {}), "([\n 'trainer-model/face/res10_300x300_ssd_iter_140000.caffemodel'])\n", (404, 474), False, 'import os\n'), ((476, 518), 'cv2.dnn.readNet', 'cv2.dnn.readNet', (['prototxtPath', 'weightsPath'], {}), '(prototxtPath, weightsPath)\n', (491, 518), False, 'import cv2\n'), ((621, 673), 'tensorflow.keras.models.load_model', 'load_model', (['"""trainer-model/mask/mask_detector.model"""'], {}), "('trainer-model/mask/mask_detector.model')\n", (631, 673), False, 'from tensorflow.keras.models import load_model\n'), ((814, 842), 'cv2.imread', 'cv2.imread', (['imageExamplePath'], {}), '(imageExamplePath)\n', (824, 842), False, 'import cv2\n'), ((927, 995), 'cv2.dnn.blobFromImage', 'cv2.dnn.blobFromImage', (['image', '(1.0)', '(300, 300)', '(104.0, 177.0, 123.0)'], {}), '(image, 1.0, (300, 300), (104.0, 177.0, 123.0))\n', (948, 995), False, 'import cv2\n'), ((2880, 2934), 'cv2.imshow', 'cv2.imshow', (['"""Mask detector -> github/hconcessa"""', 'image'], {}), "('Mask detector -> github/hconcessa', image)\n", (2890, 2934), False, 'import cv2\n'), ((2935, 2949), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (2946, 2949), False, 'import cv2\n'), ((2006, 2043), 'cv2.cvtColor', 'cv2.cvtColor', (['face', 'cv2.COLOR_BGR2RGB'], {}), '(face, cv2.COLOR_BGR2RGB)\n', (2018, 2043), False, 'import cv2\n'), ((2097, 2125), 'cv2.resize', 'cv2.resize', (['face', '(224, 224)'], {}), '(face, (224, 224))\n', (2107, 2125), False, 'import cv2\n'), ((2135, 2153), 'tensorflow.keras.preprocessing.image.img_to_array', 'img_to_array', (['face'], {}), '(face)\n', (2147, 2153), False, 'from tensorflow.keras.preprocessing.image import img_to_array\n'), ((2163, 2185), 'tensorflow.keras.applications.mobilenet_v2.preprocess_input', 'preprocess_input', (['face'], {}), '(face)\n', (2179, 2185), False, 'from tensorflow.keras.applications.mobilenet_v2 import preprocess_input\n'), ((2195, 2223), 'numpy.expand_dims', 'np.expand_dims', (['face'], {'axis': '(0)'}), '(face, axis=0)\n', (2209, 2223), True, 'import numpy as np\n'), ((2660, 2755), 'cv2.putText', 'cv2.putText', (['image', 'label', '(startX, startY - 10)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.45)', 'color', '(2)'], {}), '(image, label, (startX, startY - 10), cv2.FONT_HERSHEY_SIMPLEX, \n 0.45, color, 2)\n', (2671, 2755), False, 'import cv2\n'), ((2753, 2815), 'cv2.rectangle', 'cv2.rectangle', (['image', '(startX, startY)', '(endX, endY)', 'color', '(2)'], {}), '(image, (startX, startY), (endX, endY), color, 2)\n', (2766, 2815), False, 'import cv2\n'), ((1624, 1646), 'numpy.array', 'np.array', (['[w, h, w, h]'], {}), '([w, h, w, h])\n', (1632, 1646), True, 'import numpy as np\n')] |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from scipy.stats import binom
from scipy import linalg
from scipy.sparse.linalg import expm_multiply
from scipy.sparse import csc_matrix
import math
import timeit
def hypercube(n_dim):
n = n_dim - 1
sigma_x = np.array([[0, 1],
[1, 0]])
A = sigma_i(sigma_x, 0, n)
for i in range(1, n_dim):
A += sigma_i(sigma_x, i, n)
return -1 * A
def sigma_i(sigma_x, i, n):
if i > 0:
out = np.eye(2)
for j_before in range(i - 1):
out = np.kron(out, np.eye(2))
out = np.kron(out, sigma_x)
else:
out = sigma_x
for j_after in range(n - i):
out = np.kron(out, np.eye(2))
return out
def quantum_walk_hypercube(N, timesteps, normalise=True):
P = 2**N # number of positions
gamma = 1/N # hopping rate
A = hypercube(N)
H = gamma * (A - N * np.eye(2 ** N))
posn0 = np.zeros(P)
posn0[0] = 1
psi0 = posn0
psiN = expm_multiply(-(1j) * timesteps * H, psi0)
prob = np.real(np.conj(psiN) * psiN)
result = np.zeros(N + 1)
normalise_array = np.zeros(N + 1)
for i, probability in enumerate(prob):
binary_i = bin(i)
i_ones = [ones for ones in binary_i[2:] if ones == '1']
num_ones = len(i_ones)
result[num_ones] += probability
if normalise:
normalise_array[num_ones] += 1
if normalise:
result = result/normalise_array
return result
def run_many_walks(N, time_limit):
output = np.zeros((time_limit + 1, N + 1))
for timesteps in range(0, time_limit + 1):
output[timesteps] = quantum_walk_hypercube(N, timesteps)
print(timesteps)
return output
def plot_furthest_qubit_prob(timesteps, data):
plt.figure()
plt.plot(range(timesteps + 1), data[:, -1])
plt.xlim(0, timesteps)
plt.xticks(range(0, timesteps + 1, 5))
plt.ylim(0, 1)
plt.yticks([0, 0.2, 0.4, 0.6, 0.8, 1])
plt.show()
def plot_prob_heatmap(data, N, timesteps):
plt.rc('text', usetex=True)
plt.rc('font', size=14)
fig, ax = plt.subplots()
im = ax.imshow(data.T, interpolation="gaussian", cmap=plt.get_cmap('plasma'))
ax.set_ylabel("Hamming distance, $d$")
ax.set_xlabel("Time, $t$", rotation=0, labelpad=18)
plt.yticks(range(0, N + 1, 3))
plt.xticks(range(0, timesteps + 1, 5))
ax.invert_yaxis()
cb = fig.colorbar(cm.ScalarMappable(cmap=plt.get_cmap('plasma')))
cb.set_label('Normalised probability, $P(d, t)$')
plt.show()
def color_plot(data, x_start=0.0, y_start=0.0, x_step=1.0, y_step=1.0):
plt.rc('text', usetex=True)
plt.rc('font', size=14)
x_end = x_start+(len(data[0,:])-1)*x_step
y_end = y_start+(len(data[:,0])-1)*y_step
x = np.arange(x_start-x_step/2, x_end+x_step/2, x_step)
y = np.arange(y_start-y_step/2, y_end+y_step/2, y_step)
fig, ax = plt.subplots()
im = ax.pcolormesh(x, y, data, cmap=plt.get_cmap('plasma'), shading='gouraud')
#im = ax.pcolormesh(x, y, data, cmap=plt.get_cmap('plasma'), shading='gouraud')
ax.set_xlabel("Hamming distance, $d$")
ax.set_ylabel("Time, $t$")
plt.xticks(range(0, N + 1, 2))
plt.yticks(range(0, timesteps + 1, 5))
cb = fig.colorbar(cm.ScalarMappable(cmap=plt.get_cmap('plasma')))
cb.set_label('Normalised probability, $P(d, t)$')
plt.show()
if __name__ == '__main__':
time_start = timeit.timeit()
N = 9 # number of dimensions of hypercube
timesteps = 41
data = run_many_walks(N, timesteps) # 2D array of [timesteps_run, probability_at_distance_of_index]
time_end = timeit.timeit()
print("runtime:", time_end - time_start)
#plot_furthest_qubit_prob(timesteps, data)
#plot_prob_heatmap(data, N, timesteps)
color_plot(data)
| [
"matplotlib.pyplot.xlim",
"numpy.conj",
"matplotlib.pyplot.show",
"matplotlib.pyplot.get_cmap",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.yticks",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.array",
"matplotlib.pyplot.rc",
"numpy.arange",
"timeit.timeit",
"numpy.kron",
"numpy.eye"... | [((297, 323), 'numpy.array', 'np.array', (['[[0, 1], [1, 0]]'], {}), '([[0, 1], [1, 0]])\n', (305, 323), True, 'import numpy as np\n'), ((970, 981), 'numpy.zeros', 'np.zeros', (['P'], {}), '(P)\n', (978, 981), True, 'import numpy as np\n'), ((1028, 1070), 'scipy.sparse.linalg.expm_multiply', 'expm_multiply', (['(-1.0j * timesteps * H)', 'psi0'], {}), '(-1.0j * timesteps * H, psi0)\n', (1041, 1070), False, 'from scipy.sparse.linalg import expm_multiply\n'), ((1127, 1142), 'numpy.zeros', 'np.zeros', (['(N + 1)'], {}), '(N + 1)\n', (1135, 1142), True, 'import numpy as np\n'), ((1165, 1180), 'numpy.zeros', 'np.zeros', (['(N + 1)'], {}), '(N + 1)\n', (1173, 1180), True, 'import numpy as np\n'), ((1579, 1612), 'numpy.zeros', 'np.zeros', (['(time_limit + 1, N + 1)'], {}), '((time_limit + 1, N + 1))\n', (1587, 1612), True, 'import numpy as np\n'), ((1821, 1833), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1831, 1833), True, 'import matplotlib.pyplot as plt\n'), ((1886, 1908), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', 'timesteps'], {}), '(0, timesteps)\n', (1894, 1908), True, 'import matplotlib.pyplot as plt\n'), ((1956, 1970), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(1)'], {}), '(0, 1)\n', (1964, 1970), True, 'import matplotlib.pyplot as plt\n'), ((1975, 2013), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[0, 0.2, 0.4, 0.6, 0.8, 1]'], {}), '([0, 0.2, 0.4, 0.6, 0.8, 1])\n', (1985, 2013), True, 'import matplotlib.pyplot as plt\n'), ((2018, 2028), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2026, 2028), True, 'import matplotlib.pyplot as plt\n'), ((2078, 2105), 'matplotlib.pyplot.rc', 'plt.rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (2084, 2105), True, 'import matplotlib.pyplot as plt\n'), ((2110, 2133), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'size': '(14)'}), "('font', size=14)\n", (2116, 2133), True, 'import matplotlib.pyplot as plt\n'), ((2149, 2163), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (2161, 2163), True, 'import matplotlib.pyplot as plt\n'), ((2575, 2585), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2583, 2585), True, 'import matplotlib.pyplot as plt\n'), ((2664, 2691), 'matplotlib.pyplot.rc', 'plt.rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (2670, 2691), True, 'import matplotlib.pyplot as plt\n'), ((2696, 2719), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'size': '(14)'}), "('font', size=14)\n", (2702, 2719), True, 'import matplotlib.pyplot as plt\n'), ((2821, 2880), 'numpy.arange', 'np.arange', (['(x_start - x_step / 2)', '(x_end + x_step / 2)', 'x_step'], {}), '(x_start - x_step / 2, x_end + x_step / 2, x_step)\n', (2830, 2880), True, 'import numpy as np\n'), ((2881, 2940), 'numpy.arange', 'np.arange', (['(y_start - y_step / 2)', '(y_end + y_step / 2)', 'y_step'], {}), '(y_start - y_step / 2, y_end + y_step / 2, y_step)\n', (2890, 2940), True, 'import numpy as np\n'), ((2947, 2961), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (2959, 2961), True, 'import matplotlib.pyplot as plt\n'), ((3411, 3421), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3419, 3421), True, 'import matplotlib.pyplot as plt\n'), ((3468, 3483), 'timeit.timeit', 'timeit.timeit', ([], {}), '()\n', (3481, 3483), False, 'import timeit\n'), ((3673, 3688), 'timeit.timeit', 'timeit.timeit', ([], {}), '()\n', (3686, 3688), False, 'import timeit\n'), ((522, 531), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (528, 531), True, 'import numpy as np\n'), ((626, 647), 'numpy.kron', 'np.kron', (['out', 'sigma_x'], {}), '(out, sigma_x)\n', (633, 647), True, 'import numpy as np\n'), ((740, 749), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (746, 749), True, 'import numpy as np\n'), ((1091, 1104), 'numpy.conj', 'np.conj', (['psiN'], {}), '(psiN)\n', (1098, 1104), True, 'import numpy as np\n'), ((2222, 2244), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""plasma"""'], {}), "('plasma')\n", (2234, 2244), True, 'import matplotlib.pyplot as plt\n'), ((3002, 3024), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""plasma"""'], {}), "('plasma')\n", (3014, 3024), True, 'import matplotlib.pyplot as plt\n'), ((601, 610), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (607, 610), True, 'import numpy as np\n'), ((941, 955), 'numpy.eye', 'np.eye', (['(2 ** N)'], {}), '(2 ** N)\n', (947, 955), True, 'import numpy as np\n'), ((2491, 2513), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""plasma"""'], {}), "('plasma')\n", (2503, 2513), True, 'import matplotlib.pyplot as plt\n'), ((3327, 3349), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""plasma"""'], {}), "('plasma')\n", (3339, 3349), True, 'import matplotlib.pyplot as plt\n')] |
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import coords
from go import Position, PlayerMove, LibertyTracker, WHITE, BLACK
import go
import sgf_wrapper
from tests import test_utils
EMPTY_ROW = '.' * go.N + '\n'
TEST_BOARD = test_utils.load_board('''
.X.....OO
X........
''' + EMPTY_ROW * 7)
NO_HANDICAP_SGF = "(;CA[UTF-8]SZ[9]PB[Murakawa Daisuke]PW[Iyama Yuta]KM[6.5]HA[0]RE[W+1.5]GM[1];B[fd];W[cf];B[eg];W[dd];B[dc];W[cc];B[de];W[cd];B[ed];W[he];B[ce];W[be];B[df];W[bf];B[hd];W[ge];B[gd];W[gg];B[db];W[cb];B[cg];W[bg];B[gh];W[fh];B[hh];W[fg];B[eh];W[ei];B[di];W[fi];B[hg];W[dh];B[ch];W[ci];B[bh];W[ff];B[fe];W[hf];B[id];W[bi];B[ah];W[ef];B[dg];W[ee];B[di];W[ig];B[ai];W[ih];B[fb];W[hi];B[ag];W[ab];B[bd];W[bc];B[ae];W[ad];B[af];W[bd];B[ca];W[ba];B[da];W[ie])"
def coords_from_gtp_set(string):
return frozenset(map(coords.from_gtp, string.split()))
class TestBasicFunctions(test_utils.MinigoUnitTest):
def test_load_board(self):
self.assertEqualNPArray(go.EMPTY_BOARD, np.zeros([go.N, go.N]))
self.assertEqualNPArray(
go.EMPTY_BOARD, test_utils.load_board('. \n' * go.N ** 2))
def test_neighbors(self):
corner = coords.from_gtp('A1')
neighbors = [go.EMPTY_BOARD[c] for c in go.NEIGHBORS[corner]]
self.assertEqual(len(neighbors), 2)
side = coords.from_gtp('A2')
side_neighbors = [go.EMPTY_BOARD[c] for c in go.NEIGHBORS[side]]
self.assertEqual(len(side_neighbors), 3)
def test_is_koish(self):
self.assertEqual(go.is_koish(
TEST_BOARD, coords.from_gtp('A9')), BLACK)
self.assertEqual(go.is_koish(TEST_BOARD, coords.from_gtp('B8')), None)
self.assertEqual(go.is_koish(TEST_BOARD, coords.from_gtp('B9')), None)
self.assertEqual(go.is_koish(TEST_BOARD, coords.from_gtp('E5')), None)
def test_is_eyeish(self):
board = test_utils.load_board('''
.XX...XXX
X.X...X.X
XX.....X.
........X
XXXX.....
OOOX....O
X.OXX.OO.
.XO.X.O.O
XXO.X.OO.
''')
B_eyes = coords_from_gtp_set('A2 A9 B8 J7 H8')
W_eyes = coords_from_gtp_set('H2 J1 J3')
not_eyes = coords_from_gtp_set('B3 E5')
for be in B_eyes:
self.assertEqual(go.is_eyeish(board, be), BLACK, str(be))
for we in W_eyes:
self.assertEqual(go.is_eyeish(board, we), WHITE, str(we))
for ne in not_eyes:
self.assertEqual(go.is_eyeish(board, ne), None, str(ne))
class TestLibertyTracker(test_utils.MinigoUnitTest):
def test_lib_tracker_init(self):
board = test_utils.load_board('X........' + EMPTY_ROW * 8)
lib_tracker = LibertyTracker.from_board(board)
self.assertEqual(len(lib_tracker.groups), 1)
self.assertNotEqual(
lib_tracker.group_index[coords.from_gtp('A9')], go.MISSING_GROUP_ID)
self.assertEqual(lib_tracker.liberty_cache[coords.from_gtp('A9')], 2)
sole_group = lib_tracker.groups[lib_tracker.group_index[coords.from_gtp(
'A9')]]
self.assertEqual(sole_group.stones, coords_from_gtp_set('A9'))
self.assertEqual(sole_group.liberties, coords_from_gtp_set('B9 A8'))
self.assertEqual(sole_group.color, BLACK)
def test_place_stone(self):
board = test_utils.load_board('X........' + EMPTY_ROW * 8)
lib_tracker = LibertyTracker.from_board(board)
lib_tracker.add_stone(BLACK, coords.from_gtp('B9'))
self.assertEqual(len(lib_tracker.groups), 1)
self.assertNotEqual(
lib_tracker.group_index[coords.from_gtp('A9')], go.MISSING_GROUP_ID)
self.assertEqual(lib_tracker.liberty_cache[coords.from_gtp('A9')], 3)
self.assertEqual(lib_tracker.liberty_cache[coords.from_gtp('B9')], 3)
sole_group = lib_tracker.groups[lib_tracker.group_index[coords.from_gtp(
'A9')]]
self.assertEqual(sole_group.stones, coords_from_gtp_set('A9 B9'))
self.assertEqual(sole_group.liberties,
coords_from_gtp_set('C9 A8 B8'))
self.assertEqual(sole_group.color, BLACK)
def test_place_stone_opposite_color(self):
board = test_utils.load_board('X........' + EMPTY_ROW * 8)
lib_tracker = LibertyTracker.from_board(board)
lib_tracker.add_stone(WHITE, coords.from_gtp('B9'))
self.assertEqual(len(lib_tracker.groups), 2)
self.assertNotEqual(
lib_tracker.group_index[coords.from_gtp('A9')], go.MISSING_GROUP_ID)
self.assertNotEqual(
lib_tracker.group_index[coords.from_gtp('B9')], go.MISSING_GROUP_ID)
self.assertEqual(lib_tracker.liberty_cache[coords.from_gtp('A9')], 1)
self.assertEqual(lib_tracker.liberty_cache[coords.from_gtp('B9')], 2)
black_group = lib_tracker.groups[lib_tracker.group_index[coords.from_gtp(
'A9')]]
white_group = lib_tracker.groups[lib_tracker.group_index[coords.from_gtp(
'B9')]]
self.assertEqual(black_group.stones, coords_from_gtp_set('A9'))
self.assertEqual(black_group.liberties, coords_from_gtp_set('A8'))
self.assertEqual(black_group.color, BLACK)
self.assertEqual(white_group.stones, coords_from_gtp_set('B9'))
self.assertEqual(white_group.liberties, coords_from_gtp_set('C9 B8'))
self.assertEqual(white_group.color, WHITE)
def test_merge_multiple_groups(self):
board = test_utils.load_board('''
.X.......
X.X......
.X.......
''' + EMPTY_ROW * 6)
lib_tracker = LibertyTracker.from_board(board)
lib_tracker.add_stone(BLACK, coords.from_gtp('B8'))
self.assertEqual(len(lib_tracker.groups), 1)
self.assertNotEqual(
lib_tracker.group_index[coords.from_gtp('B8')], go.MISSING_GROUP_ID)
sole_group = lib_tracker.groups[lib_tracker.group_index[coords.from_gtp(
'B8')]]
self.assertEqual(sole_group.stones,
coords_from_gtp_set('B9 A8 B8 C8 B7'))
self.assertEqual(sole_group.liberties,
coords_from_gtp_set('A9 C9 D8 A7 C7 B6'))
self.assertEqual(sole_group.color, BLACK)
liberty_cache = lib_tracker.liberty_cache
for stone in sole_group.stones:
self.assertEqual(liberty_cache[stone], 6, str(stone))
def test_capture_stone(self):
board = test_utils.load_board('''
.X.......
XO.......
.X.......
''' + EMPTY_ROW * 6)
lib_tracker = LibertyTracker.from_board(board)
captured = lib_tracker.add_stone(BLACK, coords.from_gtp('C8'))
self.assertEqual(len(lib_tracker.groups), 4)
self.assertEqual(
lib_tracker.group_index[coords.from_gtp('B8')], go.MISSING_GROUP_ID)
self.assertEqual(captured, coords_from_gtp_set('B8'))
def test_capture_many(self):
board = test_utils.load_board('''
.XX......
XOO......
.XX......
''' + EMPTY_ROW * 6)
lib_tracker = LibertyTracker.from_board(board)
captured = lib_tracker.add_stone(BLACK, coords.from_gtp('D8'))
self.assertEqual(len(lib_tracker.groups), 4)
self.assertEqual(
lib_tracker.group_index[coords.from_gtp('B8')], go.MISSING_GROUP_ID)
self.assertEqual(captured, coords_from_gtp_set('B8 C8'))
left_group = lib_tracker.groups[lib_tracker.group_index[coords.from_gtp(
'A8')]]
self.assertEqual(left_group.stones, coords_from_gtp_set('A8'))
self.assertEqual(left_group.liberties,
coords_from_gtp_set('A9 B8 A7'))
right_group = lib_tracker.groups[lib_tracker.group_index[coords.from_gtp(
'D8')]]
self.assertEqual(right_group.stones, coords_from_gtp_set('D8'))
self.assertEqual(right_group.liberties,
coords_from_gtp_set('D9 C8 E8 D7'))
top_group = lib_tracker.groups[lib_tracker.group_index[coords.from_gtp(
'B9')]]
self.assertEqual(top_group.stones, coords_from_gtp_set('B9 C9'))
self.assertEqual(top_group.liberties,
coords_from_gtp_set('A9 D9 B8 C8'))
bottom_group = lib_tracker.groups[lib_tracker.group_index[coords.from_gtp(
'B7')]]
self.assertEqual(bottom_group.stones, coords_from_gtp_set('B7 C7'))
self.assertEqual(bottom_group.liberties,
coords_from_gtp_set('B8 C8 A7 D7 B6 C6'))
liberty_cache = lib_tracker.liberty_cache
for stone in top_group.stones:
self.assertEqual(liberty_cache[stone], 4, str(stone))
for stone in left_group.stones:
self.assertEqual(liberty_cache[stone], 3, str(stone))
for stone in right_group.stones:
self.assertEqual(liberty_cache[stone], 4, str(stone))
for stone in bottom_group.stones:
self.assertEqual(liberty_cache[stone], 6, str(stone))
for stone in captured:
self.assertEqual(liberty_cache[stone], 0, str(stone))
def test_capture_multiple_groups(self):
board = test_utils.load_board('''
.OX......
OXX......
XX.......
''' + EMPTY_ROW * 6)
lib_tracker = LibertyTracker.from_board(board)
captured = lib_tracker.add_stone(BLACK, coords.from_gtp('A9'))
self.assertEqual(len(lib_tracker.groups), 2)
self.assertEqual(captured, coords_from_gtp_set('B9 A8'))
corner_stone = lib_tracker.groups[lib_tracker.group_index[coords.from_gtp(
'A9')]]
self.assertEqual(corner_stone.stones, coords_from_gtp_set('A9'))
self.assertEqual(corner_stone.liberties, coords_from_gtp_set('B9 A8'))
surrounding_stones = lib_tracker.groups[lib_tracker.group_index[coords.from_gtp(
'C9')]]
self.assertEqual(surrounding_stones.stones,
coords_from_gtp_set('C9 B8 C8 A7 B7'))
self.assertEqual(surrounding_stones.liberties,
coords_from_gtp_set('B9 D9 A8 D8 C7 A6 B6'))
liberty_cache = lib_tracker.liberty_cache
for stone in corner_stone.stones:
self.assertEqual(liberty_cache[stone], 2, str(stone))
for stone in surrounding_stones.stones:
self.assertEqual(liberty_cache[stone], 7, str(stone))
def test_same_friendly_group_neighboring_twice(self):
board = test_utils.load_board('''
XX.......
X........
''' + EMPTY_ROW * 7)
lib_tracker = LibertyTracker.from_board(board)
captured = lib_tracker.add_stone(BLACK, coords.from_gtp('B8'))
self.assertEqual(len(lib_tracker.groups), 1)
sole_group_id = lib_tracker.group_index[coords.from_gtp('A9')]
sole_group = lib_tracker.groups[sole_group_id]
self.assertEqual(sole_group.stones,
coords_from_gtp_set('A9 B9 A8 B8'))
self.assertEqual(sole_group.liberties,
coords_from_gtp_set('C9 C8 A7 B7'))
self.assertEqual(captured, set())
def test_same_opponent_group_neighboring_twice(self):
board = test_utils.load_board('''
XX.......
X........
''' + EMPTY_ROW * 7)
lib_tracker = LibertyTracker.from_board(board)
captured = lib_tracker.add_stone(WHITE, coords.from_gtp('B8'))
self.assertEqual(len(lib_tracker.groups), 2)
black_group = lib_tracker.groups[lib_tracker.group_index[coords.from_gtp(
'A9')]]
self.assertEqual(black_group.stones, coords_from_gtp_set('A9 B9 A8'))
self.assertEqual(black_group.liberties, coords_from_gtp_set('C9 A7'))
white_group = lib_tracker.groups[lib_tracker.group_index[coords.from_gtp(
'B8')]]
self.assertEqual(white_group.stones, coords_from_gtp_set('B8'))
self.assertEqual(white_group.liberties, coords_from_gtp_set('C8 B7'))
self.assertEqual(captured, set())
class TestPosition(test_utils.MinigoUnitTest):
def test_passing(self):
start_position = Position(
board=TEST_BOARD,
n=0,
komi=6.5,
caps=(1, 2),
ko=coords.from_gtp('A1'),
recent=tuple(),
to_play=BLACK,
)
expected_position = Position(
board=TEST_BOARD,
n=1,
komi=6.5,
caps=(1, 2),
ko=None,
recent=(PlayerMove(BLACK, None),),
to_play=WHITE,
)
pass_position = start_position.pass_move()
self.assertEqualPositions(pass_position, expected_position)
def test_flipturn(self):
start_position = Position(
board=TEST_BOARD,
n=0,
komi=6.5,
caps=(1, 2),
ko=coords.from_gtp('A1'),
recent=tuple(),
to_play=BLACK,
)
expected_position = Position(
board=TEST_BOARD,
n=0,
komi=6.5,
caps=(1, 2),
ko=None,
recent=tuple(),
to_play=WHITE,
)
flip_position = start_position.flip_playerturn()
self.assertEqualPositions(flip_position, expected_position)
def test_is_move_suicidal(self):
board = test_utils.load_board('''
...O.O...
....O....
XO.....O.
OXO...OXO
O.XO.OX.O
OXO...OOX
XO.......
......XXO
.....XOO.
''')
position = Position(
board=board,
to_play=BLACK,
)
suicidal_moves = coords_from_gtp_set('E9 H5')
nonsuicidal_moves = coords_from_gtp_set('B5 J1 A9')
for move in suicidal_moves:
# sanity check my coordinate input
self.assertEqual(position.board[move], go.EMPTY)
self.assertTrue(position.is_move_suicidal(move), str(move))
for move in nonsuicidal_moves:
# sanity check my coordinate input
self.assertEqual(position.board[move], go.EMPTY)
self.assertFalse(position.is_move_suicidal(move), str(move))
def test_legal_moves(self):
board = test_utils.load_board('''
.O.O.XOX.
O..OOOOOX
......O.O
OO.....OX
XO.....X.
.O.......
OX.....OO
XX...OOOX
.....O.X.
''')
position = Position(board=board, to_play=BLACK)
illegal_moves = coords_from_gtp_set('A9 E9 J9')
legal_moves = coords_from_gtp_set('A4 G1 J1 H7') | {None}
for move in illegal_moves:
with self.subTest(type='illegal', move=move):
self.assertFalse(position.is_move_legal(move))
for move in legal_moves:
with self.subTest(type='legal', move=move):
self.assertTrue(position.is_move_legal(move))
# check that the bulk legal test agrees with move-by-move illegal test.
bulk_legality = position.all_legal_moves()
for i, bulk_legal in enumerate(bulk_legality):
with self.subTest(type='bulk', move=coords.from_flat(i)):
self.assertEqual(
bulk_legal, position.is_move_legal(coords.from_flat(i)))
# flip the colors and check that everything is still (il)legal
position = Position(board=-board, to_play=WHITE)
for move in illegal_moves:
with self.subTest(type='illegal', move=move):
self.assertFalse(position.is_move_legal(move))
for move in legal_moves:
with self.subTest(type='legal', move=move):
self.assertTrue(position.is_move_legal(move))
bulk_legality = position.all_legal_moves()
for i, bulk_legal in enumerate(bulk_legality):
with self.subTest(type='bulk', move=coords.from_flat(i)):
self.assertEqual(
bulk_legal, position.is_move_legal(coords.from_flat(i)))
def test_move(self):
start_position = Position(
board=TEST_BOARD,
n=0,
komi=6.5,
caps=(1, 2),
ko=None,
recent=tuple(),
to_play=BLACK,
)
expected_board = test_utils.load_board('''
.XX....OO
X........
''' + EMPTY_ROW * 7)
expected_position = Position(
board=expected_board,
n=1,
komi=6.5,
caps=(1, 2),
ko=None,
recent=(PlayerMove(BLACK, coords.from_gtp('C9')),),
to_play=WHITE,
)
actual_position = start_position.play_move(coords.from_gtp('C9'))
self.assertEqualPositions(actual_position, expected_position)
expected_board2 = test_utils.load_board('''
.XX....OO
X.......O
''' + EMPTY_ROW * 7)
expected_position2 = Position(
board=expected_board2,
n=2,
komi=6.5,
caps=(1, 2),
ko=None,
recent=(PlayerMove(BLACK, coords.from_gtp('C9')),
PlayerMove(WHITE, coords.from_gtp('J8'))),
to_play=BLACK,
)
actual_position2 = actual_position.play_move(coords.from_gtp('J8'))
self.assertEqualPositions(actual_position2, expected_position2)
def test_move_with_capture(self):
start_board = test_utils.load_board(EMPTY_ROW * 5 + '''
XXXX.....
XOOX.....
O.OX.....
OOXX.....
''')
start_position = Position(
board=start_board,
n=0,
komi=6.5,
caps=(1, 2),
ko=None,
recent=tuple(),
to_play=BLACK,
)
expected_board = test_utils.load_board(EMPTY_ROW * 5 + '''
XXXX.....
X..X.....
.X.X.....
..XX.....
''')
expected_position = Position(
board=expected_board,
n=1,
komi=6.5,
caps=(7, 2),
ko=None,
recent=(PlayerMove(BLACK, coords.from_gtp('B2')),),
to_play=WHITE,
)
actual_position = start_position.play_move(coords.from_gtp('B2'))
self.assertEqualPositions(actual_position, expected_position)
def test_ko_move(self):
start_board = test_utils.load_board('''
.OX......
OX.......
''' + EMPTY_ROW * 7)
start_position = Position(
board=start_board,
n=0,
komi=6.5,
caps=(1, 2),
ko=None,
recent=tuple(),
to_play=BLACK,
)
expected_board = test_utils.load_board('''
X.X......
OX.......
''' + EMPTY_ROW * 7)
expected_position = Position(
board=expected_board,
n=1,
komi=6.5,
caps=(2, 2),
ko=coords.from_gtp('B9'),
recent=(PlayerMove(BLACK, coords.from_gtp('A9')),),
to_play=WHITE,
)
actual_position = start_position.play_move(coords.from_gtp('A9'))
self.assertEqualPositions(actual_position, expected_position)
# Check that retaking ko is illegal until two intervening moves
with self.assertRaises(go.IllegalMove):
actual_position.play_move(coords.from_gtp('B9'))
pass_twice = actual_position.pass_move().pass_move()
ko_delayed_retake = pass_twice.play_move(coords.from_gtp('B9'))
expected_position = Position(
board=start_board,
n=4,
komi=6.5,
caps=(2, 3),
ko=coords.from_gtp('A9'),
recent=(
PlayerMove(BLACK, coords.from_gtp('A9')),
PlayerMove(WHITE, None),
PlayerMove(BLACK, None),
PlayerMove(WHITE, coords.from_gtp('B9'))),
to_play=BLACK,
)
self.assertEqualPositions(ko_delayed_retake, expected_position)
def test_is_game_over(self):
root = go.Position()
self.assertFalse(root.is_game_over())
first_pass = root.play_move(None)
self.assertFalse(first_pass.is_game_over())
second_pass = first_pass.play_move(None)
self.assertTrue(second_pass.is_game_over())
def test_scoring(self):
board = test_utils.load_board('''
.XX......
OOXX.....
OOOX...X.
OXX......
OOXXXXXX.
OOOXOXOXX
.O.OOXOOX
.O.O.OOXX
......OOO
''')
position = Position(
board=board,
n=54,
komi=6.5,
caps=(2, 5),
ko=None,
recent=tuple(),
to_play=BLACK,
)
expected_score = 1.5
self.assertEqual(position.score(), expected_score)
board = test_utils.load_board('''
XXX......
OOXX.....
OOOX...X.
OXX......
OOXXXXXX.
OOOXOXOXX
.O.OOXOOX
.O.O.OOXX
......OOO
''')
position = Position(
board=board,
n=55,
komi=6.5,
caps=(2, 5),
ko=None,
recent=tuple(),
to_play=WHITE,
)
expected_score = 2.5
self.assertEqual(position.score(), expected_score)
def test_replay_position(self):
sgf_positions = list(sgf_wrapper.replay_sgf(NO_HANDICAP_SGF))
initial = sgf_positions[0]
self.assertEqual(initial.result, go.WHITE)
final = sgf_positions[-1].position.play_move(
sgf_positions[-1].next_move)
# sanity check to ensure we're working with the right position
final_board = test_utils.load_board('''
.OXX.....
O.OX.X...
.OOX.....
OOOOXXXXX
XOXXOXOOO
XOOXOO.O.
XOXXXOOXO
XXX.XOXXO
X..XOO.O.
''')
expected_final_position = go.Position(
final_board,
n=62,
komi=6.5,
caps=(3, 2),
ko=None,
recent=tuple(),
to_play=go.BLACK
)
self.assertEqualPositions(expected_final_position, final)
self.assertEqual(final.n, len(final.recent))
replayed_positions = list(go.replay_position(final, 1))
for sgf_pos, replay_pos in zip(sgf_positions, replayed_positions):
self.assertEqualPositions(sgf_pos.position, replay_pos.position)
| [
"go.replay_position",
"go.is_eyeish",
"go.PlayerMove",
"go.LibertyTracker.from_board",
"tests.test_utils.load_board",
"sgf_wrapper.replay_sgf",
"go.Position",
"numpy.zeros",
"coords.from_flat",
"coords.from_gtp"
] | [((778, 844), 'tests.test_utils.load_board', 'test_utils.load_board', (['("""\n.X.....OO\nX........\n""" + EMPTY_ROW * 7)'], {}), '("""\n.X.....OO\nX........\n""" + EMPTY_ROW * 7)\n', (799, 844), False, 'from tests import test_utils\n'), ((1720, 1741), 'coords.from_gtp', 'coords.from_gtp', (['"""A1"""'], {}), "('A1')\n", (1735, 1741), False, 'import coords\n'), ((1872, 1893), 'coords.from_gtp', 'coords.from_gtp', (['"""A2"""'], {}), "('A2')\n", (1887, 1893), False, 'import coords\n'), ((2423, 2669), 'tests.test_utils.load_board', 'test_utils.load_board', (['"""\n .XX...XXX\n X.X...X.X\n XX.....X.\n ........X\n XXXX.....\n OOOX....O\n X.OXX.OO.\n .XO.X.O.O\n XXO.X.OO.\n """'], {}), '(\n """\n .XX...XXX\n X.X...X.X\n XX.....X.\n ........X\n XXXX.....\n OOOX....O\n X.OXX.OO.\n .XO.X.O.O\n XXO.X.OO.\n """\n )\n', (2444, 2669), False, 'from tests import test_utils\n'), ((3209, 3259), 'tests.test_utils.load_board', 'test_utils.load_board', (["('X........' + EMPTY_ROW * 8)"], {}), "('X........' + EMPTY_ROW * 8)\n", (3230, 3259), False, 'from tests import test_utils\n'), ((3283, 3315), 'go.LibertyTracker.from_board', 'LibertyTracker.from_board', (['board'], {}), '(board)\n', (3308, 3315), False, 'from go import Position, PlayerMove, LibertyTracker, WHITE, BLACK\n'), ((3905, 3955), 'tests.test_utils.load_board', 'test_utils.load_board', (["('X........' + EMPTY_ROW * 8)"], {}), "('X........' + EMPTY_ROW * 8)\n", (3926, 3955), False, 'from tests import test_utils\n'), ((3978, 4010), 'go.LibertyTracker.from_board', 'LibertyTracker.from_board', (['board'], {}), '(board)\n', (4003, 4010), False, 'from go import Position, PlayerMove, LibertyTracker, WHITE, BLACK\n'), ((4784, 4834), 'tests.test_utils.load_board', 'test_utils.load_board', (["('X........' + EMPTY_ROW * 8)"], {}), "('X........' + EMPTY_ROW * 8)\n", (4805, 4834), False, 'from tests import test_utils\n'), ((4857, 4889), 'go.LibertyTracker.from_board', 'LibertyTracker.from_board', (['board'], {}), '(board)\n', (4882, 4889), False, 'from go import Position, PlayerMove, LibertyTracker, WHITE, BLACK\n'), ((6041, 6171), 'tests.test_utils.load_board', 'test_utils.load_board', (['("""\n .X.......\n X.X......\n .X.......\n """\n + EMPTY_ROW * 6)'], {}), '(\n """\n .X.......\n X.X......\n .X.......\n """\n + EMPTY_ROW * 6)\n', (6062, 6171), False, 'from tests import test_utils\n'), ((6184, 6216), 'go.LibertyTracker.from_board', 'LibertyTracker.from_board', (['board'], {}), '(board)\n', (6209, 6216), False, 'from go import Position, PlayerMove, LibertyTracker, WHITE, BLACK\n'), ((7021, 7151), 'tests.test_utils.load_board', 'test_utils.load_board', (['("""\n .X.......\n XO.......\n .X.......\n """\n + EMPTY_ROW * 6)'], {}), '(\n """\n .X.......\n XO.......\n .X.......\n """\n + EMPTY_ROW * 6)\n', (7042, 7151), False, 'from tests import test_utils\n'), ((7164, 7196), 'go.LibertyTracker.from_board', 'LibertyTracker.from_board', (['board'], {}), '(board)\n', (7189, 7196), False, 'from go import Position, PlayerMove, LibertyTracker, WHITE, BLACK\n'), ((7540, 7670), 'tests.test_utils.load_board', 'test_utils.load_board', (['("""\n .XX......\n XOO......\n .XX......\n """\n + EMPTY_ROW * 6)'], {}), '(\n """\n .XX......\n XOO......\n .XX......\n """\n + EMPTY_ROW * 6)\n', (7561, 7670), False, 'from tests import test_utils\n'), ((7683, 7715), 'go.LibertyTracker.from_board', 'LibertyTracker.from_board', (['board'], {}), '(board)\n', (7708, 7715), False, 'from go import Position, PlayerMove, LibertyTracker, WHITE, BLACK\n'), ((9786, 9916), 'tests.test_utils.load_board', 'test_utils.load_board', (['("""\n .OX......\n OXX......\n XX.......\n """\n + EMPTY_ROW * 6)'], {}), '(\n """\n .OX......\n OXX......\n XX.......\n """\n + EMPTY_ROW * 6)\n', (9807, 9916), False, 'from tests import test_utils\n'), ((9929, 9961), 'go.LibertyTracker.from_board', 'LibertyTracker.from_board', (['board'], {}), '(board)\n', (9954, 9961), False, 'from go import Position, PlayerMove, LibertyTracker, WHITE, BLACK\n'), ((11106, 11214), 'tests.test_utils.load_board', 'test_utils.load_board', (['("""\n XX.......\n X........\n """ + EMPTY_ROW * 7)'], {}), '(\n """\n XX.......\n X........\n """ + EMPTY_ROW * 7\n )\n', (11127, 11214), False, 'from tests import test_utils\n'), ((11228, 11260), 'go.LibertyTracker.from_board', 'LibertyTracker.from_board', (['board'], {}), '(board)\n', (11253, 11260), False, 'from go import Position, PlayerMove, LibertyTracker, WHITE, BLACK\n'), ((11841, 11949), 'tests.test_utils.load_board', 'test_utils.load_board', (['("""\n XX.......\n X........\n """ + EMPTY_ROW * 7)'], {}), '(\n """\n XX.......\n X........\n """ + EMPTY_ROW * 7\n )\n', (11862, 11949), False, 'from tests import test_utils\n'), ((11963, 11995), 'go.LibertyTracker.from_board', 'LibertyTracker.from_board', (['board'], {}), '(board)\n', (11988, 11995), False, 'from go import Position, PlayerMove, LibertyTracker, WHITE, BLACK\n'), ((13998, 14244), 'tests.test_utils.load_board', 'test_utils.load_board', (['"""\n ...O.O...\n ....O....\n XO.....O.\n OXO...OXO\n O.XO.OX.O\n OXO...OOX\n XO.......\n ......XXO\n .....XOO.\n """'], {}), '(\n """\n ...O.O...\n ....O....\n XO.....O.\n OXO...OXO\n O.XO.OX.O\n OXO...OOX\n XO.......\n ......XXO\n .....XOO.\n """\n )\n', (14019, 14244), False, 'from tests import test_utils\n'), ((14254, 14290), 'go.Position', 'Position', ([], {'board': 'board', 'to_play': 'BLACK'}), '(board=board, to_play=BLACK)\n', (14262, 14290), False, 'from go import Position, PlayerMove, LibertyTracker, WHITE, BLACK\n'), ((14925, 15171), 'tests.test_utils.load_board', 'test_utils.load_board', (['"""\n .O.O.XOX.\n O..OOOOOX\n ......O.O\n OO.....OX\n XO.....X.\n .O.......\n OX.....OO\n XX...OOOX\n .....O.X.\n """'], {}), '(\n """\n .O.O.XOX.\n O..OOOOOX\n ......O.O\n OO.....OX\n XO.....X.\n .O.......\n OX.....OO\n XX...OOOX\n .....O.X.\n """\n )\n', (14946, 15171), False, 'from tests import test_utils\n'), ((15181, 15217), 'go.Position', 'Position', ([], {'board': 'board', 'to_play': 'BLACK'}), '(board=board, to_play=BLACK)\n', (15189, 15217), False, 'from go import Position, PlayerMove, LibertyTracker, WHITE, BLACK\n'), ((16105, 16142), 'go.Position', 'Position', ([], {'board': '(-board)', 'to_play': 'WHITE'}), '(board=-board, to_play=WHITE)\n', (16113, 16142), False, 'from go import Position, PlayerMove, LibertyTracker, WHITE, BLACK\n'), ((17003, 17111), 'tests.test_utils.load_board', 'test_utils.load_board', (['("""\n .XX....OO\n X........\n """ + EMPTY_ROW * 7)'], {}), '(\n """\n .XX....OO\n X........\n """ + EMPTY_ROW * 7\n )\n', (17024, 17111), False, 'from tests import test_utils\n'), ((17531, 17639), 'tests.test_utils.load_board', 'test_utils.load_board', (['("""\n .XX....OO\n X.......O\n """ + EMPTY_ROW * 7)'], {}), '(\n """\n .XX....OO\n X.......O\n """ + EMPTY_ROW * 7\n )\n', (17552, 17639), False, 'from tests import test_utils\n'), ((18160, 18311), 'tests.test_utils.load_board', 'test_utils.load_board', (['(EMPTY_ROW * 5 +\n """\n XXXX.....\n XOOX.....\n O.OX.....\n OOXX.....\n """\n )'], {}), '(EMPTY_ROW * 5 +\n """\n XXXX.....\n XOOX.....\n O.OX.....\n OOXX.....\n """\n )\n', (18181, 18311), False, 'from tests import test_utils\n'), ((18544, 18695), 'tests.test_utils.load_board', 'test_utils.load_board', (['(EMPTY_ROW * 5 +\n """\n XXXX.....\n X..X.....\n .X.X.....\n ..XX.....\n """\n )'], {}), '(EMPTY_ROW * 5 +\n """\n XXXX.....\n X..X.....\n .X.X.....\n ..XX.....\n """\n )\n', (18565, 18695), False, 'from tests import test_utils\n'), ((19140, 19248), 'tests.test_utils.load_board', 'test_utils.load_board', (['("""\n .OX......\n OX.......\n """ + EMPTY_ROW * 7)'], {}), '(\n """\n .OX......\n OX.......\n """ + EMPTY_ROW * 7\n )\n', (19161, 19248), False, 'from tests import test_utils\n'), ((19480, 19588), 'tests.test_utils.load_board', 'test_utils.load_board', (['("""\n X.X......\n OX.......\n """ + EMPTY_ROW * 7)'], {}), '(\n """\n X.X......\n OX.......\n """ + EMPTY_ROW * 7\n )\n', (19501, 19588), False, 'from tests import test_utils\n'), ((20863, 20876), 'go.Position', 'go.Position', ([], {}), '()\n', (20874, 20876), False, 'import go\n'), ((21163, 21449), 'tests.test_utils.load_board', 'test_utils.load_board', (['"""\n .XX......\n OOXX.....\n OOOX...X.\n OXX......\n OOXXXXXX.\n OOOXOXOXX\n .O.OOXOOX\n .O.O.OOXX\n ......OOO\n """'], {}), '(\n """\n .XX......\n OOXX.....\n OOOX...X.\n OXX......\n OOXXXXXX.\n OOOXOXOXX\n .O.OOXOOX\n .O.O.OOXX\n ......OOO\n """\n )\n', (21184, 21449), False, 'from tests import test_utils\n'), ((21750, 22036), 'tests.test_utils.load_board', 'test_utils.load_board', (['"""\n XXX......\n OOXX.....\n OOOX...X.\n OXX......\n OOXXXXXX.\n OOOXOXOXX\n .O.OOXOOX\n .O.O.OOXX\n ......OOO\n """'], {}), '(\n """\n XXX......\n OOXX.....\n OOOX...X.\n OXX......\n OOXXXXXX.\n OOOXOXOXX\n .O.OOXOOX\n .O.O.OOXX\n ......OOO\n """\n )\n', (21771, 22036), False, 'from tests import test_utils\n'), ((22703, 22949), 'tests.test_utils.load_board', 'test_utils.load_board', (['"""\n .OXX.....\n O.OX.X...\n .OOX.....\n OOOOXXXXX\n XOXXOXOOO\n XOOXOO.O.\n XOXXXOOXO\n XXX.XOXXO\n X..XOO.O.\n """'], {}), '(\n """\n .OXX.....\n O.OX.X...\n .OOX.....\n OOOOXXXXX\n XOXXOXOOO\n XOOXOO.O.\n XOXXXOOXO\n XXX.XOXXO\n X..XOO.O.\n """\n )\n', (22724, 22949), False, 'from tests import test_utils\n'), ((1544, 1566), 'numpy.zeros', 'np.zeros', (['[go.N, go.N]'], {}), '([go.N, go.N])\n', (1552, 1566), True, 'import numpy as np\n'), ((1629, 1670), 'tests.test_utils.load_board', 'test_utils.load_board', (["('. \\n' * go.N ** 2)"], {}), "('. \\n' * go.N ** 2)\n", (1650, 1670), False, 'from tests import test_utils\n'), ((4048, 4069), 'coords.from_gtp', 'coords.from_gtp', (['"""B9"""'], {}), "('B9')\n", (4063, 4069), False, 'import coords\n'), ((4927, 4948), 'coords.from_gtp', 'coords.from_gtp', (['"""B9"""'], {}), "('B9')\n", (4942, 4948), False, 'import coords\n'), ((6254, 6275), 'coords.from_gtp', 'coords.from_gtp', (['"""B8"""'], {}), "('B8')\n", (6269, 6275), False, 'import coords\n'), ((7245, 7266), 'coords.from_gtp', 'coords.from_gtp', (['"""C8"""'], {}), "('C8')\n", (7260, 7266), False, 'import coords\n'), ((7764, 7785), 'coords.from_gtp', 'coords.from_gtp', (['"""D8"""'], {}), "('D8')\n", (7779, 7785), False, 'import coords\n'), ((10010, 10031), 'coords.from_gtp', 'coords.from_gtp', (['"""A9"""'], {}), "('A9')\n", (10025, 10031), False, 'import coords\n'), ((11309, 11330), 'coords.from_gtp', 'coords.from_gtp', (['"""B8"""'], {}), "('B8')\n", (11324, 11330), False, 'import coords\n'), ((11433, 11454), 'coords.from_gtp', 'coords.from_gtp', (['"""A9"""'], {}), "('A9')\n", (11448, 11454), False, 'import coords\n'), ((12044, 12065), 'coords.from_gtp', 'coords.from_gtp', (['"""B8"""'], {}), "('B8')\n", (12059, 12065), False, 'import coords\n'), ((17411, 17432), 'coords.from_gtp', 'coords.from_gtp', (['"""C9"""'], {}), "('C9')\n", (17426, 17432), False, 'import coords\n'), ((18004, 18025), 'coords.from_gtp', 'coords.from_gtp', (['"""J8"""'], {}), "('J8')\n", (18019, 18025), False, 'import coords\n'), ((18996, 19017), 'coords.from_gtp', 'coords.from_gtp', (['"""B2"""'], {}), "('B2')\n", (19011, 19017), False, 'import coords\n'), ((19905, 19926), 'coords.from_gtp', 'coords.from_gtp', (['"""A9"""'], {}), "('A9')\n", (19920, 19926), False, 'import coords\n'), ((20291, 20312), 'coords.from_gtp', 'coords.from_gtp', (['"""B9"""'], {}), "('B9')\n", (20306, 20312), False, 'import coords\n'), ((22386, 22425), 'sgf_wrapper.replay_sgf', 'sgf_wrapper.replay_sgf', (['NO_HANDICAP_SGF'], {}), '(NO_HANDICAP_SGF)\n', (22408, 22425), False, 'import sgf_wrapper\n'), ((23319, 23347), 'go.replay_position', 'go.replay_position', (['final', '(1)'], {}), '(final, 1)\n', (23337, 23347), False, 'import go\n'), ((2108, 2129), 'coords.from_gtp', 'coords.from_gtp', (['"""A9"""'], {}), "('A9')\n", (2123, 2129), False, 'import coords\n'), ((2188, 2209), 'coords.from_gtp', 'coords.from_gtp', (['"""B8"""'], {}), "('B8')\n", (2203, 2209), False, 'import coords\n'), ((2267, 2288), 'coords.from_gtp', 'coords.from_gtp', (['"""B9"""'], {}), "('B9')\n", (2282, 2288), False, 'import coords\n'), ((2346, 2367), 'coords.from_gtp', 'coords.from_gtp', (['"""E5"""'], {}), "('E5')\n", (2361, 2367), False, 'import coords\n'), ((2867, 2890), 'go.is_eyeish', 'go.is_eyeish', (['board', 'be'], {}), '(board, be)\n', (2879, 2890), False, 'import go\n'), ((2963, 2986), 'go.is_eyeish', 'go.is_eyeish', (['board', 'we'], {}), '(board, we)\n', (2975, 2986), False, 'import go\n'), ((3061, 3084), 'go.is_eyeish', 'go.is_eyeish', (['board', 'ne'], {}), '(board, ne)\n', (3073, 3084), False, 'import go\n'), ((3434, 3455), 'coords.from_gtp', 'coords.from_gtp', (['"""A9"""'], {}), "('A9')\n", (3449, 3455), False, 'import coords\n'), ((3530, 3551), 'coords.from_gtp', 'coords.from_gtp', (['"""A9"""'], {}), "('A9')\n", (3545, 3551), False, 'import coords\n'), ((3621, 3642), 'coords.from_gtp', 'coords.from_gtp', (['"""A9"""'], {}), "('A9')\n", (3636, 3642), False, 'import coords\n'), ((4189, 4210), 'coords.from_gtp', 'coords.from_gtp', (['"""A9"""'], {}), "('A9')\n", (4204, 4210), False, 'import coords\n'), ((4285, 4306), 'coords.from_gtp', 'coords.from_gtp', (['"""A9"""'], {}), "('A9')\n", (4300, 4306), False, 'import coords\n'), ((4363, 4384), 'coords.from_gtp', 'coords.from_gtp', (['"""B9"""'], {}), "('B9')\n", (4378, 4384), False, 'import coords\n'), ((4454, 4475), 'coords.from_gtp', 'coords.from_gtp', (['"""A9"""'], {}), "('A9')\n", (4469, 4475), False, 'import coords\n'), ((5068, 5089), 'coords.from_gtp', 'coords.from_gtp', (['"""A9"""'], {}), "('A9')\n", (5083, 5089), False, 'import coords\n'), ((5178, 5199), 'coords.from_gtp', 'coords.from_gtp', (['"""B9"""'], {}), "('B9')\n", (5193, 5199), False, 'import coords\n'), ((5274, 5295), 'coords.from_gtp', 'coords.from_gtp', (['"""A9"""'], {}), "('A9')\n", (5289, 5295), False, 'import coords\n'), ((5352, 5373), 'coords.from_gtp', 'coords.from_gtp', (['"""B9"""'], {}), "('B9')\n", (5367, 5373), False, 'import coords\n'), ((5444, 5465), 'coords.from_gtp', 'coords.from_gtp', (['"""A9"""'], {}), "('A9')\n", (5459, 5465), False, 'import coords\n'), ((5546, 5567), 'coords.from_gtp', 'coords.from_gtp', (['"""B9"""'], {}), "('B9')\n", (5561, 5567), False, 'import coords\n'), ((6395, 6416), 'coords.from_gtp', 'coords.from_gtp', (['"""B8"""'], {}), "('B8')\n", (6410, 6416), False, 'import coords\n'), ((6504, 6525), 'coords.from_gtp', 'coords.from_gtp', (['"""B8"""'], {}), "('B8')\n", (6519, 6525), False, 'import coords\n'), ((7383, 7404), 'coords.from_gtp', 'coords.from_gtp', (['"""B8"""'], {}), "('B8')\n", (7398, 7404), False, 'import coords\n'), ((7902, 7923), 'coords.from_gtp', 'coords.from_gtp', (['"""B8"""'], {}), "('B8')\n", (7917, 7923), False, 'import coords\n'), ((8077, 8098), 'coords.from_gtp', 'coords.from_gtp', (['"""A8"""'], {}), "('A8')\n", (8092, 8098), False, 'import coords\n'), ((8356, 8377), 'coords.from_gtp', 'coords.from_gtp', (['"""D8"""'], {}), "('D8')\n", (8371, 8377), False, 'import coords\n'), ((8638, 8659), 'coords.from_gtp', 'coords.from_gtp', (['"""B9"""'], {}), "('B9')\n", (8653, 8659), False, 'import coords\n'), ((8922, 8943), 'coords.from_gtp', 'coords.from_gtp', (['"""B7"""'], {}), "('B7')\n", (8937, 8943), False, 'import coords\n'), ((10218, 10239), 'coords.from_gtp', 'coords.from_gtp', (['"""A9"""'], {}), "('A9')\n", (10233, 10239), False, 'import coords\n'), ((10480, 10501), 'coords.from_gtp', 'coords.from_gtp', (['"""C9"""'], {}), "('C9')\n", (10495, 10501), False, 'import coords\n'), ((12185, 12206), 'coords.from_gtp', 'coords.from_gtp', (['"""A9"""'], {}), "('A9')\n", (12200, 12206), False, 'import coords\n'), ((12444, 12465), 'coords.from_gtp', 'coords.from_gtp', (['"""B8"""'], {}), "('B8')\n", (12459, 12465), False, 'import coords\n'), ((12895, 12916), 'coords.from_gtp', 'coords.from_gtp', (['"""A1"""'], {}), "('A1')\n", (12910, 12916), False, 'import coords\n'), ((13513, 13534), 'coords.from_gtp', 'coords.from_gtp', (['"""A1"""'], {}), "('A1')\n", (13528, 13534), False, 'import coords\n'), ((19730, 19751), 'coords.from_gtp', 'coords.from_gtp', (['"""B9"""'], {}), "('B9')\n", (19745, 19751), False, 'import coords\n'), ((20158, 20179), 'coords.from_gtp', 'coords.from_gtp', (['"""B9"""'], {}), "('B9')\n", (20173, 20179), False, 'import coords\n'), ((20462, 20483), 'coords.from_gtp', 'coords.from_gtp', (['"""A9"""'], {}), "('A9')\n", (20477, 20483), False, 'import coords\n'), ((13156, 13179), 'go.PlayerMove', 'PlayerMove', (['BLACK', 'None'], {}), '(BLACK, None)\n', (13166, 13179), False, 'from go import Position, PlayerMove, LibertyTracker, WHITE, BLACK\n'), ((20580, 20603), 'go.PlayerMove', 'PlayerMove', (['WHITE', 'None'], {}), '(WHITE, None)\n', (20590, 20603), False, 'from go import Position, PlayerMove, LibertyTracker, WHITE, BLACK\n'), ((20621, 20644), 'go.PlayerMove', 'PlayerMove', (['BLACK', 'None'], {}), '(BLACK, None)\n', (20631, 20644), False, 'from go import Position, PlayerMove, LibertyTracker, WHITE, BLACK\n'), ((15881, 15900), 'coords.from_flat', 'coords.from_flat', (['i'], {}), '(i)\n', (15897, 15900), False, 'import coords\n'), ((15992, 16011), 'coords.from_flat', 'coords.from_flat', (['i'], {}), '(i)\n', (16008, 16011), False, 'import coords\n'), ((16604, 16623), 'coords.from_flat', 'coords.from_flat', (['i'], {}), '(i)\n', (16620, 16623), False, 'import coords\n'), ((16715, 16734), 'coords.from_flat', 'coords.from_flat', (['i'], {}), '(i)\n', (16731, 16734), False, 'import coords\n'), ((17297, 17318), 'coords.from_gtp', 'coords.from_gtp', (['"""C9"""'], {}), "('C9')\n", (17312, 17318), False, 'import coords\n'), ((17827, 17848), 'coords.from_gtp', 'coords.from_gtp', (['"""C9"""'], {}), "('C9')\n", (17842, 17848), False, 'import coords\n'), ((17889, 17910), 'coords.from_gtp', 'coords.from_gtp', (['"""J8"""'], {}), "('J8')\n", (17904, 17910), False, 'import coords\n'), ((18882, 18903), 'coords.from_gtp', 'coords.from_gtp', (['"""B2"""'], {}), "('B2')\n", (18897, 18903), False, 'import coords\n'), ((19791, 19812), 'coords.from_gtp', 'coords.from_gtp', (['"""A9"""'], {}), "('A9')\n", (19806, 19812), False, 'import coords\n'), ((20540, 20561), 'coords.from_gtp', 'coords.from_gtp', (['"""A9"""'], {}), "('A9')\n", (20555, 20561), False, 'import coords\n'), ((20680, 20701), 'coords.from_gtp', 'coords.from_gtp', (['"""B9"""'], {}), "('B9')\n", (20695, 20701), False, 'import coords\n')] |
import panel as pn
import numpy as np
import holoviews as hv
LOGO = "https://panel.holoviz.org/_static/logo_horizontal.png"
def test_vanilla_with_sidebar():
"""Returns an app that uses the vanilla template in various ways.
Inspect the app and verify that the issues of [Issue 1641]\
(https://github.com/holoviz/panel/issues/1641) have been solved
- Navbar is "sticky"/ fixed to the top
- Navbar supports adding header items to left, center and right
- There is a nice padding/ margin everywhere
- Independent scroll for sidebar and main
- Only vertical scrollbars
"""
vanilla = pn.template.VanillaTemplate(
title="Vanilla Template",
logo=LOGO,
)
xs = np.linspace(0, np.pi)
freq = pn.widgets.FloatSlider(name="Frequency", start=0, end=10, value=2)
phase = pn.widgets.FloatSlider(name="Phase", start=0, end=np.pi)
@pn.depends(freq=freq, phase=phase)
def sine(freq, phase):
return hv.Curve((xs, np.sin(xs * freq + phase))).opts(responsive=True, min_height=400)
@pn.depends(freq=freq, phase=phase)
def cosine(freq, phase):
return hv.Curve((xs, np.cos(xs * freq + phase))).opts(responsive=True, min_height=400)
vanilla.sidebar.append(freq)
vanilla.sidebar.append(phase)
vanilla.sidebar.append(pn.pane.Markdown(test_vanilla_with_sidebar.__doc__))
vanilla.sidebar.append(pn.pane.Markdown("## Sidebar Item\n" * 50))
vanilla.main.append(
pn.Row(
pn.Card(hv.DynamicMap(sine), title="Sine"),
pn.Card(hv.DynamicMap(cosine), title="Cosine"),
)
)
vanilla.main.append(
pn.Row(
pn.Card(hv.DynamicMap(sine), title="Sine"),
pn.Card(hv.DynamicMap(cosine), title="Cosine"),
)
)
vanilla.header[:] = [
pn.Row(
pn.widgets.Button(name="Left", sizing_mode="fixed", width=50),
pn.layout.HSpacer(),
pn.widgets.Button(name="Center", sizing_mode="fixed", width=50),
pn.layout.HSpacer(),
pn.widgets.Button(name="Right", sizing_mode="fixed", width=50),
)
]
vanilla.main_max_width = "600px"
return vanilla
def test_vanilla_with_no_sidebar():
"""Returns an app that uses the vanilla template in various ways.
Inspect the app and verify that the issues of [Issue 1641]\
(https://github.com/holoviz/panel/issues/1641) have been solved
- Navbar is "sticky"/ fixed to the top
- Navbar supports adding header items to left, center and right
- There is a nice padding/ margin everywhere
- Independent scroll for sidebar and main
- Only vertical scrollbars
"""
vanilla = pn.template.VanillaTemplate(
title="Vanilla Template",
logo=LOGO,
favicon="https://raw.githubusercontent.com/MarcSkovMadsen/awesome-panel/2781d86d4ed141889d633748879a120d7d8e777a/assets/images/favicon.ico",
)
xs = np.linspace(0, np.pi)
freq = pn.widgets.FloatSlider(name="Frequency", start=0, end=10, value=2)
phase = pn.widgets.FloatSlider(name="Phase", start=0, end=np.pi)
@pn.depends(freq=freq, phase=phase)
def sine(freq, phase):
return hv.Curve((xs, np.sin(xs * freq + phase))).opts(responsive=True, min_height=400)
@pn.depends(freq=freq, phase=phase)
def cosine(freq, phase):
return hv.Curve((xs, np.cos(xs * freq + phase))).opts(responsive=True, min_height=400)
vanilla.main.append(freq)
vanilla.main.append(phase)
vanilla.main.append(pn.pane.Markdown(test_vanilla_with_no_sidebar.__doc__))
vanilla.main.append(
pn.Row(
pn.Card(hv.DynamicMap(sine), title="Sine"),
pn.Card(hv.DynamicMap(cosine), title="Cosine"),
)
)
vanilla.main.append(
pn.Row(
pn.Card(hv.DynamicMap(sine), title="Sine"),
pn.Card(hv.DynamicMap(cosine), title="Cosine"),
)
)
vanilla.header[:] = [
pn.Row(
pn.widgets.Button(name="Left", sizing_mode="fixed", width=50),
pn.layout.HSpacer(),
pn.widgets.Button(name="Center", sizing_mode="fixed", width=50),
pn.layout.HSpacer(),
pn.widgets.Button(name="Right", sizing_mode="fixed", width=50),
)
]
vanilla.main_max_width = "600px"
return vanilla
if __name__.startswith("bokeh"):
pn.extension(sizing_mode="stretch_width")
test_vanilla_with_sidebar().servable()
# test_vanilla_with_no_sidebar().servable()
| [
"panel.pane.Markdown",
"holoviews.DynamicMap",
"panel.widgets.Button",
"panel.widgets.FloatSlider",
"panel.extension",
"panel.template.VanillaTemplate",
"numpy.sin",
"panel.layout.HSpacer",
"numpy.linspace",
"numpy.cos",
"panel.depends"
] | [((591, 655), 'panel.template.VanillaTemplate', 'pn.template.VanillaTemplate', ([], {'title': '"""Vanilla Template"""', 'logo': 'LOGO'}), "(title='Vanilla Template', logo=LOGO)\n", (618, 655), True, 'import panel as pn\n'), ((689, 710), 'numpy.linspace', 'np.linspace', (['(0)', 'np.pi'], {}), '(0, np.pi)\n', (700, 710), True, 'import numpy as np\n'), ((722, 788), 'panel.widgets.FloatSlider', 'pn.widgets.FloatSlider', ([], {'name': '"""Frequency"""', 'start': '(0)', 'end': '(10)', 'value': '(2)'}), "(name='Frequency', start=0, end=10, value=2)\n", (744, 788), True, 'import panel as pn\n'), ((801, 857), 'panel.widgets.FloatSlider', 'pn.widgets.FloatSlider', ([], {'name': '"""Phase"""', 'start': '(0)', 'end': 'np.pi'}), "(name='Phase', start=0, end=np.pi)\n", (823, 857), True, 'import panel as pn\n'), ((864, 898), 'panel.depends', 'pn.depends', ([], {'freq': 'freq', 'phase': 'phase'}), '(freq=freq, phase=phase)\n', (874, 898), True, 'import panel as pn\n'), ((1027, 1061), 'panel.depends', 'pn.depends', ([], {'freq': 'freq', 'phase': 'phase'}), '(freq=freq, phase=phase)\n', (1037, 1061), True, 'import panel as pn\n'), ((2629, 2844), 'panel.template.VanillaTemplate', 'pn.template.VanillaTemplate', ([], {'title': '"""Vanilla Template"""', 'logo': 'LOGO', 'favicon': '"""https://raw.githubusercontent.com/MarcSkovMadsen/awesome-panel/2781d86d4ed141889d633748879a120d7d8e777a/assets/images/favicon.ico"""'}), "(title='Vanilla Template', logo=LOGO, favicon=\n 'https://raw.githubusercontent.com/MarcSkovMadsen/awesome-panel/2781d86d4ed141889d633748879a120d7d8e777a/assets/images/favicon.ico'\n )\n", (2656, 2844), True, 'import panel as pn\n'), ((2876, 2897), 'numpy.linspace', 'np.linspace', (['(0)', 'np.pi'], {}), '(0, np.pi)\n', (2887, 2897), True, 'import numpy as np\n'), ((2909, 2975), 'panel.widgets.FloatSlider', 'pn.widgets.FloatSlider', ([], {'name': '"""Frequency"""', 'start': '(0)', 'end': '(10)', 'value': '(2)'}), "(name='Frequency', start=0, end=10, value=2)\n", (2931, 2975), True, 'import panel as pn\n'), ((2988, 3044), 'panel.widgets.FloatSlider', 'pn.widgets.FloatSlider', ([], {'name': '"""Phase"""', 'start': '(0)', 'end': 'np.pi'}), "(name='Phase', start=0, end=np.pi)\n", (3010, 3044), True, 'import panel as pn\n'), ((3051, 3085), 'panel.depends', 'pn.depends', ([], {'freq': 'freq', 'phase': 'phase'}), '(freq=freq, phase=phase)\n', (3061, 3085), True, 'import panel as pn\n'), ((3214, 3248), 'panel.depends', 'pn.depends', ([], {'freq': 'freq', 'phase': 'phase'}), '(freq=freq, phase=phase)\n', (3224, 3248), True, 'import panel as pn\n'), ((4308, 4349), 'panel.extension', 'pn.extension', ([], {'sizing_mode': '"""stretch_width"""'}), "(sizing_mode='stretch_width')\n", (4320, 4349), True, 'import panel as pn\n'), ((1281, 1332), 'panel.pane.Markdown', 'pn.pane.Markdown', (['test_vanilla_with_sidebar.__doc__'], {}), '(test_vanilla_with_sidebar.__doc__)\n', (1297, 1332), True, 'import panel as pn\n'), ((1361, 1403), 'panel.pane.Markdown', 'pn.pane.Markdown', (["('## Sidebar Item\\n' * 50)"], {}), "('## Sidebar Item\\n' * 50)\n", (1377, 1403), True, 'import panel as pn\n'), ((3459, 3513), 'panel.pane.Markdown', 'pn.pane.Markdown', (['test_vanilla_with_no_sidebar.__doc__'], {}), '(test_vanilla_with_no_sidebar.__doc__)\n', (3475, 3513), True, 'import panel as pn\n'), ((1806, 1867), 'panel.widgets.Button', 'pn.widgets.Button', ([], {'name': '"""Left"""', 'sizing_mode': '"""fixed"""', 'width': '(50)'}), "(name='Left', sizing_mode='fixed', width=50)\n", (1823, 1867), True, 'import panel as pn\n'), ((1881, 1900), 'panel.layout.HSpacer', 'pn.layout.HSpacer', ([], {}), '()\n', (1898, 1900), True, 'import panel as pn\n'), ((1914, 1977), 'panel.widgets.Button', 'pn.widgets.Button', ([], {'name': '"""Center"""', 'sizing_mode': '"""fixed"""', 'width': '(50)'}), "(name='Center', sizing_mode='fixed', width=50)\n", (1931, 1977), True, 'import panel as pn\n'), ((1991, 2010), 'panel.layout.HSpacer', 'pn.layout.HSpacer', ([], {}), '()\n', (2008, 2010), True, 'import panel as pn\n'), ((2024, 2086), 'panel.widgets.Button', 'pn.widgets.Button', ([], {'name': '"""Right"""', 'sizing_mode': '"""fixed"""', 'width': '(50)'}), "(name='Right', sizing_mode='fixed', width=50)\n", (2041, 2086), True, 'import panel as pn\n'), ((3915, 3976), 'panel.widgets.Button', 'pn.widgets.Button', ([], {'name': '"""Left"""', 'sizing_mode': '"""fixed"""', 'width': '(50)'}), "(name='Left', sizing_mode='fixed', width=50)\n", (3932, 3976), True, 'import panel as pn\n'), ((3990, 4009), 'panel.layout.HSpacer', 'pn.layout.HSpacer', ([], {}), '()\n', (4007, 4009), True, 'import panel as pn\n'), ((4023, 4086), 'panel.widgets.Button', 'pn.widgets.Button', ([], {'name': '"""Center"""', 'sizing_mode': '"""fixed"""', 'width': '(50)'}), "(name='Center', sizing_mode='fixed', width=50)\n", (4040, 4086), True, 'import panel as pn\n'), ((4100, 4119), 'panel.layout.HSpacer', 'pn.layout.HSpacer', ([], {}), '()\n', (4117, 4119), True, 'import panel as pn\n'), ((4133, 4195), 'panel.widgets.Button', 'pn.widgets.Button', ([], {'name': '"""Right"""', 'sizing_mode': '"""fixed"""', 'width': '(50)'}), "(name='Right', sizing_mode='fixed', width=50)\n", (4150, 4195), True, 'import panel as pn\n'), ((1467, 1486), 'holoviews.DynamicMap', 'hv.DynamicMap', (['sine'], {}), '(sine)\n', (1480, 1486), True, 'import holoviews as hv\n'), ((1523, 1544), 'holoviews.DynamicMap', 'hv.DynamicMap', (['cosine'], {}), '(cosine)\n', (1536, 1544), True, 'import holoviews as hv\n'), ((1640, 1659), 'holoviews.DynamicMap', 'hv.DynamicMap', (['sine'], {}), '(sine)\n', (1653, 1659), True, 'import holoviews as hv\n'), ((1696, 1717), 'holoviews.DynamicMap', 'hv.DynamicMap', (['cosine'], {}), '(cosine)\n', (1709, 1717), True, 'import holoviews as hv\n'), ((3576, 3595), 'holoviews.DynamicMap', 'hv.DynamicMap', (['sine'], {}), '(sine)\n', (3589, 3595), True, 'import holoviews as hv\n'), ((3632, 3653), 'holoviews.DynamicMap', 'hv.DynamicMap', (['cosine'], {}), '(cosine)\n', (3645, 3653), True, 'import holoviews as hv\n'), ((3749, 3768), 'holoviews.DynamicMap', 'hv.DynamicMap', (['sine'], {}), '(sine)\n', (3762, 3768), True, 'import holoviews as hv\n'), ((3805, 3826), 'holoviews.DynamicMap', 'hv.DynamicMap', (['cosine'], {}), '(cosine)\n', (3818, 3826), True, 'import holoviews as hv\n'), ((955, 980), 'numpy.sin', 'np.sin', (['(xs * freq + phase)'], {}), '(xs * freq + phase)\n', (961, 980), True, 'import numpy as np\n'), ((1120, 1145), 'numpy.cos', 'np.cos', (['(xs * freq + phase)'], {}), '(xs * freq + phase)\n', (1126, 1145), True, 'import numpy as np\n'), ((3142, 3167), 'numpy.sin', 'np.sin', (['(xs * freq + phase)'], {}), '(xs * freq + phase)\n', (3148, 3167), True, 'import numpy as np\n'), ((3307, 3332), 'numpy.cos', 'np.cos', (['(xs * freq + phase)'], {}), '(xs * freq + phase)\n', (3313, 3332), True, 'import numpy as np\n')] |
# Copyright (C) 2013 <NAME> and <NAME>
#
# This file is part of WESTPA.
#
# WESTPA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# WESTPA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with WESTPA. If not, see <http://www.gnu.org/licenses/>.
from collections import namedtuple
import numpy
trajnode = namedtuple('trajnode', ('n_iter', 'seg_id'))
from collections import deque
import westpa
from westtools.tool_classes.selected_segs import AllSegmentSelection
import _trajtree
from _trajtree import _trajtree_base #@UnresolvedImport
class TrajTreeSet(_trajtree_base):
def __init__(self, segsel = None, data_manager = None):
self.data_manager = data_manager or westpa.rc.get_data_manager()
self.segsel = segsel or AllSegmentSelection(data_manager = self.data_manager)
self._build_table(self.segsel, self.data_manager)
def __len__(self):
return len(self.trajtable)
def get_roots(self):
return self.trajtable[self.trajtable['parent_offset'] == -1]
#return [trajnode(root['n_iter'], root['seg_id']) for root in self._get_roots()]
def get_root_indices(self):
return numpy.squeeze(numpy.argwhere(self.trajtable['parent_offset'] == -1))
def trace_trajectories(self, visit, get_visitor_state = None, set_visitor_state = None, vargs=None, vkwargs=None):
if (get_visitor_state or set_visitor_state) and not (get_visitor_state and set_visitor_state):
raise ValueError('either both or neither of get_visitor_state and set_visitor_state must be specified')
vargs = vargs or ()
vkwargs = vkwargs or {}
n_visits = 0
trajtable = self.trajtable
roots = deque(self.get_root_indices())
print('Examining {:d} roots'.format(len(roots)))
state_stack = deque([{'subtrees': roots,
'vstate': get_visitor_state() if get_visitor_state else None}])
while state_stack:
state = state_stack.pop()
subtrees = state['subtrees']
if set_visitor_state:
set_visitor_state(state['vstate'])
while subtrees:
index = subtrees.popleft()
node = trajtable[index]
state_stack.append({'subtrees': subtrees,
'vstate': get_visitor_state() if get_visitor_state else None})
subtrees = deque(self.get_child_indices(index))
n_visits += 1
try:
visit(node['n_iter'], node['seg_id'], node['weight'], has_children = (len(subtrees) > 0), *vargs, **vkwargs)
except StopIteration:
subtrees = deque()
continue # to next sibling
return n_visits
class FakeTrajTreeSet(TrajTreeSet):
def __init__(self):
#_tt_dtype = numpy.dtype([('n_iter', numpy.uint32),
# ('seg_id', numpy.int64),
# ('parent_id', numpy.int64),
# ('parent_offset', numpy.int64), # offset of parent segment into this table
# ('weight', numpy.float64)]) # weight of this segment
self.trajtable = numpy.array([(1, 1,-1,-1,1.0), #0
(1,11,-1,-1,1.0), #1
(2, 2, 1, 0,1.0), #2
(2, 3, 1, 0,1.0), #3
(2, 4, 1, 0,1.0), #4
(2,12,11, 1,1.0), #5
(2,13,11, 1,1.0), #6
(3, 5, 2, 2,1.0), #7
(3, 6, 3, 3,1.0), #8
(3, 7, 4, 4,1.0), #9
(3, 8, 4, 4,1.0), #10
(3,14,12, 5,1.0), #11
(3,15,12, 5,1.0), #12
(4, 9, 5, 7,1.0), #13
(4,10, 5, 7,1.0), #14
], dtype=_trajtree._tt_dtype)
empty_array = numpy.array([])
self.childtable = numpy.array([numpy.array([2, 3, 4]), # segment 1
numpy.array([5, 6]), # segment 11
numpy.array([7]), # segment 2
numpy.array([8]), # segment 3
numpy.array([9, 10]), # segment 4
numpy.array([11, 12]), # segment 12
empty_array, # segment 13
numpy.array([13, 14]), # segment 5
empty_array, # segment 6
empty_array, # segment 7
empty_array, # segment 8
empty_array, # segment 14
empty_array, # segment 15
empty_array, # segment 9
empty_array, # segment 10
], dtype=numpy.object_)
self.iter_offsets = {1: 0,
2: 2,
3: 7,
4: 13}
| [
"westpa.rc.get_data_manager",
"westtools.tool_classes.selected_segs.AllSegmentSelection",
"numpy.array",
"collections.namedtuple",
"numpy.argwhere",
"collections.deque"
] | [((751, 795), 'collections.namedtuple', 'namedtuple', (['"""trajnode"""', "('n_iter', 'seg_id')"], {}), "('trajnode', ('n_iter', 'seg_id'))\n", (761, 795), False, 'from collections import namedtuple\n'), ((3799, 4155), 'numpy.array', 'numpy.array', (['[(1, 1, -1, -1, 1.0), (1, 11, -1, -1, 1.0), (2, 2, 1, 0, 1.0), (2, 3, 1, 0,\n 1.0), (2, 4, 1, 0, 1.0), (2, 12, 11, 1, 1.0), (2, 13, 11, 1, 1.0), (3, \n 5, 2, 2, 1.0), (3, 6, 3, 3, 1.0), (3, 7, 4, 4, 1.0), (3, 8, 4, 4, 1.0),\n (3, 14, 12, 5, 1.0), (3, 15, 12, 5, 1.0), (4, 9, 5, 7, 1.0), (4, 10, 5,\n 7, 1.0)]'], {'dtype': '_trajtree._tt_dtype'}), '([(1, 1, -1, -1, 1.0), (1, 11, -1, -1, 1.0), (2, 2, 1, 0, 1.0),\n (2, 3, 1, 0, 1.0), (2, 4, 1, 0, 1.0), (2, 12, 11, 1, 1.0), (2, 13, 11, \n 1, 1.0), (3, 5, 2, 2, 1.0), (3, 6, 3, 3, 1.0), (3, 7, 4, 4, 1.0), (3, 8,\n 4, 4, 1.0), (3, 14, 12, 5, 1.0), (3, 15, 12, 5, 1.0), (4, 9, 5, 7, 1.0),\n (4, 10, 5, 7, 1.0)], dtype=_trajtree._tt_dtype)\n', (3810, 4155), False, 'import numpy\n'), ((4755, 4770), 'numpy.array', 'numpy.array', (['[]'], {}), '([])\n', (4766, 4770), False, 'import numpy\n'), ((1126, 1154), 'westpa.rc.get_data_manager', 'westpa.rc.get_data_manager', ([], {}), '()\n', (1152, 1154), False, 'import westpa\n'), ((1187, 1238), 'westtools.tool_classes.selected_segs.AllSegmentSelection', 'AllSegmentSelection', ([], {'data_manager': 'self.data_manager'}), '(data_manager=self.data_manager)\n', (1206, 1238), False, 'from westtools.tool_classes.selected_segs import AllSegmentSelection\n'), ((1644, 1697), 'numpy.argwhere', 'numpy.argwhere', (["(self.trajtable['parent_offset'] == -1)"], {}), "(self.trajtable['parent_offset'] == -1)\n", (1658, 1697), False, 'import numpy\n'), ((4810, 4832), 'numpy.array', 'numpy.array', (['[2, 3, 4]'], {}), '([2, 3, 4])\n', (4821, 4832), False, 'import numpy\n'), ((4885, 4904), 'numpy.array', 'numpy.array', (['[5, 6]'], {}), '([5, 6])\n', (4896, 4904), False, 'import numpy\n'), ((4961, 4977), 'numpy.array', 'numpy.array', (['[7]'], {}), '([7])\n', (4972, 4977), False, 'import numpy\n'), ((5036, 5052), 'numpy.array', 'numpy.array', (['[8]'], {}), '([8])\n', (5047, 5052), False, 'import numpy\n'), ((5111, 5131), 'numpy.array', 'numpy.array', (['[9, 10]'], {}), '([9, 10])\n', (5122, 5131), False, 'import numpy\n'), ((5186, 5207), 'numpy.array', 'numpy.array', (['[11, 12]'], {}), '([11, 12])\n', (5197, 5207), False, 'import numpy\n'), ((5338, 5359), 'numpy.array', 'numpy.array', (['[13, 14]'], {}), '([13, 14])\n', (5349, 5359), False, 'import numpy\n'), ((3269, 3276), 'collections.deque', 'deque', ([], {}), '()\n', (3274, 3276), False, 'from collections import deque\n')] |
import matplotlib.pyplot as plt
import numpy as np
from maxtree.component_tree import MaxTree
from scipy import misc
img_rgb = misc.face()
img = np.uint16(img_rgb[:,:,0])
# Example 1
mt = MaxTree(img) # compute the max tree
mt.compute_shape_attributes() # compute shape attributes
cc_areas = mt.getAttributes('area') # retrieve the area of each connected components
idx_retained = np.logical_and(cc_areas>800, cc_areas<5000).nonzero()[0] # select the cc with an 800<area<5000
filtered_out = mt.filter(idx_retained) # direct filtering of the cc
plt.figure()
plt.subplot(1,3,1)
plt.imshow(img, cmap='Greys_r')
plt.title('first of rgb image')
plt.subplot(1,3,2)
plt.imshow(filtered_out, cmap='Greys_r')
plt.title('cc having an area between 800 and 5000')
ax = plt.subplot(1,3,3)
plt.hist(cc_areas, bins=12)
plt.xlabel('area in nb of pixels')
ax.set_yscale("log", nonposy='clip')
plt.show()
# Example 2
img_c = img.max() - img
mt = MaxTree(img_c) # compute max tree
lyr = np.float32(img_rgb[:,:,1]) # compute a layer
mt.compute_layer_attributes(lyr) # compute layer features per cc
print(mt)
avg_std = mt.getAttributes(['average_0','std_0']) # retrieve the layer average and std per cc
idx_retained = np.logical_and(avg_std[:,0]<100, avg_std[:,1]<30).nonzero()[0] # select the cc
filtered_out = mt.filter(idx_retained) # direct filtering
plt.figure()
plt.subplot(1,2,1)
plt.imshow(img_c, cmap='Greys_r')
plt.title('complement of image')
plt.subplot(1,2,2)
plt.imshow(filtered_out, cmap='Greys_r')
plt.title('cc having an average layer < 50 and std layer < 10')
plt.show()
# Example 3
mt.compute_shape_attributes()
cc_xmin = mt.getAttributes('xmin')
cc_xmax = mt.getAttributes('xmax')
scores = np.exp(-np.abs(cc_xmin-350)/100 -np.abs(cc_xmax-450)/100)
idx_retained = np.uint32(np.arange(mt.nb_connected_components))
filtered_out = mt.filter(idx_retained,scores)
plt.figure()
plt.subplot(1,2,1)
plt.imshow(img_c, cmap = 'Greys_r')
plt.title('complement of image')
plt.subplot(1,2,2)
plt.imshow(filtered_out, cmap = 'Greys_r')
plt.title('cc with scores')
plt.show()
| [
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"numpy.abs",
"matplotlib.pyplot.hist",
"numpy.logical_and",
"matplotlib.pyplot.imshow",
"numpy.float32",
"maxtree.component_tree.MaxTree",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.uint16",
"scipy.misc... | [((128, 139), 'scipy.misc.face', 'misc.face', ([], {}), '()\n', (137, 139), False, 'from scipy import misc\n'), ((146, 173), 'numpy.uint16', 'np.uint16', (['img_rgb[:, :, 0]'], {}), '(img_rgb[:, :, 0])\n', (155, 173), True, 'import numpy as np\n'), ((190, 202), 'maxtree.component_tree.MaxTree', 'MaxTree', (['img'], {}), '(img)\n', (197, 202), False, 'from maxtree.component_tree import MaxTree\n'), ((549, 561), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (559, 561), True, 'import matplotlib.pyplot as plt\n'), ((562, 582), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(3)', '(1)'], {}), '(1, 3, 1)\n', (573, 582), True, 'import matplotlib.pyplot as plt\n'), ((581, 612), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {'cmap': '"""Greys_r"""'}), "(img, cmap='Greys_r')\n", (591, 612), True, 'import matplotlib.pyplot as plt\n'), ((613, 644), 'matplotlib.pyplot.title', 'plt.title', (['"""first of rgb image"""'], {}), "('first of rgb image')\n", (622, 644), True, 'import matplotlib.pyplot as plt\n'), ((646, 666), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(3)', '(2)'], {}), '(1, 3, 2)\n', (657, 666), True, 'import matplotlib.pyplot as plt\n'), ((665, 705), 'matplotlib.pyplot.imshow', 'plt.imshow', (['filtered_out'], {'cmap': '"""Greys_r"""'}), "(filtered_out, cmap='Greys_r')\n", (675, 705), True, 'import matplotlib.pyplot as plt\n'), ((706, 757), 'matplotlib.pyplot.title', 'plt.title', (['"""cc having an area between 800 and 5000"""'], {}), "('cc having an area between 800 and 5000')\n", (715, 757), True, 'import matplotlib.pyplot as plt\n'), ((764, 784), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(3)', '(3)'], {}), '(1, 3, 3)\n', (775, 784), True, 'import matplotlib.pyplot as plt\n'), ((783, 810), 'matplotlib.pyplot.hist', 'plt.hist', (['cc_areas'], {'bins': '(12)'}), '(cc_areas, bins=12)\n', (791, 810), True, 'import matplotlib.pyplot as plt\n'), ((811, 845), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""area in nb of pixels"""'], {}), "('area in nb of pixels')\n", (821, 845), True, 'import matplotlib.pyplot as plt\n'), ((883, 893), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (891, 893), True, 'import matplotlib.pyplot as plt\n'), ((936, 950), 'maxtree.component_tree.MaxTree', 'MaxTree', (['img_c'], {}), '(img_c)\n', (943, 950), False, 'from maxtree.component_tree import MaxTree\n'), ((977, 1005), 'numpy.float32', 'np.float32', (['img_rgb[:, :, 1]'], {}), '(img_rgb[:, :, 1])\n', (987, 1005), True, 'import numpy as np\n'), ((1346, 1358), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1356, 1358), True, 'import matplotlib.pyplot as plt\n'), ((1359, 1379), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (1370, 1379), True, 'import matplotlib.pyplot as plt\n'), ((1378, 1411), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img_c'], {'cmap': '"""Greys_r"""'}), "(img_c, cmap='Greys_r')\n", (1388, 1411), True, 'import matplotlib.pyplot as plt\n'), ((1412, 1444), 'matplotlib.pyplot.title', 'plt.title', (['"""complement of image"""'], {}), "('complement of image')\n", (1421, 1444), True, 'import matplotlib.pyplot as plt\n'), ((1446, 1466), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (1457, 1466), True, 'import matplotlib.pyplot as plt\n'), ((1465, 1505), 'matplotlib.pyplot.imshow', 'plt.imshow', (['filtered_out'], {'cmap': '"""Greys_r"""'}), "(filtered_out, cmap='Greys_r')\n", (1475, 1505), True, 'import matplotlib.pyplot as plt\n'), ((1506, 1569), 'matplotlib.pyplot.title', 'plt.title', (['"""cc having an average layer < 50 and std layer < 10"""'], {}), "('cc having an average layer < 50 and std layer < 10')\n", (1515, 1569), True, 'import matplotlib.pyplot as plt\n'), ((1570, 1580), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1578, 1580), True, 'import matplotlib.pyplot as plt\n'), ((1873, 1885), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1883, 1885), True, 'import matplotlib.pyplot as plt\n'), ((1886, 1906), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (1897, 1906), True, 'import matplotlib.pyplot as plt\n'), ((1905, 1938), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img_c'], {'cmap': '"""Greys_r"""'}), "(img_c, cmap='Greys_r')\n", (1915, 1938), True, 'import matplotlib.pyplot as plt\n'), ((1941, 1973), 'matplotlib.pyplot.title', 'plt.title', (['"""complement of image"""'], {}), "('complement of image')\n", (1950, 1973), True, 'import matplotlib.pyplot as plt\n'), ((1975, 1995), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (1986, 1995), True, 'import matplotlib.pyplot as plt\n'), ((1994, 2034), 'matplotlib.pyplot.imshow', 'plt.imshow', (['filtered_out'], {'cmap': '"""Greys_r"""'}), "(filtered_out, cmap='Greys_r')\n", (2004, 2034), True, 'import matplotlib.pyplot as plt\n'), ((2037, 2064), 'matplotlib.pyplot.title', 'plt.title', (['"""cc with scores"""'], {}), "('cc with scores')\n", (2046, 2064), True, 'import matplotlib.pyplot as plt\n'), ((2065, 2075), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2073, 2075), True, 'import matplotlib.pyplot as plt\n'), ((1787, 1824), 'numpy.arange', 'np.arange', (['mt.nb_connected_components'], {}), '(mt.nb_connected_components)\n', (1796, 1824), True, 'import numpy as np\n'), ((384, 431), 'numpy.logical_and', 'np.logical_and', (['(cc_areas > 800)', '(cc_areas < 5000)'], {}), '(cc_areas > 800, cc_areas < 5000)\n', (398, 431), True, 'import numpy as np\n'), ((1207, 1262), 'numpy.logical_and', 'np.logical_and', (['(avg_std[:, 0] < 100)', '(avg_std[:, 1] < 30)'], {}), '(avg_std[:, 0] < 100, avg_std[:, 1] < 30)\n', (1221, 1262), True, 'import numpy as np\n'), ((1736, 1757), 'numpy.abs', 'np.abs', (['(cc_xmax - 450)'], {}), '(cc_xmax - 450)\n', (1742, 1757), True, 'import numpy as np\n'), ((1711, 1732), 'numpy.abs', 'np.abs', (['(cc_xmin - 350)'], {}), '(cc_xmin - 350)\n', (1717, 1732), True, 'import numpy as np\n')] |
from .common import *
from .callbacks import *
from typing import Any
import torch
from torch.nn import functional as F
import numpy as np
import pandas as pd
pd.options.mode.chained_assignment = None # default='warn'
class Learner():
def __init__(self, model, opt, loss_func, data, target_name:str, target_class:int, cols:list, cont_vars:list=None):
self.model,self.opt,self.loss_func,self.data,self.target_name,self.target_class,self.cols,self.cont_vars = model,opt,loss_func,data,target_name,target_class,cols,cont_vars
class Runner():
def __init__(self, cbs=None, cb_funcs=None):
self.in_train = False
cbs = listify(cbs)
for cbf in listify(cb_funcs):
cb = cbf()
setattr(self, cb.name, cb)
cbs.append(cb)
self.stop,self.cbs = False,[TrainEvalCallback()]+cbs
@property
def opt(self): return self.learn.opt
@property
def model(self): return self.learn.model
@property
def loss_func(self): return self.learn.loss_func
@property
def data(self): return self.learn.data
@property
def target_name(self): return self.learn.target_name
@property
def target_class(self): return self.learn.target_class
@property
def cols(self): return self.learn.cols
@property
def cont_vars(self): return self.learn.cont_vars
def one_batch(self, xb, _):
try:
self.xb = xb
self('begin_batch')
self.recon_batch, self.mu, self.logvar = self.model(self.xb)
self('after_pred')
self.loss = self.loss_func(self.recon_batch, self.xb, self.mu, self.logvar)
self('after_loss')
if not self.in_train: return
self.loss.backward()
self('after_backward')
self.opt.step()
self('after_step')
self.opt.zero_grad()
except CancelBatchException: self('after_cancel_batch')
finally: self('after_batch')
def all_batches(self, dl):
self.iters = len(dl)
try:
for xb,_ in dl: self.one_batch(xb, _)
except CancelEpochException: self('after_cancel_epoch')
def fit(self, epochs, learn):
self.epochs,self.learn,self.loss = epochs,learn,torch.tensor(0.)
try:
for cb in self.cbs: cb.set_runner(self)
self('begin_fit')
for epoch in range(epochs):
self.epoch = epoch
if not self('begin_epoch'): self.all_batches(self.data.train_dl)
with torch.no_grad():
if not self('begin_validate'): self.all_batches(self.data.test_dl)
self('after_epoch')
except CancelTrainException: self('after_cancel_train')
finally:
self('after_fit')
self.learn = None
def _get_embeddings(self):
self.in_train = False
with torch.no_grad():
for batch_idx, (xb,_) in enumerate(self.data.train_dl):
self.opt.zero_grad()
_, mu_, logvar_ = self.model(xb)
if batch_idx==0:
mu=mu_
logvar=logvar_
else:
mu=torch.cat((mu, mu_), dim=0)
logvar=torch.cat((logvar, logvar_), dim=0)
return mu, logvar
def predict_df(self, learn, no_samples:int, scaler=None):
self.learn = learn
mu, logvar = self._get_embeddings()
sigma = torch.exp(logvar/2)
no_samples = no_samples
q = torch.distributions.Normal(mu.mean(axis=0), sigma.mean(axis=0))
z = q.rsample(sample_shape=torch.Size([no_samples]))
with torch.no_grad():
pred = self.model.decode(z).cpu().numpy()
if self.target_name in self.cols: self.cols.remove(self.target_name)
df_fake = pd.DataFrame(pred, columns=self.cols)
if scaler:
if self.cont_vars:
df_fake[self.cont_vars]=scaler.inverse_transform(df_fake[self.cont_vars])
else:
df_fake=pd.DataFrame(scaler.inverse_transform(df_fake), columns=self.cols)
df_fake[self.target_name]=self.target_class
return df_fake
def predict_with_noise_df(self, learn, no_samples:int, mu:float, sigma:float, group_var:str=None, scaler=None):
self.learn = learn
df_fake_with_noise = self.predict_df(learn, no_samples, scaler=scaler)
if group_var:
np_matrix = df_fake_with_noise[self.cols].loc[:,df_fake_with_noise[self.cols].columns!=group_var].values
np_matrix = np.array([val*(1+np.random.normal(mu, sigma, 1)) for sublist in np_matrix for val in sublist]).reshape(-1,np_matrix.shape[1])
df_fake_with_noise[self.cols].loc[:,df_fake_with_noise[self.cols].columns!=group_var] = np_matrix
else:
np_matrix = df_fake_with_noise[self.cols].values
np_matrix = np.array([val*(1+np.random.normal(mu, sigma, 1)) for sublist in np_matrix for val in sublist]).reshape(-1,np_matrix.shape[1])
df_fake_with_noise[self.cols].loc[:,:] = np_matrix
return df_fake_with_noise
def __call__(self, cb_name):
res = False
for cb in sorted(self.cbs, key=lambda x: x._order): res = cb(cb_name) or res
return res | [
"pandas.DataFrame",
"torch.cat",
"torch.exp",
"torch.Size",
"numpy.random.normal",
"torch.no_grad",
"torch.tensor"
] | [((3563, 3584), 'torch.exp', 'torch.exp', (['(logvar / 2)'], {}), '(logvar / 2)\n', (3572, 3584), False, 'import torch\n'), ((3933, 3970), 'pandas.DataFrame', 'pd.DataFrame', (['pred'], {'columns': 'self.cols'}), '(pred, columns=self.cols)\n', (3945, 3970), True, 'import pandas as pd\n'), ((2336, 2353), 'torch.tensor', 'torch.tensor', (['(0.0)'], {}), '(0.0)\n', (2348, 2353), False, 'import torch\n'), ((2984, 2999), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2997, 2999), False, 'import torch\n'), ((3766, 3781), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3779, 3781), False, 'import torch\n'), ((3726, 3750), 'torch.Size', 'torch.Size', (['[no_samples]'], {}), '([no_samples])\n', (3736, 3750), False, 'import torch\n'), ((2627, 2642), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2640, 2642), False, 'import torch\n'), ((3295, 3322), 'torch.cat', 'torch.cat', (['(mu, mu_)'], {'dim': '(0)'}), '((mu, mu_), dim=0)\n', (3304, 3322), False, 'import torch\n'), ((3350, 3385), 'torch.cat', 'torch.cat', (['(logvar, logvar_)'], {'dim': '(0)'}), '((logvar, logvar_), dim=0)\n', (3359, 3385), False, 'import torch\n'), ((4710, 4740), 'numpy.random.normal', 'np.random.normal', (['mu', 'sigma', '(1)'], {}), '(mu, sigma, 1)\n', (4726, 4740), True, 'import numpy as np\n'), ((5045, 5075), 'numpy.random.normal', 'np.random.normal', (['mu', 'sigma', '(1)'], {}), '(mu, sigma, 1)\n', (5061, 5075), True, 'import numpy as np\n')] |
import os
import math
import numpy as np
import tensorflow as tf
from copy import deepcopy
from sklearn.model_selection import train_test_split
from Function.InnerFunction.model_function import load_share, save_share, load_train_data
from Function.InnerFunction.get_valid_tag_function import get_valid_tag
from Function.InnerFunction.kor2eng_function import kor2eng
current_dir_path = os.path.dirname(os.path.realpath(__file__))
class EngCharCNNWithLSTM:
def __init__(self, scope, setting, is_train=False):
self.__load_setting(scope, setting, is_train)
self.__graph = tf.Graph()
if self.__is_train:
input_data, output_data = load_train_data(self.__scope)
train_questions, test_questions, train_answers, test_answers = train_test_split(input_data, output_data, test_size=0.2)
self.__train_data = [{"question": q, "answer": a} for q, a in zip(train_questions, train_answers)]
self.__test_data = [{"question": q, "answer": a} for q, a in zip(test_questions, test_answers)]
self.__create_share(input_data, output_data)
for i in range(self.__setting["max_batch_size"], 0, -1):
if len(self.__train_data) % i == 0:
self.__setting["batch_size"] = i
break
else:
self.__setting["batch_size"] = 1
self.__share = load_share(self.__scope)
if self.__share:
self.__setting["char_num"] = len(self.__share["idx2char"])
self.__setting["label_num"] = len(self.__share["idx2label"])
if self.__model_exist():
self.__build_model()
if self.__is_train:
save_share(self.__scope, self.__share)
self.__session.run(self.__init)
else:
self.__load_model()
def __load_setting(self, scope, setting, is_train):
self.__scope = scope
self.__eng_scope = kor2eng(self.__scope)
self.__is_train = is_train
self.__setting = setting
self.__save_directory = os.path.join(current_dir_path, "..", "save", self.__eng_scope)
self.__model_path = os.path.join(self.__save_directory, self.__eng_scope + ".ckpt")
self.__share = load_share(self.__scope)
def __model_exist(self):
if self.__is_train:
if self.__share:
return True
else:
return False
else:
if self.__share and os.path.exists(self.__save_directory):
return True
else:
return False
def __create_share(self, input_data, output_data):
if input_data and output_data:
self.__share = dict()
self.__share["idx2char"], self.__share["idx2label"] = ["NULL", "UNKNOWN"], list()
for input_data, output_data in zip(input_data, output_data):
for word in input_data:
eng_word = kor2eng(word)
for char in eng_word:
if char not in self.__share["idx2char"]:
self.__share["idx2char"].append(char)
if output_data not in self.__share["idx2label"]:
self.__share["idx2label"].extend(output_data)
self.__setting["char_num"] = len(self.__share["idx2char"])
self.__setting["label_num"] = len(self.__share["idx2label"])
else:
self.__share = None
def __save_model(self):
self.__saver.save(self.__session, self.__model_path)
def __load_model(self):
if self.__model_exist():
self.__saver.restore(self.__session, self.__model_path)
def __build_model(self):
with self.__graph.as_default():
with tf.variable_scope(name_or_scope=self.__eng_scope, reuse=tf.AUTO_REUSE):
self.__create_placeholder()
self.__create_model()
if self.__is_train:
self.__create_loss_placeholder()
self.__create_loss()
self.__init = tf.global_variables_initializer()
self.__saver = tf.train.Saver()
self.__session = tf.Session(graph=self.__graph)
def __create_placeholder(self):
self.__original_sequence_in_char = tf.placeholder(name="original_sequence_in_char", dtype=tf.int64, shape=(self.__setting["batch_size"], self.__setting["max_sentence_len"], self.__setting["max_word_len"]))
self.__original_sequence_lengths = tf.placeholder(name="original_sequence_lengths", dtype=tf.int64, shape=(self.__setting["batch_size"], ))
def __create_model(self):
with tf.variable_scope(name_or_scope="charCNN_layer", reuse=tf.AUTO_REUSE):
with tf.variable_scope(name_or_scope="embedding", reuse=tf.AUTO_REUSE):
char_embedding_matrix = tf.get_variable(name="char_embedding_matrix", dtype=tf.float64, shape=(self.__setting["char_num"], self.__setting["char_dim"]))
char2vec_input_data = tf.nn.embedding_lookup(char_embedding_matrix, self.__original_sequence_in_char)
with tf.variable_scope(name_or_scope="CNN", reuse=tf.AUTO_REUSE):
CNN_filter = tf.get_variable(name="CNN_filter1", dtype=tf.float64, shape=(1, self.__setting["CNN_window"], self.__setting["char_dim"], self.__setting["CNN_output_dim"]))
CNN_output = tf.nn.conv2d(name="charCNN1", input=char2vec_input_data, filter=CNN_filter, strides=(1, 1, 1, 1), padding="SAME")
for i in range(1, self.__setting["CNN_layer_num"]):
CNN_filter = tf.get_variable(name="CNN_filter" + str(i + 1), dtype=tf.float64, shape=(1, self.__setting["CNN_window"], self.__setting["CNN_output_dim"], self.__setting["CNN_output_dim"]))
CNN_output = tf.nn.conv2d(name="charCNN" + str(i + 1), input=CNN_output, filter=CNN_filter, strides=(1, 1, 1, 1), padding="SAME")
CNN_output = tf.reduce_mean(CNN_output, axis=2)
with tf.variable_scope(name_or_scope="RNN_layer", reuse=tf.AUTO_REUSE):
with tf.variable_scope(name_or_scope="LSTM_encoding", reuse=tf.AUTO_REUSE):
cell = tf.nn.rnn_cell.BasicLSTMCell(name="cell1", num_units=self.__setting["LSTM_output_dim"])
RNN_output, state = tf.nn.dynamic_rnn(cell=cell, inputs=CNN_output, sequence_length=self.__original_sequence_lengths, initial_state=cell.zero_state(batch_size=self.__setting["batch_size"], dtype=tf.float64))
for i in range(1, self.__setting["RNN_layer_num"]):
cell = tf.nn.rnn_cell.BasicLSTMCell(name="cell" + str(i + 1), num_units=self.__setting["LSTM_output_dim"])
RNN_output, state = tf.nn.dynamic_rnn(cell=cell, inputs=CNN_output, sequence_length=self.__original_sequence_lengths, initial_state=cell.zero_state(batch_size=self.__setting["batch_size"], dtype=tf.float64))
with tf.variable_scope(name_or_scope="Fully_connected_layer", reuse=tf.AUTO_REUSE):
splited = [tf.squeeze(x, axis=0) for x in tf.split(value=RNN_output, num_or_size_splits=self.__setting["batch_size"], axis=0)]
W = tf.get_variable(name="W", dtype=tf.float64, shape=(self.__setting["label_num"], self.__setting["LSTM_output_dim"]))
b = tf.get_variable(name="b", dtype=tf.float64, shape=(self.__setting["max_sentence_len"], self.__setting["label_num"]))
fully_connected_output = list()
for val in splited:
result = tf.matmul(val, W, transpose_b=True) + b
fully_connected_output.append(tf.expand_dims(result, axis=0))
fully_connected_output = tf.concat(fully_connected_output, axis=0)
output = tf.reduce_max(fully_connected_output, axis=1)
self.__output = tf.nn.softmax(output, axis=1)
def __create_loss_placeholder(self):
self.__labels = tf.placeholder(name="labels", dtype=tf.float64, shape=(self.__setting["batch_size"], self.__setting["label_num"]))
def __create_loss(self):
with tf.variable_scope(name_or_scope="loss_layer", reuse=tf.AUTO_REUSE):
self.__loss = tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.__labels, logits=self.__output)
train_function = tf.train.AdagradOptimizer(self.__setting["learning_rate"])
self.__train_op = train_function.minimize(self.__loss)
def run(self, msg=None):
if self.__is_train:
feed_dict_base = {
self.__original_sequence_in_char.name: np.zeros(dtype=np.int64, shape=(self.__setting["batch_size"], self.__setting["max_sentence_len"], self.__setting["max_word_len"])),
self.__original_sequence_lengths.name: np.zeros(dtype=np.int64, shape=(self.__setting["batch_size"], )),
self.__labels.name: np.zeros(dtype=np.float64, shape=(self.__setting["batch_size"], self.__setting["label_num"]))
}
train_steps = math.ceil(len(self.__train_data) / self.__setting["batch_size"])
train_feed_dicts = [deepcopy(feed_dict_base) for i in range(train_steps)]
for step_idx in range(train_steps):
for batch_idx in range(min(self.__setting["batch_size"], len(self.__train_data[self.__setting["batch_size"] * step_idx:]))):
for word_idx in range(len(self.__train_data[self.__setting["batch_size"] * step_idx + batch_idx]["question"])):
char_word = kor2eng(self.__train_data[self.__setting["batch_size"] * step_idx + batch_idx]["question"][word_idx])
for char_idx in range(len(char_word)):
if char_word[char_idx] in self.__share["idx2char"]:
train_feed_dicts[step_idx][self.__original_sequence_in_char.name][batch_idx][word_idx][char_idx] = self.__share["idx2char"].index(char_word[char_idx])
else:
train_feed_dicts[step_idx][self.__original_sequence_in_char.name][batch_idx][word_idx][char_idx] = self.__share["idx2char"].index("UNKNOWN")
train_feed_dicts[step_idx][self.__original_sequence_lengths.name][batch_idx] = len(self.__train_data[self.__setting["batch_size"] * step_idx + batch_idx]["question"])
for answer_idx in range(len(self.__train_data[self.__setting["batch_size"] * step_idx + batch_idx]["answer"])):
train_feed_dicts[step_idx][self.__labels.name][batch_idx][self.__share["idx2label"].index(self.__train_data[self.__setting["batch_size"] * step_idx + batch_idx]["answer"][answer_idx])] = 1 / len(self.__train_data[self.__setting["batch_size"] * step_idx + batch_idx]["answer"])
test_steps = math.ceil(len(self.__test_data) / self.__setting["batch_size"])
test_feed_dicts = [deepcopy(feed_dict_base) for i in range(test_steps)]
for step_idx in range(test_steps):
for batch_idx in range(min(self.__setting["batch_size"], len(self.__test_data[self.__setting["batch_size"] * step_idx:]))):
for word_idx in range(len(self.__test_data[self.__setting["batch_size"] * step_idx + batch_idx]["question"])):
char_word = kor2eng(self.__test_data[self.__setting["batch_size"] * step_idx + batch_idx]["question"][word_idx])
for char_idx in range(len(char_word)):
if char_word[char_idx] in self.__share["idx2char"]:
test_feed_dicts[step_idx][self.__original_sequence_in_char.name][batch_idx][word_idx][char_idx] = self.__share["idx2char"].index(char_word[char_idx])
else:
test_feed_dicts[step_idx][self.__original_sequence_in_char.name][batch_idx][word_idx][char_idx] = self.__share["idx2char"].index("UNKNOWN")
test_feed_dicts[step_idx][self.__original_sequence_lengths.name][batch_idx] = len(self.__test_data[self.__setting["batch_size"] * step_idx + batch_idx]["question"])
for answer_idx in range(len(self.__test_data[self.__setting["batch_size"] * step_idx + batch_idx]["answer"])):
test_feed_dicts[step_idx][self.__labels.name][batch_idx][self.__share["idx2label"].index(self.__test_data[self.__setting["batch_size"] * step_idx + batch_idx]["answer"][answer_idx])] = 1 / len(self.__test_data[self.__setting["batch_size"] * step_idx + batch_idx]["answer"])
for epoch in range(self.__setting["epoch"]):
losses = list()
for feed_dict in train_feed_dicts:
local_loss, _ = self.__session.run([self.__loss, self.__train_op], feed_dict=feed_dict)
local_loss = sum(local_loss.tolist()) / self.__setting["batch_size"]
losses.append(local_loss)
print("EPOCH :", epoch + 1, "/ LOSS :", sum(losses) / len(losses))
outputs = list()
for feed_dict in test_feed_dicts:
output = self.__session.run(self.__output, feed_dict=feed_dict)
outputs.extend(output.tolist())
outputs = np.array(outputs)
results = np.argmax(outputs, axis=1).tolist()
results = [self.__share["idx2label"][idx] for idx in results]
correct = 0
for predict_answer, test_doc in zip(results, self.__test_data):
if predict_answer == test_doc["answer"]:
correct += 1
self.__save_model()
return {"total_num": len(self.__test_data), "correct_num": correct}
else:
tokenize_msg = get_valid_tag(msg)
feed_dict = {
self.__original_sequence_in_char.name: np.zeros(dtype=np.int64, shape=(self.__setting["batch_size"], self.__setting["max_sentence_len"], self.__setting["max_word_len"])),
self.__original_sequence_lengths.name: np.zeros(dtype=np.int64, shape=(self.__setting["batch_size"],))
}
feed_dict[self.__original_sequence_lengths.name][0] = len(tokenize_msg)
for word_idx in range(len(tokenize_msg)):
char_word = kor2eng(tokenize_msg[word_idx])
for char_idx in range(len(char_word)):
if char_word[char_idx] in self.__share["idx2char"]:
feed_dict[self.__original_sequence_in_char.name][0][word_idx][char_idx] = self.__share["idx2char"].index(char_word[char_idx])
else:
feed_dict[self.__original_sequence_in_char.name][0][word_idx][char_idx] = self.__share["idx2char"].index("UNKNOWN")
output = self.__session.run(self.__output, feed_dict=feed_dict)
result = output.tolist()[0]
result = [{"answer": label, "val": val} for label, val in zip(self.__share["idx2label"], result)]
result.sort(key=lambda x: x["val"], reverse=True)
return result
| [
"numpy.argmax",
"sklearn.model_selection.train_test_split",
"tensorflow.matmul",
"tensorflow.nn.conv2d",
"tensorflow.reduce_max",
"tensorflow.split",
"os.path.join",
"tensorflow.get_variable",
"tensorflow.nn.softmax",
"Function.InnerFunction.get_valid_tag_function.get_valid_tag",
"os.path.exists... | [((403, 429), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (419, 429), False, 'import os\n'), ((592, 602), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (600, 602), True, 'import tensorflow as tf\n'), ((1950, 1971), 'Function.InnerFunction.kor2eng_function.kor2eng', 'kor2eng', (['self.__scope'], {}), '(self.__scope)\n', (1957, 1971), False, 'from Function.InnerFunction.kor2eng_function import kor2eng\n'), ((2072, 2134), 'os.path.join', 'os.path.join', (['current_dir_path', '""".."""', '"""save"""', 'self.__eng_scope'], {}), "(current_dir_path, '..', 'save', self.__eng_scope)\n", (2084, 2134), False, 'import os\n'), ((2163, 2226), 'os.path.join', 'os.path.join', (['self.__save_directory', "(self.__eng_scope + '.ckpt')"], {}), "(self.__save_directory, self.__eng_scope + '.ckpt')\n", (2175, 2226), False, 'import os\n'), ((2250, 2274), 'Function.InnerFunction.model_function.load_share', 'load_share', (['self.__scope'], {}), '(self.__scope)\n', (2260, 2274), False, 'from Function.InnerFunction.model_function import load_share, save_share, load_train_data\n'), ((4195, 4225), 'tensorflow.Session', 'tf.Session', ([], {'graph': 'self.__graph'}), '(graph=self.__graph)\n', (4205, 4225), True, 'import tensorflow as tf\n'), ((4306, 4486), 'tensorflow.placeholder', 'tf.placeholder', ([], {'name': '"""original_sequence_in_char"""', 'dtype': 'tf.int64', 'shape': "(self.__setting['batch_size'], self.__setting['max_sentence_len'], self.\n __setting['max_word_len'])"}), "(name='original_sequence_in_char', dtype=tf.int64, shape=(\n self.__setting['batch_size'], self.__setting['max_sentence_len'], self.\n __setting['max_word_len']))\n", (4320, 4486), True, 'import tensorflow as tf\n'), ((4520, 4628), 'tensorflow.placeholder', 'tf.placeholder', ([], {'name': '"""original_sequence_lengths"""', 'dtype': 'tf.int64', 'shape': "(self.__setting['batch_size'],)"}), "(name='original_sequence_lengths', dtype=tf.int64, shape=(\n self.__setting['batch_size'],))\n", (4534, 4628), True, 'import tensorflow as tf\n'), ((7748, 7793), 'tensorflow.reduce_max', 'tf.reduce_max', (['fully_connected_output'], {'axis': '(1)'}), '(fully_connected_output, axis=1)\n', (7761, 7793), True, 'import tensorflow as tf\n'), ((7818, 7847), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['output'], {'axis': '(1)'}), '(output, axis=1)\n', (7831, 7847), True, 'import tensorflow as tf\n'), ((7914, 8033), 'tensorflow.placeholder', 'tf.placeholder', ([], {'name': '"""labels"""', 'dtype': 'tf.float64', 'shape': "(self.__setting['batch_size'], self.__setting['label_num'])"}), "(name='labels', dtype=tf.float64, shape=(self.__setting[\n 'batch_size'], self.__setting['label_num']))\n", (7928, 8033), True, 'import tensorflow as tf\n'), ((670, 699), 'Function.InnerFunction.model_function.load_train_data', 'load_train_data', (['self.__scope'], {}), '(self.__scope)\n', (685, 699), False, 'from Function.InnerFunction.model_function import load_share, save_share, load_train_data\n'), ((775, 831), 'sklearn.model_selection.train_test_split', 'train_test_split', (['input_data', 'output_data'], {'test_size': '(0.2)'}), '(input_data, output_data, test_size=0.2)\n', (791, 831), False, 'from sklearn.model_selection import train_test_split\n'), ((1394, 1418), 'Function.InnerFunction.model_function.load_share', 'load_share', (['self.__scope'], {}), '(self.__scope)\n', (1404, 1418), False, 'from Function.InnerFunction.model_function import load_share, save_share, load_train_data\n'), ((1708, 1746), 'Function.InnerFunction.model_function.save_share', 'save_share', (['self.__scope', 'self.__share'], {}), '(self.__scope, self.__share)\n', (1718, 1746), False, 'from Function.InnerFunction.model_function import load_share, save_share, load_train_data\n'), ((4091, 4124), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (4122, 4124), True, 'import tensorflow as tf\n'), ((4152, 4168), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (4166, 4168), True, 'import tensorflow as tf\n'), ((4669, 4738), 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': '"""charCNN_layer"""', 'reuse': 'tf.AUTO_REUSE'}), "(name_or_scope='charCNN_layer', reuse=tf.AUTO_REUSE)\n", (4686, 4738), True, 'import tensorflow as tf\n'), ((6022, 6087), 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': '"""RNN_layer"""', 'reuse': 'tf.AUTO_REUSE'}), "(name_or_scope='RNN_layer', reuse=tf.AUTO_REUSE)\n", (6039, 6087), True, 'import tensorflow as tf\n'), ((6949, 7026), 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': '"""Fully_connected_layer"""', 'reuse': 'tf.AUTO_REUSE'}), "(name_or_scope='Fully_connected_layer', reuse=tf.AUTO_REUSE)\n", (6966, 7026), True, 'import tensorflow as tf\n'), ((7183, 7303), 'tensorflow.get_variable', 'tf.get_variable', ([], {'name': '"""W"""', 'dtype': 'tf.float64', 'shape': "(self.__setting['label_num'], self.__setting['LSTM_output_dim'])"}), "(name='W', dtype=tf.float64, shape=(self.__setting[\n 'label_num'], self.__setting['LSTM_output_dim']))\n", (7198, 7303), True, 'import tensorflow as tf\n'), ((7315, 7436), 'tensorflow.get_variable', 'tf.get_variable', ([], {'name': '"""b"""', 'dtype': 'tf.float64', 'shape': "(self.__setting['max_sentence_len'], self.__setting['label_num'])"}), "(name='b', dtype=tf.float64, shape=(self.__setting[\n 'max_sentence_len'], self.__setting['label_num']))\n", (7330, 7436), True, 'import tensorflow as tf\n'), ((7688, 7729), 'tensorflow.concat', 'tf.concat', (['fully_connected_output'], {'axis': '(0)'}), '(fully_connected_output, axis=0)\n', (7697, 7729), True, 'import tensorflow as tf\n'), ((8072, 8138), 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': '"""loss_layer"""', 'reuse': 'tf.AUTO_REUSE'}), "(name_or_scope='loss_layer', reuse=tf.AUTO_REUSE)\n", (8089, 8138), True, 'import tensorflow as tf\n'), ((8166, 8257), 'tensorflow.nn.softmax_cross_entropy_with_logits_v2', 'tf.nn.softmax_cross_entropy_with_logits_v2', ([], {'labels': 'self.__labels', 'logits': 'self.__output'}), '(labels=self.__labels, logits=\n self.__output)\n', (8208, 8257), True, 'import tensorflow as tf\n'), ((8282, 8340), 'tensorflow.train.AdagradOptimizer', 'tf.train.AdagradOptimizer', (["self.__setting['learning_rate']"], {}), "(self.__setting['learning_rate'])\n", (8307, 8340), True, 'import tensorflow as tf\n'), ((13208, 13225), 'numpy.array', 'np.array', (['outputs'], {}), '(outputs)\n', (13216, 13225), True, 'import numpy as np\n'), ((13704, 13722), 'Function.InnerFunction.get_valid_tag_function.get_valid_tag', 'get_valid_tag', (['msg'], {}), '(msg)\n', (13717, 13722), False, 'from Function.InnerFunction.get_valid_tag_function import get_valid_tag\n'), ((2483, 2520), 'os.path.exists', 'os.path.exists', (['self.__save_directory'], {}), '(self.__save_directory)\n', (2497, 2520), False, 'import os\n'), ((3781, 3851), 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': 'self.__eng_scope', 'reuse': 'tf.AUTO_REUSE'}), '(name_or_scope=self.__eng_scope, reuse=tf.AUTO_REUSE)\n', (3798, 3851), True, 'import tensorflow as tf\n'), ((4757, 4822), 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': '"""embedding"""', 'reuse': 'tf.AUTO_REUSE'}), "(name_or_scope='embedding', reuse=tf.AUTO_REUSE)\n", (4774, 4822), True, 'import tensorflow as tf\n'), ((4864, 4996), 'tensorflow.get_variable', 'tf.get_variable', ([], {'name': '"""char_embedding_matrix"""', 'dtype': 'tf.float64', 'shape': "(self.__setting['char_num'], self.__setting['char_dim'])"}), "(name='char_embedding_matrix', dtype=tf.float64, shape=(self\n .__setting['char_num'], self.__setting['char_dim']))\n", (4879, 4996), True, 'import tensorflow as tf\n'), ((5030, 5109), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['char_embedding_matrix', 'self.__original_sequence_in_char'], {}), '(char_embedding_matrix, self.__original_sequence_in_char)\n', (5052, 5109), True, 'import tensorflow as tf\n'), ((5128, 5187), 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': '"""CNN"""', 'reuse': 'tf.AUTO_REUSE'}), "(name_or_scope='CNN', reuse=tf.AUTO_REUSE)\n", (5145, 5187), True, 'import tensorflow as tf\n'), ((5218, 5384), 'tensorflow.get_variable', 'tf.get_variable', ([], {'name': '"""CNN_filter1"""', 'dtype': 'tf.float64', 'shape': "(1, self.__setting['CNN_window'], self.__setting['char_dim'], self.\n __setting['CNN_output_dim'])"}), "(name='CNN_filter1', dtype=tf.float64, shape=(1, self.\n __setting['CNN_window'], self.__setting['char_dim'], self.__setting[\n 'CNN_output_dim']))\n", (5233, 5384), True, 'import tensorflow as tf\n'), ((5404, 5521), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', ([], {'name': '"""charCNN1"""', 'input': 'char2vec_input_data', 'filter': 'CNN_filter', 'strides': '(1, 1, 1, 1)', 'padding': '"""SAME"""'}), "(name='charCNN1', input=char2vec_input_data, filter=CNN_filter,\n strides=(1, 1, 1, 1), padding='SAME')\n", (5416, 5521), True, 'import tensorflow as tf\n'), ((5973, 6007), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['CNN_output'], {'axis': '(2)'}), '(CNN_output, axis=2)\n', (5987, 6007), True, 'import tensorflow as tf\n'), ((6106, 6175), 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': '"""LSTM_encoding"""', 'reuse': 'tf.AUTO_REUSE'}), "(name_or_scope='LSTM_encoding', reuse=tf.AUTO_REUSE)\n", (6123, 6175), True, 'import tensorflow as tf\n'), ((6200, 6292), 'tensorflow.nn.rnn_cell.BasicLSTMCell', 'tf.nn.rnn_cell.BasicLSTMCell', ([], {'name': '"""cell1"""', 'num_units': "self.__setting['LSTM_output_dim']"}), "(name='cell1', num_units=self.__setting[\n 'LSTM_output_dim'])\n", (6228, 6292), True, 'import tensorflow as tf\n'), ((7051, 7072), 'tensorflow.squeeze', 'tf.squeeze', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (7061, 7072), True, 'import tensorflow as tf\n'), ((8552, 8687), 'numpy.zeros', 'np.zeros', ([], {'dtype': 'np.int64', 'shape': "(self.__setting['batch_size'], self.__setting['max_sentence_len'], self.\n __setting['max_word_len'])"}), "(dtype=np.int64, shape=(self.__setting['batch_size'], self.\n __setting['max_sentence_len'], self.__setting['max_word_len']))\n", (8560, 8687), True, 'import numpy as np\n'), ((8739, 8802), 'numpy.zeros', 'np.zeros', ([], {'dtype': 'np.int64', 'shape': "(self.__setting['batch_size'],)"}), "(dtype=np.int64, shape=(self.__setting['batch_size'],))\n", (8747, 8802), True, 'import numpy as np\n'), ((8841, 8939), 'numpy.zeros', 'np.zeros', ([], {'dtype': 'np.float64', 'shape': "(self.__setting['batch_size'], self.__setting['label_num'])"}), "(dtype=np.float64, shape=(self.__setting['batch_size'], self.\n __setting['label_num']))\n", (8849, 8939), True, 'import numpy as np\n'), ((9074, 9098), 'copy.deepcopy', 'deepcopy', (['feed_dict_base'], {}), '(feed_dict_base)\n', (9082, 9098), False, 'from copy import deepcopy\n'), ((10862, 10886), 'copy.deepcopy', 'deepcopy', (['feed_dict_base'], {}), '(feed_dict_base)\n', (10870, 10886), False, 'from copy import deepcopy\n'), ((13805, 13940), 'numpy.zeros', 'np.zeros', ([], {'dtype': 'np.int64', 'shape': "(self.__setting['batch_size'], self.__setting['max_sentence_len'], self.\n __setting['max_word_len'])"}), "(dtype=np.int64, shape=(self.__setting['batch_size'], self.\n __setting['max_sentence_len'], self.__setting['max_word_len']))\n", (13813, 13940), True, 'import numpy as np\n'), ((13992, 14055), 'numpy.zeros', 'np.zeros', ([], {'dtype': 'np.int64', 'shape': "(self.__setting['batch_size'],)"}), "(dtype=np.int64, shape=(self.__setting['batch_size'],))\n", (14000, 14055), True, 'import numpy as np\n'), ((14236, 14267), 'Function.InnerFunction.kor2eng_function.kor2eng', 'kor2eng', (['tokenize_msg[word_idx]'], {}), '(tokenize_msg[word_idx])\n', (14243, 14267), False, 'from Function.InnerFunction.kor2eng_function import kor2eng\n'), ((2964, 2977), 'Function.InnerFunction.kor2eng_function.kor2eng', 'kor2eng', (['word'], {}), '(word)\n', (2971, 2977), False, 'from Function.InnerFunction.kor2eng_function import kor2eng\n'), ((7082, 7169), 'tensorflow.split', 'tf.split', ([], {'value': 'RNN_output', 'num_or_size_splits': "self.__setting['batch_size']", 'axis': '(0)'}), "(value=RNN_output, num_or_size_splits=self.__setting['batch_size'],\n axis=0)\n", (7090, 7169), True, 'import tensorflow as tf\n'), ((7533, 7568), 'tensorflow.matmul', 'tf.matmul', (['val', 'W'], {'transpose_b': '(True)'}), '(val, W, transpose_b=True)\n', (7542, 7568), True, 'import tensorflow as tf\n'), ((7619, 7649), 'tensorflow.expand_dims', 'tf.expand_dims', (['result'], {'axis': '(0)'}), '(result, axis=0)\n', (7633, 7649), True, 'import tensorflow as tf\n'), ((13248, 13274), 'numpy.argmax', 'np.argmax', (['outputs'], {'axis': '(1)'}), '(outputs, axis=1)\n', (13257, 13274), True, 'import numpy as np\n'), ((9485, 9590), 'Function.InnerFunction.kor2eng_function.kor2eng', 'kor2eng', (["self.__train_data[self.__setting['batch_size'] * step_idx + batch_idx][\n 'question'][word_idx]"], {}), "(self.__train_data[self.__setting['batch_size'] * step_idx +\n batch_idx]['question'][word_idx])\n", (9492, 9590), False, 'from Function.InnerFunction.kor2eng_function import kor2eng\n'), ((11269, 11373), 'Function.InnerFunction.kor2eng_function.kor2eng', 'kor2eng', (["self.__test_data[self.__setting['batch_size'] * step_idx + batch_idx][\n 'question'][word_idx]"], {}), "(self.__test_data[self.__setting['batch_size'] * step_idx +\n batch_idx]['question'][word_idx])\n", (11276, 11373), False, 'from Function.InnerFunction.kor2eng_function import kor2eng\n')] |
import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict
# 부모 클래스 - 자식 클래스가 가질 공통적인 속성, 메소드 선언
class Optimizer :
def __init__(self, point, iter_num, small_lr, proper_lr, large_lr):
'''
초기화
:param point: 현재 위치 : numpy array
:param iter_num: 최적화 횟수 : int
:param small_lr: 학습률1 : float
:param proper_lr: 학습률2 : float
:param large_lr: 학습률3 : float
'''
self.dict_point = defaultdict(lambda: np.array(point)) # 학습률별로 현재 점의 위치를 저장 - 딕셔너리 기본값 설정
self.dict_trace = defaultdict(lambda: {'x': [point[0]], 'y': [point[1]]}) # 점의 궤적 저장
self.iter_num = iter_num
self.lr_tup = (large_lr, proper_lr, small_lr) # 학습률 튜플
def grad(self, point):
'''
f(x,y) = (x**2)/20 + y**2 함수의 기울기를 반환하는 함수
:param x: 점의 위치 : numpy array
:return: 점의 위치에서의 기울기 : numpy array
'''
return np.array([1 / 10, 2]) * point
def method(self, point, lr):
'''
최적화 방법
:param point: 점의 위치 : numpy array
:param lr: 학습률 : float
:return: 점의 위치 : numpy array
'''
pass
def optimize(self):
'''
최적화 실행
:return: -
'''
for i in range(self.iter_num): # 설정한 최적화 횟수만큼 수행
for lr in self.lr_tup: # 학습률 리스트에 속한 학습률별로 최적화 수행, 과정 저장
self.dict_point[lr] = self.method(self.dict_point[lr], lr) # 점 위치 갱신
self.dict_trace[lr]['x'].append(self.dict_point[lr][0]) # 점의 궤적 저장
self.dict_trace[lr]['y'].append(self.dict_point[lr][1])
# 최적화 방법을 클래스로 선언, Optimizer 클래스 상속
class SGD(Optimizer):
'''
경사감소법
'''
def __init__(self, point, iter_num, small_lr, proper_lr, large_lr):
super().__init__(point, iter_num, small_lr, proper_lr, large_lr)
def method(self, point, lr):
'''
경사감소법 - 현재 점의 위치에서 학습률 * 미분만큼 이동
:param point: 점의 위치 : numpy array
:param lr: 학습률 : float
:return: 새로운 점의 위치 : numpy array
'''
return point - lr * self.grad(point)
class Momentum(Optimizer):
'''
모멘텀
'''
def __init__(self, point, iter_num, small_lr, proper_lr, large_lr):
super().__init__(point, iter_num, small_lr, proper_lr, large_lr)
self.dict_v = defaultdict(lambda : np.zeros_like(point)) # 학습률별로 이전 모멘텀을 유지하기 위한 딕셔너리
self.alpha = .9 # 모멘텀의 유지비율
def method(self, point, lr):
'''
모멘텀 - 모멘텀을 학습률 * 미분만큼 가속하고 모멘텀만큼 이동.
:param point: 점의 위치 : numpy array
:param lr: 학습률 : flaot
:return: 갱신된 점의 위치 : numpy array
'''
self.dict_v[lr] *= self.alpha
self.dict_v[lr] -= lr * self.grad(point)
return point + self.dict_v[lr]
class AdaGrad(Optimizer):
'''
AdaGrad
'''
def __init__(self, point, iter_num, small_lr, proper_lr, large_lr):
super().__init__(point, iter_num, small_lr, proper_lr, large_lr)
self.dict_h = defaultdict(lambda : np.zeros_like(point)) # 학습률을 조정할 변수 h 를 담음
self.epsilon = 1e-8
def method(self, point, lr):
'''
AdaGrad - 점의 이동 방향별로 학습률을 조절함
:param point: 점의 위치 : numpy array
:param lr: 학습률 : float
:return: 갱신된 점의 위치 : numpy array
'''
gradient = self.grad(point)
self.dict_h[lr] += gradient ** 2 # 현재 점에서의 미분의 각 원소별 제곱에 해당하는 값을 저장
return point - lr * (1/np.sqrt(self.dict_h[lr] + self.epsilon)) * gradient # 학습률에 h**(-0.5) 를 곱해 학습률을 감소시킴
class Adam(Optimizer):
def __init__(self, point, iter_num, small_lr, proper_lr, large_lr, beta1=.9, beta2=.999):
super().__init__(point, iter_num, small_lr, proper_lr, large_lr)
self.epsilon = 1e-8
self.beta1 = beta1
self.beta2 = beta2
self.m = defaultdict(lambda : np.zeros_like(point))
self.v = defaultdict(lambda : np.zeros_like(point))
def method(self, point, lr, iter):
'''
Adam - 모름
:param point: 점의 위치 : numpy array
:param lr: 학습률 : float
:param iter: 최적화횟수 : int
:return: 갱신된 점의 위치 : numpy array
'''
gradient = self.grad(point)
beta1, beta2 = self.beta1, self.beta2
self.m[lr] = beta1 * self.m[lr] + (1 - beta1) * gradient
self.v[lr] = beta2 * self.v[lr] + (1 - beta2) * (gradient ** 2)
m_t = self.m[lr] / (1 - beta1 ** iter)
v_t = self.v[lr] / (1 - beta2 ** iter)
return point - (lr / np.sqrt(v_t + self.epsilon)) * m_t
def optimize(self):
'''
최적화 실행 - 최적화 횟수를 인수로 요구하므로 오버라이딩
:return: -
'''
for i in range(self.iter_num):
for lr in self.lr_tup:
self.dict_point[lr] = self.method(self.dict_point[lr], lr, i+1)
self.dict_trace[lr]['x'].append(self.dict_point[lr][0])
self.dict_trace[lr]['y'].append(self.dict_point[lr][1])
# 점의 시작 위치
x = np.array([-7., 2.])
# 최적화 방법별로 객체 생성, 설정한 최적화 횟수별로 최적화 수행
# small_lr, proper_lr, large_lr = 학습률 설정
sgd = SGD(point=x, iter_num=50, small_lr=.4, proper_lr=.95, large_lr=1.003)
sgd.optimize()
mmt = Momentum(point=x, iter_num=25, small_lr=.03, proper_lr=.091, large_lr=.24)
mmt.optimize()
adg = AdaGrad(point=x, iter_num=30, small_lr=.5, proper_lr=1, large_lr=1.5)
adg.optimize()
# ad = Adam(point=x, iter_num=50, small_lr=.1, proper_lr=.2, large_lr=.4)
ad = Adam(point=x, iter_num=30, small_lr=.2, proper_lr=.3, large_lr=.35)
ad.optimize()
# 각 최적화 방법별로 생성한 객체를 담음
opt_lst = [sgd, mmt, adg, ad]
# 최적화 방법별로 plot 생성
plt.figure(figsize=(16, 6))
for opt, i in zip(opt_lst, range(1,5)):
plt.subplot(2, 2, i)
# 함수 Z = (X **2)/20 + Y **2 를 그림 - 등고선 형태
x = np.linspace(-8, 8, 100) # x, y 의 범위
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = (X ** 2) / 20 + Y ** 2 # 그리고자 하는 함수
levels = np.arange(0, 40, 1) # 등고선의 범위와 등고선간 간격
CS = plt.contour(X, Y, Z, levels=levels)
plt.clabel(CS, inline=1, fontsize=10) # 등고선의 값 표시
plt.grid()
plt.xlim(-8, 8)
plt.ylim(-3, 3)
for lr, format in zip(opt.lr_tup, ['.-', 'v-', 'o-']):
plt.plot(opt.dict_trace[lr]['x'], opt.dict_trace[lr]['y'], format,ms=5 ,label=lr)
plt.title(opt.__class__.__name__+' - iteration :'+str(opt.iter_num))
plt.legend(title='learning rate')
plt.show() | [
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.clabel",
"numpy.meshgrid",
"matplotlib.pyplot.show",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"numpy.zeros_like",
"matplotlib.pyplot.legend",
"collections.defaultdict",
"matplotlib.pyplot.figure",
"numpy.array... | [((4962, 4983), 'numpy.array', 'np.array', (['[-7.0, 2.0]'], {}), '([-7.0, 2.0])\n', (4970, 4983), True, 'import numpy as np\n'), ((5579, 5606), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(16, 6)'}), '(figsize=(16, 6))\n', (5589, 5606), True, 'import matplotlib.pyplot as plt\n'), ((6346, 6356), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6354, 6356), True, 'import matplotlib.pyplot as plt\n'), ((5651, 5671), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', 'i'], {}), '(2, 2, i)\n', (5662, 5671), True, 'import matplotlib.pyplot as plt\n'), ((5726, 5749), 'numpy.linspace', 'np.linspace', (['(-8)', '(8)', '(100)'], {}), '(-8, 8, 100)\n', (5737, 5749), True, 'import numpy as np\n'), ((5771, 5794), 'numpy.linspace', 'np.linspace', (['(-3)', '(3)', '(100)'], {}), '(-3, 3, 100)\n', (5782, 5794), True, 'import numpy as np\n'), ((5806, 5823), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (5817, 5823), True, 'import numpy as np\n'), ((5882, 5901), 'numpy.arange', 'np.arange', (['(0)', '(40)', '(1)'], {}), '(0, 40, 1)\n', (5891, 5901), True, 'import numpy as np\n'), ((5931, 5966), 'matplotlib.pyplot.contour', 'plt.contour', (['X', 'Y', 'Z'], {'levels': 'levels'}), '(X, Y, Z, levels=levels)\n', (5942, 5966), True, 'import matplotlib.pyplot as plt\n'), ((5971, 6008), 'matplotlib.pyplot.clabel', 'plt.clabel', (['CS'], {'inline': '(1)', 'fontsize': '(10)'}), '(CS, inline=1, fontsize=10)\n', (5981, 6008), True, 'import matplotlib.pyplot as plt\n'), ((6026, 6036), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (6034, 6036), True, 'import matplotlib.pyplot as plt\n'), ((6041, 6056), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-8)', '(8)'], {}), '(-8, 8)\n', (6049, 6056), True, 'import matplotlib.pyplot as plt\n'), ((6061, 6076), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-3)', '(3)'], {}), '(-3, 3)\n', (6069, 6076), True, 'import matplotlib.pyplot as plt\n'), ((573, 629), 'collections.defaultdict', 'defaultdict', (["(lambda : {'x': [point[0]], 'y': [point[1]]})"], {}), "(lambda : {'x': [point[0]], 'y': [point[1]]})\n", (584, 629), False, 'from collections import defaultdict\n'), ((6145, 6231), 'matplotlib.pyplot.plot', 'plt.plot', (["opt.dict_trace[lr]['x']", "opt.dict_trace[lr]['y']", 'format'], {'ms': '(5)', 'label': 'lr'}), "(opt.dict_trace[lr]['x'], opt.dict_trace[lr]['y'], format, ms=5,\n label=lr)\n", (6153, 6231), True, 'import matplotlib.pyplot as plt\n'), ((6312, 6345), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'title': '"""learning rate"""'}), "(title='learning rate')\n", (6322, 6345), True, 'import matplotlib.pyplot as plt\n'), ((938, 959), 'numpy.array', 'np.array', (['[1 / 10, 2]'], {}), '([1 / 10, 2])\n', (946, 959), True, 'import numpy as np\n'), ((494, 509), 'numpy.array', 'np.array', (['point'], {}), '(point)\n', (502, 509), True, 'import numpy as np\n'), ((2346, 2366), 'numpy.zeros_like', 'np.zeros_like', (['point'], {}), '(point)\n', (2359, 2366), True, 'import numpy as np\n'), ((3022, 3042), 'numpy.zeros_like', 'np.zeros_like', (['point'], {}), '(point)\n', (3035, 3042), True, 'import numpy as np\n'), ((3850, 3870), 'numpy.zeros_like', 'np.zeros_like', (['point'], {}), '(point)\n', (3863, 3870), True, 'import numpy as np\n'), ((3910, 3930), 'numpy.zeros_like', 'np.zeros_like', (['point'], {}), '(point)\n', (3923, 3930), True, 'import numpy as np\n'), ((4504, 4531), 'numpy.sqrt', 'np.sqrt', (['(v_t + self.epsilon)'], {}), '(v_t + self.epsilon)\n', (4511, 4531), True, 'import numpy as np\n'), ((3453, 3492), 'numpy.sqrt', 'np.sqrt', (['(self.dict_h[lr] + self.epsilon)'], {}), '(self.dict_h[lr] + self.epsilon)\n', (3460, 3492), True, 'import numpy as np\n')] |
"""
audio_recognize.py
This file contains the basic functions used for audio clustering and recognition
Maintainer: <NAME> {<EMAIL>}
"""
# -*- coding: utf-8 -*-
import numpy as np
from sklearn.cluster import KMeans, AgglomerativeClustering, Birch, MiniBatchKMeans, estimate_bandwidth
from sklearn.svm import SVR
from sklearn.mixture import GaussianMixture
from sklearn.metrics import silhouette_samples, silhouette_score, calinski_harabasz_score, davies_bouldin_score
from sklearn.manifold import TSNE
from sklearn.feature_selection import VarianceThreshold
import plotly.graph_objs as go
from sklearn.decomposition import PCA
import warnings
from sklearn.exceptions import ConvergenceWarning
import torch
import torch.nn as nn
from torchvision import transforms
import torch.nn.functional as F
import matplotlib.pyplot as plt
from torch.utils.data import TensorDataset, DataLoader
from sklearn.preprocessing import MinMaxScaler, StandardScaler, RobustScaler
from PIL import Image
import statistics
def metrics(X, y):
silhouette_avg = silhouette_score(X, y)
ch_score = calinski_harabasz_score(X,y)
db_score = davies_bouldin_score(X,y)
return silhouette_avg, ch_score, db_score
def cluster_syllables(syllables, specgram, sp_freq,
f_low, f_high, win, train = False, model_name = '\.model_test', comp=False):
"""
TODO
:param syllables:
:param specgram:
:param sp_freq:
:param f_low:
:param f_high:
:param win:
:return:
"""
warnings.filterwarnings('ignore', category=ConvergenceWarning)
features_s, countour_points, init_points = [], [], []
f1 = np.argmin(np.abs(sp_freq - f_low))
f2 = np.argmin(np.abs(sp_freq - f_high))
freqs = [f1,f2]
images = []
segments = []
max_dur = 0
test = []
syllables_final = []
vec1 = []
for syl in syllables:
# for each detected syllable (vocalization)
# A. get the spectrogram area in the defined frequency range
start = int(syl[0] / win)
end = int(syl[1] / win)
cur_image = specgram[start:end, f1:f2]
if train:
images.append(cur_image)
continue
images.append(cur_image)
segments.append([start,end])
syllables_final.append(syl)
if cur_image.shape[0] > max_dur:
max_dur = cur_image.shape[0]
# B. perform frequency contour detection through SVM regression
# B1. get the positions and values of the maximum frequencies
# per time window:
max_pos = np.argmax(cur_image, axis=1)
max_vals = np.max(cur_image, axis=1)
threshold = np.percentile(max_vals, 20)
point_time, point_freq = [], []
# B2. keep only the points where the frequencies are larger than the
# lower 20% percentile of the highest frequencies of each frame
# (thresholding)
for ip in range(1, len(max_vals)-1):
if max_vals[ip] > threshold:
point_time.append(ip)
point_freq.append(max_pos[ip])
# B3. train a regression SVM to map time coordinates to frequency values
svr = SVR(kernel='rbf', C=1e3, gamma=0.1)
svr = svr.fit(np.array(point_time).reshape(-1, 1), np.array(point_freq))
# B4. predict the frequencies for the same time range
x_new = list(range(min(point_time), max(point_time)+1))
y_new = svr.predict(np.array(x_new).reshape(-1, 1))
y_new[y_new + f1 > sp_freq.shape[0]] = sp_freq.shape[0] - f1 - 1
points_t = [j * win + syl[0] for j in x_new]
points_f = [sp_freq[int(j + f1)] for j in y_new]
points_t_init = [j * win + syl[0] for j in point_time]
points_f_init = [sp_freq[int(j + f1)] for j in point_freq]
init_points.append([points_t_init, points_f_init])
countour_points.append([points_t, points_f])
# C. Extract features based on the frequency contour
delta = np.diff(points_f)
delta_2 = np.diff(delta)
duration = points_t[-1] - points_t[0]
max_freq = np.max(points_f)
min_freq = np.min(points_f)
mean_freq = np.mean(points_f)
max_freq_change = np.max(np.abs(delta))
min_freq_change = np.min(np.abs(delta))
delta_mean = np.mean(delta)
delta_std = np.std(delta)
delta2_mean = np.mean(delta_2)
delta2_std = np.std(delta_2)
freq_start = points_f[0]
freq_end = points_f[-1]
pos_min_freq = (points_t[np.argmin(points_f)] - points_t[0]) / duration
pos_max_freq = (points_t[np.argmax(points_f)] - points_t[0]) / duration
feature_mode = 2
if feature_mode == 1:
cur_features = [duration, min_freq, max_freq, mean_freq,
max_freq_change, min_freq_change,
delta_mean, delta_std,
delta2_mean, delta2_std,
freq_start, freq_end]
elif feature_mode == 2:
cur_features = [duration,
pos_min_freq,
pos_max_freq,
(freq_start - freq_end) / mean_freq]
else:
import scipy.signal
desired = 100
ratio = int(100 * (desired / len(points_f)))
cur_features = scipy.signal.resample_poly(points_f, up=ratio, down=100)
cur_features = cur_features[0:desired - 10].tolist()
features_s.append(cur_features)
if train or comp:
return images
features_s = StandardScaler().fit_transform(features_s)
feature_names = ["duration",
"min_freq", "max_freq", "mean_freq",
"max_freq_change", "min_freq_change",
"delta_mean", "delta_std",
"delta2_mean", "delta2_std",
"freq_start", "freq_end"]
init_images = np.array(images, dtype = object)
#crop and normalize images
time_limit = 64
for i in range(len(images)):
if len(images[i])>time_limit:
images[i] = images[i][int((len(images[i])-time_limit)/2):int((len(images[i])-time_limit)/2)+time_limit,:]/np.amax(images[i])
elif len(images[i])<time_limit:
images[i] = np.pad(images[i]/np.amax(images[i]), ((int((time_limit-images[i].shape[0])/2), (time_limit-images[i].shape[0]) - int((time_limit-images[i].shape[0])/2)),(0,0)))
else:
images[i] = images[i]/np.amax(images[i])
specs = np.array(images)
specs = specs.reshape(specs.shape[0], 1, specs.shape[1], specs.shape[2])
model = torch.load(model_name, map_location=torch.device('cpu'))
dataset = TensorDataset(torch.tensor(specs, dtype = torch.float))
batch_size = 32
test_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle = False)
outputs = []
model.eval()
with torch.no_grad():
for data in test_loader:
outputs += model(data[0], False)
for i in range(len(outputs)):
outputs[i] = outputs[i].detach().numpy().flatten()
outputs=np.array(outputs)
features = outputs
selector = VarianceThreshold(threshold=(1.2*np.mean(np.var(features, axis = 0))))
features = selector.fit_transform(features)
scaler = StandardScaler()
features = scaler.fit_transform(features)
test = min(100,features.shape[0], features.shape[1])
n_comp = 0
while (1):
pca = PCA(n_components=test, random_state=9)
pca.fit(features)
evar = pca.explained_variance_ratio_
cum_evar = np.cumsum(evar)
n_comp = np.where(cum_evar >= 0.95)
if not list(n_comp[0]):
test = test + 50
else:
n_comp = n_comp[0][0] + 1
break
pca = PCA(n_components=n_comp, random_state=9)
features = pca.fit_transform(features)
features_d = features
return images, list(init_images), countour_points, \
init_points, [features_s, features_d, outputs], feature_names, freqs, segments, syllables_final,\
selector, scaler, pca
def cluster_help(clusterer, features, n_clusters):
y = clusterer.fit_predict(features)
#In case of Birch clustering, if threshold is too big for generating n_clusters clusters
if len(np.unique(y))< n_clusters:
return y,[]
scores = metrics(features, y)
return y, scores
def clustering(method, n_clusters, features):
if method == 'agg':
clusterer = AgglomerativeClustering(n_clusters=n_clusters)
y, scores = cluster_help(clusterer, features, n_clusters)
elif method == 'birch':
clusterer = Birch(n_clusters = n_clusters)
y, scores = cluster_help(clusterer,features, n_clusters)
elif method == 'gmm':
clusterer = GaussianMixture(n_components=n_clusters, random_state=9)
y, scores = cluster_help(clusterer,features, n_clusters)
elif method == 'kmeans':
clusterer = KMeans(n_clusters=n_clusters, random_state=9)
y, scores = cluster_help(clusterer, features, n_clusters)
elif method == 'mbkmeans':
clusterer = MiniBatchKMeans(n_clusters = n_clusters, random_state=9)
y, scores = cluster_help(clusterer, features, n_clusters)
return y, scores | [
"sklearn.cluster.MiniBatchKMeans",
"sklearn.preprocessing.StandardScaler",
"numpy.abs",
"numpy.argmax",
"sklearn.mixture.GaussianMixture",
"numpy.argmin",
"numpy.mean",
"torch.device",
"torch.no_grad",
"sklearn.metrics.davies_bouldin_score",
"numpy.unique",
"torch.utils.data.DataLoader",
"nu... | [((1043, 1065), 'sklearn.metrics.silhouette_score', 'silhouette_score', (['X', 'y'], {}), '(X, y)\n', (1059, 1065), False, 'from sklearn.metrics import silhouette_samples, silhouette_score, calinski_harabasz_score, davies_bouldin_score\n'), ((1081, 1110), 'sklearn.metrics.calinski_harabasz_score', 'calinski_harabasz_score', (['X', 'y'], {}), '(X, y)\n', (1104, 1110), False, 'from sklearn.metrics import silhouette_samples, silhouette_score, calinski_harabasz_score, davies_bouldin_score\n'), ((1125, 1151), 'sklearn.metrics.davies_bouldin_score', 'davies_bouldin_score', (['X', 'y'], {}), '(X, y)\n', (1145, 1151), False, 'from sklearn.metrics import silhouette_samples, silhouette_score, calinski_harabasz_score, davies_bouldin_score\n'), ((1513, 1575), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'ConvergenceWarning'}), "('ignore', category=ConvergenceWarning)\n", (1536, 1575), False, 'import warnings\n'), ((5984, 6014), 'numpy.array', 'np.array', (['images'], {'dtype': 'object'}), '(images, dtype=object)\n', (5992, 6014), True, 'import numpy as np\n'), ((6591, 6607), 'numpy.array', 'np.array', (['images'], {}), '(images)\n', (6599, 6607), True, 'import numpy as np\n'), ((6862, 6936), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': 'batch_size', 'shuffle': '(False)'}), '(dataset, batch_size=batch_size, shuffle=False)\n', (6889, 6936), False, 'import torch\n'), ((7184, 7201), 'numpy.array', 'np.array', (['outputs'], {}), '(outputs)\n', (7192, 7201), True, 'import numpy as np\n'), ((7373, 7389), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (7387, 7389), False, 'from sklearn.preprocessing import MinMaxScaler, StandardScaler, RobustScaler\n'), ((7868, 7908), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'n_comp', 'random_state': '(9)'}), '(n_components=n_comp, random_state=9)\n', (7871, 7908), False, 'from sklearn.decomposition import PCA\n'), ((1654, 1677), 'numpy.abs', 'np.abs', (['(sp_freq - f_low)'], {}), '(sp_freq - f_low)\n', (1660, 1677), True, 'import numpy as np\n'), ((1698, 1722), 'numpy.abs', 'np.abs', (['(sp_freq - f_high)'], {}), '(sp_freq - f_high)\n', (1704, 1722), True, 'import numpy as np\n'), ((2581, 2609), 'numpy.argmax', 'np.argmax', (['cur_image'], {'axis': '(1)'}), '(cur_image, axis=1)\n', (2590, 2609), True, 'import numpy as np\n'), ((2629, 2654), 'numpy.max', 'np.max', (['cur_image'], {'axis': '(1)'}), '(cur_image, axis=1)\n', (2635, 2654), True, 'import numpy as np\n'), ((2675, 2702), 'numpy.percentile', 'np.percentile', (['max_vals', '(20)'], {}), '(max_vals, 20)\n', (2688, 2702), True, 'import numpy as np\n'), ((3197, 3235), 'sklearn.svm.SVR', 'SVR', ([], {'kernel': '"""rbf"""', 'C': '(1000.0)', 'gamma': '(0.1)'}), "(kernel='rbf', C=1000.0, gamma=0.1)\n", (3200, 3235), False, 'from sklearn.svm import SVR\n'), ((4005, 4022), 'numpy.diff', 'np.diff', (['points_f'], {}), '(points_f)\n', (4012, 4022), True, 'import numpy as np\n'), ((4041, 4055), 'numpy.diff', 'np.diff', (['delta'], {}), '(delta)\n', (4048, 4055), True, 'import numpy as np\n'), ((4121, 4137), 'numpy.max', 'np.max', (['points_f'], {}), '(points_f)\n', (4127, 4137), True, 'import numpy as np\n'), ((4157, 4173), 'numpy.min', 'np.min', (['points_f'], {}), '(points_f)\n', (4163, 4173), True, 'import numpy as np\n'), ((4194, 4211), 'numpy.mean', 'np.mean', (['points_f'], {}), '(points_f)\n', (4201, 4211), True, 'import numpy as np\n'), ((4329, 4343), 'numpy.mean', 'np.mean', (['delta'], {}), '(delta)\n', (4336, 4343), True, 'import numpy as np\n'), ((4364, 4377), 'numpy.std', 'np.std', (['delta'], {}), '(delta)\n', (4370, 4377), True, 'import numpy as np\n'), ((4400, 4416), 'numpy.mean', 'np.mean', (['delta_2'], {}), '(delta_2)\n', (4407, 4416), True, 'import numpy as np\n'), ((4438, 4453), 'numpy.std', 'np.std', (['delta_2'], {}), '(delta_2)\n', (4444, 4453), True, 'import numpy as np\n'), ((6782, 6820), 'torch.tensor', 'torch.tensor', (['specs'], {'dtype': 'torch.float'}), '(specs, dtype=torch.float)\n', (6794, 6820), False, 'import torch\n'), ((6982, 6997), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6995, 6997), False, 'import torch\n'), ((7538, 7576), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'test', 'random_state': '(9)'}), '(n_components=test, random_state=9)\n', (7541, 7576), False, 'from sklearn.decomposition import PCA\n'), ((7667, 7682), 'numpy.cumsum', 'np.cumsum', (['evar'], {}), '(evar)\n', (7676, 7682), True, 'import numpy as np\n'), ((7700, 7726), 'numpy.where', 'np.where', (['(cum_evar >= 0.95)'], {}), '(cum_evar >= 0.95)\n', (7708, 7726), True, 'import numpy as np\n'), ((8574, 8620), 'sklearn.cluster.AgglomerativeClustering', 'AgglomerativeClustering', ([], {'n_clusters': 'n_clusters'}), '(n_clusters=n_clusters)\n', (8597, 8620), False, 'from sklearn.cluster import KMeans, AgglomerativeClustering, Birch, MiniBatchKMeans, estimate_bandwidth\n'), ((3292, 3312), 'numpy.array', 'np.array', (['point_freq'], {}), '(point_freq)\n', (3300, 3312), True, 'import numpy as np\n'), ((4245, 4258), 'numpy.abs', 'np.abs', (['delta'], {}), '(delta)\n', (4251, 4258), True, 'import numpy as np\n'), ((4293, 4306), 'numpy.abs', 'np.abs', (['delta'], {}), '(delta)\n', (4299, 4306), True, 'import numpy as np\n'), ((5629, 5645), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (5643, 5645), False, 'from sklearn.preprocessing import MinMaxScaler, StandardScaler, RobustScaler\n'), ((6733, 6752), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (6745, 6752), False, 'import torch\n'), ((8379, 8391), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (8388, 8391), True, 'import numpy as np\n'), ((8735, 8763), 'sklearn.cluster.Birch', 'Birch', ([], {'n_clusters': 'n_clusters'}), '(n_clusters=n_clusters)\n', (8740, 8763), False, 'from sklearn.cluster import KMeans, AgglomerativeClustering, Birch, MiniBatchKMeans, estimate_bandwidth\n'), ((6263, 6281), 'numpy.amax', 'np.amax', (['images[i]'], {}), '(images[i])\n', (6270, 6281), True, 'import numpy as np\n'), ((8877, 8933), 'sklearn.mixture.GaussianMixture', 'GaussianMixture', ([], {'n_components': 'n_clusters', 'random_state': '(9)'}), '(n_components=n_clusters, random_state=9)\n', (8892, 8933), False, 'from sklearn.mixture import GaussianMixture\n'), ((3255, 3275), 'numpy.array', 'np.array', (['point_time'], {}), '(point_time)\n', (3263, 3275), True, 'import numpy as np\n'), ((3469, 3484), 'numpy.array', 'np.array', (['x_new'], {}), '(x_new)\n', (3477, 3484), True, 'import numpy as np\n'), ((4552, 4571), 'numpy.argmin', 'np.argmin', (['points_f'], {}), '(points_f)\n', (4561, 4571), True, 'import numpy as np\n'), ((4632, 4651), 'numpy.argmax', 'np.argmax', (['points_f'], {}), '(points_f)\n', (4641, 4651), True, 'import numpy as np\n'), ((6555, 6573), 'numpy.amax', 'np.amax', (['images[i]'], {}), '(images[i])\n', (6562, 6573), True, 'import numpy as np\n'), ((7281, 7305), 'numpy.var', 'np.var', (['features'], {'axis': '(0)'}), '(features, axis=0)\n', (7287, 7305), True, 'import numpy as np\n'), ((9048, 9093), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': 'n_clusters', 'random_state': '(9)'}), '(n_clusters=n_clusters, random_state=9)\n', (9054, 9093), False, 'from sklearn.cluster import KMeans, AgglomerativeClustering, Birch, MiniBatchKMeans, estimate_bandwidth\n'), ((6363, 6381), 'numpy.amax', 'np.amax', (['images[i]'], {}), '(images[i])\n', (6370, 6381), True, 'import numpy as np\n'), ((9211, 9265), 'sklearn.cluster.MiniBatchKMeans', 'MiniBatchKMeans', ([], {'n_clusters': 'n_clusters', 'random_state': '(9)'}), '(n_clusters=n_clusters, random_state=9)\n', (9226, 9265), False, 'from sklearn.cluster import KMeans, AgglomerativeClustering, Birch, MiniBatchKMeans, estimate_bandwidth\n')] |
import os
import numpy as np
import pickle
from hips.plotting.layout import create_figure
from hips.plotting.colormaps import gradient_cmap
import matplotlib.pyplot as plt
import brewer2mpl
from scipy.misc import logsumexp
from spclust import find_blockifying_perm
colors = brewer2mpl.get_map("Set1", "Qualitative", 9).mpl_colors
goodcolors = np.array([0,1,2,4,6,7,8])
colors = np.array(colors)[goodcolors]
def logma(v):
def logavg(v):
return logsumexp(v) - np.log(len(v))
return np.array([logavg(v[n//2:n]) for n in range(2,len(v))])
def corr_matrix(a):
return a / np.outer(np.sqrt(np.diag(a)), np.sqrt(np.diag(a)))
def top_k(words, pi, k=8):
# Get the top k words ranked by pi
perm = np.argsort(pi)[::-1]
return np.array(words)[perm][:k]
def plot_correlation_matrix(Sigma,
betas,
words,
results_dir,
outname="corr_matrix.pdf",
blockify=False,
highlight=[]):
# Get topic names
topic_names = [np.array(words)[np.argmax(beta)] for beta in betas.T]
# Plot the log likelihood
sz = 5.25/3. # Three NIPS panels
fig = create_figure(figsize=(sz, 2.5), transparent=True)
fig.set_tight_layout(True)
ax = fig.add_subplot(111)
C = corr_matrix(Sigma)
T = C.shape[0]
lim = abs(C).max()
cmap = gradient_cmap([colors[1], np.ones(3), colors[0]])
if blockify:
perm = find_blockifying_perm(C, k=4, nclusters=4)
C = C[np.ix_(perm, perm)]
im = plt.imshow(np.kron(C, np.ones((50,50))), interpolation="none", vmin=-lim, vmax=lim, cmap=cmap, extent=(1,T+1,T+1,1))
from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(ax)
cax = divider.append_axes("bottom", size="5%", pad=0.05)
cbar = plt.colorbar(im, cax=cax,
orientation="horizontal",
ticks=[-1, -0.5, 0., 0.5, 1.0],
label="Topic Correlation")
# cbar.set_label("Probability", labelpad=10)
plt.subplots_adjust(left=0.05, bottom=0.1, top=0.9, right=0.85)
# Highlight some cells
import string
from matplotlib.patches import Rectangle
for i,(j,k) in enumerate(highlight):
ax.add_patch(Rectangle((k+1, j+1), 1, 1, facecolor="none", edgecolor='k', linewidth=1))
ax.text(k+1-1.5,j+1+1,string.ascii_lowercase[i], )
print("")
print("CC: ", C[j,k])
print("Topic ", j)
print(top_k(words, betas[:,j]))
print("Topic ", k)
print(top_k(words, betas[:,k]))
print("")
# Find the most correlated off diagonal entry
C_offdiag = np.tril(C,k=-1)
sorted_pairs = np.argsort(C_offdiag.ravel())
for i in range(5):
print("")
imax,jmax = np.unravel_index(sorted_pairs[-i], (T,T))
print("Correlated Topics (%d, %d): " % (imax, jmax))
print(top_k(words, betas[:,imax]), "\n and \n", top_k(words, betas[:,jmax]))
print("correlation coeff: ", C[imax, jmax])
print("-" * 50)
print("")
print("-" * 50)
print("-" * 50)
print("-" * 50)
for i in range(5):
print("")
imin,jmin = np.unravel_index(sorted_pairs[i], (T,T))
print("Anticorrelated Topics (%d, %d): " % (imin, jmin))
# print topic_names[imin], " and ", topic_names[jmin]
print(top_k(words, betas[:,imin]), "\n and \n", top_k(words, betas[:,jmin]))
print("correlation coeff: ", C[imin, jmin])
print("-" * 50)
print("")
# Move main axis ticks to top
ax.xaxis.tick_top()
# ax.set_title("Topic Correlation", y=1.1)
fig.savefig(os.path.join(results_dir, outname))
plt.show()
def print_topics(betas, words):
for t, beta in enumerate(betas.T):
print("Topic ", t)
print(top_k(words, beta, k=10))
print("")
def plot_pred_log_likelihood(timestamp_list,
pred_ll_list, names,
results_dir,
outname="ctm_pred_ll_vs_time.pdf",
title=None,
smooth=True, burnin=3,
normalizer=4632. # Number of words in test dataset
):
# Plot the log likelihood
width = 5.25/3. # Three NIPS panels
fig = create_figure(figsize=(width, 2.25), transparent=True)
fig.set_tight_layout(True)
min_time = np.min([np.min(times[burnin+2:]) for times in timestamp_list])
max_time = np.max([np.max(times[burnin+2:]) for times in timestamp_list])
for i,(times, pred_ll, name) in enumerate(zip(timestamp_list, pred_ll_list, names)[::-1]):
# Smooth the log likelihood
smooth_pred_ll = logma(pred_ll)
plt.plot(np.clip(times[burnin+2:], 1e-3,np.inf),
smooth_pred_ll[burnin:] / normalizer,
lw=2, color=colors[3-i], label=name)
# plt.plot(np.clip(times[burnin:], 1e-3,np.inf),
# pred_ll[burnin:] / normalizer,
# lw=2, color=colors[3-i], label=None)
N = len(pred_ll)
avg_pll = logsumexp(pred_ll[N//2:]) - np.log(N-N//2)
plt.plot([min_time, max_time], avg_pll / normalizer * np.ones(2), ls='--', color=colors[3-i])
plt.xlabel('Time [s] (log scale) ', fontsize=9)
plt.xscale("log")
plt.xlim(min_time, max_time)
plt.ylabel("Pred. Log Lkhd. [nats/word]", fontsize=9)
plt.ylim(-2.6, -2.47)
plt.yticks([-2.6, -2.55, -2.5])
# plt.subplots_adjust(left=0.05)
if title:
plt.title(title)
# plt.ylim(-9.,-8.4)
plt.savefig(os.path.join(results_dir, outname))
plt.show()
def plot_figure_legend(results_dir):
"""
Make a standalone legend
:return:
"""
from hips.plotting.layout import create_legend_figure
labels = ["SBM-CTM (Gibbs)", "LNM-CTM (Gibbs)", "CTM (EM)", "LDA (Gibbs)"]
fig = create_legend_figure(labels, colors[:4], size=(5.25,0.5),
lineargs={"lw": 2},
legendargs={"columnspacing": 0.75,
"handletextpad": 0.125})
fig.savefig(os.path.join(results_dir, "ctm_legend.pdf"))
if __name__ == "__main__":
# res_dir = os.path.join("results", "newsgroups_lda")
# res_file = os.path.join(res_dir, "lda_bignewsgroups_results2.pkl")
res_dir = os.path.join("results", "ap_lda")
res_file = os.path.join(res_dir, "ec2_results2_c.pkl")
with open(res_file) as f:
res = pickle.load(f)
# Plot pred ll vs time
models = ["sb", "ln", "em", "lda"]
names = ["SBM-CTM (Gibbs)", "LNM-CTM (Gibbs)", "CTM (EM)", "LDA (collapsed Gibbs)"]
# models = ["sb", "em"]
# names = ["SBM-CTM", "LNM-CTM (EM)"]
times = [np.array(res[k]["timestamps"]) for k in models]
pred_lls = [np.array(res[k]["predictive_lls"]) for k in models]
plot_pred_log_likelihood(times, pred_lls, names, res_dir, title="AP News")
# Plot the correlation matrix
# from experiments.newsgroups_lda import load_ap_data, load_newsgroup_data
# from pgmult.lda import StickbreakingCorrelatedLDA
# counts, words = load_newsgroup_data(V=1000, cats=None)
# last_sample = res["sb"]["samples"]
# assert isinstance(last_sample, StickbreakingCorrelatedLDA)
#
# # Topics to highlight:
# # highlight = [(9,6), (3,10)]
# highlight = []
# plot_correlation_matrix(last_sample.theta_prior.sigma,
# last_sample.beta,
# words,
# res_dir,
# highlight=highlight)
#
# from pgmult.utils import psi_to_pi
# topic_probs = psi_to_pi(last_sample.theta_prior.mu)
# topic_perm = np.argsort(topic_probs)
# print_topics(last_sample.beta[:,topic_perm], words)
plot_figure_legend(res_dir)
| [
"matplotlib.pyplot.title",
"numpy.argmax",
"numpy.ones",
"numpy.clip",
"numpy.argsort",
"hips.plotting.layout.create_legend_figure",
"pickle.load",
"brewer2mpl.get_map",
"numpy.diag",
"os.path.join",
"matplotlib.patches.Rectangle",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.colorbar",
... | [((347, 378), 'numpy.array', 'np.array', (['[0, 1, 2, 4, 6, 7, 8]'], {}), '([0, 1, 2, 4, 6, 7, 8])\n', (355, 378), True, 'import numpy as np\n'), ((277, 321), 'brewer2mpl.get_map', 'brewer2mpl.get_map', (['"""Set1"""', '"""Qualitative"""', '(9)'], {}), "('Set1', 'Qualitative', 9)\n", (295, 321), False, 'import brewer2mpl\n'), ((382, 398), 'numpy.array', 'np.array', (['colors'], {}), '(colors)\n', (390, 398), True, 'import numpy as np\n'), ((1258, 1308), 'hips.plotting.layout.create_figure', 'create_figure', ([], {'figsize': '(sz, 2.5)', 'transparent': '(True)'}), '(figsize=(sz, 2.5), transparent=True)\n', (1271, 1308), False, 'from hips.plotting.layout import create_figure\n'), ((1813, 1836), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (1832, 1836), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((1909, 2025), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['im'], {'cax': 'cax', 'orientation': '"""horizontal"""', 'ticks': '[-1, -0.5, 0.0, 0.5, 1.0]', 'label': '"""Topic Correlation"""'}), "(im, cax=cax, orientation='horizontal', ticks=[-1, -0.5, 0.0, \n 0.5, 1.0], label='Topic Correlation')\n", (1921, 2025), True, 'import matplotlib.pyplot as plt\n'), ((2145, 2208), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': '(0.05)', 'bottom': '(0.1)', 'top': '(0.9)', 'right': '(0.85)'}), '(left=0.05, bottom=0.1, top=0.9, right=0.85)\n', (2164, 2208), True, 'import matplotlib.pyplot as plt\n'), ((2765, 2781), 'numpy.tril', 'np.tril', (['C'], {'k': '(-1)'}), '(C, k=-1)\n', (2772, 2781), True, 'import numpy as np\n'), ((3807, 3817), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3815, 3817), True, 'import matplotlib.pyplot as plt\n'), ((4469, 4523), 'hips.plotting.layout.create_figure', 'create_figure', ([], {'figsize': '(width, 2.25)', 'transparent': '(True)'}), '(figsize=(width, 2.25), transparent=True)\n', (4482, 4523), False, 'from hips.plotting.layout import create_figure\n'), ((5411, 5458), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time [s] (log scale) """'], {'fontsize': '(9)'}), "('Time [s] (log scale) ', fontsize=9)\n", (5421, 5458), True, 'import matplotlib.pyplot as plt\n'), ((5463, 5480), 'matplotlib.pyplot.xscale', 'plt.xscale', (['"""log"""'], {}), "('log')\n", (5473, 5480), True, 'import matplotlib.pyplot as plt\n'), ((5485, 5513), 'matplotlib.pyplot.xlim', 'plt.xlim', (['min_time', 'max_time'], {}), '(min_time, max_time)\n', (5493, 5513), True, 'import matplotlib.pyplot as plt\n'), ((5519, 5572), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Pred. Log Lkhd. [nats/word]"""'], {'fontsize': '(9)'}), "('Pred. Log Lkhd. [nats/word]', fontsize=9)\n", (5529, 5572), True, 'import matplotlib.pyplot as plt\n'), ((5577, 5598), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-2.6)', '(-2.47)'], {}), '(-2.6, -2.47)\n', (5585, 5598), True, 'import matplotlib.pyplot as plt\n'), ((5603, 5634), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[-2.6, -2.55, -2.5]'], {}), '([-2.6, -2.55, -2.5])\n', (5613, 5634), True, 'import matplotlib.pyplot as plt\n'), ((5794, 5804), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5802, 5804), True, 'import matplotlib.pyplot as plt\n'), ((6049, 6192), 'hips.plotting.layout.create_legend_figure', 'create_legend_figure', (['labels', 'colors[:4]'], {'size': '(5.25, 0.5)', 'lineargs': "{'lw': 2}", 'legendargs': "{'columnspacing': 0.75, 'handletextpad': 0.125}"}), "(labels, colors[:4], size=(5.25, 0.5), lineargs={'lw': \n 2}, legendargs={'columnspacing': 0.75, 'handletextpad': 0.125})\n", (6069, 6192), False, 'from hips.plotting.layout import create_legend_figure\n'), ((6526, 6559), 'os.path.join', 'os.path.join', (['"""results"""', '"""ap_lda"""'], {}), "('results', 'ap_lda')\n", (6538, 6559), False, 'import os\n'), ((6575, 6618), 'os.path.join', 'os.path.join', (['res_dir', '"""ec2_results2_c.pkl"""'], {}), "(res_dir, 'ec2_results2_c.pkl')\n", (6587, 6618), False, 'import os\n'), ((731, 745), 'numpy.argsort', 'np.argsort', (['pi'], {}), '(pi)\n', (741, 745), True, 'import numpy as np\n'), ((1534, 1576), 'spclust.find_blockifying_perm', 'find_blockifying_perm', (['C'], {'k': '(4)', 'nclusters': '(4)'}), '(C, k=4, nclusters=4)\n', (1555, 1576), False, 'from spclust import find_blockifying_perm\n'), ((2891, 2933), 'numpy.unravel_index', 'np.unravel_index', (['sorted_pairs[-i]', '(T, T)'], {}), '(sorted_pairs[-i], (T, T))\n', (2907, 2933), True, 'import numpy as np\n'), ((3296, 3337), 'numpy.unravel_index', 'np.unravel_index', (['sorted_pairs[i]', '(T, T)'], {}), '(sorted_pairs[i], (T, T))\n', (3312, 3337), True, 'import numpy as np\n'), ((3766, 3800), 'os.path.join', 'os.path.join', (['results_dir', 'outname'], {}), '(results_dir, outname)\n', (3778, 3800), False, 'import os\n'), ((5695, 5711), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (5704, 5711), True, 'import matplotlib.pyplot as plt\n'), ((5754, 5788), 'os.path.join', 'os.path.join', (['results_dir', 'outname'], {}), '(results_dir, outname)\n', (5766, 5788), False, 'import os\n'), ((6308, 6351), 'os.path.join', 'os.path.join', (['results_dir', '"""ctm_legend.pdf"""'], {}), "(results_dir, 'ctm_legend.pdf')\n", (6320, 6351), False, 'import os\n'), ((6663, 6677), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (6674, 6677), False, 'import pickle\n'), ((6916, 6946), 'numpy.array', 'np.array', (["res[k]['timestamps']"], {}), "(res[k]['timestamps'])\n", (6924, 6946), True, 'import numpy as np\n'), ((6980, 7014), 'numpy.array', 'np.array', (["res[k]['predictive_lls']"], {}), "(res[k]['predictive_lls'])\n", (6988, 7014), True, 'import numpy as np\n'), ((460, 472), 'scipy.misc.logsumexp', 'logsumexp', (['v'], {}), '(v)\n', (469, 472), False, 'from scipy.misc import logsumexp\n'), ((767, 782), 'numpy.array', 'np.array', (['words'], {}), '(words)\n', (775, 782), True, 'import numpy as np\n'), ((1124, 1139), 'numpy.array', 'np.array', (['words'], {}), '(words)\n', (1132, 1139), True, 'import numpy as np\n'), ((1140, 1155), 'numpy.argmax', 'np.argmax', (['beta'], {}), '(beta)\n', (1149, 1155), True, 'import numpy as np\n'), ((1477, 1487), 'numpy.ones', 'np.ones', (['(3)'], {}), '(3)\n', (1484, 1487), True, 'import numpy as np\n'), ((1591, 1609), 'numpy.ix_', 'np.ix_', (['perm', 'perm'], {}), '(perm, perm)\n', (1597, 1609), True, 'import numpy as np\n'), ((1643, 1660), 'numpy.ones', 'np.ones', (['(50, 50)'], {}), '((50, 50))\n', (1650, 1660), True, 'import numpy as np\n'), ((2362, 2439), 'matplotlib.patches.Rectangle', 'Rectangle', (['(k + 1, j + 1)', '(1)', '(1)'], {'facecolor': '"""none"""', 'edgecolor': '"""k"""', 'linewidth': '(1)'}), "((k + 1, j + 1), 1, 1, facecolor='none', edgecolor='k', linewidth=1)\n", (2371, 2439), False, 'from matplotlib.patches import Rectangle\n'), ((4579, 4605), 'numpy.min', 'np.min', (['times[burnin + 2:]'], {}), '(times[burnin + 2:])\n', (4585, 4605), True, 'import numpy as np\n'), ((4657, 4683), 'numpy.max', 'np.max', (['times[burnin + 2:]'], {}), '(times[burnin + 2:])\n', (4663, 4683), True, 'import numpy as np\n'), ((4902, 4944), 'numpy.clip', 'np.clip', (['times[burnin + 2:]', '(0.001)', 'np.inf'], {}), '(times[burnin + 2:], 0.001, np.inf)\n', (4909, 4944), True, 'import numpy as np\n'), ((5259, 5286), 'scipy.misc.logsumexp', 'logsumexp', (['pred_ll[N // 2:]'], {}), '(pred_ll[N // 2:])\n', (5268, 5286), False, 'from scipy.misc import logsumexp\n'), ((5287, 5305), 'numpy.log', 'np.log', (['(N - N // 2)'], {}), '(N - N // 2)\n', (5293, 5305), True, 'import numpy as np\n'), ((611, 621), 'numpy.diag', 'np.diag', (['a'], {}), '(a)\n', (618, 621), True, 'import numpy as np\n'), ((632, 642), 'numpy.diag', 'np.diag', (['a'], {}), '(a)\n', (639, 642), True, 'import numpy as np\n'), ((5365, 5375), 'numpy.ones', 'np.ones', (['(2)'], {}), '(2)\n', (5372, 5375), True, 'import numpy as np\n')] |
# coding=utf-8
# Copyright (c) DIRECT Contributors
import logging
import numpy as np
import torch
import os
import sys
import pathlib
import functools
from direct.common.subsample import build_masking_function
from direct.data.mri_transforms import build_mri_transforms
from direct.data.datasets import build_dataset_from_input
from direct.data.lr_scheduler import WarmupMultiStepLR
from direct.environment import setup_training_environment, Args
from direct.launch import launch
from direct.utils import str_to_class, set_all_seeds, remove_keys
from direct.utils.dataset import get_filenames_for_datasets
from direct.utils.io import read_json
from collections import defaultdict
logger = logging.getLogger(__name__)
def parse_noise_dict(noise_dict, percentile=1.0, multiplier=1.0):
logger.info("Parsing noise dictionary...")
output = defaultdict(dict)
for filename in noise_dict:
data_per_volume = noise_dict[filename]
for slice_no in data_per_volume:
curr_data = data_per_volume[slice_no]
if percentile != 1.0:
lower_clip = np.percentile(curr_data, 100 * (1 - percentile))
upper_clip = np.percentile(curr_data, 100 * percentile)
curr_data = np.clip(curr_data, lower_clip, upper_clip)
output[filename][int(slice_no)] = (
curr_data * multiplier
) ** 2 # np.asarray(curr_data) * multiplier# (np.clip(curr_data, lower_clip, upper_clip) * multiplier) ** 2
return output
def build_transforms_from_environment(env, dataset_config):
mri_transforms_func = functools.partial(
build_mri_transforms,
forward_operator=env.engine.forward_operator,
backward_operator=env.engine.backward_operator,
mask_func=build_masking_function(**dataset_config.transforms.masking),
)
transforms = mri_transforms_func(**remove_keys(dataset_config.transforms, "masking"))
return transforms
def build_training_datasets_from_environment(
env,
datasets_config,
lists_root,
data_root,
initial_images=None,
initial_kspaces=None,
pass_text_description=True,
pass_dictionaries=None,
**kwargs,
):
datasets = []
for idx, dataset_config in enumerate(datasets_config):
if pass_text_description:
if not dataset_config.text_description:
dataset_config.text_description = f"ds{idx}" if len(datasets_config) > 1 else None
else:
dataset_config.text_description = None
transforms = build_transforms_from_environment(env, dataset_config)
filenames_filter = get_filenames_for_datasets(dataset_config, lists_root, data_root)
dataset = build_dataset_from_input(
transforms,
dataset_config,
initial_images,
initial_kspaces,
filenames_filter,
data_root,
pass_dictionaries,
)
logger.debug(f"Transforms {idx + 1} / {len(datasets_config)} :\n{transforms}")
datasets.append(dataset)
logger.info(
f"Data size for" f" {dataset_config.text_description} ({idx + 1}/{len(datasets_config)}): {len(dataset)}."
)
return datasets
def setup_train(
run_name,
training_root,
validation_root,
base_directory,
cfg_filename,
force_validation,
initialization_checkpoint,
initial_images,
initial_kspace,
noise,
device,
num_workers,
resume,
machine_rank,
mixed_precision,
debug,
):
env = setup_training_environment(
run_name,
base_directory,
cfg_filename,
device,
machine_rank,
mixed_precision,
debug=debug,
)
# Trigger cudnn benchmark and remove the associated cache
torch.backends.cudnn.benchmark = True
torch.cuda.empty_cache()
if initial_kspace is not None and initial_images is not None:
raise ValueError("Cannot both provide initial kspace or initial images.")
pass_dictionaries = {}
if noise is not None:
if not env.cfg.physics.use_noise_matrix:
raise ValueError("cfg.physics.use_noise_matrix is null, yet command line passed noise files.")
noise = [read_json(fn) for fn in noise]
pass_dictionaries["loglikelihood_scaling"] = [
parse_noise_dict(_, percentile=0.999, multiplier=env.cfg.physics.noise_matrix_scaling) for _ in noise
]
# Create training and validation data
# Transforms configuration
# TODO: More ** passing...
training_datasets = build_training_datasets_from_environment(
env=env,
datasets_config=env.cfg.training.datasets,
lists_root=cfg_filename.parents[0],
data_root=training_root,
initial_images=None if initial_images is None else initial_images[0],
initial_kspaces=None if initial_kspace is None else initial_kspace[0],
pass_text_description=False,
pass_dictionaries=pass_dictionaries,
)
training_data_sizes = [len(_) for _ in training_datasets]
logger.info(f"Training data sizes: {training_data_sizes} (sum={sum(training_data_sizes)}).")
if validation_root:
validation_data = build_training_datasets_from_environment(
env=env,
datasets_config=env.cfg.validation.datasets,
lists_root=cfg_filename.parents[0],
data_root=validation_root,
initial_images=None if initial_images is None else initial_images[1],
initial_kspaces=None if initial_kspace is None else initial_kspace[1],
pass_text_description=True,
)
else:
logger.info("No validation data.")
validation_data = None
# Create the optimizers
logger.info("Building optimizers.")
optimizer_params = [{"params": env.engine.model.parameters()}]
for curr_model_name in env.engine.models:
# TODO(jt): Can get learning rate from the config per additional model too.
curr_learning_rate = env.cfg.training.lr
logger.info(f"Adding model parameters of {curr_model_name} with learning rate {curr_learning_rate}.")
optimizer_params.append(
{
"params": env.engine.models[curr_model_name].parameters(),
"lr": curr_learning_rate,
}
)
optimizer: torch.optim.Optimizer = str_to_class("torch.optim", env.cfg.training.optimizer)( # noqa
optimizer_params,
lr=env.cfg.training.lr,
weight_decay=env.cfg.training.weight_decay,
) # noqa
# Build the LR scheduler, we use a fixed LR schedule step size, no adaptive training schedule.
solver_steps = list(
range(
env.cfg.training.lr_step_size,
env.cfg.training.num_iterations,
env.cfg.training.lr_step_size,
)
)
lr_scheduler = WarmupMultiStepLR(
optimizer,
solver_steps,
env.cfg.training.lr_gamma,
warmup_factor=1 / 3.0,
warmup_iterations=env.cfg.training.lr_warmup_iter,
warmup_method="linear",
)
# Just to make sure.
torch.cuda.empty_cache()
env.engine.train(
optimizer,
lr_scheduler,
training_datasets,
env.experiment_dir,
validation_datasets=validation_data,
resume=resume,
initialization=initialization_checkpoint,
start_with_validation=force_validation,
num_workers=num_workers,
)
def check_train_val(key, name):
if key is not None and len(key) != 2:
sys.exit(f"--{name} has to be of the form `train_folder, validation_folder` if a validation folder is set.")
if __name__ == "__main__":
# This sets MKL threads to 1.
# DataLoader can otherwise bring a l ot of difficulties when computing CPU FFTs in the transforms.
torch.set_num_threads(1)
os.environ["OMP_NUM_THREADS"] = "1"
# Remove warnings from named tensors being experimental
os.environ["PYTHONWARNINGS"] = "ignore"
epilog = f"""
Examples:
Run on single machine:
$ {sys.argv[0]} training_set validation_set experiment_dir --num-gpus 8 --cfg cfg.yaml
Run on multiple machines:
(machine0)$ {sys.argv[0]} training_set validation_set experiment_dir --machine-rank 0 --num-machines 2 --dist-url <URL> [--other-flags]
(machine1)$ {sys.argv[0]} training_set validation_set experiment_dir --machine-rank 1 --num-machines 2 --dist-url <URL> [--other-flags]
"""
parser = Args(epilog=epilog)
parser.add_argument("training_root", type=pathlib.Path, help="Path to the training data.")
parser.add_argument("validation_root", type=pathlib.Path, help="Path to the validation data.")
parser.add_argument(
"experiment_dir",
type=pathlib.Path,
help="Path to the experiment directory.",
)
parser.add_argument(
"--cfg",
dest="cfg_file",
help="Config file for training.",
required=True,
type=pathlib.Path,
)
parser.add_argument(
"--initialization-checkpoint",
type=pathlib.Path, # noqa
help="If this value is set to a proper checkpoint when training starts, "
"the model will be initialized with the weights given. "
"No other keys in the checkpoint will be loaded. "
"When another checkpoint would be available and the --resume flag is used, "
"this flag is ignored.",
)
parser.add_argument("--resume", help="Resume training if possible.", action="store_true")
parser.add_argument(
"--force-validation",
help="Start with a validation round, when recovering from a crash. "
"If you use this option, be aware that when combined with --resume, "
"each new run will start with a validation round.",
action="store_true",
)
parser.add_argument("--name", help="Run name.", required=False, type=str)
args = parser.parse_args()
if args.initialization_images is not None and args.initialization_kspace is not None:
sys.exit("--initialization-images and --initialization-kspace are mutually exclusive.")
check_train_val(args.initialization_images, "initialization-images")
check_train_val(args.initialization_kspace, "initialization-kspace")
check_train_val(args.noise, "noise")
set_all_seeds(args.seed)
run_name = args.name if args.name is not None else os.path.basename(args.cfg_file)[:-5]
# TODO(jt): Duplicate params
launch(
setup_train,
args.num_machines,
args.num_gpus,
args.machine_rank,
args.dist_url,
run_name,
args.training_root,
args.validation_root,
args.experiment_dir,
args.cfg_file,
args.force_validation,
args.initialization_checkpoint,
args.initialization_images,
args.initialization_kspace,
args.noise,
args.device,
args.num_workers,
args.resume,
args.machine_rank,
args.mixed_precision,
args.debug,
)
| [
"direct.utils.set_all_seeds",
"direct.environment.Args",
"numpy.clip",
"collections.defaultdict",
"torch.set_num_threads",
"direct.launch.launch",
"direct.common.subsample.build_masking_function",
"direct.utils.io.read_json",
"direct.data.datasets.build_dataset_from_input",
"direct.data.lr_schedul... | [((694, 721), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (711, 721), False, 'import logging\n'), ((850, 867), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (861, 867), False, 'from collections import defaultdict\n'), ((3559, 3681), 'direct.environment.setup_training_environment', 'setup_training_environment', (['run_name', 'base_directory', 'cfg_filename', 'device', 'machine_rank', 'mixed_precision'], {'debug': 'debug'}), '(run_name, base_directory, cfg_filename, device,\n machine_rank, mixed_precision, debug=debug)\n', (3585, 3681), False, 'from direct.environment import setup_training_environment, Args\n'), ((3850, 3874), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (3872, 3874), False, 'import torch\n'), ((6888, 7064), 'direct.data.lr_scheduler.WarmupMultiStepLR', 'WarmupMultiStepLR', (['optimizer', 'solver_steps', 'env.cfg.training.lr_gamma'], {'warmup_factor': '(1 / 3.0)', 'warmup_iterations': 'env.cfg.training.lr_warmup_iter', 'warmup_method': '"""linear"""'}), "(optimizer, solver_steps, env.cfg.training.lr_gamma,\n warmup_factor=1 / 3.0, warmup_iterations=env.cfg.training.\n lr_warmup_iter, warmup_method='linear')\n", (6905, 7064), False, 'from direct.data.lr_scheduler import WarmupMultiStepLR\n'), ((7141, 7165), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (7163, 7165), False, 'import torch\n'), ((7853, 7877), 'torch.set_num_threads', 'torch.set_num_threads', (['(1)'], {}), '(1)\n', (7874, 7877), False, 'import torch\n'), ((8546, 8565), 'direct.environment.Args', 'Args', ([], {'epilog': 'epilog'}), '(epilog=epilog)\n', (8550, 8565), False, 'from direct.environment import setup_training_environment, Args\n'), ((10376, 10400), 'direct.utils.set_all_seeds', 'set_all_seeds', (['args.seed'], {}), '(args.seed)\n', (10389, 10400), False, 'from direct.utils import str_to_class, set_all_seeds, remove_keys\n'), ((10532, 10951), 'direct.launch.launch', 'launch', (['setup_train', 'args.num_machines', 'args.num_gpus', 'args.machine_rank', 'args.dist_url', 'run_name', 'args.training_root', 'args.validation_root', 'args.experiment_dir', 'args.cfg_file', 'args.force_validation', 'args.initialization_checkpoint', 'args.initialization_images', 'args.initialization_kspace', 'args.noise', 'args.device', 'args.num_workers', 'args.resume', 'args.machine_rank', 'args.mixed_precision', 'args.debug'], {}), '(setup_train, args.num_machines, args.num_gpus, args.machine_rank,\n args.dist_url, run_name, args.training_root, args.validation_root, args\n .experiment_dir, args.cfg_file, args.force_validation, args.\n initialization_checkpoint, args.initialization_images, args.\n initialization_kspace, args.noise, args.device, args.num_workers, args.\n resume, args.machine_rank, args.mixed_precision, args.debug)\n', (10538, 10951), False, 'from direct.launch import launch\n'), ((2634, 2699), 'direct.utils.dataset.get_filenames_for_datasets', 'get_filenames_for_datasets', (['dataset_config', 'lists_root', 'data_root'], {}), '(dataset_config, lists_root, data_root)\n', (2660, 2699), False, 'from direct.utils.dataset import get_filenames_for_datasets\n'), ((2718, 2855), 'direct.data.datasets.build_dataset_from_input', 'build_dataset_from_input', (['transforms', 'dataset_config', 'initial_images', 'initial_kspaces', 'filenames_filter', 'data_root', 'pass_dictionaries'], {}), '(transforms, dataset_config, initial_images,\n initial_kspaces, filenames_filter, data_root, pass_dictionaries)\n', (2742, 2855), False, 'from direct.data.datasets import build_dataset_from_input\n'), ((6393, 6448), 'direct.utils.str_to_class', 'str_to_class', (['"""torch.optim"""', 'env.cfg.training.optimizer'], {}), "('torch.optim', env.cfg.training.optimizer)\n", (6405, 6448), False, 'from direct.utils import str_to_class, set_all_seeds, remove_keys\n'), ((7574, 7692), 'sys.exit', 'sys.exit', (['f"""--{name} has to be of the form `train_folder, validation_folder` if a validation folder is set."""'], {}), "(\n f'--{name} has to be of the form `train_folder, validation_folder` if a validation folder is set.'\n )\n", (7582, 7692), False, 'import sys\n'), ((10096, 10193), 'sys.exit', 'sys.exit', (['"""--initialization-images and --initialization-kspace are mutually exclusive."""'], {}), "(\n '--initialization-images and --initialization-kspace are mutually exclusive.'\n )\n", (10104, 10193), False, 'import sys\n'), ((1786, 1845), 'direct.common.subsample.build_masking_function', 'build_masking_function', ([], {}), '(**dataset_config.transforms.masking)\n', (1808, 1845), False, 'from direct.common.subsample import build_masking_function\n'), ((1893, 1942), 'direct.utils.remove_keys', 'remove_keys', (['dataset_config.transforms', '"""masking"""'], {}), "(dataset_config.transforms, 'masking')\n", (1904, 1942), False, 'from direct.utils import str_to_class, set_all_seeds, remove_keys\n'), ((4252, 4265), 'direct.utils.io.read_json', 'read_json', (['fn'], {}), '(fn)\n', (4261, 4265), False, 'from direct.utils.io import read_json\n'), ((10457, 10488), 'os.path.basename', 'os.path.basename', (['args.cfg_file'], {}), '(args.cfg_file)\n', (10473, 10488), False, 'import os\n'), ((1101, 1149), 'numpy.percentile', 'np.percentile', (['curr_data', '(100 * (1 - percentile))'], {}), '(curr_data, 100 * (1 - percentile))\n', (1114, 1149), True, 'import numpy as np\n'), ((1179, 1221), 'numpy.percentile', 'np.percentile', (['curr_data', '(100 * percentile)'], {}), '(curr_data, 100 * percentile)\n', (1192, 1221), True, 'import numpy as np\n'), ((1250, 1292), 'numpy.clip', 'np.clip', (['curr_data', 'lower_clip', 'upper_clip'], {}), '(curr_data, lower_clip, upper_clip)\n', (1257, 1292), True, 'import numpy as np\n')] |
#!/usr/bin/python3
import argparse, hashlib, json, logging, os, sys
import numpy as np
import torch
# local imports
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from lib.data import *
from lib.utils import *
def parse_arguments():
arg_parser = argparse.ArgumentParser(description='Universal Dependencies - Contextual Embedding')
arg_parser.add_argument('ud_path', help='path to Universal Dependencies directory')
arg_parser.add_argument('model', help='model name in the transformers library')
arg_parser.add_argument('out_path', help='path to output directory')
arg_parser.add_argument('-s', '--split', help='path to data split definition pickle (default: None - full UD)')
arg_parser.add_argument('-mp', '--model_path', help='path to pretrained model (default: None - default pretrained weights)')
arg_parser.add_argument('-bs', '--batch_size', type=int, default=64, help='batch size while embedding the corpus (default: 64)')
arg_parser.add_argument('-pl', '--pooling', default='mean', choices=['mean', 'cls', 'none'], help='strategy for pooling word-level embeddings to sentence-level (default: mean)')
arg_parser.add_argument('-of', '--out_format', default='numpy', choices=['numpy', 'map'], help='output format (default: numpy)')
return arg_parser.parse_args()
def main():
args = parse_arguments()
# check if output dir exists
setup_output_directory(args.out_path)
# setup logging
setup_logging(os.path.join(args.out_path, 'embed.log'))
# load data split definition (if supplied)
ud_idcs, ud_filter = None, None
if args.split:
with open(args.split, 'rb') as fp:
splits = pickle.load(fp)
# create filter to load only relevant indices (train, dev)
ud_idcs = set(splits['train']) | set(splits['dev']) | set(splits['test'])
ud_filter = UniversalDependenciesIndexFilter(ud_idcs)
ud_idcs = sorted(ud_idcs)
logging.info(f"Loaded data splits {', '.join([f'{s}: {len(idcs)}' for s, idcs in splits.items()])}.")
# load Universal Dependencies
ud = UniversalDependencies.from_directory(args.ud_path, ud_filter=ud_filter, verbose=True)
ud_idcs = list(range(len(ud))) if ud_idcs is None else sorted(ud_idcs)
logging.info(f"Loaded {ud} with {len(ud_idcs)} relevant sentences.")
# load transformer model
model_type = 'standard'
if args.model.startswith('sentence/'):
from sentence_transformers import SentenceTransformer
model = SentenceTransformer(args.model.replace('sentence/', ''))
tokenizer = model.tokenizer
model_type = 'sentence'
else:
from transformers import AutoTokenizer, AutoModel
tokenizer = AutoTokenizer.from_pretrained(args.model)
model = AutoModel.from_pretrained(args.model_path if args.model_path else args.model, return_dict=True)
# check CUDA availability
if torch.cuda.is_available(): model.to(torch.device('cuda'))
logging.info(f"Loaded {model_type}-type '{args.model}' {model.__class__.__name__} with {tokenizer.__class__.__name__}.")
# main embedding loop
embeddings = []
sen_hashes = []
tkn_count, unk_count, max_len = 0, 0, 1
cursor = 0
while cursor < len(ud_idcs):
# set up batch
start_idx = cursor
end_idx = min(start_idx + args.batch_size, len(ud_idcs))
cursor = end_idx
sentences = ud[ud_idcs[start_idx:end_idx]]
batch = [s.to_words() for s in sentences]
sen_hashes += [hashlib.md5(' '.join(s).encode('utf-8')).hexdigest() for s in batch]
if tokenizer:
# tokenize batch: {input_ids: [[]], token_type_ids: [[]], attention_mask: [[]]}
enc_batch = tokenizer(batch, return_tensors='pt', is_split_into_words=True, padding=True, truncation=True)
# count tokens and UNK
tkn_count += int(torch.sum((enc_batch['input_ids'] != tokenizer.pad_token_id)))
unk_count += int(torch.sum((enc_batch['input_ids'] == tokenizer.unk_token_id)))
# set maximum length
cur_max_len = int(torch.max(torch.sum(enc_batch['attention_mask'], dim=-1)))
max_len = cur_max_len if cur_max_len > max_len else max_len
# no gradients required during inference
with torch.no_grad():
# embed batch (sentence-level)
if model_type == 'sentence':
# SentenceTransformer takes list[str] as input
emb_sentences = model.encode(batch, convert_to_tensor=True) # (batch_size, hidden_dim)
embeddings += [emb_sentences[sidx] for sidx in range(emb_sentences.shape[0])]
# embed batch (token-level)
else:
# move input to GPU (if available)
if torch.cuda.is_available():
enc_batch = {k: v.to(torch.device('cuda')) for k, v in enc_batch.items()}
# perform embedding forward pass
model_outputs = model(**enc_batch)
emb_batch = model_outputs.last_hidden_state # (batch_size, max_len, hidden_dim)
att_batch = enc_batch['attention_mask'] > 0 # create boolean mask (batch_size, max_len)
# perform pooling over sentence tokens with specified strategy
for sidx in range(emb_batch.shape[0]):
# mean pooling over tokens in each sentence
if args.pooling == 'mean':
# reduce (1, max_length, hidden_dim) -> (1, num_tokens, hidden_dim) -> (hidden_dim)
embeddings.append(torch.mean(emb_batch[sidx, att_batch[sidx], :], dim=0))
# get cls token from each sentence
elif args.pooling == 'cls':
# reduce (1, max_length, hidden_dim) -> (hidden_dim)
embeddings.append(emb_batch[sidx, 0, :])
# no reduction
elif args.pooling == 'none':
# (sen_len, hidden_dim)
embeddings.append(emb_batch[sidx, att_batch[sidx], :])
sys.stdout.write(f"\r[{(cursor*100)/len(ud_idcs):.2f}%] Embedding...")
sys.stdout.flush()
print("\r")
if tkn_count: logging.info(f"{tokenizer.__class__.__name__} encoded corpus to {tkn_count} tokens with {unk_count} UNK tokens ({unk_count/tkn_count:.4f}).")
logging.info(f"{model.__class__.__name__} embedded corpus with {len(embeddings)} sentences.")
# export embeddings to numpy arrays
if args.out_format == 'numpy':
# TODO export with padding
if args.pooling == 'none': raise NotImplementedError
# split embedded corpus by language
start_idx = 0
for sidx, uidx in enumerate(ud_idcs):
cur_language = ud.get_language_of_index(uidx)
embeddings[sidx] = list(embeddings[sidx])
# check if next index is new language
if (sidx == len(ud_idcs) - 1) or (cur_language != ud.get_language_of_index(ud_idcs[sidx+1])):
# save tensors to disk as numpy arrays
tensor_path = os.path.join(args.out_path, f'{cur_language.replace(" ", "_")}.npy')
np.save(tensor_path, np.array(embeddings[start_idx:sidx+1]))
start_idx = sidx+1
logging.info(f"Saved embeddings to '{tensor_path}' as numpy array.")
# export embeddings to hash->emb map
elif args.out_format == 'map':
hash_emb_map = {sen_hashes[sidx]: embeddings[sidx] for sidx in range(len(embeddings))}
# save to disk
out_file = os.path.join(args.out_path, 'map.pkl')
with open(out_file, 'wb') as fp:
pickle.dump(hash_emb_map, fp)
logging.info(f"Saved 'sentence hash' -> 'embedding tensor' map to '{out_file}'.")
if __name__ == '__main__':
main() | [
"torch.mean",
"argparse.ArgumentParser",
"torch.sum",
"os.path.dirname",
"transformers.AutoModel.from_pretrained",
"logging.info",
"transformers.AutoTokenizer.from_pretrained",
"torch.cuda.is_available",
"sys.stdout.flush",
"numpy.array",
"torch.device",
"torch.no_grad",
"os.path.join"
] | [((267, 356), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Universal Dependencies - Contextual Embedding"""'}), "(description=\n 'Universal Dependencies - Contextual Embedding')\n", (290, 356), False, 'import argparse, hashlib, json, logging, os, sys\n'), ((2817, 2947), 'logging.info', 'logging.info', (['f"""Loaded {model_type}-type \'{args.model}\' {model.__class__.__name__} with {tokenizer.__class__.__name__}."""'], {}), '(\n f"Loaded {model_type}-type \'{args.model}\' {model.__class__.__name__} with {tokenizer.__class__.__name__}."\n )\n', (2829, 2947), False, 'import argparse, hashlib, json, logging, os, sys\n'), ((148, 173), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (163, 173), False, 'import argparse, hashlib, json, logging, os, sys\n'), ((1440, 1480), 'os.path.join', 'os.path.join', (['args.out_path', '"""embed.log"""'], {}), "(args.out_path, 'embed.log')\n", (1452, 1480), False, 'import argparse, hashlib, json, logging, os, sys\n'), ((2576, 2617), 'transformers.AutoTokenizer.from_pretrained', 'AutoTokenizer.from_pretrained', (['args.model'], {}), '(args.model)\n', (2605, 2617), False, 'from transformers import AutoTokenizer, AutoModel\n'), ((2628, 2728), 'transformers.AutoModel.from_pretrained', 'AutoModel.from_pretrained', (['(args.model_path if args.model_path else args.model)'], {'return_dict': '(True)'}), '(args.model_path if args.model_path else args.\n model, return_dict=True)\n', (2653, 2728), False, 'from transformers import AutoTokenizer, AutoModel\n'), ((2757, 2782), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2780, 2782), False, 'import torch\n'), ((5503, 5521), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (5519, 5521), False, 'import argparse, hashlib, json, logging, os, sys\n'), ((5551, 5704), 'logging.info', 'logging.info', (['f"""{tokenizer.__class__.__name__} encoded corpus to {tkn_count} tokens with {unk_count} UNK tokens ({unk_count / tkn_count:.4f})."""'], {}), "(\n f'{tokenizer.__class__.__name__} encoded corpus to {tkn_count} tokens with {unk_count} UNK tokens ({unk_count / tkn_count:.4f}).'\n )\n", (5563, 5704), False, 'import argparse, hashlib, json, logging, os, sys\n'), ((3991, 4006), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4004, 4006), False, 'import torch\n'), ((6749, 6787), 'os.path.join', 'os.path.join', (['args.out_path', '"""map.pkl"""'], {}), "(args.out_path, 'map.pkl')\n", (6761, 6787), False, 'import argparse, hashlib, json, logging, os, sys\n'), ((6858, 6944), 'logging.info', 'logging.info', (['f"""Saved \'sentence hash\' -> \'embedding tensor\' map to \'{out_file}\'."""'], {}), '(\n f"Saved \'sentence hash\' -> \'embedding tensor\' map to \'{out_file}\'.")\n', (6870, 6944), False, 'import argparse, hashlib, json, logging, os, sys\n'), ((2793, 2813), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (2805, 2813), False, 'import torch\n'), ((3627, 3686), 'torch.sum', 'torch.sum', (["(enc_batch['input_ids'] != tokenizer.pad_token_id)"], {}), "(enc_batch['input_ids'] != tokenizer.pad_token_id)\n", (3636, 3686), False, 'import torch\n'), ((3710, 3769), 'torch.sum', 'torch.sum', (["(enc_batch['input_ids'] == tokenizer.unk_token_id)"], {}), "(enc_batch['input_ids'] == tokenizer.unk_token_id)\n", (3719, 3769), False, 'import torch\n'), ((4384, 4409), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (4407, 4409), False, 'import torch\n'), ((6490, 6558), 'logging.info', 'logging.info', (['f"""Saved embeddings to \'{tensor_path}\' as numpy array."""'], {}), '(f"Saved embeddings to \'{tensor_path}\' as numpy array.")\n', (6502, 6558), False, 'import argparse, hashlib, json, logging, os, sys\n'), ((3828, 3874), 'torch.sum', 'torch.sum', (["enc_batch['attention_mask']"], {'dim': '(-1)'}), "(enc_batch['attention_mask'], dim=-1)\n", (3837, 3874), False, 'import torch\n'), ((6423, 6463), 'numpy.array', 'np.array', (['embeddings[start_idx:sidx + 1]'], {}), '(embeddings[start_idx:sidx + 1])\n', (6431, 6463), True, 'import numpy as np\n'), ((4437, 4457), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (4449, 4457), False, 'import torch\n'), ((5047, 5101), 'torch.mean', 'torch.mean', (['emb_batch[sidx, att_batch[sidx], :]'], {'dim': '(0)'}), '(emb_batch[sidx, att_batch[sidx], :], dim=0)\n', (5057, 5101), False, 'import torch\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import math
import unittest
import numpy as np
from federatedml.optim import activation
class TestConvergeFunction(unittest.TestCase):
def test_numeric_stability(self):
x_list = np.linspace(-709, 709, 10000)
# Original function
# a = 1. / (1. + np.exp(-x))
for x in x_list:
a1 = 1. / (1. + np.exp(-x))
a2 = activation.sigmoid(x)
self.assertTrue(np.abs(a1 - a2) < 1e-5)
if __name__ == '__main__':
unittest.main()
| [
"unittest.main",
"numpy.abs",
"numpy.exp",
"numpy.linspace",
"federatedml.optim.activation.sigmoid"
] | [((1139, 1154), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1152, 1154), False, 'import unittest\n'), ((854, 883), 'numpy.linspace', 'np.linspace', (['(-709)', '(709)', '(10000)'], {}), '(-709, 709, 10000)\n', (865, 883), True, 'import numpy as np\n'), ((1032, 1053), 'federatedml.optim.activation.sigmoid', 'activation.sigmoid', (['x'], {}), '(x)\n', (1050, 1053), False, 'from federatedml.optim import activation\n'), ((1003, 1013), 'numpy.exp', 'np.exp', (['(-x)'], {}), '(-x)\n', (1009, 1013), True, 'import numpy as np\n'), ((1082, 1097), 'numpy.abs', 'np.abs', (['(a1 - a2)'], {}), '(a1 - a2)\n', (1088, 1097), True, 'import numpy as np\n')] |
from numpy import *
from pyboltz.basis import get_basis
import numpy as np
import h5py
from matplotlib.pyplot import *
from eigenhdf import load_sparse_h5
spectral_basis = get_basis()
S = np.matrix(spectral_basis.make_mass_matrix())
Sinv = np.matrix(diag(1/diag(S)))
matrices = []
with h5py.File('p2h.hdf5', 'r') as fh5:
matrices = []
for name, obj in fh5.items():
try:
k = int(name, base=10)
matrices.append({'k': k, 'M': np.array(obj)})
except:
if not obj.dtype == np.dtype('float64'):
P = load_sparse_h5(fh5, name)
matrices = [x['M'] for x in sorted(matrices, key=lambda x: x['k'])]
shapes = [x.shape[0] for x in matrices]
offsets = hstack((0, np.cumsum(shapes)))
n = offsets[-1]
M = np.matrix(np.zeros((n, n)))
for i in range(len(offsets)-1):
M[offsets[i]:offsets[i+1], offsets[i]:offsets[i+1]] = matrices[i]
I = Sinv*P.T*M.T*M*P
err = abs(I-eye(*I.shape)).sum()
print('error (cwise.sum): ', err)
| [
"h5py.File",
"pyboltz.basis.get_basis",
"numpy.zeros",
"numpy.dtype",
"numpy.cumsum",
"numpy.array",
"eigenhdf.load_sparse_h5"
] | [((173, 184), 'pyboltz.basis.get_basis', 'get_basis', ([], {}), '()\n', (182, 184), False, 'from pyboltz.basis import get_basis\n'), ((287, 313), 'h5py.File', 'h5py.File', (['"""p2h.hdf5"""', '"""r"""'], {}), "('p2h.hdf5', 'r')\n", (296, 313), False, 'import h5py\n'), ((775, 791), 'numpy.zeros', 'np.zeros', (['(n, n)'], {}), '((n, n))\n', (783, 791), True, 'import numpy as np\n'), ((725, 742), 'numpy.cumsum', 'np.cumsum', (['shapes'], {}), '(shapes)\n', (734, 742), True, 'import numpy as np\n'), ((464, 477), 'numpy.array', 'np.array', (['obj'], {}), '(obj)\n', (472, 477), True, 'import numpy as np\n'), ((569, 594), 'eigenhdf.load_sparse_h5', 'load_sparse_h5', (['fh5', 'name'], {}), '(fh5, name)\n', (583, 594), False, 'from eigenhdf import load_sparse_h5\n'), ((528, 547), 'numpy.dtype', 'np.dtype', (['"""float64"""'], {}), "('float64')\n", (536, 547), True, 'import numpy as np\n')] |
"""
Additional functions and demos for Burgers' equation.
"""
import sys, os
from clawpack import pyclaw
from clawpack import riemann
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import animation
import numpy as np
from utils import riemann_tools
from . import burgers
def multivalued_solution(t,fig=0):
"""Plots bump-into-wave figure at different times for interactive figure."""
if fig==0:
fig = plt.figure()
x = np.arange(-11.0,11.0,0.1)
y = np.exp(-x*x/10)
x2 = 1.0*x
x2 = x2 + t*y
plt.plot(x, y, '--k', label = "Initial Condition")
plt.plot(x2, y, '-k', label = r"Solution at time $t$")
plt.xlim([-10,10])
plt.legend(loc = 'upper left')
plt.title('t = %.2f' % t)
if t != 0:
numarrows = 7
arrowIndexList = np.linspace(len(x)/3,2*len(x)/3,numarrows, dtype = int)
for i in arrowIndexList:
plt.arrow(x[i], y[i], np.abs(t*y[i]-0.4), 0, head_width=0.02, head_length=0.4, fc='k', ec='k')
if fig==0: plt.show()
def shock():
"""Returns plot function for a shock solution."""
q_l, q_r = 5.0, 1.0
states, speeds, reval, wave_type = burgers.exact_riemann_solution(q_l ,q_r)
plot_function = riemann_tools.make_plot_function(states, speeds, reval, wave_type,
layout='horizontal',
variable_names=['q'],
plot_chars=[burgers.speed])
return plot_function
def shock_location(xshock=7.75,fig=0):
"""Plots equal-area shock figure for different shock positions for interactive figure."""
if fig==0:
fig = plt.figure()
t=10
x = np.arange(-11.0,11.0,0.05)
y = np.exp(-x*x/10)
x = x + t*y
x2 = 1.0*x
y2 = 1.0*y
region = -1
for i in range(len(x)):
if (x2[i] >= xshock and region == -1):
region = 0
maxy = 1.0*y[i-1]
if (x2[i] >= xshock and region == 0):
x2[i] = 1.0*xshock
y2[i] = 1.0*maxy
if (x2[i] < xshock and region == 0):
region = 1
maxy = 1.0*y[i-1]
if (x2[i] <= xshock and region == 1):
x2[i] = 1.0*xshock
y2[i] = 1.0*maxy
if (x2[i] > xshock and region == 1):
region = 2
plt.plot(x, y, '-k', lw = 2, label = "Multivalued solution")
plt.plot(x2, y2, '--r', lw = 2, label = "Shock solution")
if (xshock == 7.75):
plt.annotate(r"$A_1$", xy=(2, 0), xytext=(8.5,0.83), fontsize=15)
plt.annotate(r"$A_2$", xy=(2, 0), xytext=(6.5,0.15), fontsize=15)
plt.annotate(r"Equal Areas", xy=(2, 0), xytext=(-3,0.62), fontsize=15)
plt.annotate(r"$A_1=A_2$", xy=(2, 0), xytext=(-2.5,0.5), fontsize=15)
plt.xlim([-7.5,11])
plt.legend(loc = 'upper left')
if fig==0: plt.show()
def rarefaction_figure(t):
"""Plots rarefaction figure at different times for interactive figure."""
numarrows = 6
x = [-5., 0.0]
y = [0.2, 0.2]
for i in range(numarrows):
x.append(0.0)
y.append(y[0] + (i+1)*(1.0-y[0])/(numarrows+1))
x.extend([0.0,10.0])
y.extend([1.0,1.0])
x2 = 1.0*np.array(x)
x2[1:-1] = x2[1:-1] + t*np.array(y[1:-1])
plt.plot(x, y, '--k', label = "Initial Condition")
plt.plot(x2, y, '-k', label = r"Solution at time $t$")
plt.xlim([-5,10])
plt.ylim([0.0,1.2])
plt.legend(loc = 'upper left')
plt.title('t = %.2f' % t)
if t != 0:
for i in range(numarrows):
plt.arrow(x[2+i], y[2+i], np.abs(t*y[2+i]-0.4), 0, head_width=0.02, head_length=0.4, fc='k', ec='k')
plt.annotate(r"$q_r t$", xy=(2, 1), xytext=(t/2-0.2, 1.05), fontsize=12)
if t > 2:
plt.annotate(r"$q_l t$", xy=(2, 0), xytext=(t/8-0.4, 0.12), fontsize=12)
plt.arrow(t/2-0.3, 1.07, -t/2+0.8, 0, head_width=0.02, head_length=0.4, fc='k', ec='k')
plt.arrow(t/2+0.7, 1.07, t*y[-1] - t/2 - 1, 0, head_width=0.02, head_length=0.4, fc='k', ec='k')
def rarefaction():
"""Returns plot function for a rarefaction solution."""
q_l, q_r = 2.0, 4.0
states, speeds, reval, wave_type = burgers.exact_riemann_solution(q_l ,q_r)
plot_function = riemann_tools.make_plot_function(states, speeds, reval, wave_type,
layout='horizontal',
variable_names=['q'],
plot_chars=[burgers.speed])
return plot_function
def unphysical():
"""Returns plot function for an unphysical solution."""
q_l, q_r = 1.0, 5.0
states, speeds, reval, wave_type = burgers.unphysical_riemann_solution(q_l ,q_r)
plot_function = riemann_tools.make_plot_function(states, speeds, reval, wave_type,
layout='horizontal',
variable_names=['q'],
plot_chars=[burgers.speed])
return plot_function
def bump_animation(numframes):
"""Plots animation of solution with bump initial condition,
using pyclaw (calls bump_pyclaw)."""
x, frames = bump_pyclaw(numframes)
fig = plt.figure()
ax = plt.axes(xlim=(-1, 1), ylim=(-0.2, 1.2))
line, = ax.plot([], [], '-k', lw=2)
def fplot(frame_number):
frame = frames[frame_number]
pressure = frame.q[0,:]
line.set_data(x,pressure)
return line,
return animation.FuncAnimation(fig, fplot, frames=len(frames), interval=30)
def bump_pyclaw(numframes):
"""Returns pyclaw solution of bump initial condition."""
# Set pyclaw for burgers equation 1D
claw = pyclaw.Controller()
claw.tfinal = 1.5 # Set final time
claw.keep_copy = True # Keep solution data in memory for plotting
claw.output_format = None # Don't write solution data to file
claw.num_output_times = numframes # Number of output frames
claw.solver = pyclaw.ClawSolver1D(riemann.burgers_1D) # Choose burgers 1D Riemann solver
claw.solver.all_bcs = pyclaw.BC.periodic # Choose periodic BCs
claw.verbosity = False # Don't print pyclaw output
domain = pyclaw.Domain( (-1.,), (1.,), (500,)) # Choose domain and mesh resolution
claw.solution = pyclaw.Solution(claw.solver.num_eqn,domain)
# Set initial condition
x=domain.grid.x.centers
claw.solution.q[0,:] = np.exp(-10 * (x)**2)
claw.solver.dt_initial = 1.e99
# Run pyclaw
status = claw.run()
return x, claw.frames
def triplestate_animation(ql, qm, qr, numframes):
"""Plots animation of solution with triple-state initial condition, using pyclaw (calls
triplestate_pyclaw). Also plots characteristic structure by plotting contour plots of the
solution in the x-t plane """
# Get solution for animation and set plot
x, frames = triplestate_pyclaw(ql, qm, qr, numframes)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9,4))
ax1.set_xlim(-3, 3)
ax1.set_ylim(-3, 5)
ax2.set_xlim(-3, 3)
ax2.set_ylim(0, 2)
ax1.set_title('Solution q(x)')
ax1.set_xlabel('$x$')
ax1.set_ylabel('$q$')
ax2.set_title('xt-plane')
ax2.set_xlabel('$x$')
ax2.set_ylabel('$t$')
matplotlib.rcParams['contour.negative_linestyle'] = 'solid'
line1, = ax1.plot([], [], '-k', lw=2)
# Contour plot of high-res solution to show characteristic structure in xt-plane
meshpts = 2400
numframes2 = 600
x2, frames2 = triplestate_pyclaw(ql, qm, qr, numframes2)
characs = np.zeros([numframes2,meshpts])
xx = np.linspace(-12,12,meshpts)
tt = np.linspace(0,2,numframes2)
for j in range(numframes2):
characs[j] = frames2[j].q[0]
X,T = np.meshgrid(xx,tt)
ax2.contour(X, T, characs, levels=np.linspace(ql, ql+0.11 ,20), linewidths=0.5, colors='k')
ax2.contour(X, T, characs, levels=np.linspace(qm+0.11, qm+0.13 ,7), linewidths=0.5, colors='k')
ax2.contour(X, T, characs, levels=np.linspace(qr+0.13, qr+0.2 ,15), linewidths=0.5, colors='k')
ax2.contour(X, T, characs, 12, linewidths=0.5, colors='k')
#ax2.contour(X, T, characs, 38, colors='k')
# Add animated time line to xt-plane
line2, = ax2.plot(x, 0*x , '--k')
line = [line1, line2]
# Update data function for animation
def fplot(frame_number):
frame = frames[frame_number]
pressure = frame.q[0,:]
line[0].set_data(x,pressure)
line[1].set_data(x,0*x+frame.t)
return line
return animation.FuncAnimation(fig, fplot, frames=len(frames), interval=30, blit=False)
def triplestate_pyclaw(ql, qm, qr, numframes):
"""Returns pyclaw solution of triple-state initial condition."""
# Set pyclaw for burgers equation 1D
meshpts = 2400 #600
claw = pyclaw.Controller()
claw.tfinal = 2.0 # Set final time
claw.keep_copy = True # Keep solution data in memory for plotting
claw.output_format = None # Don't write solution data to file
claw.num_output_times = numframes # Number of output frames
claw.solver = pyclaw.ClawSolver1D(riemann.burgers_1D) # Choose burgers 1D Riemann solver
claw.solver.all_bcs = pyclaw.BC.extrap # Choose periodic BCs
claw.verbosity = False # Don't print pyclaw output
domain = pyclaw.Domain( (-12.,), (12.,), (meshpts,)) # Choose domain and mesh resolution
claw.solution = pyclaw.Solution(claw.solver.num_eqn,domain)
# Set initial condition
x=domain.grid.x.centers
q0 = 0.0*x
xtick1 = 900 + int(meshpts/12)
xtick2 = xtick1 + int(meshpts/12)
for i in range(xtick1):
q0[i] = ql + i*0.0001
#q0[0:xtick1] = ql
for i in np.arange(xtick1, xtick2):
q0[i] = qm + i*0.0001
#q0[xtick1:xtick2] = qm
for i in np.arange(xtick2, meshpts):
q0[i] = qr + i*0.0001
#q0[xtick2:meshpts] = qr
claw.solution.q[0,:] = q0
claw.solver.dt_initial = 1.e99
# Run pyclaw
status = claw.run()
return x, claw.frames
| [
"matplotlib.pyplot.title",
"numpy.abs",
"matplotlib.pyplot.axes",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.exp",
"clawpack.pyclaw.Domain",
"matplotlib.pyplot.arrow",
"numpy.meshgrid",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"clawpack.pyclaw.ClawSolver1D",
"matplotlib.pyplot... | [((457, 484), 'numpy.arange', 'np.arange', (['(-11.0)', '(11.0)', '(0.1)'], {}), '(-11.0, 11.0, 0.1)\n', (466, 484), True, 'import numpy as np\n'), ((491, 510), 'numpy.exp', 'np.exp', (['(-x * x / 10)'], {}), '(-x * x / 10)\n', (497, 510), True, 'import numpy as np\n'), ((544, 592), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""--k"""'], {'label': '"""Initial Condition"""'}), "(x, y, '--k', label='Initial Condition')\n", (552, 592), True, 'import matplotlib.pyplot as plt\n'), ((599, 650), 'matplotlib.pyplot.plot', 'plt.plot', (['x2', 'y', '"""-k"""'], {'label': '"""Solution at time $t$"""'}), "(x2, y, '-k', label='Solution at time $t$')\n", (607, 650), True, 'import matplotlib.pyplot as plt\n'), ((658, 677), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[-10, 10]'], {}), '([-10, 10])\n', (666, 677), True, 'import matplotlib.pyplot as plt\n'), ((681, 709), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""'}), "(loc='upper left')\n", (691, 709), True, 'import matplotlib.pyplot as plt\n'), ((716, 741), 'matplotlib.pyplot.title', 'plt.title', (["('t = %.2f' % t)"], {}), "('t = %.2f' % t)\n", (725, 741), True, 'import matplotlib.pyplot as plt\n'), ((1219, 1361), 'utils.riemann_tools.make_plot_function', 'riemann_tools.make_plot_function', (['states', 'speeds', 'reval', 'wave_type'], {'layout': '"""horizontal"""', 'variable_names': "['q']", 'plot_chars': '[burgers.speed]'}), "(states, speeds, reval, wave_type, layout=\n 'horizontal', variable_names=['q'], plot_chars=[burgers.speed])\n", (1251, 1361), False, 'from utils import riemann_tools\n'), ((1732, 1760), 'numpy.arange', 'np.arange', (['(-11.0)', '(11.0)', '(0.05)'], {}), '(-11.0, 11.0, 0.05)\n', (1741, 1760), True, 'import numpy as np\n'), ((1767, 1786), 'numpy.exp', 'np.exp', (['(-x * x / 10)'], {}), '(-x * x / 10)\n', (1773, 1786), True, 'import numpy as np\n'), ((2355, 2411), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""-k"""'], {'lw': '(2)', 'label': '"""Multivalued solution"""'}), "(x, y, '-k', lw=2, label='Multivalued solution')\n", (2363, 2411), True, 'import matplotlib.pyplot as plt\n'), ((2420, 2473), 'matplotlib.pyplot.plot', 'plt.plot', (['x2', 'y2', '"""--r"""'], {'lw': '(2)', 'label': '"""Shock solution"""'}), "(x2, y2, '--r', lw=2, label='Shock solution')\n", (2428, 2473), True, 'import matplotlib.pyplot as plt\n'), ((2812, 2832), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[-7.5, 11]'], {}), '([-7.5, 11])\n', (2820, 2832), True, 'import matplotlib.pyplot as plt\n'), ((2836, 2864), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""'}), "(loc='upper left')\n", (2846, 2864), True, 'import matplotlib.pyplot as plt\n'), ((3289, 3337), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""--k"""'], {'label': '"""Initial Condition"""'}), "(x, y, '--k', label='Initial Condition')\n", (3297, 3337), True, 'import matplotlib.pyplot as plt\n'), ((3344, 3395), 'matplotlib.pyplot.plot', 'plt.plot', (['x2', 'y', '"""-k"""'], {'label': '"""Solution at time $t$"""'}), "(x2, y, '-k', label='Solution at time $t$')\n", (3352, 3395), True, 'import matplotlib.pyplot as plt\n'), ((3403, 3421), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[-5, 10]'], {}), '([-5, 10])\n', (3411, 3421), True, 'import matplotlib.pyplot as plt\n'), ((3425, 3445), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0.0, 1.2]'], {}), '([0.0, 1.2])\n', (3433, 3445), True, 'import matplotlib.pyplot as plt\n'), ((3449, 3477), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""'}), "(loc='upper left')\n", (3459, 3477), True, 'import matplotlib.pyplot as plt\n'), ((3484, 3509), 'matplotlib.pyplot.title', 'plt.title', (["('t = %.2f' % t)"], {}), "('t = %.2f' % t)\n", (3493, 3509), True, 'import matplotlib.pyplot as plt\n'), ((4271, 4413), 'utils.riemann_tools.make_plot_function', 'riemann_tools.make_plot_function', (['states', 'speeds', 'reval', 'wave_type'], {'layout': '"""horizontal"""', 'variable_names': "['q']", 'plot_chars': '[burgers.speed]'}), "(states, speeds, reval, wave_type, layout=\n 'horizontal', variable_names=['q'], plot_chars=[burgers.speed])\n", (4303, 4413), False, 'from utils import riemann_tools\n'), ((4800, 4942), 'utils.riemann_tools.make_plot_function', 'riemann_tools.make_plot_function', (['states', 'speeds', 'reval', 'wave_type'], {'layout': '"""horizontal"""', 'variable_names': "['q']", 'plot_chars': '[burgers.speed]'}), "(states, speeds, reval, wave_type, layout=\n 'horizontal', variable_names=['q'], plot_chars=[burgers.speed])\n", (4832, 4942), False, 'from utils import riemann_tools\n'), ((5308, 5320), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5318, 5320), True, 'import matplotlib.pyplot as plt\n'), ((5330, 5370), 'matplotlib.pyplot.axes', 'plt.axes', ([], {'xlim': '(-1, 1)', 'ylim': '(-0.2, 1.2)'}), '(xlim=(-1, 1), ylim=(-0.2, 1.2))\n', (5338, 5370), True, 'import matplotlib.pyplot as plt\n'), ((5788, 5807), 'clawpack.pyclaw.Controller', 'pyclaw.Controller', ([], {}), '()\n', (5805, 5807), False, 'from clawpack import pyclaw\n'), ((6084, 6123), 'clawpack.pyclaw.ClawSolver1D', 'pyclaw.ClawSolver1D', (['riemann.burgers_1D'], {}), '(riemann.burgers_1D)\n', (6103, 6123), False, 'from clawpack import pyclaw\n'), ((6341, 6379), 'clawpack.pyclaw.Domain', 'pyclaw.Domain', (['(-1.0,)', '(1.0,)', '(500,)'], {}), '((-1.0,), (1.0,), (500,))\n', (6354, 6379), False, 'from clawpack import pyclaw\n'), ((6443, 6487), 'clawpack.pyclaw.Solution', 'pyclaw.Solution', (['claw.solver.num_eqn', 'domain'], {}), '(claw.solver.num_eqn, domain)\n', (6458, 6487), False, 'from clawpack import pyclaw\n'), ((6570, 6590), 'numpy.exp', 'np.exp', (['(-10 * x ** 2)'], {}), '(-10 * x ** 2)\n', (6576, 6590), True, 'import numpy as np\n'), ((7104, 7138), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(9, 4)'}), '(1, 2, figsize=(9, 4))\n', (7116, 7138), True, 'import matplotlib.pyplot as plt\n'), ((7710, 7741), 'numpy.zeros', 'np.zeros', (['[numframes2, meshpts]'], {}), '([numframes2, meshpts])\n', (7718, 7741), True, 'import numpy as np\n'), ((7750, 7779), 'numpy.linspace', 'np.linspace', (['(-12)', '(12)', 'meshpts'], {}), '(-12, 12, meshpts)\n', (7761, 7779), True, 'import numpy as np\n'), ((7787, 7816), 'numpy.linspace', 'np.linspace', (['(0)', '(2)', 'numframes2'], {}), '(0, 2, numframes2)\n', (7798, 7816), True, 'import numpy as np\n'), ((7894, 7913), 'numpy.meshgrid', 'np.meshgrid', (['xx', 'tt'], {}), '(xx, tt)\n', (7905, 7913), True, 'import numpy as np\n'), ((8950, 8969), 'clawpack.pyclaw.Controller', 'pyclaw.Controller', ([], {}), '()\n', (8967, 8969), False, 'from clawpack import pyclaw\n'), ((9246, 9285), 'clawpack.pyclaw.ClawSolver1D', 'pyclaw.ClawSolver1D', (['riemann.burgers_1D'], {}), '(riemann.burgers_1D)\n', (9265, 9285), False, 'from clawpack import pyclaw\n'), ((9500, 9544), 'clawpack.pyclaw.Domain', 'pyclaw.Domain', (['(-12.0,)', '(12.0,)', '(meshpts,)'], {}), '((-12.0,), (12.0,), (meshpts,))\n', (9513, 9544), False, 'from clawpack import pyclaw\n'), ((9602, 9646), 'clawpack.pyclaw.Solution', 'pyclaw.Solution', (['claw.solver.num_eqn', 'domain'], {}), '(claw.solver.num_eqn, domain)\n', (9617, 9646), False, 'from clawpack import pyclaw\n'), ((9881, 9906), 'numpy.arange', 'np.arange', (['xtick1', 'xtick2'], {}), '(xtick1, xtick2)\n', (9890, 9906), True, 'import numpy as np\n'), ((9979, 10005), 'numpy.arange', 'np.arange', (['xtick2', 'meshpts'], {}), '(xtick2, meshpts)\n', (9988, 10005), True, 'import numpy as np\n'), ((436, 448), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (446, 448), True, 'import matplotlib.pyplot as plt\n'), ((1015, 1025), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1023, 1025), True, 'import matplotlib.pyplot as plt\n'), ((1702, 1714), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1712, 1714), True, 'import matplotlib.pyplot as plt\n'), ((2511, 2576), 'matplotlib.pyplot.annotate', 'plt.annotate', (['"""$A_1$"""'], {'xy': '(2, 0)', 'xytext': '(8.5, 0.83)', 'fontsize': '(15)'}), "('$A_1$', xy=(2, 0), xytext=(8.5, 0.83), fontsize=15)\n", (2523, 2576), True, 'import matplotlib.pyplot as plt\n'), ((2585, 2650), 'matplotlib.pyplot.annotate', 'plt.annotate', (['"""$A_2$"""'], {'xy': '(2, 0)', 'xytext': '(6.5, 0.15)', 'fontsize': '(15)'}), "('$A_2$', xy=(2, 0), xytext=(6.5, 0.15), fontsize=15)\n", (2597, 2650), True, 'import matplotlib.pyplot as plt\n'), ((2659, 2729), 'matplotlib.pyplot.annotate', 'plt.annotate', (['"""Equal Areas"""'], {'xy': '(2, 0)', 'xytext': '(-3, 0.62)', 'fontsize': '(15)'}), "('Equal Areas', xy=(2, 0), xytext=(-3, 0.62), fontsize=15)\n", (2671, 2729), True, 'import matplotlib.pyplot as plt\n'), ((2738, 2807), 'matplotlib.pyplot.annotate', 'plt.annotate', (['"""$A_1=A_2$"""'], {'xy': '(2, 0)', 'xytext': '(-2.5, 0.5)', 'fontsize': '(15)'}), "('$A_1=A_2$', xy=(2, 0), xytext=(-2.5, 0.5), fontsize=15)\n", (2750, 2807), True, 'import matplotlib.pyplot as plt\n'), ((2882, 2892), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2890, 2892), True, 'import matplotlib.pyplot as plt\n'), ((3227, 3238), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (3235, 3238), True, 'import numpy as np\n'), ((3681, 3756), 'matplotlib.pyplot.annotate', 'plt.annotate', (['"""$q_r t$"""'], {'xy': '(2, 1)', 'xytext': '(t / 2 - 0.2, 1.05)', 'fontsize': '(12)'}), "('$q_r t$', xy=(2, 1), xytext=(t / 2 - 0.2, 1.05), fontsize=12)\n", (3693, 3756), True, 'import matplotlib.pyplot as plt\n'), ((3267, 3284), 'numpy.array', 'np.array', (['y[1:-1]'], {}), '(y[1:-1])\n', (3275, 3284), True, 'import numpy as np\n'), ((3784, 3859), 'matplotlib.pyplot.annotate', 'plt.annotate', (['"""$q_l t$"""'], {'xy': '(2, 0)', 'xytext': '(t / 8 - 0.4, 0.12)', 'fontsize': '(12)'}), "('$q_l t$', xy=(2, 0), xytext=(t / 8 - 0.4, 0.12), fontsize=12)\n", (3796, 3859), True, 'import matplotlib.pyplot as plt\n'), ((3869, 3969), 'matplotlib.pyplot.arrow', 'plt.arrow', (['(t / 2 - 0.3)', '(1.07)', '(-t / 2 + 0.8)', '(0)'], {'head_width': '(0.02)', 'head_length': '(0.4)', 'fc': '"""k"""', 'ec': '"""k"""'}), "(t / 2 - 0.3, 1.07, -t / 2 + 0.8, 0, head_width=0.02, head_length=\n 0.4, fc='k', ec='k')\n", (3878, 3969), True, 'import matplotlib.pyplot as plt\n'), ((3969, 4077), 'matplotlib.pyplot.arrow', 'plt.arrow', (['(t / 2 + 0.7)', '(1.07)', '(t * y[-1] - t / 2 - 1)', '(0)'], {'head_width': '(0.02)', 'head_length': '(0.4)', 'fc': '"""k"""', 'ec': '"""k"""'}), "(t / 2 + 0.7, 1.07, t * y[-1] - t / 2 - 1, 0, head_width=0.02,\n head_length=0.4, fc='k', ec='k')\n", (3978, 4077), True, 'import matplotlib.pyplot as plt\n'), ((7951, 7981), 'numpy.linspace', 'np.linspace', (['ql', '(ql + 0.11)', '(20)'], {}), '(ql, ql + 0.11, 20)\n', (7962, 7981), True, 'import numpy as np\n'), ((8047, 8083), 'numpy.linspace', 'np.linspace', (['(qm + 0.11)', '(qm + 0.13)', '(7)'], {}), '(qm + 0.11, qm + 0.13, 7)\n', (8058, 8083), True, 'import numpy as np\n'), ((8147, 8183), 'numpy.linspace', 'np.linspace', (['(qr + 0.13)', '(qr + 0.2)', '(15)'], {}), '(qr + 0.13, qr + 0.2, 15)\n', (8158, 8183), True, 'import numpy as np\n'), ((927, 949), 'numpy.abs', 'np.abs', (['(t * y[i] - 0.4)'], {}), '(t * y[i] - 0.4)\n', (933, 949), True, 'import numpy as np\n'), ((3598, 3624), 'numpy.abs', 'np.abs', (['(t * y[2 + i] - 0.4)'], {}), '(t * y[2 + i] - 0.4)\n', (3604, 3624), True, 'import numpy as np\n')] |
import json
import cv2
import numpy as np
import os
import sys
sys.path.append('../')
import Rect
#input original image and page bbox, output ROI (text region) bbox
def ExpandCol(rect,n):
#scale width by n
rect = [list(rect[0]), list(rect[1]), rect[2]]
if rect[1][0] > rect[1][1]:
rect[1][1] = rect[1][1] * n
else:
rect[1][0] = rect[1][0] * n
return tuple(rect)
def ShiftCol(rect,n):
#shift center by n (col width)
rect = [list(rect[0]), list(rect[1]), rect[2]]
colWidth=min(rect[1])/5
if rect[2]>-45:
rect[0][0] = rect[0][0] - colWidth * n * np.cos(np.deg2rad(rect[2]))
rect[0][1] = rect[0][1] - colWidth * n * np.sin(np.deg2rad(rect[2]))
else:
rect[0][0] = rect[0][0] - colWidth * n * np.sin(np.deg2rad(rect[2]))
rect[0][1] = rect[0][1] - colWidth * n * np.cos(np.deg2rad(rect[2]))
return rect
pagedir='../../results/personnel-records/1954/seg/official_office/ROI_rect'
pagefilename="pr1954_p0111_1.json"
with open(os.path.join(pagedir,pagefilename)) as file:
print("processing "+os.path.join(pagedir,pagefilename))
rect = json.load(file)
rect=ExpandCol(rect,5/6)
#rect=ShiftCol(rect,-0.5)
with open(os.path.join(pagedir,pagefilename), 'w') as outfile:
json.dump(rect, outfile)
print("writing to " + os.path.join(pagedir, pagefilename)) | [
"sys.path.append",
"json.dump",
"json.load",
"numpy.deg2rad",
"os.path.join"
] | [((63, 85), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (78, 85), False, 'import sys\n'), ((1135, 1150), 'json.load', 'json.load', (['file'], {}), '(file)\n', (1144, 1150), False, 'import json\n'), ((1272, 1296), 'json.dump', 'json.dump', (['rect', 'outfile'], {}), '(rect, outfile)\n', (1281, 1296), False, 'import json\n'), ((1019, 1054), 'os.path.join', 'os.path.join', (['pagedir', 'pagefilename'], {}), '(pagedir, pagefilename)\n', (1031, 1054), False, 'import os\n'), ((1215, 1250), 'os.path.join', 'os.path.join', (['pagedir', 'pagefilename'], {}), '(pagedir, pagefilename)\n', (1227, 1250), False, 'import os\n'), ((1088, 1123), 'os.path.join', 'os.path.join', (['pagedir', 'pagefilename'], {}), '(pagedir, pagefilename)\n', (1100, 1123), False, 'import os\n'), ((1323, 1358), 'os.path.join', 'os.path.join', (['pagedir', 'pagefilename'], {}), '(pagedir, pagefilename)\n', (1335, 1358), False, 'import os\n'), ((617, 636), 'numpy.deg2rad', 'np.deg2rad', (['rect[2]'], {}), '(rect[2])\n', (627, 636), True, 'import numpy as np\n'), ((694, 713), 'numpy.deg2rad', 'np.deg2rad', (['rect[2]'], {}), '(rect[2])\n', (704, 713), True, 'import numpy as np\n'), ((781, 800), 'numpy.deg2rad', 'np.deg2rad', (['rect[2]'], {}), '(rect[2])\n', (791, 800), True, 'import numpy as np\n'), ((858, 877), 'numpy.deg2rad', 'np.deg2rad', (['rect[2]'], {}), '(rect[2])\n', (868, 877), True, 'import numpy as np\n')] |
import quantities as pq
import numpy as np
def poisson_continuity_correction(n, observed):
"""
n : array
Likelihood to observe n or more events
observed : array
Rate of Poisson process
References
----------
<NAME>., & <NAME>. (2009). Unbiased estimation of precise temporal
correlations between spike trains. Journal of neuroscience methods, 179(1),
90-100.
"""
if n.ndim == 0:
n = np.array([n])
assert n.ndim == 1
from scipy.stats import poisson
assert np.all(n >= 0)
result = np.zeros(n.shape)
if n.shape != observed.shape:
observed = np.repeat(observed, n.size)
for i, (n_i, rate) in enumerate(zip(n, observed)):
if n_i == 0:
result[i] = 1.
else:
rates = [poisson.pmf(j, rate) for j in range(n_i)]
result[i] = 1 - np.sum(rates) - 0.5 * poisson.pmf(n_i, rate)
return result
def hollow_kernel(kernlen, width, hollow_fraction=0.6, kerntype='gaussian'):
'''
Returns a hollow kernel normalized to it's sum
Parameters
----------
kernlen : int
Length of kernel, must be uneven (kernlen % 2 == 1)
width : float
Width of kernel (std if gaussian)
hollow_fraction : float
Fractoin of the central bin to removed.
Returns
-------
kernel : array
'''
if kerntype == 'gaussian':
from scipy.signal import gaussian
assert kernlen % 2 == 1
kernel = gaussian(kernlen, width)
kernel[int(kernlen / 2.)] *= (1 - hollow_fraction)
else:
raise NotImplementedError
return kernel / sum(kernel)
def cch_convolve(cch, width, hollow_fraction, kerntype):
import scipy.signal as scs
kernlen = len(cch) - 1
kernel = hollow_kernel(kernlen, width, hollow_fraction, kerntype)
# padd edges
len_padd = int(kernlen / 2.)
cch_padded = np.zeros(len(cch) + 2 * len_padd)
# "firstW/2 bins (excluding the very first bin) are duplicated,
# reversed in time, and prepended to the cch prior to convolving"
cch_padded[0:len_padd] = cch[1:len_padd+1][::-1]
cch_padded[len_padd: - len_padd] = cch
# # "Likewise, the lastW/2 bins aresymmetrically appended to the cch."
cch_padded[-len_padd:] = cch[-len_padd-1:-1][::-1]
# convolve cch with kernel
result = scs.fftconvolve(cch_padded, kernel, mode='valid')
assert len(cch) == len(result)
return result
def cch_significance(t1, t2, binsize, limit, hollow_fraction, width,
kerntype='gaussian'):
"""
Parameters
---------
t1 : np.array, or neo.SpikeTrain
First spiketrain, raw spike times in seconds.
t2 : np.array, or neo.SpikeTrain
Second spiketrain, raw spike times in seconds.
binsize : float, or quantities.Quantity
Width of each bar in histogram in seconds.
limit : float, or quantities.Quantity
Positive and negative extent of histogram, in seconds.
kernlen : int
Length of kernel, must be uneven (kernlen % 2 == 1)
width : float
Width of kernel (std if gaussian)
hollow_fraction : float
Fraction of the central bin to removed.
References
----------
<NAME>., & <NAME>. (2009). Unbiased estimation of precise temporal
correlations between spike trains. Journal of neuroscience methods, 179(1),
90-100.
English et al. 2017, Neuron, Pyramidal Cell-Interneuron Circuit Architecture
and Dynamics in Hippocampal Networks
"""
cch, bins = correlogram(t1, t2, binsize=binsize, limit=limit,
density=False)
pfast = np.zeros(cch.shape)
cch_smooth = cch_convolve(cch=cch, width=width,
hollow_fraction=hollow_fraction,
kerntype=kerntype)
pfast = poisson_continuity_correction(cch, cch_smooth)
# ppeak describes the probability of obtaining a peak with positive lag
# of the histogram, that is signficantly larger than the largest peak
# in the negative lag direction.
ppeak = np.zeros(cch.shape)
max_vals = np.zeros(cch.shape)
cch_half_len = int(np.floor(len(cch) / 2.))
max_vals[cch_half_len:] = np.max(cch[:cch_half_len])
max_vals[:cch_half_len] = np.max(cch[cch_half_len:])
ppeak = poisson_continuity_correction(cch, max_vals)
return ppeak, pfast, bins, cch, cch_smooth
def transfer_probability(t1, t2, binsize, limit, hollow_fraction, width,
latency, winsize, kerntype='gaussian'):
cch, bins = correlogram(t1, t2, binsize=binsize, limit=limit,
density=False)
cch_s = cch_convolve(cch=cch, width=width,
hollow_fraction=hollow_fraction,
kerntype=kerntype)
mask = (bins >= latency) & (bins <= latency + winsize)
cmax = np.max(cch[mask])
idx, = np.where(cch==cmax * mask)
idx = idx if len(idx) == 1 else idx[0]
pfast, = poisson_continuity_correction(cmax, cch_s[idx])
cch_half_len = int(np.floor(len(cch) / 2.))
max_pre = np.max(cch[:cch_half_len])
ppeak, = poisson_continuity_correction(cmax, max_pre)
ptime = float(bins[idx])
trans_prob = sum(cch[mask] - cch_s[mask]) / len(t1)
return trans_prob, ppeak, pfast, ptime, cmax
def correlogram(t1, t2=None, binsize=.001, limit=.02, auto=False,
density=False):
"""Return crosscorrelogram of two spike trains.
Essentially, this algorithm subtracts each spike time in `t1`
from all of `t2` and bins the results with np.histogram, though
several tweaks were made for efficiency.
Originally authored by <NAME>, copied from OpenElectrophy, licenced
with CeCill-B. Examples and testing written by exana team.
Parameters
---------
t1 : np.array, or neo.SpikeTrain
First spiketrain, raw spike times in seconds.
t2 : np.array, or neo.SpikeTrain
Second spiketrain, raw spike times in seconds.
binsize : float, or quantities.Quantity
Width of each bar in histogram in seconds.
limit : float, or quantities.Quantity
Positive and negative extent of histogram, in seconds.
auto : bool
If True, then returns autocorrelogram of `t1` and in
this case `t2` can be None. Default is False.
density : bool
If True, then returns the probability density function.
See also
--------
:func:`numpy.histogram` : The histogram function in use.
Returns
-------
(count, bins) : tuple
A tuple containing the bin right edges and the
count/density of spikes in each bin.
Note
----
`bins` are relative to `t1`. That is, if `t1` leads `t2`, then
`count` will peak in a positive time bin.
Examples
--------
>>> t1 = np.arange(0, .5, .1)
>>> t2 = np.arange(0.1, .6, .1)
>>> limit = 1
>>> binsize = .1
>>> counts, bins = correlogram(t1=t1, t2=t2, binsize=binsize,
... limit=limit, auto=False)
>>> counts
array([0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0, 0, 0, 0])
The interpretation of this result is that there are 5 occurences where
in the bin 0 to 0.1, i.e.
>>> idx = np.argmax(counts)
>>> '%.1f, %.1f' % (abs(bins[idx - 1]), bins[idx])
'0.0, 0.1'
The correlogram algorithm is identical to, but computationally faster than
the histogram of differences of each timepoint, i.e.
>>> diff = [t2 - t for t in t1]
>>> counts2, bins = np.histogram(diff, bins=bins)
>>> np.array_equal(counts2, counts)
True
"""
if auto: t2 = t1
lot = [t1, t2, limit, binsize]
if any(isinstance(a, pq.Quantity) for a in lot):
if not all(isinstance(a, pq.Quantity) for a in lot):
raise ValueError('If any is quantity all must be ' +
'{}'.format([type(d) for d in lot]))
dim = t1.dimensionality
t1, t2, limit, binsize = [a.rescale(dim).magnitude for a in lot]
# For auto-CCGs, make sure we use the same exact values
# Otherwise numerical issues may arise when we compensate for zeros later
if not int(limit * 1e10) % int(binsize * 1e10) == 0:
raise ValueError('Time limit {} must be a '.format(limit) +
'multiple of binsize {}'.format(binsize) +
' remainder = {}'.format(limit % binsize))
# For efficiency, `t1` should be no longer than `t2`
swap_args = False
if len(t1) > len(t2):
swap_args = True
t1, t2 = t2, t1
# Sort both arguments (this takes negligible time)
t1 = np.sort(t1)
t2 = np.sort(t2)
# Determine the bin edges for the histogram
# Later we will rely on the symmetry of `bins` for undoing `swap_args`
limit = float(limit)
# The numpy.arange method overshoots slightly the edges i.e. binsize + epsilon
# which leads to inclusion of spikes falling on edges.
bins = np.arange(-limit, limit + binsize, binsize)
# Determine the indexes into `t2` that are relevant for each spike in `t1`
ii2 = np.searchsorted(t2, t1 - limit)
jj2 = np.searchsorted(t2, t1 + limit)
# Concatenate the recentered spike times into a big array
# We have excluded spikes outside of the histogram range to limit
# memory use here.
big = np.concatenate([t2[i:j] - t for t, i, j in zip(t1, ii2, jj2)])
# Actually do the histogram. Note that calls to np.histogram are
# expensive because it does not assume sorted data.
count, bins = np.histogram(big, bins=bins, density=density)
if auto:
# Compensate for the peak at time zero that results in autocorrelations
# by subtracting the total number of spikes from that bin. Note
# possible numerical issue here because 0.0 may fall at a bin edge.
c_temp, bins_temp = np.histogram([0.], bins=bins)
bin_containing_zero = np.nonzero(c_temp)[0][0]
count[bin_containing_zero] = 0#-= len(t1)
# Finally compensate for the swapping of t1 and t2
if swap_args:
# Here we rely on being able to simply reverse `counts`. This is only
# possible because of the way `bins` was defined (bins = -bins[::-1])
count = count[::-1]
return count, bins[1:]
| [
"numpy.sum",
"numpy.zeros",
"numpy.searchsorted",
"scipy.signal.gaussian",
"scipy.stats.poisson.pmf",
"numpy.nonzero",
"numpy.sort",
"numpy.max",
"numpy.where",
"numpy.arange",
"numpy.histogram",
"numpy.array",
"scipy.signal.fftconvolve",
"numpy.all",
"numpy.repeat"
] | [((531, 545), 'numpy.all', 'np.all', (['(n >= 0)'], {}), '(n >= 0)\n', (537, 545), True, 'import numpy as np\n'), ((559, 576), 'numpy.zeros', 'np.zeros', (['n.shape'], {}), '(n.shape)\n', (567, 576), True, 'import numpy as np\n'), ((2340, 2389), 'scipy.signal.fftconvolve', 'scs.fftconvolve', (['cch_padded', 'kernel'], {'mode': '"""valid"""'}), "(cch_padded, kernel, mode='valid')\n", (2355, 2389), True, 'import scipy.signal as scs\n'), ((3635, 3654), 'numpy.zeros', 'np.zeros', (['cch.shape'], {}), '(cch.shape)\n', (3643, 3654), True, 'import numpy as np\n'), ((4077, 4096), 'numpy.zeros', 'np.zeros', (['cch.shape'], {}), '(cch.shape)\n', (4085, 4096), True, 'import numpy as np\n'), ((4112, 4131), 'numpy.zeros', 'np.zeros', (['cch.shape'], {}), '(cch.shape)\n', (4120, 4131), True, 'import numpy as np\n'), ((4210, 4236), 'numpy.max', 'np.max', (['cch[:cch_half_len]'], {}), '(cch[:cch_half_len])\n', (4216, 4236), True, 'import numpy as np\n'), ((4267, 4293), 'numpy.max', 'np.max', (['cch[cch_half_len:]'], {}), '(cch[cch_half_len:])\n', (4273, 4293), True, 'import numpy as np\n'), ((4877, 4894), 'numpy.max', 'np.max', (['cch[mask]'], {}), '(cch[mask])\n', (4883, 4894), True, 'import numpy as np\n'), ((4906, 4934), 'numpy.where', 'np.where', (['(cch == cmax * mask)'], {}), '(cch == cmax * mask)\n', (4914, 4934), True, 'import numpy as np\n'), ((5099, 5125), 'numpy.max', 'np.max', (['cch[:cch_half_len]'], {}), '(cch[:cch_half_len])\n', (5105, 5125), True, 'import numpy as np\n'), ((8640, 8651), 'numpy.sort', 'np.sort', (['t1'], {}), '(t1)\n', (8647, 8651), True, 'import numpy as np\n'), ((8661, 8672), 'numpy.sort', 'np.sort', (['t2'], {}), '(t2)\n', (8668, 8672), True, 'import numpy as np\n'), ((8976, 9019), 'numpy.arange', 'np.arange', (['(-limit)', '(limit + binsize)', 'binsize'], {}), '(-limit, limit + binsize, binsize)\n', (8985, 9019), True, 'import numpy as np\n'), ((9110, 9141), 'numpy.searchsorted', 'np.searchsorted', (['t2', '(t1 - limit)'], {}), '(t2, t1 - limit)\n', (9125, 9141), True, 'import numpy as np\n'), ((9152, 9183), 'numpy.searchsorted', 'np.searchsorted', (['t2', '(t1 + limit)'], {}), '(t2, t1 + limit)\n', (9167, 9183), True, 'import numpy as np\n'), ((9557, 9602), 'numpy.histogram', 'np.histogram', (['big'], {'bins': 'bins', 'density': 'density'}), '(big, bins=bins, density=density)\n', (9569, 9602), True, 'import numpy as np\n'), ((447, 460), 'numpy.array', 'np.array', (['[n]'], {}), '([n])\n', (455, 460), True, 'import numpy as np\n'), ((630, 657), 'numpy.repeat', 'np.repeat', (['observed', 'n.size'], {}), '(observed, n.size)\n', (639, 657), True, 'import numpy as np\n'), ((1484, 1508), 'scipy.signal.gaussian', 'gaussian', (['kernlen', 'width'], {}), '(kernlen, width)\n', (1492, 1508), False, 'from scipy.signal import gaussian\n'), ((9873, 9903), 'numpy.histogram', 'np.histogram', (['[0.0]'], {'bins': 'bins'}), '([0.0], bins=bins)\n', (9885, 9903), True, 'import numpy as np\n'), ((796, 816), 'scipy.stats.poisson.pmf', 'poisson.pmf', (['j', 'rate'], {}), '(j, rate)\n', (807, 816), False, 'from scipy.stats import poisson\n'), ((9933, 9951), 'numpy.nonzero', 'np.nonzero', (['c_temp'], {}), '(c_temp)\n', (9943, 9951), True, 'import numpy as np\n'), ((866, 879), 'numpy.sum', 'np.sum', (['rates'], {}), '(rates)\n', (872, 879), True, 'import numpy as np\n'), ((888, 910), 'scipy.stats.poisson.pmf', 'poisson.pmf', (['n_i', 'rate'], {}), '(n_i, rate)\n', (899, 910), False, 'from scipy.stats import poisson\n')] |
# ==============================================================================
# This file is part of the SPNC project under the Apache License v2.0 by the
# Embedded Systems and Applications Group, TU Darmstadt.
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
# SPDX-License-Identifier: Apache-2.0
# ==============================================================================
import numpy as np
import pytest
from spn.structure.Base import Product, Sum
from spn.structure.leaves.parametric.Parametric import Categorical
from spn.algorithms.Inference import log_likelihood
from spnc.gpu import CUDACompiler
@pytest.mark.skipif(not CUDACompiler.isAvailable(), reason="CUDA not supported")
def test_cuda_marginal_categorical():
# Construct a minimal SPN
c1 = Categorical(p=[0.35, 0.55, 0.1], scope=0)
c2 = Categorical(p=[0.25, 0.625, 0.125], scope=1)
c3 = Categorical(p=[0.5, 0.2, 0.3], scope=2)
c4 = Categorical(p=[0.6, 0.15, 0.25], scope=3)
c5 = Categorical(p=[0.7, 0.11, 0.19], scope=4)
c6 = Categorical(p=[0.8, 0.14, 0.06], scope=5)
p = Product(children=[c1, c2, c3, c4, c5, c6])
# Randomly sample input values.
inputs = np.column_stack((
np.random.randint(3, size=30),
np.random.randint(3, size=30),
np.random.randint(3, size=30),
np.random.randint(3, size=30),
np.random.randint(3, size=30),
np.random.randint(3, size=30),
)).astype("float64")
# Insert some NaN in random places into the input data.
inputs.ravel()[np.random.choice(inputs.size, 10, replace=False)] = np.nan
if not CUDACompiler.isAvailable():
print("Test not supported by the compiler installation")
return 0
# Execute the compiled Kernel.
results = CUDACompiler().log_likelihood(p, inputs)
# Compute the reference results using the inference from SPFlow.
reference = log_likelihood(p, inputs)
reference = reference.reshape(30)
# Check the computation results against the reference
# Check in normal space if log-results are not very close to each other.
assert np.all(np.isclose(results, reference)) or np.all(np.isclose(np.exp(results), np.exp(reference)))
if __name__ == "__main__":
test_cuda_marginal_categorical()
print("COMPUTATION OK")
| [
"spnc.gpu.CUDACompiler.isAvailable",
"spnc.gpu.CUDACompiler",
"numpy.isclose",
"numpy.random.randint",
"spn.algorithms.Inference.log_likelihood",
"numpy.exp",
"spn.structure.leaves.parametric.Parametric.Categorical",
"numpy.random.choice",
"spn.structure.Base.Product"
] | [((858, 899), 'spn.structure.leaves.parametric.Parametric.Categorical', 'Categorical', ([], {'p': '[0.35, 0.55, 0.1]', 'scope': '(0)'}), '(p=[0.35, 0.55, 0.1], scope=0)\n', (869, 899), False, 'from spn.structure.leaves.parametric.Parametric import Categorical\n'), ((909, 953), 'spn.structure.leaves.parametric.Parametric.Categorical', 'Categorical', ([], {'p': '[0.25, 0.625, 0.125]', 'scope': '(1)'}), '(p=[0.25, 0.625, 0.125], scope=1)\n', (920, 953), False, 'from spn.structure.leaves.parametric.Parametric import Categorical\n'), ((963, 1002), 'spn.structure.leaves.parametric.Parametric.Categorical', 'Categorical', ([], {'p': '[0.5, 0.2, 0.3]', 'scope': '(2)'}), '(p=[0.5, 0.2, 0.3], scope=2)\n', (974, 1002), False, 'from spn.structure.leaves.parametric.Parametric import Categorical\n'), ((1012, 1053), 'spn.structure.leaves.parametric.Parametric.Categorical', 'Categorical', ([], {'p': '[0.6, 0.15, 0.25]', 'scope': '(3)'}), '(p=[0.6, 0.15, 0.25], scope=3)\n', (1023, 1053), False, 'from spn.structure.leaves.parametric.Parametric import Categorical\n'), ((1063, 1104), 'spn.structure.leaves.parametric.Parametric.Categorical', 'Categorical', ([], {'p': '[0.7, 0.11, 0.19]', 'scope': '(4)'}), '(p=[0.7, 0.11, 0.19], scope=4)\n', (1074, 1104), False, 'from spn.structure.leaves.parametric.Parametric import Categorical\n'), ((1114, 1155), 'spn.structure.leaves.parametric.Parametric.Categorical', 'Categorical', ([], {'p': '[0.8, 0.14, 0.06]', 'scope': '(5)'}), '(p=[0.8, 0.14, 0.06], scope=5)\n', (1125, 1155), False, 'from spn.structure.leaves.parametric.Parametric import Categorical\n'), ((1164, 1206), 'spn.structure.Base.Product', 'Product', ([], {'children': '[c1, c2, c3, c4, c5, c6]'}), '(children=[c1, c2, c3, c4, c5, c6])\n', (1171, 1206), False, 'from spn.structure.Base import Product, Sum\n'), ((1971, 1996), 'spn.algorithms.Inference.log_likelihood', 'log_likelihood', (['p', 'inputs'], {}), '(p, inputs)\n', (1985, 1996), False, 'from spn.algorithms.Inference import log_likelihood\n'), ((1613, 1661), 'numpy.random.choice', 'np.random.choice', (['inputs.size', '(10)'], {'replace': '(False)'}), '(inputs.size, 10, replace=False)\n', (1629, 1661), True, 'import numpy as np\n'), ((1684, 1710), 'spnc.gpu.CUDACompiler.isAvailable', 'CUDACompiler.isAvailable', ([], {}), '()\n', (1708, 1710), False, 'from spnc.gpu import CUDACompiler\n'), ((724, 750), 'spnc.gpu.CUDACompiler.isAvailable', 'CUDACompiler.isAvailable', ([], {}), '()\n', (748, 750), False, 'from spnc.gpu import CUDACompiler\n'), ((1844, 1858), 'spnc.gpu.CUDACompiler', 'CUDACompiler', ([], {}), '()\n', (1856, 1858), False, 'from spnc.gpu import CUDACompiler\n'), ((2189, 2219), 'numpy.isclose', 'np.isclose', (['results', 'reference'], {}), '(results, reference)\n', (2199, 2219), True, 'import numpy as np\n'), ((2242, 2257), 'numpy.exp', 'np.exp', (['results'], {}), '(results)\n', (2248, 2257), True, 'import numpy as np\n'), ((2259, 2276), 'numpy.exp', 'np.exp', (['reference'], {}), '(reference)\n', (2265, 2276), True, 'import numpy as np\n'), ((1283, 1312), 'numpy.random.randint', 'np.random.randint', (['(3)'], {'size': '(30)'}), '(3, size=30)\n', (1300, 1312), True, 'import numpy as np\n'), ((1322, 1351), 'numpy.random.randint', 'np.random.randint', (['(3)'], {'size': '(30)'}), '(3, size=30)\n', (1339, 1351), True, 'import numpy as np\n'), ((1361, 1390), 'numpy.random.randint', 'np.random.randint', (['(3)'], {'size': '(30)'}), '(3, size=30)\n', (1378, 1390), True, 'import numpy as np\n'), ((1400, 1429), 'numpy.random.randint', 'np.random.randint', (['(3)'], {'size': '(30)'}), '(3, size=30)\n', (1417, 1429), True, 'import numpy as np\n'), ((1439, 1468), 'numpy.random.randint', 'np.random.randint', (['(3)'], {'size': '(30)'}), '(3, size=30)\n', (1456, 1468), True, 'import numpy as np\n'), ((1478, 1507), 'numpy.random.randint', 'np.random.randint', (['(3)'], {'size': '(30)'}), '(3, size=30)\n', (1495, 1507), True, 'import numpy as np\n')] |
'''
torch = 0.41
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import gym
import time
##################### hyper parameters ####################
MAX_EPISODES = 200
MAX_EP_STEPS = 200
LR_A = 0.001 # learning rate for actor
LR_C = 0.002 # learning rate for critic
GAMMA = 0.9 # reward discount
TAU = 0.01 # soft replacement
MEMORY_CAPACITY = 10000
BATCH_SIZE = 32
TAU = 0.01
RENDER = False
ENV_NAME = 'Pendulum-v0'
############################### DDPG ####################################
class ANet(nn.Module): # ae(s)=a
def __init__(self,s_dim,a_dim):
super(ANet,self).__init__()
self.fc1 = nn.Linear(s_dim,30)
self.fc1.weight.data.normal_(0,0.1) # initialization
self.out = nn.Linear(30,a_dim)
self.out.weight.data.normal_(0,0.1) # initialization
def forward(self,x):
x = self.fc1(x)
x = F.relu(x)
x = self.out(x)
x = F.tanh(x)
actions_value = x*2
return actions_value
class CNet(nn.Module): # ae(s)=a
def __init__(self,s_dim,a_dim):
super(CNet,self).__init__()
self.fcs = nn.Linear(s_dim,30)
self.fcs.weight.data.normal_(0,0.1) # initialization
self.fca = nn.Linear(a_dim,30)
self.fca.weight.data.normal_(0,0.1) # initialization
self.out = nn.Linear(30,1)
self.out.weight.data.normal_(0, 0.1) # initialization
def forward(self,s,a):
x = self.fcs(s)
y = self.fca(a)
net = F.relu(x+y)
actions_value = self.out(net)
return actions_value
class DDPG(object):
def __init__(self, a_dim, s_dim, a_bound,):
self.a_dim, self.s_dim, self.a_bound = a_dim, s_dim, a_bound,
self.memory = np.zeros((MEMORY_CAPACITY, s_dim * 2 + a_dim + 1), dtype=np.float32)
self.pointer = 0
#self.sess = tf.Session()
self.Actor_eval = ANet(s_dim,a_dim)
self.Actor_target = ANet(s_dim,a_dim)
self.Critic_eval = CNet(s_dim,a_dim)
self.Critic_target = CNet(s_dim,a_dim)
self.ctrain = torch.optim.Adam(self.Critic_eval.parameters(),lr=LR_C)
self.atrain = torch.optim.Adam(self.Actor_eval.parameters(),lr=LR_A)
self.loss_td = nn.MSELoss()
def choose_action(self, s):
s = torch.unsqueeze(torch.FloatTensor(s), 0)
return self.Actor_eval(s)[0].detach() # ae(s)
def learn(self):
for x in self.Actor_target.state_dict().keys():
eval('self.Actor_target.' + x + '.data.mul_((1-TAU))')
eval('self.Actor_target.' + x + '.data.add_(TAU*self.Actor_eval.' + x + '.data)')
for x in self.Critic_target.state_dict().keys():
eval('self.Critic_target.' + x + '.data.mul_((1-TAU))')
eval('self.Critic_target.' + x + '.data.add_(TAU*self.Critic_eval.' + x + '.data)')
# soft target replacement
#self.sess.run(self.soft_replace) # 用ae、ce更新at,ct
indices = np.random.choice(MEMORY_CAPACITY, size=BATCH_SIZE)
bt = self.memory[indices, :]
bs = torch.FloatTensor(bt[:, :self.s_dim])
ba = torch.FloatTensor(bt[:, self.s_dim: self.s_dim + self.a_dim])
br = torch.FloatTensor(bt[:, -self.s_dim - 1: -self.s_dim])
bs_ = torch.FloatTensor(bt[:, -self.s_dim:])
a = self.Actor_eval(bs)
q = self.Critic_eval(bs,a) # loss=-q=-ce(s,ae(s))更新ae ae(s)=a ae(s_)=a_
# 如果 a是一个正确的行为的话,那么它的Q应该更贴近0
loss_a = -torch.mean(q)
#print(q)
#print(loss_a)
self.atrain.zero_grad()
loss_a.backward()
self.atrain.step()
a_ = self.Actor_target(bs_) # 这个网络不及时更新参数, 用于预测 Critic 的 Q_target 中的 action
q_ = self.Critic_target(bs_,a_) # 这个网络不及时更新参数, 用于给出 Actor 更新参数时的 Gradient ascent 强度
q_target = br+GAMMA*q_ # q_target = 负的
#print(q_target)
q_v = self.Critic_eval(bs,ba)
#print(q_v)
td_error = self.loss_td(q_target,q_v)
# td_error=R + GAMMA * ct(bs_,at(bs_))-ce(s,ba) 更新ce ,但这个ae(s)是记忆中的ba,让ce得出的Q靠近Q_target,让评价更准确
#print(td_error)
self.ctrain.zero_grad()
td_error.backward()
self.ctrain.step()
def store_transition(self, s, a, r, s_):
transition = np.hstack((s, a, [r], s_))
index = self.pointer % MEMORY_CAPACITY # replace the old memory with new memory
self.memory[index, :] = transition
self.pointer += 1
############################### training ####################################
env = gym.make(ENV_NAME)
env = env.unwrapped
env.seed(1)
s_dim = env.observation_space.shape[0]
a_dim = env.action_space.shape[0]
a_bound = env.action_space.high
ddpg = DDPG(a_dim, s_dim, a_bound)
var = 3 # control exploration
t1 = time.time()
for i in range(MAX_EPISODES):
s = env.reset()
ep_reward = 0
for j in range(MAX_EP_STEPS):
if RENDER:
env.render()
# Add exploration noise
a = ddpg.choose_action(s)
a = np.clip(np.random.normal(a, var), -2, 2) # add randomness to action selection for exploration
s_, r, done, info = env.step(a)
ddpg.store_transition(s, a, r / 10, s_)
if ddpg.pointer > MEMORY_CAPACITY:
var *= .9995 # decay the action randomness
ddpg.learn()
s = s_
ep_reward += r
if j == MAX_EP_STEPS-1:
print('Episode:', i, ' Reward: %i' % int(ep_reward), 'Explore: %.2f' % var, )
if ep_reward > -300:RENDER = True
break
print('Running time: ', time.time() - t1)
| [
"torch.mean",
"numpy.random.choice",
"torch.nn.MSELoss",
"gym.make",
"numpy.zeros",
"torch.FloatTensor",
"time.time",
"numpy.hstack",
"numpy.random.normal",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.nn.functional.tanh"
] | [((4547, 4565), 'gym.make', 'gym.make', (['ENV_NAME'], {}), '(ENV_NAME)\n', (4555, 4565), False, 'import gym\n'), ((4776, 4787), 'time.time', 'time.time', ([], {}), '()\n', (4785, 4787), False, 'import time\n'), ((682, 702), 'torch.nn.Linear', 'nn.Linear', (['s_dim', '(30)'], {}), '(s_dim, 30)\n', (691, 702), True, 'import torch.nn as nn\n'), ((782, 802), 'torch.nn.Linear', 'nn.Linear', (['(30)', 'a_dim'], {}), '(30, a_dim)\n', (791, 802), True, 'import torch.nn as nn\n'), ((924, 933), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (930, 933), True, 'import torch.nn.functional as F\n'), ((970, 979), 'torch.nn.functional.tanh', 'F.tanh', (['x'], {}), '(x)\n', (976, 979), True, 'import torch.nn.functional as F\n'), ((1164, 1184), 'torch.nn.Linear', 'nn.Linear', (['s_dim', '(30)'], {}), '(s_dim, 30)\n', (1173, 1184), True, 'import torch.nn as nn\n'), ((1264, 1284), 'torch.nn.Linear', 'nn.Linear', (['a_dim', '(30)'], {}), '(a_dim, 30)\n', (1273, 1284), True, 'import torch.nn as nn\n'), ((1364, 1380), 'torch.nn.Linear', 'nn.Linear', (['(30)', '(1)'], {}), '(30, 1)\n', (1373, 1380), True, 'import torch.nn as nn\n'), ((1532, 1545), 'torch.nn.functional.relu', 'F.relu', (['(x + y)'], {}), '(x + y)\n', (1538, 1545), True, 'import torch.nn.functional as F\n'), ((1773, 1841), 'numpy.zeros', 'np.zeros', (['(MEMORY_CAPACITY, s_dim * 2 + a_dim + 1)'], {'dtype': 'np.float32'}), '((MEMORY_CAPACITY, s_dim * 2 + a_dim + 1), dtype=np.float32)\n', (1781, 1841), True, 'import numpy as np\n'), ((2261, 2273), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (2271, 2273), True, 'import torch.nn as nn\n'), ((2988, 3038), 'numpy.random.choice', 'np.random.choice', (['MEMORY_CAPACITY'], {'size': 'BATCH_SIZE'}), '(MEMORY_CAPACITY, size=BATCH_SIZE)\n', (3004, 3038), True, 'import numpy as np\n'), ((3089, 3126), 'torch.FloatTensor', 'torch.FloatTensor', (['bt[:, :self.s_dim]'], {}), '(bt[:, :self.s_dim])\n', (3106, 3126), False, 'import torch\n'), ((3140, 3200), 'torch.FloatTensor', 'torch.FloatTensor', (['bt[:, self.s_dim:self.s_dim + self.a_dim]'], {}), '(bt[:, self.s_dim:self.s_dim + self.a_dim])\n', (3157, 3200), False, 'import torch\n'), ((3215, 3268), 'torch.FloatTensor', 'torch.FloatTensor', (['bt[:, -self.s_dim - 1:-self.s_dim]'], {}), '(bt[:, -self.s_dim - 1:-self.s_dim])\n', (3232, 3268), False, 'import torch\n'), ((3284, 3322), 'torch.FloatTensor', 'torch.FloatTensor', (['bt[:, -self.s_dim:]'], {}), '(bt[:, -self.s_dim:])\n', (3301, 3322), False, 'import torch\n'), ((4275, 4301), 'numpy.hstack', 'np.hstack', (['(s, a, [r], s_)'], {}), '((s, a, [r], s_))\n', (4284, 4301), True, 'import numpy as np\n'), ((5575, 5586), 'time.time', 'time.time', ([], {}), '()\n', (5584, 5586), False, 'import time\n'), ((2335, 2355), 'torch.FloatTensor', 'torch.FloatTensor', (['s'], {}), '(s)\n', (2352, 2355), False, 'import torch\n'), ((3496, 3509), 'torch.mean', 'torch.mean', (['q'], {}), '(q)\n', (3506, 3509), False, 'import torch\n'), ((5021, 5045), 'numpy.random.normal', 'np.random.normal', (['a', 'var'], {}), '(a, var)\n', (5037, 5045), True, 'import numpy as np\n')] |
################################################################################
# skforecast #
# #
# This work by <NAME> is licensed under a Creative Commons #
# Attribution 4.0 International License. #
################################################################################
# coding=utf-8
import typing
from typing import Union, Dict
import warnings
import logging
import numpy as np
import pandas as pd
import sklearn
import tqdm
from sklearn.multioutput import MultiOutputRegressor
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_absolute_percentage_error
logging.basicConfig(
format = '%(asctime)-5s %(name)-10s %(levelname)-5s %(message)s',
level = logging.INFO,
)
################################################################################
# ForecasterAutoregMultiOutput #
################################################################################
class ForecasterAutoregMultiOutput():
'''
This class turns a scikit-learn regressor into a autoregressive multi-output
forecaster. A separate model is created for each forecast time step. See Notes
for more details.
Parameters
----------
regressor : scikit-learn regressor
An instance of a scikit-learn regressor.
lags : int, list, 1D np.array, range
Lags used as predictors. Index starts at 1, so lag 1 is equal to t-1.
`int`: include lags from 1 to `lags` (included).
`list` or `np.array`: include only lags present in `lags`.
steps : int
Number of future steps the forecaster will predict when using method
`predict()`. Since a diferent model is created for each step, this value
should be defined before training.
Attributes
----------
regressor : scikit-learn regressor
An instance of a scikit-learn regressor.
steps : int
Number of future steps the forecaster will predict when using method
`predict()`. Since a diferent model is created for each step, this value
should be defined before training.
lags : 1D np.array
Lags used as predictors.
max_lag : int
Maximum value of lag included in lags.
last_window : 1D np.ndarray
Last time window the forecaster has seen when trained. It stores the
values needed to calculate the lags used to predict the next `step`
after the training data.
included_exog : bool
If the forecaster has been trained using exogenous variable/s.
exog_type : type
Type used for the exogenous variable/s.
exog_shape : tuple
Shape of exog used in training.
in_sample_residuals: np.ndarray
Residuals of the model when predicting training data.
out_sample_residuals: np.ndarray
Residuals of the model when predicting non training data.
Notes
-----
A separate model is created for each forecast time step using
`sklearn.multioutput.MultiOutputRegressor`. This scikit learn class
is a wrapper that automize fitting one regressor per target. It is important
to note that all models share the same configuration of parameters and
hiperparameters.
'''
def __init__(self, regressor, steps: int,
lags: Union[int, np.ndarray, list]) -> None:
self.regressor = MultiOutputRegressor(regressor)
self.steps = steps
self.last_window = None
self.included_exog = False
self.exog_type = False
self.exog_shape = None
self.in_sample_residuals = None
self.out_sample_residuals = None
if not isinstance(steps, int) or steps < 1:
raise Exception(
f"`steps` must be integer greater than 0. Got {steps}."
)
if isinstance(lags, int) and lags < 1:
raise Exception('min value of lags allowed is 1')
if isinstance(lags, (list, range, np.ndarray)) and min(lags) < 1:
raise Exception('min value of lags allowed is 1')
if isinstance(lags, int):
self.lags = np.arange(lags) + 1
elif isinstance(lags, (list, range)):
self.lags = np.array(lags)
elif isinstance(lags, np.ndarray):
self.lags = lags
else:
raise Exception(
f"`lags` argument must be `int`, `1D np.ndarray`, `range` or `list`. "
f"Got {type(lags)}"
)
self.max_lag = max(self.lags)
def __repr__(self) -> str:
'''
Information displayed when a ForecasterAutoreg object is printed.
'''
info = "============================" \
+ "ForecasterAutoregMultiOutput" \
+ "============================" \
+ "\n" \
+ "Regressor: " + str(self.regressor) \
+ "\n" \
+ "Steps: " + str(self.steps) \
+ "\n" \
+ "Lags: " + str(self.lags) \
+ "\n" \
+ "Exogenous variable: " + str(self.included_exog) \
+ "\n" \
+ "Parameters: " + str(self.regressor.get_params())
return info
def create_lags(self, y: Union[np.ndarray, pd.Series]) -> Dict[np.ndarray, np.ndarray]:
'''
Transforms a time series into two 2D arrays of pairs predictor-response.
Notice that the returned matrix X_data, contains the lag 1 in the
first column, the lag 2 in the second column and so on.
Parameters
----------
y : 1D np.ndarray, pd.Series
Training time series.
Returns
-------
X_data : 2D np.ndarray
2D array with the lag values (predictors).
y_data : 2D np.ndarray
Values of the time series related to each row of `X_data`.
'''
self._check_y(y=y)
y = self._preproces_y(y=y)
if self.max_lag > len(y):
raise Exception(
f"Maximum lag can't be higer than `y` length. "
f"Got maximum lag={self.max_lag} and `y` length={len(y)}."
)
n_splits = len(y) - self.max_lag - (self.steps -1)
X_data = np.full(shape=(n_splits, self.max_lag), fill_value=np.nan, dtype=float)
y_data = np.full(shape=(n_splits, self.steps), fill_value=np.nan, dtype= float)
for i in range(n_splits):
train_index = np.arange(i, self.max_lag + i)
test_index = np.arange(self.max_lag + i, self.max_lag + i + self.steps)
X_data[i, :] = y[train_index]
y_data[i, :] = y[test_index]
X_data = X_data[:, -self.lags]
return X_data, y_data
def fit(self, y: Union[np.ndarray, pd.Series],
exog: Union[np.ndarray, pd.Series]=None) -> None:
'''
Training ForecasterAutoregMultiOutput
Parameters
----------
y : 1D np.ndarray, pd.Series
Training time series.
exog : np.ndarray, pd.Series, default `None`
Exogenous variable/s included as predictor/s. Must have the same
number of observations as `y` and should be aligned so that y[i] is
regressed on exog[i].
Returns
-------
self : ForecasterAutoregMultiOutput
Trained ForecasterAutoregMultiOutput
'''
# Reset values in case the forecaster has already been fitted before.
self.included_exog = False
self.exog_type = None
self.exog_shape = None
self._check_y(y=y)
y = self._preproces_y(y=y)
if exog is not None:
self._check_exog(exog=exog)
self.exog_type = type(exog)
exog = self._preproces_exog(exog=exog)
self.included_exog = True
self.exog_shape = exog.shape
if exog.shape[0] != len(y):
raise Exception(
f"`exog` must have same number of samples as `y`"
)
X_train, y_train = self.create_lags(y=y)
if exog is not None:
self.regressor.fit(
# The first `self.max_lag` positions have to be removed from exog
# since they are not in X_train.
X = np.column_stack((X_train, exog[self.max_lag + self.steps - 1:,])),
y = y_train
)
self.in_sample_residuals = \
y_train - self.regressor.predict(
np.column_stack((X_train, exog[self.max_lag + self.steps - 1:,]))
)
else:
self.regressor.fit(X=X_train, y=y_train)
self.in_sample_residuals = y_train - self.regressor.predict(X_train)
# The last time window of training data is stored so that lags needed as
# predictors in the first iteration of `predict()` can be calculated.
if self.steps >= self.max_lag:
self.last_window = y_train[-1, -self.max_lag:]
else:
self.last_window = np.hstack((
y_train[-(self.max_lag-self.steps + 1):-1, 0],
y_train[-1, :]
))
def predict(self, last_window: Union[np.ndarray, pd.Series]=None,
exog: np.ndarray=None, steps=None):
'''
Multi-step prediction with a MultiOutputRegressor. The number of future
steps predicted is defined when ininitializing the forecaster.
Parameters
----------
last_window : 1D np.ndarray, pd.Series, shape (, max_lag), default `None`
Values of the series used to create the predictors (lags) need in the
first iteration of predictiont (t + 1).
If `last_window = None`, the values stored in` self.last_window` are
used to calculate the initial predictors, and the predictions start
right after training data.
exog : np.ndarray, pd.Series, default `None`
Exogenous variable/s included as predictor/s.
steps : Ignored
Not used, present here for API consistency by convention.
Returns
-------
predictions : 1D np.array, shape (steps,)
Values predicted.
'''
if exog is None and self.included_exog:
raise Exception(
f"Forecaster trained with exogenous variable/s. "
f"Same variable/s must be provided in `predict()`."
)
if exog is not None and not self.included_exog:
raise Exception(
f"Forecaster trained without exogenous variable/s. "
f"`exog` must be `None` in `predict()`."
)
if exog is not None:
self._check_exog(
exog=exog, ref_type = self.exog_type, ref_shape=self.exog_shape
)
exog = self._preproces_exog(exog=exog)
if exog.shape[0] < self.steps:
raise Exception(
f"`exog` must have at least as many values as `steps` predicted."
)
if last_window is not None:
self._check_last_window(last_window=last_window)
last_window = self._preproces_last_window(last_window=last_window)
if last_window.shape[0] < self.max_lag:
raise Exception(
f"`last_window` must have as many values as as needed to "
f"calculate the maximum lag ({self.max_lag})."
)
else:
last_window = self.last_window.copy()
X = last_window[-self.lags].reshape(1, -1)
if exog is None:
predictions = self.regressor.predict(X)
else:
X = np.hstack([X, exog[0].reshape(1, -1)])
predictions = self.regressor.predict(X)
predictions = predictions.reshape(-1)
return predictions
def _check_y(self, y: Union[np.ndarray, pd.Series]) -> None:
'''
Raise Exception if `y` is not 1D `np.ndarray` or `pd.Series`.
Parameters
----------
y : np.ndarray, pd.Series
Time series values
'''
if not isinstance(y, (np.ndarray, pd.Series)):
raise Exception('`y` must be `1D np.ndarray` or `pd.Series`.')
elif isinstance(y, np.ndarray) and y.ndim != 1:
raise Exception(
f"`y` must be `1D np.ndarray` o `pd.Series`, "
f"got `np.ndarray` with {y.ndim} dimensions."
)
return
def _check_last_window(self, last_window: Union[np.ndarray, pd.Series]) -> None:
'''
Raise Exception if `last_window` is not 1D `np.ndarray` or `pd.Series`.
Parameters
----------
last_window : np.ndarray, pd.Series
Time series values
'''
if not isinstance(last_window, (np.ndarray, pd.Series)):
raise Exception('`last_window` must be `1D np.ndarray` or `pd.Series`.')
elif isinstance(last_window, np.ndarray) and last_window.ndim != 1:
raise Exception(
f"`last_window` must be `1D np.ndarray` o `pd.Series`, "
f"got `np.ndarray` with {last_window.ndim} dimensions."
)
return
def _check_exog(self, exog: Union[np.ndarray, pd.Series],
ref_type: type=None, ref_shape: tuple=None) -> None:
'''
Raise Exception if `exog` is not `np.ndarray` or `pd.Series`.
If `ref_shape` is provided, raise Exception if `ref_shape[1]` do not match
`exog.shape[1]` (number of columns).
Parameters
----------
exog : np.ndarray, pd.Series
Time series values
'''
if not isinstance(exog, (np.ndarray, pd.Series)):
raise Exception('`exog` must be `np.ndarray` or `pd.Series`.')
if isinstance(exog, np.ndarray) and exog.ndim > 2:
raise Exception(
f" If `exog` is `np.ndarray`, maximum allowed dim=2. "
f"Got {exog.ndim}."
)
if ref_type is not None:
if ref_type == pd.Series:
if isinstance(exog, pd.Series):
return
elif isinstance(exog, np.ndarray) and exog.ndim == 1:
return
elif isinstance(exog, np.ndarray) and exog.shape[1] == 1:
return
else:
raise Exception(
f"`exog` must be: `pd.Series`, `np.ndarray` with 1 dimension"
f"or `np.ndarray` with 1 column in the second dimension. "
f"Got `np.ndarray` with {exog.shape[1]} columns."
)
if ref_type == np.ndarray:
if exog.ndim == 1 and ref_shape[1] == 1:
return
elif exog.ndim == 1 and ref_shape[1] > 1:
raise Exception(
f"`exog` must have {ref_shape[1]} columns. "
f"Got `np.ndarray` with 1 dimension or `pd.Series`."
)
elif ref_shape[1] != exog.shape[1]:
raise Exception(
f"`exog` must have {ref_shape[1]} columns. "
f"Got `np.ndarray` with {exog.shape[1]} columns."
)
return
def _preproces_y(self, y) -> np.ndarray:
'''
Transforms `y` to 1D `np.ndarray` if it is `pd.Series`.
Parameters
----------
y :1D np.ndarray, pd.Series
Time series values
Returns
-------
y: 1D np.ndarray, shape(samples,)
'''
if isinstance(y, pd.Series):
return y.to_numpy().copy()
else:
return y.copy()
def _preproces_last_window(self, last_window) -> np.ndarray:
'''
Transforms `last_window` to 1D `np.ndarray` if it is `pd.Series`.
Parameters
----------
last_window :1D np.ndarray, pd.Series
Time series values
Returns
-------
last_window: 1D np.ndarray, shape(samples,)
'''
if isinstance(last_window, pd.Series):
return last_window.to_numpy().copy()
else:
return last_window.copy()
def _preproces_exog(self, exog) -> np.ndarray:
'''
Transforms `exog` to `np.ndarray` if it is `pd.Series`.
If 1D `np.ndarray` reshape it to (n_samples, 1)
Parameters
----------
exog : np.ndarray, pd.Series
Time series values
Returns
-------
exog: np.ndarray, shape(samples,)
'''
if isinstance(exog, pd.Series):
exog_prep = exog.to_numpy().reshape(-1, 1).copy()
elif isinstance(exog, np.ndarray) and exog.ndim == 1:
exog_prep = exog.reshape(-1, 1).copy()
else:
exog_prep = exog.copy()
return exog_prep
def _exog_to_multi_output(self, exog):
'''
DEPRECATED
Transforms `exog` to `np.ndarray` with the shape needed for multioutput
regresors.
Parameters
----------
exog : np.ndarray, shape(samples,)
Time series values
Returns
-------
exog_transformed: np.ndarray, shape(samples - self.max_lag, self.steps)
'''
exog_transformed = []
for column in range(exog.shape[1]):
exog_column_transformed = []
for i in range(exog.shape[0] - (self.steps -1)):
exog_column_transformed.append(exog[i:i + self.steps, column])
if len(exog_column_transformed) > 1:
exog_column_transformed = np.vstack(exog_column_transformed)
exog_transformed.append(exog_column_transformed)
if len(exog_transformed) > 1:
exog_transformed = np.hstack(exog_transformed)
else:
exog_transformed = exog_column_transformed
return exog_transformed
def set_params(self, **params: dict) -> None:
'''
Set new values to the parameters of the scikit learn model stored in the
forecaster. A separate model is created for each forecast time step using
`sklearn.multioutput.MultiOutputRegressor`. This scikit learn class is a
wrapper that automize fitting one regressor per target. It is important
to note that all models share the same configuration of parameters and
hiperparameters.
Parameters
----------
params : dict
Parameters values.
Returns
-------
self
'''
self.regressor.set_params(**params)
def set_lags(self, lags: int) -> None:
'''
Set new value to the attribute `lags`.
Attribute `max_lag` is also updated.
Parameters
----------
lags : int, list, 1D np.array, range
Lags used as predictors. Index starts at 1, so lag 1 is equal to t-1.
`int`: include lags from 1 to `lags`.
`list` or `np.array`: include only lags present in `lags`.
Returns
-------
self
'''
if isinstance(lags, int) and lags < 1:
raise Exception('min value of lags allowed is 1')
if isinstance(lags, (list, range, np.ndarray)) and min(lags) < 1:
raise Exception('min value of lags allowed is 1')
if isinstance(lags, int):
self.lags = np.arange(lags) + 1
elif isinstance(lags, (list, range)):
self.lags = np.array(lags)
elif isinstance(lags, np.ndarray):
self.lags = lags
else:
raise Exception(
f"`lags` argument must be `int`, `1D np.ndarray`, `range` or `list`. "
f"Got {type(lags)}"
)
self.max_lag = max(self.lags)
def get_coef(self, step) -> np.ndarray:
'''
Return estimated coefficients for the linear regression model stored in
the forecaster for a specific step. Since a separate model is created for
each forecast time step, it is necessary to select the model from which
retireve information.
Only valid when the forecaster has been trained using as `regressor:
`LinearRegression()`, `Lasso()` or `Ridge()`.
Parameters
----------
step : int
Model from which retireve information (a separate model is created for
each forecast time step).
Returns
-------
coef : 1D np.ndarray
Value of the coefficients associated with each predictor (lag).
Coefficients are aligned so that `coef[i]` is the value associated
with `self.lags[i]`.
'''
if step > self.steps:
raise Exception(
f"Forecaster traied for {self.steps} steps. Got step={step}."
)
valid_instances = (sklearn.linear_model._base.LinearRegression,
sklearn.linear_model._coordinate_descent.Lasso,
sklearn.linear_model._ridge.Ridge
)
if not isinstance(self.regressor.estimator, valid_instances):
warnings.warn(
('Only forecasters with `regressor` `LinearRegression()`, ' +
' `Lasso()` or `Ridge()` have coef.')
)
return
else:
coef = self.regressor.estimators_[step-1].coef_
return coef
def get_feature_importances(self, step) -> np.ndarray:
'''
Return impurity-based feature importances of the model stored in
the forecaster for a specific step. Since a separate model is created for
each forecast time step, it is necessary to select the model from which
retireve information.
Only valid when the forecaster has been trained using
`regressor=GradientBoostingRegressor()` or `regressor=RandomForestRegressor`.
Parameters
----------
step : int
Model from which retireve information (a separate model is created for
each forecast time step).
Returns
-------
feature_importances : 1D np.ndarray
Impurity-based feature importances associated with each predictor (lag).
Values are aligned so that `feature_importances[i]` is the value
associated with `self.lags[i]`.
'''
if step > self.steps:
raise Exception(
f"Forecaster traied for {self.steps} steps. Got step={step}."
)
valid_instances = (sklearn.ensemble._forest.RandomForestRegressor,
sklearn.ensemble._gb.GradientBoostingRegressor)
if not isinstance(self.regressor.estimator, valid_instances):
warnings.warn(
('Only forecasters with `regressor=GradientBoostingRegressor()` '
'or `regressor=RandomForestRegressor`.')
)
return
else:
feature_importances = self.regressor.estimators_[step-1].feature_importances_
return feature_importances
| [
"numpy.full",
"logging.basicConfig",
"sklearn.multioutput.MultiOutputRegressor",
"numpy.hstack",
"numpy.arange",
"numpy.array",
"numpy.column_stack",
"warnings.warn",
"numpy.vstack"
] | [((840, 953), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)-5s %(name)-10s %(levelname)-5s %(message)s"""', 'level': 'logging.INFO'}), "(format=\n '%(asctime)-5s %(name)-10s %(levelname)-5s %(message)s', level=logging.INFO\n )\n", (859, 953), False, 'import logging\n'), ((3764, 3795), 'sklearn.multioutput.MultiOutputRegressor', 'MultiOutputRegressor', (['regressor'], {}), '(regressor)\n', (3784, 3795), False, 'from sklearn.multioutput import MultiOutputRegressor\n'), ((6830, 6901), 'numpy.full', 'np.full', ([], {'shape': '(n_splits, self.max_lag)', 'fill_value': 'np.nan', 'dtype': 'float'}), '(shape=(n_splits, self.max_lag), fill_value=np.nan, dtype=float)\n', (6837, 6901), True, 'import numpy as np\n'), ((6920, 6989), 'numpy.full', 'np.full', ([], {'shape': '(n_splits, self.steps)', 'fill_value': 'np.nan', 'dtype': 'float'}), '(shape=(n_splits, self.steps), fill_value=np.nan, dtype=float)\n', (6927, 6989), True, 'import numpy as np\n'), ((7052, 7082), 'numpy.arange', 'np.arange', (['i', '(self.max_lag + i)'], {}), '(i, self.max_lag + i)\n', (7061, 7082), True, 'import numpy as np\n'), ((7109, 7167), 'numpy.arange', 'np.arange', (['(self.max_lag + i)', '(self.max_lag + i + self.steps)'], {}), '(self.max_lag + i, self.max_lag + i + self.steps)\n', (7118, 7167), True, 'import numpy as np\n'), ((9827, 9903), 'numpy.hstack', 'np.hstack', (['(y_train[-(self.max_lag - self.steps + 1):-1, 0], y_train[-1, :])'], {}), '((y_train[-(self.max_lag - self.steps + 1):-1, 0], y_train[-1, :]))\n', (9836, 9903), True, 'import numpy as np\n'), ((19334, 19361), 'numpy.hstack', 'np.hstack', (['exog_transformed'], {}), '(exog_transformed)\n', (19343, 19361), True, 'import numpy as np\n'), ((22916, 23032), 'warnings.warn', 'warnings.warn', (["('Only forecasters with `regressor` `LinearRegression()`, ' +\n ' `Lasso()` or `Ridge()` have coef.')"], {}), "('Only forecasters with `regressor` `LinearRegression()`, ' +\n ' `Lasso()` or `Ridge()` have coef.')\n", (22929, 23032), False, 'import warnings\n'), ((24574, 24700), 'warnings.warn', 'warnings.warn', (['"""Only forecasters with `regressor=GradientBoostingRegressor()` or `regressor=RandomForestRegressor`."""'], {}), "(\n 'Only forecasters with `regressor=GradientBoostingRegressor()` or `regressor=RandomForestRegressor`.'\n )\n", (24587, 24700), False, 'import warnings\n'), ((4565, 4580), 'numpy.arange', 'np.arange', (['lags'], {}), '(lags)\n', (4574, 4580), True, 'import numpy as np\n'), ((4655, 4669), 'numpy.array', 'np.array', (['lags'], {}), '(lags)\n', (4663, 4669), True, 'import numpy as np\n'), ((19167, 19201), 'numpy.vstack', 'np.vstack', (['exog_column_transformed'], {}), '(exog_column_transformed)\n', (19176, 19201), True, 'import numpy as np\n'), ((21054, 21069), 'numpy.arange', 'np.arange', (['lags'], {}), '(lags)\n', (21063, 21069), True, 'import numpy as np\n'), ((21144, 21158), 'numpy.array', 'np.array', (['lags'], {}), '(lags)\n', (21152, 21158), True, 'import numpy as np\n'), ((9042, 9107), 'numpy.column_stack', 'np.column_stack', (['(X_train, exog[self.max_lag + self.steps - 1:,])'], {}), '((X_train, exog[self.max_lag + self.steps - 1:,]))\n', (9057, 9107), True, 'import numpy as np\n'), ((9274, 9339), 'numpy.column_stack', 'np.column_stack', (['(X_train, exog[self.max_lag + self.steps - 1:,])'], {}), '((X_train, exog[self.max_lag + self.steps - 1:,]))\n', (9289, 9339), True, 'import numpy as np\n')] |
import unittest
from unittest.mock import Mock, patch
import numpy as np
import numpy.typing as npt
from nuplan.common.actor_state.state_representation import Point2D, StateSE2
from nuplan.common.geometry.transform import (
rotate,
rotate_2d,
rotate_angle,
transform,
translate,
translate_laterally,
translate_longitudinally,
translate_longitudinally_and_laterally,
)
class TestTransform(unittest.TestCase):
"""Tests for transform functions"""
def test_rotate_2d(self) -> None:
"""Tests rotation of 2D point"""
# Setup
point = Point2D(1, 0)
rotation_matrix = np.array([[0, 1], [-1, 0]], dtype=np.float32) # type: npt.NDArray[np.float32]
# Function call
result = rotate_2d(point, rotation_matrix)
# Checks
self.assertEqual(result, Point2D(0, 1))
def test_translate(self) -> None:
"""Tests translate"""
# Setup
pose = StateSE2(3, 5, np.pi / 4)
translation = np.array([1, 2], dtype=np.float32) # type: npt.NDArray[np.float32]
# Function call
result = translate(pose, translation)
# Checks
self.assertEqual(result, StateSE2(4, 7, np.pi / 4))
def test_rotate(self) -> None:
"""Tests rotation of SE2 pose by rotation matrix"""
# Setup
pose = StateSE2(1, 2, np.pi / 4)
rotation_matrix = np.array([[0, 1], [-1, 0]], dtype=np.float32) # type: npt.NDArray[np.float32]
# Function call
result = rotate(pose, rotation_matrix)
# Checks
self.assertAlmostEqual(result.x, -2)
self.assertAlmostEqual(result.y, 1)
self.assertAlmostEqual(result.heading, -np.pi / 4)
def test_rotate_angle(self) -> None:
"""Tests rotation of SE2 pose by angle (in radian)"""
# Setup
pose = StateSE2(1, 2, np.pi / 4)
angle = -np.pi / 2
# Function call
result = rotate_angle(pose, angle)
# Checks
self.assertAlmostEqual(result.x, -2)
self.assertAlmostEqual(result.y, 1)
self.assertAlmostEqual(result.heading, -np.pi / 4)
def test_transform(self) -> None:
"""Tests transformation of SE2 pose"""
# Setup
pose = StateSE2(1, 2, 0)
transform_matrix = np.array(
[[-3, -2, 5], [0, -1, 4], [0, 0, 1]], dtype=np.float32
) # type: npt.NDArray[np.float32]
# Function call
result = transform(pose, transform_matrix)
# Checks
self.assertAlmostEqual(result.x, 2)
self.assertAlmostEqual(result.y, 0)
self.assertAlmostEqual(result.heading, np.pi, places=4)
@patch("nuplan.common.geometry.transform.translate")
def test_translate_longitudinally(self, mock_translate: Mock) -> None:
"""Tests longitudinal translation"""
# Setup
pose = StateSE2(1, 2, np.arctan(1 / 3))
# Function call
result = translate_longitudinally(pose, np.sqrt(10))
# Checks
np.testing.assert_array_almost_equal(mock_translate.call_args.args[1], np.array([3, 1]))
self.assertEqual(result, mock_translate.return_value)
@patch("nuplan.common.geometry.transform.translate")
def test_translate_laterally(self, mock_translate: Mock) -> None:
"""Tests lateral translation"""
# Setup
pose = StateSE2(1, 2, np.arctan(1 / 3))
# Function call
result = translate_laterally(pose, np.sqrt(10))
# Checks
np.testing.assert_array_almost_equal(mock_translate.call_args.args[1], np.array([-1, 3]))
self.assertEqual(result, mock_translate.return_value)
@patch("nuplan.common.geometry.transform.translate")
def test_translate_longitudinally_and_laterally(self, mock_translate: Mock) -> None:
"""Tests longitudinal and lateral translation"""
# Setup
pose = StateSE2(1, 2, np.arctan(1 / 3))
# Function call
result = translate_longitudinally_and_laterally(pose, np.sqrt(10), np.sqrt(10))
# Checks
np.testing.assert_array_almost_equal(mock_translate.call_args.args[1], np.array([2, 4]))
self.assertEqual(result, mock_translate.return_value)
if __name__ == "__main__":
unittest.main()
| [
"unittest.main",
"nuplan.common.actor_state.state_representation.StateSE2",
"nuplan.common.geometry.transform.rotate_2d",
"unittest.mock.patch",
"nuplan.common.actor_state.state_representation.Point2D",
"nuplan.common.geometry.transform.transform",
"numpy.array",
"nuplan.common.geometry.transform.tran... | [((2672, 2723), 'unittest.mock.patch', 'patch', (['"""nuplan.common.geometry.transform.translate"""'], {}), "('nuplan.common.geometry.transform.translate')\n", (2677, 2723), False, 'from unittest.mock import Mock, patch\n'), ((3177, 3228), 'unittest.mock.patch', 'patch', (['"""nuplan.common.geometry.transform.translate"""'], {}), "('nuplan.common.geometry.transform.translate')\n", (3182, 3228), False, 'from unittest.mock import Mock, patch\n'), ((3668, 3719), 'unittest.mock.patch', 'patch', (['"""nuplan.common.geometry.transform.translate"""'], {}), "('nuplan.common.geometry.transform.translate')\n", (3673, 3719), False, 'from unittest.mock import Mock, patch\n'), ((4253, 4268), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4266, 4268), False, 'import unittest\n'), ((596, 609), 'nuplan.common.actor_state.state_representation.Point2D', 'Point2D', (['(1)', '(0)'], {}), '(1, 0)\n', (603, 609), False, 'from nuplan.common.actor_state.state_representation import Point2D, StateSE2\n'), ((636, 681), 'numpy.array', 'np.array', (['[[0, 1], [-1, 0]]'], {'dtype': 'np.float32'}), '([[0, 1], [-1, 0]], dtype=np.float32)\n', (644, 681), True, 'import numpy as np\n'), ((756, 789), 'nuplan.common.geometry.transform.rotate_2d', 'rotate_2d', (['point', 'rotation_matrix'], {}), '(point, rotation_matrix)\n', (765, 789), False, 'from nuplan.common.geometry.transform import rotate, rotate_2d, rotate_angle, transform, translate, translate_laterally, translate_longitudinally, translate_longitudinally_and_laterally\n'), ((956, 981), 'nuplan.common.actor_state.state_representation.StateSE2', 'StateSE2', (['(3)', '(5)', '(np.pi / 4)'], {}), '(3, 5, np.pi / 4)\n', (964, 981), False, 'from nuplan.common.actor_state.state_representation import Point2D, StateSE2\n'), ((1004, 1038), 'numpy.array', 'np.array', (['[1, 2]'], {'dtype': 'np.float32'}), '([1, 2], dtype=np.float32)\n', (1012, 1038), True, 'import numpy as np\n'), ((1114, 1142), 'nuplan.common.geometry.transform.translate', 'translate', (['pose', 'translation'], {}), '(pose, translation)\n', (1123, 1142), False, 'from nuplan.common.geometry.transform import rotate, rotate_2d, rotate_angle, transform, translate, translate_laterally, translate_longitudinally, translate_longitudinally_and_laterally\n'), ((1348, 1373), 'nuplan.common.actor_state.state_representation.StateSE2', 'StateSE2', (['(1)', '(2)', '(np.pi / 4)'], {}), '(1, 2, np.pi / 4)\n', (1356, 1373), False, 'from nuplan.common.actor_state.state_representation import Point2D, StateSE2\n'), ((1400, 1445), 'numpy.array', 'np.array', (['[[0, 1], [-1, 0]]'], {'dtype': 'np.float32'}), '([[0, 1], [-1, 0]], dtype=np.float32)\n', (1408, 1445), True, 'import numpy as np\n'), ((1520, 1549), 'nuplan.common.geometry.transform.rotate', 'rotate', (['pose', 'rotation_matrix'], {}), '(pose, rotation_matrix)\n', (1526, 1549), False, 'from nuplan.common.geometry.transform import rotate, rotate_2d, rotate_angle, transform, translate, translate_laterally, translate_longitudinally, translate_longitudinally_and_laterally\n'), ((1851, 1876), 'nuplan.common.actor_state.state_representation.StateSE2', 'StateSE2', (['(1)', '(2)', '(np.pi / 4)'], {}), '(1, 2, np.pi / 4)\n', (1859, 1876), False, 'from nuplan.common.actor_state.state_representation import Point2D, StateSE2\n'), ((1946, 1971), 'nuplan.common.geometry.transform.rotate_angle', 'rotate_angle', (['pose', 'angle'], {}), '(pose, angle)\n', (1958, 1971), False, 'from nuplan.common.geometry.transform import rotate, rotate_2d, rotate_angle, transform, translate, translate_laterally, translate_longitudinally, translate_longitudinally_and_laterally\n'), ((2255, 2272), 'nuplan.common.actor_state.state_representation.StateSE2', 'StateSE2', (['(1)', '(2)', '(0)'], {}), '(1, 2, 0)\n', (2263, 2272), False, 'from nuplan.common.actor_state.state_representation import Point2D, StateSE2\n'), ((2300, 2364), 'numpy.array', 'np.array', (['[[-3, -2, 5], [0, -1, 4], [0, 0, 1]]'], {'dtype': 'np.float32'}), '([[-3, -2, 5], [0, -1, 4], [0, 0, 1]], dtype=np.float32)\n', (2308, 2364), True, 'import numpy as np\n'), ((2462, 2495), 'nuplan.common.geometry.transform.transform', 'transform', (['pose', 'transform_matrix'], {}), '(pose, transform_matrix)\n', (2471, 2495), False, 'from nuplan.common.geometry.transform import rotate, rotate_2d, rotate_angle, transform, translate, translate_laterally, translate_longitudinally, translate_longitudinally_and_laterally\n'), ((841, 854), 'nuplan.common.actor_state.state_representation.Point2D', 'Point2D', (['(0)', '(1)'], {}), '(0, 1)\n', (848, 854), False, 'from nuplan.common.actor_state.state_representation import Point2D, StateSE2\n'), ((1194, 1219), 'nuplan.common.actor_state.state_representation.StateSE2', 'StateSE2', (['(4)', '(7)', '(np.pi / 4)'], {}), '(4, 7, np.pi / 4)\n', (1202, 1219), False, 'from nuplan.common.actor_state.state_representation import Point2D, StateSE2\n'), ((2890, 2906), 'numpy.arctan', 'np.arctan', (['(1 / 3)'], {}), '(1 / 3)\n', (2899, 2906), True, 'import numpy as np\n'), ((2981, 2992), 'numpy.sqrt', 'np.sqrt', (['(10)'], {}), '(10)\n', (2988, 2992), True, 'import numpy as np\n'), ((3091, 3107), 'numpy.array', 'np.array', (['[3, 1]'], {}), '([3, 1])\n', (3099, 3107), True, 'import numpy as np\n'), ((3385, 3401), 'numpy.arctan', 'np.arctan', (['(1 / 3)'], {}), '(1 / 3)\n', (3394, 3401), True, 'import numpy as np\n'), ((3471, 3482), 'numpy.sqrt', 'np.sqrt', (['(10)'], {}), '(10)\n', (3478, 3482), True, 'import numpy as np\n'), ((3581, 3598), 'numpy.array', 'np.array', (['[-1, 3]'], {}), '([-1, 3])\n', (3589, 3598), True, 'import numpy as np\n'), ((3912, 3928), 'numpy.arctan', 'np.arctan', (['(1 / 3)'], {}), '(1 / 3)\n', (3921, 3928), True, 'import numpy as np\n'), ((4017, 4028), 'numpy.sqrt', 'np.sqrt', (['(10)'], {}), '(10)\n', (4024, 4028), True, 'import numpy as np\n'), ((4030, 4041), 'numpy.sqrt', 'np.sqrt', (['(10)'], {}), '(10)\n', (4037, 4041), True, 'import numpy as np\n'), ((4140, 4156), 'numpy.array', 'np.array', (['[2, 4]'], {}), '([2, 4])\n', (4148, 4156), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Predict with Mars in R/rpy2
MARS: Multivariate Adaptive Regression Splines
"""
import rpy2
import rpy2.robjects as ro
import rpy2.rinterface as ri
import numpy as np
import pandas as pd
from rpy2.robjects.packages import importr
from rpy2.robjects import pandas2ri
pandas2ri.activate()
r = ro.r
# _ = importr('class')
mda = importr('mda')
from sklearn.base import BaseEstimator, RegressorMixin
class Mars(BaseEstimator, RegressorMixin):
'''MARS: Multivariate Adaptive Regression Splines
MARS is an adaptive procedure for regression, and is well suited for high-dim problems.
It uses expansions in basis functions {(x-t)+, (x-t)-, ...}
Extends:
RegressorMixin
Variables:
xkeys {Array} -- [description]
ykeys {Array} -- [description]
'''
xkeys = None
ykeys = None
def __init__(self, degree=1, nk=None, penalty=2, thresh=0.001, prune=True, trace_mars=False,
forward_step=True, prevfit=False):
self.degree=degree
self.nk = nk
self.penalty = penalty
self.thresh = thresh
self.prune = prune
self.trace_mars = trace_mars
self.forward_step = forward_step
self.prevfit = prevfit
@property
def estimator(self):
return self.__estimator
@estimator.setter
def estimator(self, x):
self.__estimator = x
def get_params(self, deep=True):
return {'degree':self.degree, 'nk':self.nk, 'penalty':self.penalty, 'trace_mars':self.trace_mars, 'forward_step':self.forward_step, 'prevfit':self.prevfit}
def fit(self, X, Y, sample_weight=None):
self.outdim = Y.ndim
if isinstance(X, pd.DataFrame):
self.xkeys = X.columns
Xtrain = pandas2ri.py2rpy_pandasdataframe(X)
else:
if self.xkeys is None:
self.xkeys = ['x%d'%k for k in range(X.shape[1])]
Xtrain=ro.DataFrame({key:ro.FloatVector(X[:,k].astype(np.float64, copy=False)) for k, key in enumerate(self.xkeys)})
if self.ykeys is None:
if self.outdim == 1:
self.ykeys = ['y1']
else:
self.ykeys = ['y%d'%k for k in range(Y.shape[1])]
if self.outdim == 1:
Ytrain=ro.DataFrame({self.ykeys[0]:ro.FloatVector(Y)})
else:
Ytrain=ro.DataFrame({key:ro.FloatVector(Y[:,k].astype(np.float64, copy=False)) for k, key in enumerate(self.ykeys)})
if self.nk is None:
self.nk = max((21, 2*X.shape[1]+1))
if sample_weight is None:
self.estimator = mda.mars(Xtrain, Ytrain, degree=self.degree, nk=self.nk, penalty=self.penalty, trace_mars=self.trace_mars, forward_step=self.forward_step, prevfit=self.prevfit)
else:
self.estimator = mda.mars(Xtrain, Ytrain, w=ro.FloatVector(sample_weight), degree=self.degree, nk=self.nk, penalty=self.penalty, trace_mars=self.trace_mars, forward_step=self.forward_step, prevfit=self.prevfit)
return self
def predict(self, X):
if not isinstance(X, np.ndarray):
X = np.array(X)
Xtest=ro.DataFrame({key:ro.FloatVector(X[:,k].astype(np.float64, copy=False)) for k, key in enumerate(self.xkeys)})
Ypred = r.predict(self.estimator, Xtest)
if self.outdim==1:
return np.array(Ypred)[:,0]
else:
return np.array(Ypred)
| [
"rpy2.robjects.packages.importr",
"rpy2.robjects.pandas2ri.activate",
"rpy2.robjects.pandas2ri.py2rpy_pandasdataframe",
"numpy.array",
"rpy2.robjects.FloatVector"
] | [((317, 337), 'rpy2.robjects.pandas2ri.activate', 'pandas2ri.activate', ([], {}), '()\n', (335, 337), False, 'from rpy2.robjects import pandas2ri\n'), ((377, 391), 'rpy2.robjects.packages.importr', 'importr', (['"""mda"""'], {}), "('mda')\n", (384, 391), False, 'from rpy2.robjects.packages import importr\n'), ((1805, 1840), 'rpy2.robjects.pandas2ri.py2rpy_pandasdataframe', 'pandas2ri.py2rpy_pandasdataframe', (['X'], {}), '(X)\n', (1837, 1840), False, 'from rpy2.robjects import pandas2ri\n'), ((3159, 3170), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (3167, 3170), True, 'import numpy as np\n'), ((3444, 3459), 'numpy.array', 'np.array', (['Ypred'], {}), '(Ypred)\n', (3452, 3459), True, 'import numpy as np\n'), ((3390, 3405), 'numpy.array', 'np.array', (['Ypred'], {}), '(Ypred)\n', (3398, 3405), True, 'import numpy as np\n'), ((2345, 2362), 'rpy2.robjects.FloatVector', 'ro.FloatVector', (['Y'], {}), '(Y)\n', (2359, 2362), True, 'import rpy2.robjects as ro\n'), ((2887, 2916), 'rpy2.robjects.FloatVector', 'ro.FloatVector', (['sample_weight'], {}), '(sample_weight)\n', (2901, 2916), True, 'import rpy2.robjects as ro\n')] |
"""
Created on Tue Jul 21 2020
@author: TheDrDOS
Interface with COVID, population, and location data from various sources
"""
# For updating git
import os
# For data processing
import pandas as pd
import numpy as np
import progress_bar as pbar
import hashlib
import json
import multiprocessing as mp
from time import time as now
from time import perf_counter as pnow
import gzip
T0 = now()
# %% Update and denote datafiles
def update():
"""
Updates the Database
Returns
-------
None.
"""
os.system("git submodule update --recursive --remote")
return None
'''
------------------------------------------------------------------------------
Load Data
------------------------------------------------------------------------------
'''
print('Update data')
update()
print("Load Data:")
t0 = pnow()
# src = "../DataSet/NYT/rolling-averages/us-counties-recent.csv"
src = "../DataSet/NYT/rolling-averages/us-counties.csv"
df = pd.read_csv(src)
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
df.set_index('date',inplace=True)
df.sort_index(inplace=True)
df['location'] = df['county']+', '+df['state']+', US'
df.drop(columns=['county','state','geoid'],inplace=True)
# dates = df['date'].unique().tolist()
dates = df.index.unique().tolist()
dfmt = '%Y%m%d';
nan_code = -987654321
df.fillna(value=nan_code,inplace=True)
# dates_str = dates.strftime()
# data = {}
# for d in dates:
# dstr = d.strftime(dfmt)
# data[dstr] = {}
# data[dstr]['date'] = dstr
# for k in df.keys().tolist():
# data[dstr][k] = df[k].tolist()
# This spits out the dictionary I want
# df[df.index==pd.to_datetime('2021-08-03')].set_index('location').to_dict('index')
print(" Completed in :{} sec".format(pnow()-t0))
# %%
'''
------------------------------------------------------------------------------
Support Functions
------------------------------------------------------------------------------
'''
def short_hash(st,digits=8,num_only=False):
''' Generate a short hash from a string '''
if num_only:
if digits>49:
digits=49;
return int(hashlib.sha1(st.encode()).hexdigest(),16)%(10**digits)
else:
if digits>40:
digits=40;
return hashlib.sha1(st.encode()).hexdigest().upper()[0:digits-1]
def dic_to_jsonreadydata(dic,nan_code):
data = {}
for k in dic:
data[k] = np.nan_to_num(dic[k],nan=nan_code).tolist() # replace NaNs and cast to float using tolist, the first tolist is needed for string arrays with NaNs to be processed (will replace with 'nan')
return data
def mp_dump_date_gz(d):
''' Dump data for a date to json files'''
FilesMade = 0
if d in dates:
filename = d.strftime(dfmt)
data = {
'filename': filename,
'date': d.value, #/1e6,
'nan_code': nan_code,
'data': df[df.index==d].set_index('location').to_dict('index') ,
}
with gzip.GzipFile(ext_data_path+filename+'.json'+'.gz', 'w') as outfile:
outfile.write(json.dumps(data).encode('utf-8'))
FilesMade +=1
return FilesMade
# %%
'''
------------------------------------------------------------------------------
Make filenames and json datafiles
Use short hash for filenames to generate a short filenames that uniquely
(one-to-one and onto) correspond to the location strings.
This allows consistent file naming if locations are added or removed.
Of course, the file name will change if the location name is changed.
------------------------------------------------------------------------------
'''
ext_data_path = "../site/plots/data/"
# ext_data_path = "./tmpdata/"
N = len(dates)
n = 0
Ncpu = min([mp.cpu_count(),N]) # use maximal number of local CPUs
chunksize = 1
pool = mp.Pool(processes=Ncpu)
print("Dump Data To json Files For All Dates:")
t0 = pnow()
for n,d in enumerate(pool.imap_unordered(mp_dump_date_gz,dates,chunksize=chunksize)):
if n%15==0:
pbar.progress_bar(n,N-1)
pass
if d==0:
print("No output file made for (Date not found): "+d)
pbar.progress_bar(n,N-1)
pool.terminate()
print(" Completed in :{} sec".format(pnow()-t0))
filename = 'date_to_filename'
data = {d.value: d.strftime(dfmt) for d in dates};
data['date_to_filename_format'] = dfmt
data['dates'] = sorted([d.value for d in dates])
with gzip.GzipFile(ext_data_path+filename+'.json'+'.gz', 'w') as outfile:
outfile.write(json.dumps(data).encode('utf-8'))
filename = 'filename_to_date'
data = {d.strftime(dfmt):d.value for d in dates};
with gzip.GzipFile(ext_data_path+filename+'.json'+'.gz', 'w') as outfile:
outfile.write(json.dumps(data).encode('utf-8'))
print("Script Completed in :{} sec".format(now()-T0)) | [
"progress_bar.progress_bar",
"numpy.nan_to_num",
"pandas.read_csv",
"time.perf_counter",
"os.system",
"time.time",
"json.dumps",
"pandas.to_datetime",
"gzip.GzipFile",
"multiprocessing.Pool",
"multiprocessing.cpu_count"
] | [((393, 398), 'time.time', 'now', ([], {}), '()\n', (396, 398), True, 'from time import time as now\n'), ((831, 837), 'time.perf_counter', 'pnow', ([], {}), '()\n', (835, 837), True, 'from time import perf_counter as pnow\n'), ((965, 981), 'pandas.read_csv', 'pd.read_csv', (['src'], {}), '(src)\n', (976, 981), True, 'import pandas as pd\n'), ((995, 1040), 'pandas.to_datetime', 'pd.to_datetime', (["df['date']"], {'format': '"""%Y-%m-%d"""'}), "(df['date'], format='%Y-%m-%d')\n", (1009, 1040), True, 'import pandas as pd\n'), ((3843, 3866), 'multiprocessing.Pool', 'mp.Pool', ([], {'processes': 'Ncpu'}), '(processes=Ncpu)\n', (3850, 3866), True, 'import multiprocessing as mp\n'), ((3920, 3926), 'time.perf_counter', 'pnow', ([], {}), '()\n', (3924, 3926), True, 'from time import perf_counter as pnow\n'), ((4147, 4174), 'progress_bar.progress_bar', 'pbar.progress_bar', (['n', '(N - 1)'], {}), '(n, N - 1)\n', (4164, 4174), True, 'import progress_bar as pbar\n'), ((528, 582), 'os.system', 'os.system', (['"""git submodule update --recursive --remote"""'], {}), "('git submodule update --recursive --remote')\n", (537, 582), False, 'import os\n'), ((4418, 4480), 'gzip.GzipFile', 'gzip.GzipFile', (["(ext_data_path + filename + '.json' + '.gz')", '"""w"""'], {}), "(ext_data_path + filename + '.json' + '.gz', 'w')\n", (4431, 4480), False, 'import gzip\n'), ((4625, 4687), 'gzip.GzipFile', 'gzip.GzipFile', (["(ext_data_path + filename + '.json' + '.gz')", '"""w"""'], {}), "(ext_data_path + filename + '.json' + '.gz', 'w')\n", (4638, 4687), False, 'import gzip\n'), ((3768, 3782), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (3780, 3782), True, 'import multiprocessing as mp\n'), ((4038, 4065), 'progress_bar.progress_bar', 'pbar.progress_bar', (['n', '(N - 1)'], {}), '(n, N - 1)\n', (4055, 4065), True, 'import progress_bar as pbar\n'), ((1763, 1769), 'time.perf_counter', 'pnow', ([], {}), '()\n', (1767, 1769), True, 'from time import perf_counter as pnow\n'), ((3002, 3064), 'gzip.GzipFile', 'gzip.GzipFile', (["(ext_data_path + filename + '.json' + '.gz')", '"""w"""'], {}), "(ext_data_path + filename + '.json' + '.gz', 'w')\n", (3015, 3064), False, 'import gzip\n'), ((4230, 4236), 'time.perf_counter', 'pnow', ([], {}), '()\n', (4234, 4236), True, 'from time import perf_counter as pnow\n'), ((4792, 4797), 'time.time', 'now', ([], {}), '()\n', (4795, 4797), True, 'from time import time as now\n'), ((2413, 2448), 'numpy.nan_to_num', 'np.nan_to_num', (['dic[k]'], {'nan': 'nan_code'}), '(dic[k], nan=nan_code)\n', (2426, 2448), True, 'import numpy as np\n'), ((4505, 4521), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\n', (4515, 4521), False, 'import json\n'), ((4712, 4728), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\n', (4722, 4728), False, 'import json\n'), ((3097, 3113), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\n', (3107, 3113), False, 'import json\n')] |
__copyright__ = "Copyright (C) 2009-2013 <NAME>"
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import numpy as np
import pytest
import modepy as mp
import logging
logger = logging.getLogger(__name__)
def test_transformed_quadrature():
"""Test 1D quadrature on arbitrary intervals"""
def gaussian_density(x, mu, sigma):
return 1 / (sigma * np.sqrt(2*np.pi)) * np.exp(-(x-mu)**2 / (2 * sigma**2))
from modepy.quadrature import Transformed1DQuadrature
from modepy.quadrature.jacobi_gauss import LegendreGaussQuadrature
mu = 17
sigma = 12
tq = Transformed1DQuadrature(LegendreGaussQuadrature(20),
mu - 6*sigma, mu + 6*sigma)
result = tq(lambda x: gaussian_density(x, mu, sigma))
assert abs(result - 1) < 1.0e-9
try:
import scipy # noqa
except ImportError:
BACKENDS = [None, "builtin"]
else:
BACKENDS = [None, "builtin", "scipy"]
@pytest.mark.parametrize("backend", BACKENDS)
def test_gauss_quadrature(backend):
from modepy.quadrature.jacobi_gauss import LegendreGaussQuadrature
for s in range(9 + 1):
quad = LegendreGaussQuadrature(s, backend)
for deg in range(quad.exact_to + 1):
def f(x):
return x**deg
i_f = quad(f)
i_f_true = 1 / (deg+1) * (1 - (-1)**(deg + 1))
err = abs(i_f - i_f_true)
assert err < 2.0e-15, (s, deg, err, i_f, i_f_true)
def test_clenshaw_curtis_quadrature():
from modepy.quadrature.clenshaw_curtis import ClenshawCurtisQuadrature
for s in range(1, 9 + 1):
quad = ClenshawCurtisQuadrature(s)
for deg in range(quad.exact_to + 1):
def f(x):
return x**deg
i_f = quad(f)
i_f_true = 1 / (deg+1) * (1 - (-1)**(deg + 1))
err = abs(i_f - i_f_true)
assert err < 2.0e-15, (s, deg, err, i_f, i_f_true)
@pytest.mark.parametrize("kind", [1, 2])
def test_fejer_quadrature(kind):
from modepy.quadrature.clenshaw_curtis import FejerQuadrature
for deg in range(1, 9 + 1):
s = deg * 3
quad = FejerQuadrature(s, kind)
def f(x):
return x**deg
i_f = quad(f)
i_f_true = 1 / (deg+1) * (1 - (-1)**(deg + 1))
err = abs(i_f - i_f_true)
assert err < 2.0e-15, (s, deg, err, i_f, i_f_true)
@pytest.mark.parametrize(("quad_class", "highest_order"), [
(mp.XiaoGimbutasSimplexQuadrature, None),
(mp.VioreanuRokhlinSimplexQuadrature, None),
(mp.GrundmannMoellerSimplexQuadrature, 3),
])
@pytest.mark.parametrize("dim", [2, 3])
def test_simplex_quadrature(quad_class, highest_order, dim):
"""Check that quadratures on simplices works as advertised"""
from pytools import generate_nonnegative_integer_tuples_summing_to_at_most \
as gnitstam
from modepy.tools import Monomial
order = 1
while True:
try:
quad = quad_class(order, dim)
except mp.QuadratureRuleUnavailable:
print(("UNAVAILABLE", quad_class, order))
break
if isinstance(quad_class, mp.VioreanuRokhlinSimplexQuadrature):
assert (quad.weights > 0).all()
if 0:
import matplotlib.pyplot as pt
pt.plot(quad.nodes[0], quad.nodes[1])
pt.show()
print((quad_class, order, quad.exact_to))
for comb in gnitstam(quad.exact_to, dim):
f = Monomial(comb)
i_f = quad(f)
ref = f.simplex_integral()
err = abs(i_f - ref)
assert err < 6e-15, (err, comb, i_f, ref)
order += 1
if highest_order is not None and order >= highest_order:
break
@pytest.mark.parametrize("dim", [2, 3])
@pytest.mark.parametrize(("quad_class", "max_order"), [
(mp.WitherdenVincentQuadrature, np.inf),
(mp.LegendreGaussTensorProductQuadrature, 6),
])
def test_hypercube_quadrature(dim, quad_class, max_order):
from pytools import \
generate_nonnegative_integer_tuples_summing_to_at_most as gnitstam
from modepy.tools import Monomial
def _check_monomial(quad, comb):
f = Monomial(comb)
int_approx = quad(f)
int_exact = 2**dim * f.hypercube_integral()
error = abs(int_approx - int_exact) / abs(int_exact)
logger.info("%s: %.5e %.5e / rel error %.5e",
comb, int_approx, int_exact, error)
return error
order = 1
while order < max_order:
try:
quad = quad_class(order, dim)
except mp.QuadratureRuleUnavailable:
logger.info("UNAVAILABLE at order %d", order)
break
assert np.all(quad.weights > 0)
logger.info("quadrature: %s %d %d",
quad_class.__name__.lower(), order, quad.exact_to)
for comb in gnitstam(quad.exact_to, dim):
assert _check_monomial(quad, comb) < 5.0e-15
comb = (0,) * (dim - 1) + (quad.exact_to + 1,)
assert _check_monomial(quad, comb) > 5.0e-15
order += 2
# You can test individual routines by typing
# $ python test_quadrature.py 'test_routine()'
if __name__ == "__main__":
import sys
if len(sys.argv) > 1:
exec(sys.argv[1])
else:
from pytest import main
main([__file__])
# vim: fdm=marker
| [
"matplotlib.pyplot.show",
"modepy.tools.Monomial",
"modepy.quadrature.jacobi_gauss.LegendreGaussQuadrature",
"matplotlib.pyplot.plot",
"modepy.quadrature.clenshaw_curtis.FejerQuadrature",
"pytools.generate_nonnegative_integer_tuples_summing_to_at_most",
"modepy.quadrature.clenshaw_curtis.ClenshawCurtisQ... | [((1176, 1203), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1193, 1203), False, 'import logging\n'), ((1909, 1953), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""backend"""', 'BACKENDS'], {}), "('backend', BACKENDS)\n", (1932, 1953), False, 'import pytest\n'), ((2901, 2940), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""kind"""', '[1, 2]'], {}), "('kind', [1, 2])\n", (2924, 2940), False, 'import pytest\n'), ((3352, 3555), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["('quad_class', 'highest_order')", '[(mp.XiaoGimbutasSimplexQuadrature, None), (mp.\n VioreanuRokhlinSimplexQuadrature, None), (mp.\n GrundmannMoellerSimplexQuadrature, 3)]'], {}), "(('quad_class', 'highest_order'), [(mp.\n XiaoGimbutasSimplexQuadrature, None), (mp.\n VioreanuRokhlinSimplexQuadrature, None), (mp.\n GrundmannMoellerSimplexQuadrature, 3)])\n", (3375, 3555), False, 'import pytest\n'), ((3561, 3599), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""dim"""', '[2, 3]'], {}), "('dim', [2, 3])\n", (3584, 3599), False, 'import pytest\n'), ((4710, 4748), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""dim"""', '[2, 3]'], {}), "('dim', [2, 3])\n", (4733, 4748), False, 'import pytest\n'), ((4750, 4901), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["('quad_class', 'max_order')", '[(mp.WitherdenVincentQuadrature, np.inf), (mp.\n LegendreGaussTensorProductQuadrature, 6)]'], {}), "(('quad_class', 'max_order'), [(mp.\n WitherdenVincentQuadrature, np.inf), (mp.\n LegendreGaussTensorProductQuadrature, 6)])\n", (4773, 4901), False, 'import pytest\n'), ((1609, 1636), 'modepy.quadrature.jacobi_gauss.LegendreGaussQuadrature', 'LegendreGaussQuadrature', (['(20)'], {}), '(20)\n', (1632, 1636), False, 'from modepy.quadrature.jacobi_gauss import LegendreGaussQuadrature\n'), ((2104, 2139), 'modepy.quadrature.jacobi_gauss.LegendreGaussQuadrature', 'LegendreGaussQuadrature', (['s', 'backend'], {}), '(s, backend)\n', (2127, 2139), False, 'from modepy.quadrature.jacobi_gauss import LegendreGaussQuadrature\n'), ((2586, 2613), 'modepy.quadrature.clenshaw_curtis.ClenshawCurtisQuadrature', 'ClenshawCurtisQuadrature', (['s'], {}), '(s)\n', (2610, 2613), False, 'from modepy.quadrature.clenshaw_curtis import ClenshawCurtisQuadrature\n'), ((3108, 3132), 'modepy.quadrature.clenshaw_curtis.FejerQuadrature', 'FejerQuadrature', (['s', 'kind'], {}), '(s, kind)\n', (3123, 3132), False, 'from modepy.quadrature.clenshaw_curtis import FejerQuadrature\n'), ((4391, 4419), 'pytools.generate_nonnegative_integer_tuples_summing_to_at_most', 'gnitstam', (['quad.exact_to', 'dim'], {}), '(quad.exact_to, dim)\n', (4399, 4419), True, 'from pytools import generate_nonnegative_integer_tuples_summing_to_at_most as gnitstam\n'), ((5159, 5173), 'modepy.tools.Monomial', 'Monomial', (['comb'], {}), '(comb)\n', (5167, 5173), False, 'from modepy.tools import Monomial\n'), ((5681, 5705), 'numpy.all', 'np.all', (['(quad.weights > 0)'], {}), '(quad.weights > 0)\n', (5687, 5705), True, 'import numpy as np\n'), ((5838, 5866), 'pytools.generate_nonnegative_integer_tuples_summing_to_at_most', 'gnitstam', (['quad.exact_to', 'dim'], {}), '(quad.exact_to, dim)\n', (5846, 5866), True, 'from pytools import generate_nonnegative_integer_tuples_summing_to_at_most as gnitstam\n'), ((6293, 6309), 'pytest.main', 'main', (['[__file__]'], {}), '([__file__])\n', (6297, 6309), False, 'from pytest import main\n'), ((1382, 1423), 'numpy.exp', 'np.exp', (['(-(x - mu) ** 2 / (2 * sigma ** 2))'], {}), '(-(x - mu) ** 2 / (2 * sigma ** 2))\n', (1388, 1423), True, 'import numpy as np\n'), ((4260, 4297), 'matplotlib.pyplot.plot', 'pt.plot', (['quad.nodes[0]', 'quad.nodes[1]'], {}), '(quad.nodes[0], quad.nodes[1])\n', (4267, 4297), True, 'import matplotlib.pyplot as pt\n'), ((4310, 4319), 'matplotlib.pyplot.show', 'pt.show', ([], {}), '()\n', (4317, 4319), True, 'import matplotlib.pyplot as pt\n'), ((4437, 4451), 'modepy.tools.Monomial', 'Monomial', (['comb'], {}), '(comb)\n', (4445, 4451), False, 'from modepy.tools import Monomial\n'), ((1362, 1380), 'numpy.sqrt', 'np.sqrt', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (1369, 1380), True, 'import numpy as np\n')] |
# Copyright 2018 The Lucid Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from __future__ import absolute_import, division, print_function
from os import path
import tensorflow as tf
import numpy as np
from lucid.modelzoo.util import load_text_labels, load_graphdef, forget_xy
from lucid.misc.io import load
import lucid.misc.io.showing as showing
IMAGENET_MEAN = np.array([123.68, 116.779, 103.939])
IMAGENET_MEAN_BGR = np.flip(IMAGENET_MEAN, 0)
class Model(object):
"""Base pretrained model importer."""
model_path = None
labels_path = None
labels = None
image_value_range = (-1, 1)
image_shape = [None, None, 3]
def __init__(self):
self.graph_def = None
if self.labels_path is not None:
self.labels = load_text_labels(self.labels_path)
def load_graphdef(self):
self.graph_def = load_graphdef(self.model_path)
def post_import(self, scope):
pass
def create_input(self, t_input=None, forget_xy_shape=True):
"""Create input tensor."""
if t_input is None:
t_input = tf.placeholder(tf.float32, self.image_shape)
t_prep_input = t_input
if len(t_prep_input.shape) == 3:
t_prep_input = tf.expand_dims(t_prep_input, 0)
if forget_xy_shape:
t_prep_input = forget_xy(t_prep_input)
if hasattr(self, "is_BGR") and self.is_BGR == True:
t_prep_input = tf.reverse(t_prep_input, [-1])
lo, hi = self.image_value_range
t_prep_input = lo + t_prep_input * (hi-lo)
return t_input, t_prep_input
def import_graph(self, t_input=None, scope='import', forget_xy_shape=True):
"""Import model GraphDef into the current graph."""
if self.graph_def is None:
raise Exception("Model.import_graph(): Must load graph def before importing it.")
graph = tf.get_default_graph()
assert graph.unique_name(scope, False) == scope, (
'Scope "%s" already exists. Provide explicit scope names when '
'importing multiple instances of the model.') % scope
t_input, t_prep_input = self.create_input(t_input, forget_xy_shape)
tf.import_graph_def(
self.graph_def, {self.input_name: t_prep_input}, name=scope)
self.post_import(scope)
def show_graph(self):
if self.graph_def is None:
raise Exception("Model.show_graph(): Must load graph def before showing it.")
showing.graph(self.graph_def)
class SerializedModel(Model):
"""Allows importing various types of serialized models from a directory.
(Currently only supports frozen graph models and relies on manifest.json file.
In the future we may want to support automatically detecting the type and
support loading more ways of saving models: tf.SavedModel, metagraphs, etc.)
"""
@classmethod
def from_directory(cls, model_path):
manifest_path = path.join(model_path, 'manifest.json')
try:
manifest = load(manifest_path)
except Exception as e:
raise ValueError("Could not find manifest.json file in dir {}. Error: {}".format(model_path, e))
if manifest.get('type', 'frozen') == 'frozen':
return FrozenGraphModel(model_path, manifest)
else: # TODO: add tf.SavedModel support, etc
raise NotImplementedError("SerializedModel Manifest type '{}' has not been implemented!".format(manifest.get('type')))
class FrozenGraphModel(SerializedModel):
def __init__(self, model_directory, manifest):
model_path = manifest.get('model_path', 'graph.pb')
if model_path.startswith("./"): # TODO: can we be less specific here?
self.model_path = path.join(model_directory, model_path)
else:
self.model_path = model_path
self.labels_path = manifest.get('labels_path', None)
self.image_value_range = manifest.get('image_value_range', None)
self.image_shape = manifest.get('image_shape', None)
self.input_name = manifest.get('input_name', 'input:0')
super().__init__()
| [
"lucid.misc.io.load",
"numpy.flip",
"tensorflow.reverse",
"tensorflow.get_default_graph",
"tensorflow.placeholder",
"lucid.modelzoo.util.load_graphdef",
"numpy.array",
"lucid.misc.io.showing.graph",
"lucid.modelzoo.util.load_text_labels",
"tensorflow.import_graph_def",
"lucid.modelzoo.util.forge... | [((978, 1014), 'numpy.array', 'np.array', (['[123.68, 116.779, 103.939]'], {}), '([123.68, 116.779, 103.939])\n', (986, 1014), True, 'import numpy as np\n'), ((1035, 1060), 'numpy.flip', 'np.flip', (['IMAGENET_MEAN', '(0)'], {}), '(IMAGENET_MEAN, 0)\n', (1042, 1060), True, 'import numpy as np\n'), ((1433, 1463), 'lucid.modelzoo.util.load_graphdef', 'load_graphdef', (['self.model_path'], {}), '(self.model_path)\n', (1446, 1463), False, 'from lucid.modelzoo.util import load_text_labels, load_graphdef, forget_xy\n'), ((2361, 2383), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (2381, 2383), True, 'import tensorflow as tf\n'), ((2649, 2734), 'tensorflow.import_graph_def', 'tf.import_graph_def', (['self.graph_def', '{self.input_name: t_prep_input}'], {'name': 'scope'}), '(self.graph_def, {self.input_name: t_prep_input}, name=scope\n )\n', (2668, 2734), True, 'import tensorflow as tf\n'), ((2915, 2944), 'lucid.misc.io.showing.graph', 'showing.graph', (['self.graph_def'], {}), '(self.graph_def)\n', (2928, 2944), True, 'import lucid.misc.io.showing as showing\n'), ((3370, 3408), 'os.path.join', 'path.join', (['model_path', '"""manifest.json"""'], {}), "(model_path, 'manifest.json')\n", (3379, 3408), False, 'from os import path\n'), ((1349, 1383), 'lucid.modelzoo.util.load_text_labels', 'load_text_labels', (['self.labels_path'], {}), '(self.labels_path)\n', (1365, 1383), False, 'from lucid.modelzoo.util import load_text_labels, load_graphdef, forget_xy\n'), ((1640, 1684), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', 'self.image_shape'], {}), '(tf.float32, self.image_shape)\n', (1654, 1684), True, 'import tensorflow as tf\n'), ((1770, 1801), 'tensorflow.expand_dims', 'tf.expand_dims', (['t_prep_input', '(0)'], {}), '(t_prep_input, 0)\n', (1784, 1801), True, 'import tensorflow as tf\n'), ((1847, 1870), 'lucid.modelzoo.util.forget_xy', 'forget_xy', (['t_prep_input'], {}), '(t_prep_input)\n', (1856, 1870), False, 'from lucid.modelzoo.util import load_text_labels, load_graphdef, forget_xy\n'), ((1948, 1978), 'tensorflow.reverse', 'tf.reverse', (['t_prep_input', '[-1]'], {}), '(t_prep_input, [-1])\n', (1958, 1978), True, 'import tensorflow as tf\n'), ((3435, 3454), 'lucid.misc.io.load', 'load', (['manifest_path'], {}), '(manifest_path)\n', (3439, 3454), False, 'from lucid.misc.io import load\n'), ((4109, 4147), 'os.path.join', 'path.join', (['model_directory', 'model_path'], {}), '(model_directory, model_path)\n', (4118, 4147), False, 'from os import path\n')] |
'''
created on Mar 13, 2018
@author: <NAME> (t-shsu)
'''
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn.utils import clip_grad_norm
import torch.optim as optim
import numpy as np
import random
from deep_dialog import dialog_config
use_cuda = torch.cuda.is_available()
class Discriminator(nn.Module):
def __init__(self, input_size=100, hidden_size=128, output_size=1, nn_type="MLP", movie_dict=None, act_set=None, slot_set=None, start_set=None, params=None):
super(Discriminator, self).__init__()
#############################
# misc setting #
#############################
self.movie_dict = movie_dict
self.act_set = act_set
self.slot_set = slot_set
self.start_set = start_set
self.act_cardinality = len(act_set.keys())
self.slot_cardinality = len(slot_set.keys())
self.feasible_actions = dialog_config.feasible_actions
self.feasible_actions_users = dialog_config.feasible_actions_users
self.num_actions = len(self.feasible_actions)
self.num_actions_user = len(self.feasible_actions_users)
self.max_turn = params['max_turn'] + 5
self.state_dimension = 193
self.hidden_size = hidden_size
self.cell_state_dimension = 193
self.nn_type = nn_type
self.threshold_upperbound = 0.55
self.threshold_lowerbound = 0.45
#############################
# model setting #
#############################
# (1) MLP discriminator (2) RNN discriminator
# (3) RNN encoder -> MLP discriminator
if nn_type == "MLP":
self.model = nn.Sequential(nn.Linear(self.state_dimension, hidden_size), nn.ELU(), nn.Linear(hidden_size, output_size), nn.Sigmoid())
elif nn_type == "RNN":
self.transform_layer = nn.Linear(self.cell_state_dimension, hidden_size)
self.model = nn.LSTM(126, hidden_size, 1, dropout=0.00, bidirectional=False)
self.output_layer = nn.Sequential(nn.Linear(hidden_size, output_size), nn.Sigmoid())
self.user_model_experience_pool = list()
self.user_experience_pool = list()
# hyperparameters
self.max_norm = 1
lr = 0.001
if nn_type == "MLP":
self.optimizer = optim.RMSprop(self.model.parameters(), lr=lr)
elif nn_type == "RNN":
params = []
params.extend(list(self.transform_layer.parameters()))
params.extend(list(self.model.parameters()))
params.extend(list(self.output_layer.parameters()))
self.optimizer = optim.RMSprop(params, lr=lr)
self.BCELoss = nn.BCELoss()
if use_cuda:
self.cuda()
def store_user_model_experience(self, experience):
self.user_model_experience_pool.append(experience)
if len(self.user_model_experience_pool) > 10000:
self.user_model_experience_pool = self.user_model_experience_pool[-9000:]
def store_user_experience(self, experience):
self.user_experience_pool.append(experience)
if len(self.user_experience_pool) > 10000:
self.user_experience_pool = self.user_experience_pool[-9000:]
def Variable(self, x):
return Variable(x, requires_grad=False).cuda() if use_cuda else Variable(x, requires_grad=False)
# discriminate a batch
def forward(self, experience=[]):
if self.nn_type == "MLP":
# define the policy here
d = [self.discriminate(exp).data.cpu().numpy()[0] for exp in experience]
# NOTE: be careful
if np.mean(d) < self.threshold_upperbound and np.mean(d) > self.threshold_lowerbound:
return True
else:
return False
elif self.nn_type == "RNN":
# define the policy here
d = [self.discriminate(exp).data.cpu().numpy()[0][0] for exp in experience]
# NOTE: be careful
if np.mean(d) < self.threshold_upperbound and np.mean(d) > self.threshold_lowerbound:
return True
else:
return False
def single_check(self, example):
d = self.discriminate(example).data.cpu().numpy()[0]
if d < self.threshold_upperbound and d > self.threshold_lowerbound:
return True
else:
return False
def discriminate(self, example):
if self.nn_type == "MLP":
state = self.prepare_state_representation(example[0])[0]
model_input = self.Variable(torch.FloatTensor(state))
return self.model(model_input)
elif self.nn_type == "RNN":
inputs = self.Variable(torch.FloatTensor([self.prepare_state_representation_for_RNN(history) for history in example[0]['history']]))
h_0 = self.Variable(torch.FloatTensor(self.prepare_initial_state_for_RNN(example[0])))
c_0 = self.Variable(torch.zeros(1, 1, self.hidden_size))
output, hn = self.model(inputs, (self.transform_layer(h_0).unsqueeze(0), c_0))
return self.output_layer(output[-1])
# D(s, a) determines 'how real is the example'
def train_single_batch(self, batch_size=16):
self.optimizer.zero_grad()
loss = 0
# sample positive and negative examples
pos_experiences = random.sample(self.user_experience_pool, batch_size)
neg_experiences = random.sample(self.user_model_experience_pool, batch_size)
for pos_exp, neg_exp in zip(pos_experiences, neg_experiences):
loss += self.BCELoss(self.discriminate(pos_exp), self.Variable(torch.ones(1))) + self.BCELoss(self.discriminate(neg_exp), self.Variable(torch.zeros(1)))
loss.backward()
clip_grad_norm(self.parameters(), self.max_norm)
self.optimizer.step()
return loss
def train(self, batch_size=16, batch_num=0):
loss = 0
if batch_num == 0:
batch_num = min(len(self.user_experience_pool) // batch_size, len(self.user_model_experience_pool)//batch_size)
for _ in range(batch_num):
loss += self.train_single_batch(batch_size)
return (loss/batch_num)
def prepare_state_representation(self, state):
""" Create the representation for each state """
user_action = state['user_action']
current_slots = state['current_slots']
agent_last = state['agent_action']
########################################################################
# Create one-hot of acts to represent the current user action
########################################################################
user_act_rep = np.zeros((1, self.act_cardinality))
user_act_rep[0, self.act_set[user_action['diaact']]] = 1.0
########################################################################
# Create bag of inform slots representation to represent the current user action
########################################################################
user_inform_slots_rep = np.zeros((1, self.slot_cardinality))
for slot in user_action['inform_slots'].keys():
user_inform_slots_rep[0, self.slot_set[slot]] = 1.0
########################################################################
# Create bag of request slots representation to represent the current user action
########################################################################
user_request_slots_rep = np.zeros((1, self.slot_cardinality))
for slot in user_action['request_slots'].keys():
user_request_slots_rep[0, self.slot_set[slot]] = 1.0
########################################################################
# Creat bag of filled_in slots based on the current_slots
########################################################################
current_slots_rep = np.zeros((1, self.slot_cardinality))
for slot in current_slots['inform_slots']:
current_slots_rep[0, self.slot_set[slot]] = 1.0
########################################################################
# Encode last agent act
########################################################################
agent_act_rep = np.zeros((1, self.act_cardinality))
if agent_last:
agent_act_rep[0, self.act_set[agent_last['diaact']]] = 1.0
########################################################################
# Encode last agent inform slots
########################################################################
agent_inform_slots_rep = np.zeros((1, self.slot_cardinality))
if agent_last:
for slot in agent_last['inform_slots'].keys():
agent_inform_slots_rep[0, self.slot_set[slot]] = 1.0
########################################################################
# Encode last agent request slots
########################################################################
agent_request_slots_rep = np.zeros((1, self.slot_cardinality))
if agent_last:
for slot in agent_last['request_slots'].keys():
agent_request_slots_rep[0, self.slot_set[slot]] = 1.0
# turn_rep = np.zeros((1, 1)) + state['turn'] / 10.
turn_rep = np.zeros((1, 1))
########################################################################
# One-hot representation of the turn count?
########################################################################
turn_onehot_rep = np.zeros((1, self.max_turn))
turn_onehot_rep[0, state['turn']] = 1.0
self.final_representation = np.hstack([user_act_rep, user_inform_slots_rep, user_request_slots_rep, agent_act_rep, agent_inform_slots_rep, agent_request_slots_rep, current_slots_rep, turn_rep, turn_onehot_rep])
return self.final_representation
def prepare_initial_state_for_RNN(self, state):
user_action = state['user_action']
current_slots = state['current_slots']
agent_last = state['agent_action']
########################################################################
# Create one-hot of acts to represent the current user action
########################################################################
user_act_rep = np.zeros((1, self.act_cardinality))
user_act_rep[0, self.act_set[user_action['diaact']]] = 1.0
########################################################################
# Create bag of inform slots representation to represent the current user action
########################################################################
user_inform_slots_rep = np.zeros((1, self.slot_cardinality))
for slot in user_action['inform_slots'].keys():
user_inform_slots_rep[0, self.slot_set[slot]] = 1.0
########################################################################
# Create bag of request slots representation to represent the current user action
########################################################################
user_request_slots_rep = np.zeros((1, self.slot_cardinality))
for slot in user_action['request_slots'].keys():
user_request_slots_rep[0, self.slot_set[slot]] = 1.0
########################################################################
# Creat bag of filled_in slots based on the current_slots
########################################################################
current_slots_rep = np.zeros((1, self.slot_cardinality))
for slot in current_slots['inform_slots']:
current_slots_rep[0, self.slot_set[slot]] = 1.0
########################################################################
# Encode last agent act
########################################################################
agent_act_rep = np.zeros((1, self.act_cardinality))
if agent_last:
agent_act_rep[0, self.act_set[agent_last['diaact']]] = 1.0
########################################################################
# Encode last agent inform slots
########################################################################
agent_inform_slots_rep = np.zeros((1, self.slot_cardinality))
if agent_last:
for slot in agent_last['inform_slots'].keys():
agent_inform_slots_rep[0, self.slot_set[slot]] = 1.0
########################################################################
# Encode last agent request slots
########################################################################
agent_request_slots_rep = np.zeros((1, self.slot_cardinality))
if agent_last:
for slot in agent_last['request_slots'].keys():
agent_request_slots_rep[0, self.slot_set[slot]] = 1.0
# turn_rep = np.zeros((1, 1)) + state['turn'] / 10.
turn_rep = np.zeros((1, 1))
########################################################################
# One-hot representation of the turn count?
########################################################################
turn_onehot_rep = np.zeros((1, self.max_turn))
turn_onehot_rep[0, state['turn']] = 1.0
self.final_representation = np.hstack([user_act_rep, user_inform_slots_rep, user_request_slots_rep, agent_act_rep, agent_inform_slots_rep, agent_request_slots_rep, current_slots_rep, turn_rep, turn_onehot_rep])
return self.final_representation
# {'request_slots': {'theater': 'UNK'}, 'turn': 0, 'speaker': 'user', 'inform_slots': {'numberofpeople': '3', 'moviename': '10 cloverfield lane'}, 'diaact': 'request'}
def prepare_state_representation_for_RNN(self, state):
########################################################################
# Create one-hot of acts to represent the current user action
########################################################################
user_act_rep = np.zeros((1, self.act_cardinality))
if state['speaker'] == 'user':
user_act_rep[0, self.act_set[state['diaact']]] = 1.0
########################################################################
# Create bag of inform slots representation to represent the current user action
########################################################################
user_inform_slots_rep = np.zeros((1, self.slot_cardinality))
for slot in state['inform_slots'].keys():
user_inform_slots_rep[0, self.slot_set[slot]] = 1.0
########################################################################
# Create bag of request slots representation to represent the current user action
########################################################################
user_request_slots_rep = np.zeros((1, self.slot_cardinality))
for slot in state['request_slots'].keys():
user_request_slots_rep[0, self.slot_set[slot]] = 1.0
########################################################################
# Encode last agent act
########################################################################
agent_act_rep = np.zeros((1, self.act_cardinality))
if state['speaker'] == 'agent':
agent_act_rep[0, self.act_set[state['diaact']]] = 1.0
turn_rep = np.zeros((1, 1))
########################################################################
# One-hot representation of the turn count?
########################################################################
turn_onehot_rep = np.zeros((1, self.max_turn))
turn_onehot_rep[0, state['turn']] = 1.0
self.final_representation = np.hstack([user_act_rep, user_inform_slots_rep, user_request_slots_rep, agent_act_rep, turn_rep, turn_onehot_rep])
return self.final_representation
| [
"torch.ones",
"torch.nn.BCELoss",
"random.sample",
"torch.autograd.Variable",
"numpy.zeros",
"torch.FloatTensor",
"numpy.hstack",
"torch.nn.ELU",
"numpy.mean",
"torch.cuda.is_available",
"torch.nn.Linear",
"torch.zeros",
"torch.nn.LSTM",
"torch.optim.RMSprop",
"torch.nn.Sigmoid"
] | [((281, 306), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (304, 306), False, 'import torch\n'), ((2722, 2734), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (2732, 2734), True, 'import torch.nn as nn\n'), ((5394, 5446), 'random.sample', 'random.sample', (['self.user_experience_pool', 'batch_size'], {}), '(self.user_experience_pool, batch_size)\n', (5407, 5446), False, 'import random\n'), ((5473, 5531), 'random.sample', 'random.sample', (['self.user_model_experience_pool', 'batch_size'], {}), '(self.user_model_experience_pool, batch_size)\n', (5486, 5531), False, 'import random\n'), ((6744, 6779), 'numpy.zeros', 'np.zeros', (['(1, self.act_cardinality)'], {}), '((1, self.act_cardinality))\n', (6752, 6779), True, 'import numpy as np\n'), ((7133, 7169), 'numpy.zeros', 'np.zeros', (['(1, self.slot_cardinality)'], {}), '((1, self.slot_cardinality))\n', (7141, 7169), True, 'import numpy as np\n'), ((7578, 7614), 'numpy.zeros', 'np.zeros', (['(1, self.slot_cardinality)'], {}), '((1, self.slot_cardinality))\n', (7586, 7614), True, 'import numpy as np\n'), ((7996, 8032), 'numpy.zeros', 'np.zeros', (['(1, self.slot_cardinality)'], {}), '((1, self.slot_cardinality))\n', (8004, 8032), True, 'import numpy as np\n'), ((8365, 8400), 'numpy.zeros', 'np.zeros', (['(1, self.act_cardinality)'], {}), '((1, self.act_cardinality))\n', (8373, 8400), True, 'import numpy as np\n'), ((8734, 8770), 'numpy.zeros', 'np.zeros', (['(1, self.slot_cardinality)'], {}), '((1, self.slot_cardinality))\n', (8742, 8770), True, 'import numpy as np\n'), ((9163, 9199), 'numpy.zeros', 'np.zeros', (['(1, self.slot_cardinality)'], {}), '((1, self.slot_cardinality))\n', (9171, 9199), True, 'import numpy as np\n'), ((9433, 9449), 'numpy.zeros', 'np.zeros', (['(1, 1)'], {}), '((1, 1))\n', (9441, 9449), True, 'import numpy as np\n'), ((9692, 9720), 'numpy.zeros', 'np.zeros', (['(1, self.max_turn)'], {}), '((1, self.max_turn))\n', (9700, 9720), True, 'import numpy as np\n'), ((9806, 9996), 'numpy.hstack', 'np.hstack', (['[user_act_rep, user_inform_slots_rep, user_request_slots_rep, agent_act_rep,\n agent_inform_slots_rep, agent_request_slots_rep, current_slots_rep,\n turn_rep, turn_onehot_rep]'], {}), '([user_act_rep, user_inform_slots_rep, user_request_slots_rep,\n agent_act_rep, agent_inform_slots_rep, agent_request_slots_rep,\n current_slots_rep, turn_rep, turn_onehot_rep])\n', (9815, 9996), True, 'import numpy as np\n'), ((10474, 10509), 'numpy.zeros', 'np.zeros', (['(1, self.act_cardinality)'], {}), '((1, self.act_cardinality))\n', (10482, 10509), True, 'import numpy as np\n'), ((10865, 10901), 'numpy.zeros', 'np.zeros', (['(1, self.slot_cardinality)'], {}), '((1, self.slot_cardinality))\n', (10873, 10901), True, 'import numpy as np\n'), ((11310, 11346), 'numpy.zeros', 'np.zeros', (['(1, self.slot_cardinality)'], {}), '((1, self.slot_cardinality))\n', (11318, 11346), True, 'import numpy as np\n'), ((11728, 11764), 'numpy.zeros', 'np.zeros', (['(1, self.slot_cardinality)'], {}), '((1, self.slot_cardinality))\n', (11736, 11764), True, 'import numpy as np\n'), ((12097, 12132), 'numpy.zeros', 'np.zeros', (['(1, self.act_cardinality)'], {}), '((1, self.act_cardinality))\n', (12105, 12132), True, 'import numpy as np\n'), ((12466, 12502), 'numpy.zeros', 'np.zeros', (['(1, self.slot_cardinality)'], {}), '((1, self.slot_cardinality))\n', (12474, 12502), True, 'import numpy as np\n'), ((12895, 12931), 'numpy.zeros', 'np.zeros', (['(1, self.slot_cardinality)'], {}), '((1, self.slot_cardinality))\n', (12903, 12931), True, 'import numpy as np\n'), ((13165, 13181), 'numpy.zeros', 'np.zeros', (['(1, 1)'], {}), '((1, 1))\n', (13173, 13181), True, 'import numpy as np\n'), ((13424, 13452), 'numpy.zeros', 'np.zeros', (['(1, self.max_turn)'], {}), '((1, self.max_turn))\n', (13432, 13452), True, 'import numpy as np\n'), ((13538, 13728), 'numpy.hstack', 'np.hstack', (['[user_act_rep, user_inform_slots_rep, user_request_slots_rep, agent_act_rep,\n agent_inform_slots_rep, agent_request_slots_rep, current_slots_rep,\n turn_rep, turn_onehot_rep]'], {}), '([user_act_rep, user_inform_slots_rep, user_request_slots_rep,\n agent_act_rep, agent_inform_slots_rep, agent_request_slots_rep,\n current_slots_rep, turn_rep, turn_onehot_rep])\n', (13547, 13728), True, 'import numpy as np\n'), ((14253, 14288), 'numpy.zeros', 'np.zeros', (['(1, self.act_cardinality)'], {}), '((1, self.act_cardinality))\n', (14261, 14288), True, 'import numpy as np\n'), ((14679, 14715), 'numpy.zeros', 'np.zeros', (['(1, self.slot_cardinality)'], {}), '((1, self.slot_cardinality))\n', (14687, 14715), True, 'import numpy as np\n'), ((15118, 15154), 'numpy.zeros', 'np.zeros', (['(1, self.slot_cardinality)'], {}), '((1, self.slot_cardinality))\n', (15126, 15154), True, 'import numpy as np\n'), ((15492, 15527), 'numpy.zeros', 'np.zeros', (['(1, self.act_cardinality)'], {}), '((1, self.act_cardinality))\n', (15500, 15527), True, 'import numpy as np\n'), ((15654, 15670), 'numpy.zeros', 'np.zeros', (['(1, 1)'], {}), '((1, 1))\n', (15662, 15670), True, 'import numpy as np\n'), ((15913, 15941), 'numpy.zeros', 'np.zeros', (['(1, self.max_turn)'], {}), '((1, self.max_turn))\n', (15921, 15941), True, 'import numpy as np\n'), ((16027, 16145), 'numpy.hstack', 'np.hstack', (['[user_act_rep, user_inform_slots_rep, user_request_slots_rep, agent_act_rep,\n turn_rep, turn_onehot_rep]'], {}), '([user_act_rep, user_inform_slots_rep, user_request_slots_rep,\n agent_act_rep, turn_rep, turn_onehot_rep])\n', (16036, 16145), True, 'import numpy as np\n'), ((3366, 3398), 'torch.autograd.Variable', 'Variable', (['x'], {'requires_grad': '(False)'}), '(x, requires_grad=False)\n', (3374, 3398), False, 'from torch.autograd import Variable\n'), ((1720, 1764), 'torch.nn.Linear', 'nn.Linear', (['self.state_dimension', 'hidden_size'], {}), '(self.state_dimension, hidden_size)\n', (1729, 1764), True, 'import torch.nn as nn\n'), ((1766, 1774), 'torch.nn.ELU', 'nn.ELU', ([], {}), '()\n', (1772, 1774), True, 'import torch.nn as nn\n'), ((1776, 1811), 'torch.nn.Linear', 'nn.Linear', (['hidden_size', 'output_size'], {}), '(hidden_size, output_size)\n', (1785, 1811), True, 'import torch.nn as nn\n'), ((1813, 1825), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (1823, 1825), True, 'import torch.nn as nn\n'), ((1893, 1942), 'torch.nn.Linear', 'nn.Linear', (['self.cell_state_dimension', 'hidden_size'], {}), '(self.cell_state_dimension, hidden_size)\n', (1902, 1942), True, 'import torch.nn as nn\n'), ((1968, 2030), 'torch.nn.LSTM', 'nn.LSTM', (['(126)', 'hidden_size', '(1)'], {'dropout': '(0.0)', 'bidirectional': '(False)'}), '(126, hidden_size, 1, dropout=0.0, bidirectional=False)\n', (1975, 2030), True, 'import torch.nn as nn\n'), ((2670, 2698), 'torch.optim.RMSprop', 'optim.RMSprop', (['params'], {'lr': 'lr'}), '(params, lr=lr)\n', (2683, 2698), True, 'import torch.optim as optim\n'), ((4609, 4633), 'torch.FloatTensor', 'torch.FloatTensor', (['state'], {}), '(state)\n', (4626, 4633), False, 'import torch\n'), ((2078, 2113), 'torch.nn.Linear', 'nn.Linear', (['hidden_size', 'output_size'], {}), '(hidden_size, output_size)\n', (2087, 2113), True, 'import torch.nn as nn\n'), ((2115, 2127), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (2125, 2127), True, 'import torch.nn as nn\n'), ((3309, 3341), 'torch.autograd.Variable', 'Variable', (['x'], {'requires_grad': '(False)'}), '(x, requires_grad=False)\n', (3317, 3341), False, 'from torch.autograd import Variable\n'), ((3667, 3677), 'numpy.mean', 'np.mean', (['d'], {}), '(d)\n', (3674, 3677), True, 'import numpy as np\n'), ((3710, 3720), 'numpy.mean', 'np.mean', (['d'], {}), '(d)\n', (3717, 3720), True, 'import numpy as np\n'), ((4990, 5025), 'torch.zeros', 'torch.zeros', (['(1)', '(1)', 'self.hidden_size'], {}), '(1, 1, self.hidden_size)\n', (5001, 5025), False, 'import torch\n'), ((4032, 4042), 'numpy.mean', 'np.mean', (['d'], {}), '(d)\n', (4039, 4042), True, 'import numpy as np\n'), ((4075, 4085), 'numpy.mean', 'np.mean', (['d'], {}), '(d)\n', (4082, 4085), True, 'import numpy as np\n'), ((5679, 5692), 'torch.ones', 'torch.ones', (['(1)'], {}), '(1)\n', (5689, 5692), False, 'import torch\n'), ((5752, 5766), 'torch.zeros', 'torch.zeros', (['(1)'], {}), '(1)\n', (5763, 5766), False, 'import torch\n')] |
# Copyright (c) 2020, Xilinx
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of FINN nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pytest
import brevitas.onnx as bo
import csv
import numpy as np
import os
import torch
import torchvision.datasets as datasets
import torchvision.transforms as transforms
import finn.core.onnx_exec as oxe
import finn.transformation.streamline.absorb as absorb
import finn.util.imagenet as imagenet_util
from finn.core.modelwrapper import ModelWrapper
from finn.transformation.fold_constants import FoldConstants
from finn.transformation.general import (
GiveReadableTensorNames,
GiveUniqueNodeNames,
GiveUniqueParameterTensors,
RemoveStaticGraphInputs,
)
from finn.transformation.infer_data_layouts import InferDataLayouts
from finn.transformation.infer_datatypes import InferDataTypes
from finn.transformation.infer_shapes import InferShapes
from finn.transformation.insert_topk import InsertTopK
from finn.transformation.merge_onnx_models import MergeONNXModels
from finn.util.basic import make_build_dir
from finn.util.pytorch import NormalizePreProc
from finn.util.test import get_test_model_trained
# normalization (preprocessing) settings for MobileNet-v1 w4a4
mean = [0.485, 0.456, 0.406]
std = 0.226
ch = 3
def test_brevitas_mobilenet_preproc():
if "IMAGENET_VAL_PATH" not in os.environ.keys():
pytest.skip("Can't do validation without IMAGENET_VAL_PATH")
n_images = 1000
# Brevitas-style: use torchvision pipeline
std_arr = [std, std, std]
normalize = transforms.Normalize(mean=mean, std=std_arr)
val_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(
os.environ["IMAGENET_VAL_PATH"] + "/../",
transforms.Compose(
[
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
]
),
),
batch_size=1,
shuffle=False,
num_workers=0,
)
# FINN-style: load_resize_crop then normalization as PyTorch graph
preproc = NormalizePreProc(mean, std, ch)
finn_loader = imagenet_util.get_val_images(n_images)
val_loader = iter(val_loader)
for i in range(n_images):
(img_path, finn_target) = next(finn_loader)
finn_img = imagenet_util.load_resize_crop(img_path)
finn_img = preproc.forward(torch.from_numpy(finn_img).float())
(pyt_img, pyt_target) = next(val_loader)
assert finn_img.shape == pyt_img.shape
assert (finn_img == pyt_img).all()
@pytest.mark.slow
# marked as XFAIL until Brevitas export issues are resolved:
# https://github.com/Xilinx/brevitas/issues/173
@pytest.mark.xfail
def test_brevitas_compare_exported_mobilenet():
if "IMAGENET_VAL_PATH" not in os.environ.keys():
pytest.skip("Can't do validation without IMAGENET_VAL_PATH")
n_images = 10
debug_mode = False
export_onnx_path = make_build_dir("test_brevitas_mobilenet-v1_")
# export preprocessing
preproc_onnx = export_onnx_path + "/quant_mobilenet_v1_4b_preproc.onnx"
preproc = NormalizePreProc(mean, std, ch)
bo.export_finn_onnx(preproc, (1, 3, 224, 224), preproc_onnx)
preproc_model = ModelWrapper(preproc_onnx)
preproc_model = preproc_model.transform(InferShapes())
preproc_model = preproc_model.transform(GiveUniqueNodeNames())
preproc_model = preproc_model.transform(GiveUniqueParameterTensors())
preproc_model = preproc_model.transform(GiveReadableTensorNames())
# export the actual MobileNet-v1
finn_onnx = export_onnx_path + "/quant_mobilenet_v1_4b.onnx"
mobilenet = get_test_model_trained("mobilenet", 4, 4)
if debug_mode:
dbg_hook = bo.enable_debug(mobilenet)
bo.export_finn_onnx(mobilenet, (1, 3, 224, 224), finn_onnx)
model = ModelWrapper(finn_onnx)
model = model.transform(InferShapes())
model = model.transform(FoldConstants())
model = model.transform(RemoveStaticGraphInputs())
model = model.transform(InsertTopK())
# get initializer from Mul that will be absorbed into topk
a0 = model.get_initializer(model.get_nodes_by_op_type("Mul")[-1].input[1])
model = model.transform(absorb.AbsorbScalarMulAddIntoTopK())
model = model.transform(InferShapes())
model = model.transform(InferDataTypes())
model = model.transform(InferDataLayouts())
model = model.transform(GiveUniqueNodeNames())
model = model.transform(GiveUniqueParameterTensors())
model = model.transform(GiveReadableTensorNames())
model.save(export_onnx_path + "/quant_mobilenet_v1_4b_wo_preproc.onnx")
# create merged preprocessing + MobileNet-v1 model
model = model.transform(MergeONNXModels(preproc_model))
model.save(export_onnx_path + "/quant_mobilenet_v1_4b.onnx")
with open(
export_onnx_path + "/mobilenet_validation.csv", "w", newline=""
) as csvfile:
writer = csv.writer(csvfile)
writer.writerow(
[
"goldenID",
"brevitasTop5",
"brevitasTop5[%]",
"finnTop5",
"finnTop5[%]",
"top5equal",
"top5%equal",
]
)
csvfile.flush()
workload = imagenet_util.get_val_images(n_images, interleave_classes=True)
all_inds_ok = True
all_probs_ok = True
for (img_path, target_id) in workload:
img_np = imagenet_util.load_resize_crop(img_path)
img_torch = torch.from_numpy(img_np).float()
# do forward pass in PyTorch/Brevitas
input_tensor = preproc.forward(img_torch)
expected = mobilenet.forward(input_tensor).detach().numpy()
expected_topk = expected.flatten()
expected_top5 = np.argsort(expected_topk)[-5:]
expected_top5 = np.flip(expected_top5)
expected_top5_prob = []
for index in expected_top5:
expected_top5_prob.append(expected_topk[index])
idict = {model.graph.input[0].name: img_np}
odict = oxe.execute_onnx(model, idict, return_full_exec_context=True)
produced = odict[model.graph.output[0].name]
produced_prob = odict["TopK_0_out0"] * a0
inds_ok = (produced.flatten() == expected_top5).all()
probs_ok = np.isclose(produced_prob.flatten(), expected_top5_prob).all()
all_inds_ok = all_inds_ok and inds_ok
all_probs_ok = all_probs_ok and probs_ok
writer.writerow(
[
str(target_id),
str(expected_top5),
str(expected_top5_prob),
str(produced.flatten()),
str(produced_prob.flatten()),
str(inds_ok),
str(probs_ok),
]
)
csvfile.flush()
if ((not inds_ok) or (not probs_ok)) and debug_mode:
print("Results differ for %s" % img_path)
# check all tensors at debug markers
names_brevitas = set(dbg_hook.values.keys())
names_finn = set(odict.keys())
names_common = names_brevitas.intersection(names_finn)
for dbg_name in names_common:
if not np.isclose(
dbg_hook.values[dbg_name].detach().numpy(),
odict[dbg_name],
atol=1e-3,
).all():
print("Tensor %s differs between Brevitas and FINN" % dbg_name)
assert all_inds_ok and all_probs_ok
| [
"finn.transformation.infer_shapes.InferShapes",
"finn.util.pytorch.NormalizePreProc",
"finn.core.onnx_exec.execute_onnx",
"finn.transformation.merge_onnx_models.MergeONNXModels",
"finn.transformation.general.GiveUniqueNodeNames",
"numpy.argsort",
"finn.util.imagenet.get_val_images",
"torchvision.trans... | [((2935, 2979), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'mean': 'mean', 'std': 'std_arr'}), '(mean=mean, std=std_arr)\n', (2955, 2979), True, 'import torchvision.transforms as transforms\n'), ((3529, 3560), 'finn.util.pytorch.NormalizePreProc', 'NormalizePreProc', (['mean', 'std', 'ch'], {}), '(mean, std, ch)\n', (3545, 3560), False, 'from finn.util.pytorch import NormalizePreProc\n'), ((3579, 3617), 'finn.util.imagenet.get_val_images', 'imagenet_util.get_val_images', (['n_images'], {}), '(n_images)\n', (3607, 3617), True, 'import finn.util.imagenet as imagenet_util\n'), ((4386, 4431), 'finn.util.basic.make_build_dir', 'make_build_dir', (['"""test_brevitas_mobilenet-v1_"""'], {}), "('test_brevitas_mobilenet-v1_')\n", (4400, 4431), False, 'from finn.util.basic import make_build_dir\n'), ((4549, 4580), 'finn.util.pytorch.NormalizePreProc', 'NormalizePreProc', (['mean', 'std', 'ch'], {}), '(mean, std, ch)\n', (4565, 4580), False, 'from finn.util.pytorch import NormalizePreProc\n'), ((4585, 4645), 'brevitas.onnx.export_finn_onnx', 'bo.export_finn_onnx', (['preproc', '(1, 3, 224, 224)', 'preproc_onnx'], {}), '(preproc, (1, 3, 224, 224), preproc_onnx)\n', (4604, 4645), True, 'import brevitas.onnx as bo\n'), ((4666, 4692), 'finn.core.modelwrapper.ModelWrapper', 'ModelWrapper', (['preproc_onnx'], {}), '(preproc_onnx)\n', (4678, 4692), False, 'from finn.core.modelwrapper import ModelWrapper\n'), ((5082, 5123), 'finn.util.test.get_test_model_trained', 'get_test_model_trained', (['"""mobilenet"""', '(4)', '(4)'], {}), "('mobilenet', 4, 4)\n", (5104, 5123), False, 'from finn.util.test import get_test_model_trained\n'), ((5193, 5252), 'brevitas.onnx.export_finn_onnx', 'bo.export_finn_onnx', (['mobilenet', '(1, 3, 224, 224)', 'finn_onnx'], {}), '(mobilenet, (1, 3, 224, 224), finn_onnx)\n', (5212, 5252), True, 'import brevitas.onnx as bo\n'), ((5265, 5288), 'finn.core.modelwrapper.ModelWrapper', 'ModelWrapper', (['finn_onnx'], {}), '(finn_onnx)\n', (5277, 5288), False, 'from finn.core.modelwrapper import ModelWrapper\n'), ((2734, 2751), 'os.environ.keys', 'os.environ.keys', ([], {}), '()\n', (2749, 2751), False, 'import os\n'), ((2761, 2821), 'pytest.skip', 'pytest.skip', (['"""Can\'t do validation without IMAGENET_VAL_PATH"""'], {}), '("Can\'t do validation without IMAGENET_VAL_PATH")\n', (2772, 2821), False, 'import pytest\n'), ((3753, 3793), 'finn.util.imagenet.load_resize_crop', 'imagenet_util.load_resize_crop', (['img_path'], {}), '(img_path)\n', (3783, 3793), True, 'import finn.util.imagenet as imagenet_util\n'), ((4234, 4251), 'os.environ.keys', 'os.environ.keys', ([], {}), '()\n', (4249, 4251), False, 'import os\n'), ((4261, 4321), 'pytest.skip', 'pytest.skip', (['"""Can\'t do validation without IMAGENET_VAL_PATH"""'], {}), '("Can\'t do validation without IMAGENET_VAL_PATH")\n', (4272, 4321), False, 'import pytest\n'), ((4737, 4750), 'finn.transformation.infer_shapes.InferShapes', 'InferShapes', ([], {}), '()\n', (4748, 4750), False, 'from finn.transformation.infer_shapes import InferShapes\n'), ((4796, 4817), 'finn.transformation.general.GiveUniqueNodeNames', 'GiveUniqueNodeNames', ([], {}), '()\n', (4815, 4817), False, 'from finn.transformation.general import GiveReadableTensorNames, GiveUniqueNodeNames, GiveUniqueParameterTensors, RemoveStaticGraphInputs\n'), ((4863, 4891), 'finn.transformation.general.GiveUniqueParameterTensors', 'GiveUniqueParameterTensors', ([], {}), '()\n', (4889, 4891), False, 'from finn.transformation.general import GiveReadableTensorNames, GiveUniqueNodeNames, GiveUniqueParameterTensors, RemoveStaticGraphInputs\n'), ((4937, 4962), 'finn.transformation.general.GiveReadableTensorNames', 'GiveReadableTensorNames', ([], {}), '()\n', (4960, 4962), False, 'from finn.transformation.general import GiveReadableTensorNames, GiveUniqueNodeNames, GiveUniqueParameterTensors, RemoveStaticGraphInputs\n'), ((5162, 5188), 'brevitas.onnx.enable_debug', 'bo.enable_debug', (['mobilenet'], {}), '(mobilenet)\n', (5177, 5188), True, 'import brevitas.onnx as bo\n'), ((5317, 5330), 'finn.transformation.infer_shapes.InferShapes', 'InferShapes', ([], {}), '()\n', (5328, 5330), False, 'from finn.transformation.infer_shapes import InferShapes\n'), ((5360, 5375), 'finn.transformation.fold_constants.FoldConstants', 'FoldConstants', ([], {}), '()\n', (5373, 5375), False, 'from finn.transformation.fold_constants import FoldConstants\n'), ((5405, 5430), 'finn.transformation.general.RemoveStaticGraphInputs', 'RemoveStaticGraphInputs', ([], {}), '()\n', (5428, 5430), False, 'from finn.transformation.general import GiveReadableTensorNames, GiveUniqueNodeNames, GiveUniqueParameterTensors, RemoveStaticGraphInputs\n'), ((5460, 5472), 'finn.transformation.insert_topk.InsertTopK', 'InsertTopK', ([], {}), '()\n', (5470, 5472), False, 'from finn.transformation.insert_topk import InsertTopK\n'), ((5645, 5680), 'finn.transformation.streamline.absorb.AbsorbScalarMulAddIntoTopK', 'absorb.AbsorbScalarMulAddIntoTopK', ([], {}), '()\n', (5678, 5680), True, 'import finn.transformation.streamline.absorb as absorb\n'), ((5710, 5723), 'finn.transformation.infer_shapes.InferShapes', 'InferShapes', ([], {}), '()\n', (5721, 5723), False, 'from finn.transformation.infer_shapes import InferShapes\n'), ((5753, 5769), 'finn.transformation.infer_datatypes.InferDataTypes', 'InferDataTypes', ([], {}), '()\n', (5767, 5769), False, 'from finn.transformation.infer_datatypes import InferDataTypes\n'), ((5799, 5817), 'finn.transformation.infer_data_layouts.InferDataLayouts', 'InferDataLayouts', ([], {}), '()\n', (5815, 5817), False, 'from finn.transformation.infer_data_layouts import InferDataLayouts\n'), ((5847, 5868), 'finn.transformation.general.GiveUniqueNodeNames', 'GiveUniqueNodeNames', ([], {}), '()\n', (5866, 5868), False, 'from finn.transformation.general import GiveReadableTensorNames, GiveUniqueNodeNames, GiveUniqueParameterTensors, RemoveStaticGraphInputs\n'), ((5898, 5926), 'finn.transformation.general.GiveUniqueParameterTensors', 'GiveUniqueParameterTensors', ([], {}), '()\n', (5924, 5926), False, 'from finn.transformation.general import GiveReadableTensorNames, GiveUniqueNodeNames, GiveUniqueParameterTensors, RemoveStaticGraphInputs\n'), ((5956, 5981), 'finn.transformation.general.GiveReadableTensorNames', 'GiveReadableTensorNames', ([], {}), '()\n', (5979, 5981), False, 'from finn.transformation.general import GiveReadableTensorNames, GiveUniqueNodeNames, GiveUniqueParameterTensors, RemoveStaticGraphInputs\n'), ((6142, 6172), 'finn.transformation.merge_onnx_models.MergeONNXModels', 'MergeONNXModels', (['preproc_model'], {}), '(preproc_model)\n', (6157, 6172), False, 'from finn.transformation.merge_onnx_models import MergeONNXModels\n'), ((6362, 6381), 'csv.writer', 'csv.writer', (['csvfile'], {}), '(csvfile)\n', (6372, 6381), False, 'import csv\n'), ((6701, 6764), 'finn.util.imagenet.get_val_images', 'imagenet_util.get_val_images', (['n_images'], {'interleave_classes': '(True)'}), '(n_images, interleave_classes=True)\n', (6729, 6764), True, 'import finn.util.imagenet as imagenet_util\n'), ((6888, 6928), 'finn.util.imagenet.load_resize_crop', 'imagenet_util.load_resize_crop', (['img_path'], {}), '(img_path)\n', (6918, 6928), True, 'import finn.util.imagenet as imagenet_util\n'), ((7296, 7318), 'numpy.flip', 'np.flip', (['expected_top5'], {}), '(expected_top5)\n', (7303, 7318), True, 'import numpy as np\n'), ((7535, 7596), 'finn.core.onnx_exec.execute_onnx', 'oxe.execute_onnx', (['model', 'idict'], {'return_full_exec_context': '(True)'}), '(model, idict, return_full_exec_context=True)\n', (7551, 7596), True, 'import finn.core.onnx_exec as oxe\n'), ((7237, 7262), 'numpy.argsort', 'np.argsort', (['expected_topk'], {}), '(expected_topk)\n', (7247, 7262), True, 'import numpy as np\n'), ((3180, 3202), 'torchvision.transforms.Resize', 'transforms.Resize', (['(256)'], {}), '(256)\n', (3197, 3202), True, 'import torchvision.transforms as transforms\n'), ((3224, 3250), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(224)'], {}), '(224)\n', (3245, 3250), True, 'import torchvision.transforms as transforms\n'), ((3272, 3293), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (3291, 3293), True, 'import torchvision.transforms as transforms\n'), ((3829, 3855), 'torch.from_numpy', 'torch.from_numpy', (['finn_img'], {}), '(finn_img)\n', (3845, 3855), False, 'import torch\n'), ((6953, 6977), 'torch.from_numpy', 'torch.from_numpy', (['img_np'], {}), '(img_np)\n', (6969, 6977), False, 'import torch\n')] |
class node():
def __init__(self, state, parent, action, g_cost, depth, h_cost, x, y, move, check):
self.state = state
self.parent = parent
self.action = action
self.g_cost = g_cost
self.depth = depth
self.h_cost = h_cost
self.x=x
self.y=y
self.move=move
self.check=check
def __lt__(self, other):
if self.check == 0:
return self.g_cost<other.g_cost
elif self.check == 1:
return self.h_cost<other.h_cost
elif self.check == 2:
return (self.h_cost+self.g_cost)<(other.h_cost+other.g_cost)
def Plot_Graph():
BFS_depth = []
BFS_time = []
BFS_node = []
UCS_depth = []
UCS_time = []
UCS_node = []
DLS_depth = []
DLS_time = []
DLS_node = []
IDS_depth = []
IDS_time = []
IDS_node = []
GBFS_depth = []
GBFS_time = []
GBFS_node = []
A_star_depth = []
A_star_time = []
A_star_node = []
file = open("plot_data.txt","r")
j=1
while True:
arr =[]
ff= file.readline();
if len(ff)==0:
break
if len(ff)>1 and j>2:
tmp= [i for i in ff.split('#')]
if tmp[1]=='bfs':
BFS_depth.append(tmp[2])
BFS_node.append(tmp[3])
BFS_time.append(int(float(tmp[4])))
elif tmp[1]=='ucs':
UCS_depth.append(tmp[2])
UCS_node.append(tmp[3])
UCS_time.append(int(float(tmp[4])))
elif tmp[1]=='dls':
DLS_depth.append(tmp[2])
DLS_node.append(tmp[3])
DLS_time.append(int(float(tmp[4])))
elif tmp[1]=='ids':
IDS_depth.append(tmp[2])
IDS_node.append(tmp[3])
IDS_time.append(int(float(tmp[4])))
elif tmp[1]=='gbfs':
GBFS_depth.append(tmp[2])
GBFS_node.append(tmp[3])
GBFS_time.append(int(float(tmp[4])))
elif tmp[1]=='a_star':
A_star_depth.append(tmp[2])
A_star_node.append(tmp[3])
A_star_time.append(int(float(tmp[4])))
j+=1
file.close()
# print(BFS_depth)
# print(BFS_node)
# print(BFS_time)
# plot line and give color for each line
plt.plot(BFS_depth, color='red')
plt.plot(UCS_depth, color='green')
plt.plot(DLS_depth, color='orange')
plt.plot(IDS_depth, color='purple')
plt.plot(GBFS_depth, color='blue')
plt.plot(A_star_depth, color='cyan')
##path cost vs depth
# graph title
plt.title("Depth vs Depth")
# labels
plt.xlabel('Distance(initial-goal state)')
plt.ylabel('Path cost')
plt.xticks(numpy.arange(len(BFS_depth)), BFS_depth, rotation=90)
# legend
red_patch = mpatches.Patch(color='red', label='BFS')
green_patch = mpatches.Patch(color='green', label='UCS')
orange_patch = mpatches.Patch(color='orange', label='DLS')
purple_patch = mpatches.Patch(color='purple', label='IDS')
blue_patch = mpatches.Patch(color='blue', label='GBFS')
cyan_patch = mpatches.Patch(color='cyan', label='A*')
plt.legend(handles=[red_patch, green_patch, orange_patch, purple_patch, blue_patch, cyan_patch])
# add grid
plt.grid(True)
plt.show()
##Time vs depth
#plot time vs depth
plt.plot(BFS_time, color='red')
plt.plot(UCS_time, color='green')
plt.plot(DLS_time, color='orange')
plt.plot(IDS_time, color='purple')
plt.plot(GBFS_time, color='blue')
plt.plot(A_star_time, color='cyan')
# graph title
plt.title("Time vs Depth")
# labels
plt.xlabel('Distance(initial-goal state)')
plt.ylabel('Time')
plt.xticks(numpy.arange(len(BFS_depth)), BFS_depth, rotation=90)
# legend
red_patch = mpatches.Patch(color='red', label='BFS')
green_patch = mpatches.Patch(color='green', label='UCS')
orange_patch = mpatches.Patch(color='orange', label='DLS')
purple_patch = mpatches.Patch(color='purple', label='IDS')
blue_patch = mpatches.Patch(color='blue', label='GBFS')
cyan_patch = mpatches.Patch(color='cyan', label='A*')
plt.legend(handles=[red_patch, green_patch, orange_patch, purple_patch, blue_patch, cyan_patch])
# add grid
plt.grid(True)
plt.show()
#plot node vs depth
plt.plot(BFS_node, color='red')
plt.plot(UCS_node, color='green')
plt.plot(DLS_node, color='orange')
plt.plot(IDS_node, color='purple')
plt.plot(GBFS_node, color='blue')
plt.plot(A_star_node, color='cyan')
# graph title
plt.title("Node vs Depth")
# labels
plt.xlabel('Distance(initial-goal state)')
plt.ylabel('Number of Node created')
plt.xticks(numpy.arange(len(BFS_depth)), BFS_depth, rotation=90)
# legend
red_patch = mpatches.Patch(color='red', label='BFS')
green_patch = mpatches.Patch(color='green', label='UCS')
orange_patch = mpatches.Patch(color='orange', label='DLS')
purple_patch = mpatches.Patch(color='purple', label='IDS')
blue_patch = mpatches.Patch(color='blue', label='GBFS')
cyan_patch = mpatches.Patch(color='cyan', label='A*')
plt.legend(handles=[red_patch, green_patch, orange_patch, purple_patch, blue_patch, cyan_patch])
# add grid
plt.grid(True)
plt.show()
def storeData(my_list):
print(my_list)
with open('plot_data.txt', 'a') as f:
for item in my_list:
f.write("%s#" % item)
if my_list.index(item)==4:
f.write("\n")
# f.close()
def initFinalState(acceptState, tmp):
# print(tmp)
cnt = 1
row = len(acceptState)
l = len(tmp)
# for i in range(0, l):
# print(tmp[i])
k = 0
for i in range(0,row):
for j in range(0,row):
acceptState[i][j]= tmp[k]
k+=1
def printState(state):
row = len(state)
for i in range(row):
for j in range(row):
print(state[i][j],end=" ")
print("")
print("")
def filePrint(file,state):
row = len(state)
for i in range(row):
for j in range(row):
file.write(str(state[i][j])+" ")
file.write("\n")
file.write("\n")
def getAction(x,y):
limit = row-1
result = []
if x<limit:
result+=["down"]
if x>0:
result+=["up"]
if y<limit:
result+=["right"]
if y>0:
result+=["left"]
return result
def movCheck(mov,x,y):
if mov =="up":
X=x-1
Y=y
elif mov == "down":
X=x+1
Y=y
elif mov =="right":
X=x
Y=y+1
elif mov =="left":
X=x
Y=y-1
return X,Y
def listToString(tmp):
string =""
for i in range(len(tmp)):
for j in range(len(tmp)):
string+=str(tmp[i][j])
string+=' '
return string
def heuristic(tmpState,check):
row = len(tmpState)
cnt = 0
if check == 1:
for i in range(0, row):
for j in range(0, row):
if (tmpState[i][j]!=acceptState[i][j]) and tmpState[i][j]!=0:
cnt+=1
elif check == 2:
mpp= collections.ChainMap()
for i in range(0, row):
for j in range(0, row):
mpp[acceptState[i][j]]=[i,j]
for i in range(0, row):
for j in range(0, row):
tmp = mpp[tmpState[i][j]]
cnt+=(abs(i-tmp[0])+abs(j-tmp[1]))
return cnt
def BFS(tmpState):
mp.clear()
global indx
indx = 0
tmp = listToString(tmpState.copy())
mp[tmp] = indx
indx += 1
global Node
Node = []
global call
call = 0
tmpNode = node(state=tmpState, parent=-1, action=getAction(startX, startY), g_cost=0, depth=0, h_cost=0, x=startX, y=startY,move="intit",check=0)
Node += [tmpNode]
isVisited.clear()
queuee = []
queuee.append(tmpNode)
isVisited[listToString(tmpNode.state)] = 1
while len(queuee) !=0:
nd = queuee.pop(0)
x=nd.x
y=nd.y
call+=1
if nd.state==acceptState:
return nd
for mov in nd.action:
X,Y=movCheck(mov,x,y)
nwstate = copy.deepcopy(nd.state)
nwstate[x][y]=nd.state[X][Y]
nwstate[X][Y] = nd.state[x][y]
tmp=listToString(nwstate)
nwNode = node(nwstate,mp[listToString(nd.state)],getAction(X,Y),nd.g_cost,nd.depth+1,nd.h_cost,X,Y,mov,0)
if tmp not in mp:
mp[tmp]=indx
indx+=1
Node+=[nwNode]
if nwstate==acceptState:
return nwNode
if tmp not in isVisited:
queuee.append(nwNode)
isVisited[tmp] = 1
return None
def BFS_print():
file = open("1_BFS.txt", "w")
file.write("Initial state :\n")
filePrint(file, tmpState)
startTime = time.time()
print("BFS Running...")
nd=BFS(tmpState)
print("BFS Finished!")
elapsedTime = time.time() - startTime
if nd == None:
print("No Aceepted state found!")
file.write("No Aceepted state found!\n")
file.write("Number of call: " + str(call) + "\nNumber of node created: " + str(indx) + "\nTime : " + str(elapsedTime) + "\n")
else:
print("Aceepted state found!")
file.write("Depth: " + str(nd.depth) + "\nNumber of call: " + str(call) + "\nNumber of node created: " + str(indx) + "\nTime : " + str(elapsedTime) + "\n\n")
answer = []
tmpnd = copy.deepcopy(nd)
while tmpnd.parent != -1:
answer += [tmpnd]
tmpnd = Node[tmpnd.parent]
answer.reverse()
for nn in answer:
file.write("Current Move: " + nn.move + ", Current Depth: "+str(nn.depth)+"\n")
filePrint(file, nn.state)
file.close()
D = nd.depth
N = indx
T = elapsedTime
return D,N,T
def UCS(tmpState):
mp.clear()
global indx
indx = 0
tmp = listToString(tmpState.copy())
mp[tmp] = indx
indx += 1
global Node
Node = []
global call
call = 0
tmpNode = node(state=tmpState, parent=-1, action=getAction(startX, startY), g_cost=0, depth=0, h_cost=0, x=startX, y=startY, move="intit",check=0)
Node += [tmpNode]
isVisited.clear()
q = queue.PriorityQueue()
q.put(tmpNode)
isVisited[listToString(tmpNode.state)] = 1
while not q.empty():
nd = q.get()
x=nd.x
y=nd.y
call+=1
isVisited[listToString(nd.state)] = 2
if nd.state==acceptState:
return nd
for mov in nd.action:
X,Y=movCheck(mov,x,y)
nwstate = copy.deepcopy(nd.state)
nwstate[x][y]=nd.state[X][Y]
nwstate[X][Y] = nd.state[x][y]
tmp=listToString(nwstate)
nwNode = node(nwstate,mp[listToString(nd.state)],getAction(X,Y),nd.g_cost+1,nd.depth+1,nd.h_cost,X,Y,mov,0)
if tmp not in mp:
mp[tmp]=indx
indx+=1
Node+=[nwNode]
if tmp not in isVisited:
q.put(nwNode)
isVisited[tmp] = 1
elif isVisited[tmp]==1:
q.put(nwNode)
return None
def UCS_print():
file = open("2_UCS.txt", "w")
file.write("Initial state :\n")
filePrint(file, tmpState)
startTime = time.time()
print("UCS Running...")
nd=UCS(tmpState)
print("UCS Finished!")
elapsedTime = time.time() - startTime
if nd == None:
print("No Aceepted state found!")
file.write("No Aceepted state found!\n")
file.write("Number of call: " + str(call) + "\nNumber of node created: " + str(indx) + "\nTime : " + str(elapsedTime) + "\n")
else:
print("Aceepted state found!")
file.write("Depth: " + str(nd.g_cost) + "\nNumber of call: " + str(call) + "\nNumber of node created: " + str(indx) + "\nTime : " + str(elapsedTime) + "\n\n")
answer = []
tmpnd = copy.deepcopy(nd)
while tmpnd.parent != -1:
answer += [tmpnd]
tmpnd = Node[tmpnd.parent]
answer.reverse()
for nn in answer:
file.write("Current Move: " + nn.move + ", Current Depth: "+str(nn.depth)+"\n")
filePrint(file, nn.state)
file.close()
D = nd.depth
N = indx
T = elapsedTime
return D,N,T
def DLS(tmpNode,cutOffNode,limit):
isVisited[listToString(tmpNode.state)] = 1
nd = copy.deepcopy(tmpNode)
x=nd.x
y=nd.y
global call
call+=1
if nd.state==acceptState:
return nd
elif limit==0:
return cutOffNode
isCutOff = False
for mov in nd.action:
X,Y=movCheck(mov,x,y)
nwstate = copy.deepcopy(nd.state)
nwstate[x][y]=nd.state[X][Y]
nwstate[X][Y] = nd.state[x][y]
tmp=listToString(nwstate)
nwNode = node(nwstate,mp[listToString(nd.state)],getAction(X,Y),nd.g_cost,nd.depth+1,nd.h_cost,X,Y,mov,0)
if nwstate==acceptState:
return nwNode
if tmp not in mp:
global indx
mp[tmp]=indx
indx+=1
global Node
Node+=[nwNode]
rslt = DLS(nwNode, cutOffNode, limit - 1)
if rslt == cutOffNode:
isCutOff = True
elif rslt != None:
return rslt
else :
chk=mp[tmp]
chkNode = Node[chk]
if chkNode.depth > nwNode.depth:
Node[chk]=nwNode
rslt = DLS(nwNode, cutOffNode, limit - 1)
if rslt == cutOffNode:
isCutOff = True
elif rslt != None:
return rslt
if isCutOff == True:
return cutOffNode
else:
return None
def DLS_print(tmpState,limit):
file = open("3_DLS.txt", "w")
file.write("Initial state :\n")
filePrint(file, tmpState)
mp.clear()
global indx
indx = 0
tmp = listToString(tmpState.copy())
mp[tmp] = indx
indx += 1
global Node
Node = []
global call
call = 0
tmpNode = node(state=tmpState, parent=-1, action=getAction(startX, startY), g_cost=0, depth=0, h_cost=0, x=startX, y=startY, move="intit",check=0)
Node += [tmpNode]
cutOffNode = node(state=tmpState, parent=-5, action=getAction(startX, startY), g_cost=-1, depth=-1, h_cost=-1, x=startX, y=startY, move="intit",check=0)
isVisited.clear()
startTime = time.time()
print("DLS running...")
nd = DLS(tmpNode,cutOffNode,limit)
print("DLS Finished!")
elapsedTime = time.time() - startTime
if nd == None:
print("No Aceepted state found!")
file.write("No Aceepted state found!\n")
file.write("Number of call: " + str(call) + "\nNumber of node created: " + str(indx) + "\nTime : " + str(
elapsedTime) + "\n")
elif nd == cutOffNode:
print("CutOff occured.")
file.write("CutOff occured. \nNo Aceepted state found!\n")
file.write("Number of call: " + str(call) + "\nNumber of node created: " + str(indx) + "\nTime : " + str(elapsedTime) + "\n")
else:
print("Aceepted state found!")
file.write("Depth: " + str(nd.depth) + "\nNumber of call: " + str(call) + "\nNumber of node created: " + str(indx) + "\nTime : " + str(elapsedTime) + "\n\n")
answer = []
tmpnd = copy.deepcopy(nd)
while tmpnd.parent != -1:
answer += [tmpnd]
tmpnd = Node[tmpnd.parent]
answer.reverse()
for nn in answer:
file.write("Current Move: " + nn.move + ", Current Depth: "+str(nn.depth)+"\n")
filePrint(file, nn.state)
file.close()
D = nd.depth
N = indx
T = elapsedTime
return D,N,T
def IDS(tmpState,cutOffNode,limit):
mp.clear()
global indx
indx = 0
tmp = listToString(tmpState.copy())
mp[tmp] = indx
indx += 1
global Node
Node = []
tmpNode = node(state=tmpState, parent=-1, action=getAction(startX, startY), g_cost=0, depth=0, h_cost=0, x=startX, y=startY, move="intit",check=0)
Node += [tmpNode]
isVisited.clear()
nd = DLS(tmpNode, cutOffNode, limit)
return nd,indx
def IDS_print(tmpState):
file = open("4_IDS.txt", "w")
file.write("Initial state :\n")
filePrint(file, tmpState)
global call
call = 0
nodeCount = 0
cutOffNode = node(state=tmpState, parent=-5, action=getAction(startX, startY), g_cost=-1, depth=-1, h_cost=-1, x=startX, y=startY, move="intit",check=0)
print("IDS running...")
startTime = time.time()
for depthh in range(0,100):
nd,tt=IDS(tmpState,cutOffNode,depthh)
nodeCount+=tt
if nd == None:
print("IDS Finished!")
elapsedTime = time.time() - startTime
print("No Aceepted state found!")
file.write("No Aceepted state!\n")
file.write("Number of call: " + str(call) + "\nNumber of node created: " + str(nodeCount) + "\nTime : " + str(
elapsedTime) + "\n")
break
elif nd != cutOffNode:
print("IDS Finished!")
elapsedTime = time.time() - startTime
print("Aceepted state found!")
file.write("Depth: " + str(nd.depth) + "\nNumber of call: " + str(call) + "\nNumber of node created: " + str(nodeCount) +"\nLimit: "+str(depthh)+ "\nTime : " + str(elapsedTime) + "\n\n")
answer = []
tmpnd = copy.deepcopy(nd)
while tmpnd.parent != -1:
answer += [tmpnd]
tmpnd = Node[tmpnd.parent]
answer.reverse()
for nn in answer:
file.write("Current Move: " + nn.move + ", Current Depth: "+str(nn.depth)+"\n")
filePrint(file, nn.state)
file.close()
D = nd.depth
N = indx
T = elapsedTime
return D,N,T
# break
def GBFS(tmpState,chk):
mp.clear()
global indx
indx = 0
tmp = listToString(tmpState.copy())
mp[tmp] = indx
indx += 1
global Node
Node = []
global call
call = 0
cost=heuristic(tmpState,chk)
tmpNode = node(state=tmpState, parent=-1, action=getAction(startX, startY), g_cost=0, depth=0, h_cost=cost, x=startX, y=startY, move="intit",check=1)
Node += [tmpNode]
isVisited.clear()
q = queue.PriorityQueue()
q.put(tmpNode)
isVisited[listToString(tmpNode.state)] = 1
while not q.empty():
nd = q.get()
x=nd.x
y=nd.y
call+=1
isVisited[listToString(nd.state)] = 2
if nd.state==acceptState:
return nd
for mov in nd.action:
X,Y=movCheck(mov,x,y)
nwstate = copy.deepcopy(nd.state)
nwstate[x][y]=nd.state[X][Y]
nwstate[X][Y] = nd.state[x][y]
tmp=listToString(nwstate)
cost = heuristic(nwstate,chk)
nwNode = node(nwstate,mp[listToString(nd.state)],getAction(X,Y),nd.g_cost,nd.depth+1,cost,X,Y,mov,1)
if tmp not in isVisited:
mp[tmp] = indx
indx += 1
Node += [nwNode]
q.put(nwNode)
isVisited[tmp] = 1
return None
def GBFS_print():
file = open("5_GBFS.txt", "w")
file.write("Initial state :\n")
filePrint(file, tmpState)
startTime = time.time()
print("GBFS running...")
print("Enter heuristic choice:\n1. Misplaced tiles\n2. Manhattan distance")
ch = int(input())
nd=GBFS(tmpState,ch)
print("GBFS Finished!")
elapsedTime = time.time() - startTime
if nd == None:
print("No Aceepted state found!")
file.write("No Aceepted state found!\n")
file.write("Number of call: " + str(call) + "\nNumber of node created: " + str(indx) + "\nTime : " + str(elapsedTime) + "\n")
else:
print("Aceepted state found!")
file.write("Depth: " + str(nd.depth) + "\nNumber of call: " + str(call) + "\nNumber of node created: " + str(indx) + "\nTime : " + str(elapsedTime) + "\n\n")
answer = []
tmpnd = copy.deepcopy(nd)
while tmpnd.parent != -1:
answer += [tmpnd]
tmpnd = Node[tmpnd.parent]
answer.reverse()
for nn in answer:
file.write("Current Move: " + nn.move + ", Current Depth: "+str(nn.depth)+"\n")
filePrint(file, nn.state)
file.close()
D = nd.depth
N = indx
T = elapsedTime
return D,N,T
def A_star(tmpState,chk):
mp.clear()
global indx
indx = 0
tmp = listToString(tmpState.copy())
mp[tmp] = indx
indx += 1
global Node
Node = []
global call
call = 0
cost = heuristic(tmpState, chk)
tmpNode = node(state=tmpState, parent=-1, action=getAction(startX, startY), g_cost=0, depth=0, h_cost=cost, x=startX, y=startY, move="intit", check=2)
Node += [tmpNode]
isVisited.clear()
q = queue.PriorityQueue()
q.put(tmpNode)
isVisited[listToString(tmpNode.state)] = 1
while not q.empty():
nd = q.get()
x=nd.x
y=nd.y
call+=1
isVisited[listToString(nd.state)] = 2
if nd.state==acceptState:
return nd
for mov in nd.action:
X,Y=movCheck(mov,x,y)
nwstate = copy.deepcopy(nd.state)
nwstate[x][y]=nd.state[X][Y]
nwstate[X][Y] = nd.state[x][y]
tmp=listToString(nwstate)
cost = heuristic(nwstate,chk)
nwNode = node(nwstate,mp[listToString(nd.state)],getAction(X,Y),nd.g_cost+1,nd.depth+1,cost,X,Y,mov,2)
if tmp not in isVisited:
mp[tmp] = indx
indx += 1
Node += [nwNode]
q.put(nwNode)
isVisited[tmp] = 1
return None
def A_star_print():
file = open("6_A_star.txt", "w")
file.write("Initial state :\n")
filePrint(file, tmpState)
startTime = time.time()
print("A* running...")
print("Enter heuristic choice:\n1. Misplaced tiles\n2. Manhattan distance")
ch = int(input())
nd=A_star(tmpState, ch)
print("A* Finished!")
elapsedTime = time.time() - startTime
if nd == None:
print("No Aceepted state found!")
file.write("No Aceepted state found!\n")
file.write("Number of call: " + str(call) + "\nNumber of node created: " + str(indx) + "\nTime : " + str(elapsedTime) + "\n")
else:
print("Aceepted state found")
file.write("Depth: " + str(nd.g_cost) + "\nNumber of call: " + str(call) + "\nNumber of node created: " + str(indx) + "\nTime : " + str(elapsedTime) + "\n\n")
answer = []
tmpnd = copy.deepcopy(nd)
while tmpnd.parent != -1:
answer += [tmpnd]
tmpnd = Node[tmpnd.parent]
answer.reverse()
for nn in answer:
file.write("Current Move: " + nn.move + ", Current Depth: "+str(nn.depth)+"\n")
filePrint(file, nn.state)
file.close()
D = nd.depth
N = indx
T = elapsedTime
return D,N,T
if __name__ == '__main__':
try:
import numpy as np
from operator import itemgetter
import time
import math
import collections
import copy
import queue
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy
Node = []
mp = collections.ChainMap()
indx = 0
isVisited = collections.ChainMap()
call = 0
except Exception as e:
print("Some Modules are missing {}".format(e))
else:
# Take input n, initial and final state from input.txt file
with open("input.txt") as file:
print("Value of n is: ")
n_input=[int(x) for x in next(file).split()]
n = n_input[0]
print(n)
row = column = round(math.sqrt(n + 1))
# acceptState = [[0 for i in range(column)] for j in range(row)]
# initAcState(acceptState)
print("Initial state :")
tmpState = [[0 for i in range(column)] for j in range(row)]
i = -1
for line in file:
i += 1
if i==3:
break
j = -1
for x in line.split():
j += 1
val = int(x)
tmpState[i][j] = val
if val ==0:
startX = i
startY = j
printState(tmpState)
file.close()
tmp = []
fp = open("input.txt")
for i, line in enumerate(fp):
if i >= 5:
for x in line.split():
# print(x)
val = int(x)
tmp.append(val)
fp.close()
# print(tmp)
print("Final State:")
acceptState = [[0 for i in range(column)] for j in range(row)]
initFinalState(acceptState,tmp)
final =np.array(tmp).reshape(3,3)
print(final)
while True:
print("\nPlease, Select your option:")
print("\t1. Testing mode\n\t2. Offline mode\n\t3. Exit\n")
option = int(input())
if option==1:
while True:
print("\tSelect your algorithm to solve puzzle:")
print("\t1. BFS\n\t2. UCS\n\t3. DLS\n\t4. IDS\n\t5. GBFS\n\t6. A*\n\t7. All(BFS, UCS, DLS, IDS, GBFS, A*)\n\t8. Back\n\t9. Exit")
choice = int(input())
if choice==9:
exit()
if choice==1:
my_list = []
my_list.append(n)
D,N,T = BFS_print()
my_list.append('bfs')
my_list.append(D)
my_list.append(N)
my_list.append(T)
elif choice == 2:
my_list = []
my_list.append(n)
D,N,T = UCS_print()
my_list.append('ucs')
my_list.append(D)
my_list.append(N)
my_list.append(T)
elif choice == 3:
print("Enter Limit for DLS:\n")
limit = int(input())
my_list = []
my_list.append(n)
# startTime = time.time()
D,N,T = DLS_print(tmpState,limit)
my_list.append('dls')
my_list.append(D)
my_list.append(N)
my_list.append(T)
elif choice == 4:
my_list = []
my_list.append(n)
D,N,T = IDS_print(tmpState)
my_list.append('ids')
my_list.append(D)
my_list.append(N)
my_list.append(T)
elif choice == 5:
my_list = []
my_list.append(n)
D,N,T = GBFS_print()
my_list.append('gbfs')
my_list.append(D)
my_list.append(N)
my_list.append(T)
elif choice == 6:
my_list = []
my_list.append(n)
D,N,T = A_star_print()
my_list.append('a_star')
my_list.append(D)
my_list.append(N)
my_list.append(T)
elif choice == 7:
print("Enter DLS LIMIT: ")
DLS_limit = int(input())
my_list = []
my_list.append(n)
D,N,T = BFS_print()
my_list.append('bfs')
my_list.append(D)
my_list.append(N)
my_list.append(T)
storeData(my_list)
my_list = []
my_list.append(n)
D,N,T = UCS_print()
my_list.append('ucs')
my_list.append(D)
my_list.append(N)
my_list.append(T)
storeData(my_list)
my_list = []
my_list.append(n)
D,N,T = DLS_print(tmpState,DLS_limit)
my_list.append('dls')
my_list.append(D)
my_list.append(N)
my_list.append(T)
storeData(my_list)
my_list = []
my_list.append(n)
D,N,T = IDS_print(tmpState)
my_list.append('ids')
my_list.append(D)
my_list.append(N)
my_list.append(T)
storeData(my_list)
my_list = []
my_list.append(n)
D,N,T = GBFS_print()
my_list.append('gbfs')
my_list.append(D)
my_list.append(N)
my_list.append(T)
storeData(my_list)
my_list = []
my_list.append(n)
D,N,T = A_star_print()
my_list.append('a_star')
my_list.append(D)
my_list.append(N)
my_list.append(T)
storeData(my_list)
elif choice==8:
break
elif option==2:
print("Offline mode")
Plot_Graph()
elif option==3:
exit()
finally:
print("\n\tGoog bye!!!\nSuccessfully end the program")
| [
"matplotlib.pyplot.title",
"copy.deepcopy",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"math.sqrt",
"matplotlib.pyplot.legend",
"time.time",
"queue.PriorityQueue",
"numpy.array",
"collections.ChainMap",
"matplotlib.pyplot.ylabel",
"matplotlib.patches.Patch",
"matplotlib.pyplot.xlabe... | [((2161, 2193), 'matplotlib.pyplot.plot', 'plt.plot', (['BFS_depth'], {'color': '"""red"""'}), "(BFS_depth, color='red')\n", (2169, 2193), True, 'import matplotlib.pyplot as plt\n'), ((2195, 2229), 'matplotlib.pyplot.plot', 'plt.plot', (['UCS_depth'], {'color': '"""green"""'}), "(UCS_depth, color='green')\n", (2203, 2229), True, 'import matplotlib.pyplot as plt\n'), ((2231, 2266), 'matplotlib.pyplot.plot', 'plt.plot', (['DLS_depth'], {'color': '"""orange"""'}), "(DLS_depth, color='orange')\n", (2239, 2266), True, 'import matplotlib.pyplot as plt\n'), ((2268, 2303), 'matplotlib.pyplot.plot', 'plt.plot', (['IDS_depth'], {'color': '"""purple"""'}), "(IDS_depth, color='purple')\n", (2276, 2303), True, 'import matplotlib.pyplot as plt\n'), ((2305, 2339), 'matplotlib.pyplot.plot', 'plt.plot', (['GBFS_depth'], {'color': '"""blue"""'}), "(GBFS_depth, color='blue')\n", (2313, 2339), True, 'import matplotlib.pyplot as plt\n'), ((2341, 2377), 'matplotlib.pyplot.plot', 'plt.plot', (['A_star_depth'], {'color': '"""cyan"""'}), "(A_star_depth, color='cyan')\n", (2349, 2377), True, 'import matplotlib.pyplot as plt\n'), ((2418, 2445), 'matplotlib.pyplot.title', 'plt.title', (['"""Depth vs Depth"""'], {}), "('Depth vs Depth')\n", (2427, 2445), True, 'import matplotlib.pyplot as plt\n'), ((2458, 2500), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Distance(initial-goal state)"""'], {}), "('Distance(initial-goal state)')\n", (2468, 2500), True, 'import matplotlib.pyplot as plt\n'), ((2502, 2525), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Path cost"""'], {}), "('Path cost')\n", (2512, 2525), True, 'import matplotlib.pyplot as plt\n'), ((2616, 2656), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""red"""', 'label': '"""BFS"""'}), "(color='red', label='BFS')\n", (2630, 2656), True, 'import matplotlib.patches as mpatches\n'), ((2672, 2714), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""green"""', 'label': '"""UCS"""'}), "(color='green', label='UCS')\n", (2686, 2714), True, 'import matplotlib.patches as mpatches\n'), ((2731, 2774), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""orange"""', 'label': '"""DLS"""'}), "(color='orange', label='DLS')\n", (2745, 2774), True, 'import matplotlib.patches as mpatches\n'), ((2791, 2834), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""purple"""', 'label': '"""IDS"""'}), "(color='purple', label='IDS')\n", (2805, 2834), True, 'import matplotlib.patches as mpatches\n'), ((2849, 2891), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""blue"""', 'label': '"""GBFS"""'}), "(color='blue', label='GBFS')\n", (2863, 2891), True, 'import matplotlib.patches as mpatches\n'), ((2906, 2946), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""cyan"""', 'label': '"""A*"""'}), "(color='cyan', label='A*')\n", (2920, 2946), True, 'import matplotlib.patches as mpatches\n'), ((2949, 3049), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'handles': '[red_patch, green_patch, orange_patch, purple_patch, blue_patch, cyan_patch]'}), '(handles=[red_patch, green_patch, orange_patch, purple_patch,\n blue_patch, cyan_patch])\n', (2959, 3049), True, 'import matplotlib.pyplot as plt\n'), ((3060, 3074), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (3068, 3074), True, 'import matplotlib.pyplot as plt\n'), ((3077, 3087), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3085, 3087), True, 'import matplotlib.pyplot as plt\n'), ((3130, 3161), 'matplotlib.pyplot.plot', 'plt.plot', (['BFS_time'], {'color': '"""red"""'}), "(BFS_time, color='red')\n", (3138, 3161), True, 'import matplotlib.pyplot as plt\n'), ((3163, 3196), 'matplotlib.pyplot.plot', 'plt.plot', (['UCS_time'], {'color': '"""green"""'}), "(UCS_time, color='green')\n", (3171, 3196), True, 'import matplotlib.pyplot as plt\n'), ((3198, 3232), 'matplotlib.pyplot.plot', 'plt.plot', (['DLS_time'], {'color': '"""orange"""'}), "(DLS_time, color='orange')\n", (3206, 3232), True, 'import matplotlib.pyplot as plt\n'), ((3234, 3268), 'matplotlib.pyplot.plot', 'plt.plot', (['IDS_time'], {'color': '"""purple"""'}), "(IDS_time, color='purple')\n", (3242, 3268), True, 'import matplotlib.pyplot as plt\n'), ((3270, 3303), 'matplotlib.pyplot.plot', 'plt.plot', (['GBFS_time'], {'color': '"""blue"""'}), "(GBFS_time, color='blue')\n", (3278, 3303), True, 'import matplotlib.pyplot as plt\n'), ((3305, 3340), 'matplotlib.pyplot.plot', 'plt.plot', (['A_star_time'], {'color': '"""cyan"""'}), "(A_star_time, color='cyan')\n", (3313, 3340), True, 'import matplotlib.pyplot as plt\n'), ((3359, 3385), 'matplotlib.pyplot.title', 'plt.title', (['"""Time vs Depth"""'], {}), "('Time vs Depth')\n", (3368, 3385), True, 'import matplotlib.pyplot as plt\n'), ((3398, 3440), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Distance(initial-goal state)"""'], {}), "('Distance(initial-goal state)')\n", (3408, 3440), True, 'import matplotlib.pyplot as plt\n'), ((3442, 3460), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Time"""'], {}), "('Time')\n", (3452, 3460), True, 'import matplotlib.pyplot as plt\n'), ((3551, 3591), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""red"""', 'label': '"""BFS"""'}), "(color='red', label='BFS')\n", (3565, 3591), True, 'import matplotlib.patches as mpatches\n'), ((3607, 3649), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""green"""', 'label': '"""UCS"""'}), "(color='green', label='UCS')\n", (3621, 3649), True, 'import matplotlib.patches as mpatches\n'), ((3666, 3709), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""orange"""', 'label': '"""DLS"""'}), "(color='orange', label='DLS')\n", (3680, 3709), True, 'import matplotlib.patches as mpatches\n'), ((3726, 3769), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""purple"""', 'label': '"""IDS"""'}), "(color='purple', label='IDS')\n", (3740, 3769), True, 'import matplotlib.patches as mpatches\n'), ((3784, 3826), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""blue"""', 'label': '"""GBFS"""'}), "(color='blue', label='GBFS')\n", (3798, 3826), True, 'import matplotlib.patches as mpatches\n'), ((3841, 3881), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""cyan"""', 'label': '"""A*"""'}), "(color='cyan', label='A*')\n", (3855, 3881), True, 'import matplotlib.patches as mpatches\n'), ((3884, 3984), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'handles': '[red_patch, green_patch, orange_patch, purple_patch, blue_patch, cyan_patch]'}), '(handles=[red_patch, green_patch, orange_patch, purple_patch,\n blue_patch, cyan_patch])\n', (3894, 3984), True, 'import matplotlib.pyplot as plt\n'), ((3995, 4009), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (4003, 4009), True, 'import matplotlib.pyplot as plt\n'), ((4012, 4022), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4020, 4022), True, 'import matplotlib.pyplot as plt\n'), ((4047, 4078), 'matplotlib.pyplot.plot', 'plt.plot', (['BFS_node'], {'color': '"""red"""'}), "(BFS_node, color='red')\n", (4055, 4078), True, 'import matplotlib.pyplot as plt\n'), ((4080, 4113), 'matplotlib.pyplot.plot', 'plt.plot', (['UCS_node'], {'color': '"""green"""'}), "(UCS_node, color='green')\n", (4088, 4113), True, 'import matplotlib.pyplot as plt\n'), ((4115, 4149), 'matplotlib.pyplot.plot', 'plt.plot', (['DLS_node'], {'color': '"""orange"""'}), "(DLS_node, color='orange')\n", (4123, 4149), True, 'import matplotlib.pyplot as plt\n'), ((4151, 4185), 'matplotlib.pyplot.plot', 'plt.plot', (['IDS_node'], {'color': '"""purple"""'}), "(IDS_node, color='purple')\n", (4159, 4185), True, 'import matplotlib.pyplot as plt\n'), ((4187, 4220), 'matplotlib.pyplot.plot', 'plt.plot', (['GBFS_node'], {'color': '"""blue"""'}), "(GBFS_node, color='blue')\n", (4195, 4220), True, 'import matplotlib.pyplot as plt\n'), ((4222, 4257), 'matplotlib.pyplot.plot', 'plt.plot', (['A_star_node'], {'color': '"""cyan"""'}), "(A_star_node, color='cyan')\n", (4230, 4257), True, 'import matplotlib.pyplot as plt\n'), ((4275, 4301), 'matplotlib.pyplot.title', 'plt.title', (['"""Node vs Depth"""'], {}), "('Node vs Depth')\n", (4284, 4301), True, 'import matplotlib.pyplot as plt\n'), ((4314, 4356), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Distance(initial-goal state)"""'], {}), "('Distance(initial-goal state)')\n", (4324, 4356), True, 'import matplotlib.pyplot as plt\n'), ((4358, 4394), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Number of Node created"""'], {}), "('Number of Node created')\n", (4368, 4394), True, 'import matplotlib.pyplot as plt\n'), ((4485, 4525), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""red"""', 'label': '"""BFS"""'}), "(color='red', label='BFS')\n", (4499, 4525), True, 'import matplotlib.patches as mpatches\n'), ((4541, 4583), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""green"""', 'label': '"""UCS"""'}), "(color='green', label='UCS')\n", (4555, 4583), True, 'import matplotlib.patches as mpatches\n'), ((4600, 4643), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""orange"""', 'label': '"""DLS"""'}), "(color='orange', label='DLS')\n", (4614, 4643), True, 'import matplotlib.patches as mpatches\n'), ((4660, 4703), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""purple"""', 'label': '"""IDS"""'}), "(color='purple', label='IDS')\n", (4674, 4703), True, 'import matplotlib.patches as mpatches\n'), ((4718, 4760), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""blue"""', 'label': '"""GBFS"""'}), "(color='blue', label='GBFS')\n", (4732, 4760), True, 'import matplotlib.patches as mpatches\n'), ((4775, 4815), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': '"""cyan"""', 'label': '"""A*"""'}), "(color='cyan', label='A*')\n", (4789, 4815), True, 'import matplotlib.patches as mpatches\n'), ((4818, 4918), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'handles': '[red_patch, green_patch, orange_patch, purple_patch, blue_patch, cyan_patch]'}), '(handles=[red_patch, green_patch, orange_patch, purple_patch,\n blue_patch, cyan_patch])\n', (4828, 4918), True, 'import matplotlib.pyplot as plt\n'), ((4929, 4943), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (4937, 4943), True, 'import matplotlib.pyplot as plt\n'), ((4946, 4956), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4954, 4956), True, 'import matplotlib.pyplot as plt\n'), ((8436, 8447), 'time.time', 'time.time', ([], {}), '()\n', (8445, 8447), False, 'import time\n'), ((9728, 9749), 'queue.PriorityQueue', 'queue.PriorityQueue', ([], {}), '()\n', (9747, 9749), False, 'import queue\n'), ((10786, 10797), 'time.time', 'time.time', ([], {}), '()\n', (10795, 10797), False, 'import time\n'), ((11759, 11781), 'copy.deepcopy', 'copy.deepcopy', (['tmpNode'], {}), '(tmpNode)\n', (11772, 11781), False, 'import copy\n'), ((13767, 13778), 'time.time', 'time.time', ([], {}), '()\n', (13776, 13778), False, 'import time\n'), ((15908, 15919), 'time.time', 'time.time', ([], {}), '()\n', (15917, 15919), False, 'import time\n'), ((17727, 17748), 'queue.PriorityQueue', 'queue.PriorityQueue', ([], {}), '()\n', (17746, 17748), False, 'import queue\n'), ((18733, 18744), 'time.time', 'time.time', ([], {}), '()\n', (18742, 18744), False, 'import time\n'), ((20165, 20186), 'queue.PriorityQueue', 'queue.PriorityQueue', ([], {}), '()\n', (20184, 20186), False, 'import queue\n'), ((21177, 21188), 'time.time', 'time.time', ([], {}), '()\n', (21186, 21188), False, 'import time\n'), ((8532, 8543), 'time.time', 'time.time', ([], {}), '()\n', (8541, 8543), False, 'import time\n'), ((9004, 9021), 'copy.deepcopy', 'copy.deepcopy', (['nd'], {}), '(nd)\n', (9017, 9021), False, 'import copy\n'), ((10880, 10891), 'time.time', 'time.time', ([], {}), '()\n', (10889, 10891), False, 'import time\n'), ((11353, 11370), 'copy.deepcopy', 'copy.deepcopy', (['nd'], {}), '(nd)\n', (11366, 11370), False, 'import copy\n'), ((12022, 12045), 'copy.deepcopy', 'copy.deepcopy', (['nd.state'], {}), '(nd.state)\n', (12035, 12045), False, 'import copy\n'), ((13891, 13902), 'time.time', 'time.time', ([], {}), '()\n', (13900, 13902), False, 'import time\n'), ((18933, 18944), 'time.time', 'time.time', ([], {}), '()\n', (18942, 18944), False, 'import time\n'), ((19404, 19421), 'copy.deepcopy', 'copy.deepcopy', (['nd'], {}), '(nd)\n', (19417, 19421), False, 'import copy\n'), ((21375, 21386), 'time.time', 'time.time', ([], {}), '()\n', (21384, 21386), False, 'import time\n'), ((21847, 21864), 'copy.deepcopy', 'copy.deepcopy', (['nd'], {}), '(nd)\n', (21860, 21864), False, 'import copy\n'), ((22475, 22497), 'collections.ChainMap', 'collections.ChainMap', ([], {}), '()\n', (22495, 22497), False, 'import collections\n'), ((22529, 22551), 'collections.ChainMap', 'collections.ChainMap', ([], {}), '()\n', (22549, 22551), False, 'import collections\n'), ((6705, 6727), 'collections.ChainMap', 'collections.ChainMap', ([], {}), '()\n', (6725, 6727), False, 'import collections\n'), ((7741, 7764), 'copy.deepcopy', 'copy.deepcopy', (['nd.state'], {}), '(nd.state)\n', (7754, 7764), False, 'import copy\n'), ((10097, 10120), 'copy.deepcopy', 'copy.deepcopy', (['nd.state'], {}), '(nd.state)\n', (10110, 10120), False, 'import copy\n'), ((14684, 14701), 'copy.deepcopy', 'copy.deepcopy', (['nd'], {}), '(nd)\n', (14697, 14701), False, 'import copy\n'), ((18096, 18119), 'copy.deepcopy', 'copy.deepcopy', (['nd.state'], {}), '(nd.state)\n', (18109, 18119), False, 'import copy\n'), ((20534, 20557), 'copy.deepcopy', 'copy.deepcopy', (['nd.state'], {}), '(nd.state)\n', (20547, 20557), False, 'import copy\n'), ((16107, 16118), 'time.time', 'time.time', ([], {}), '()\n', (16116, 16118), False, 'import time\n'), ((16806, 16823), 'copy.deepcopy', 'copy.deepcopy', (['nd'], {}), '(nd)\n', (16819, 16823), False, 'import copy\n'), ((22880, 22896), 'math.sqrt', 'math.sqrt', (['(n + 1)'], {}), '(n + 1)\n', (22889, 22896), False, 'import math\n'), ((23757, 23770), 'numpy.array', 'np.array', (['tmp'], {}), '(tmp)\n', (23765, 23770), True, 'import numpy as np\n'), ((16495, 16506), 'time.time', 'time.time', ([], {}), '()\n', (16504, 16506), False, 'import time\n')] |
# -*- encoding: utf-8 -*-
def run_readdata(filedir):
from glob import glob
import nibabel as ni
import numpy as np
import dtimp as DTII
file_DTI = filedir+"diffusion.nii.gz"
file_T1 = filedir+"t1.nii.gz"
file_mask = glob('{}/*.tag'.format(filedir))[0]
file_bet = filedir+"nodif_brain_mask.nii.gz"
file_L1 = filedir+"dti_L1.nii.gz"
file_FA = filedir+"dti_FA.nii.gz"
#Lendo T1
t1 = ni.load(file_T1).get_data()
shape = t1.shape
#Lendo RAW
vol_dti = ni.load(file_DTI).get_data()
volume = vol_dti.transpose(3,0,2,1)#.copy()
#Lendo matriz de registro e calculando transformada
T = DTII.readAffineMatrix('{}reg.mat'.format(filedir))
scale = np.diag([1,1,2,1])
T = np.dot(T, scale)
#Lendo eigenvalores, eigenvetores
eigvals, eigvects, T3 = DTII.loadNiftiDTI(filedir, reorient=True)
#Lendo mapa de FA
FA,MD = DTII.getFractionalAnisotropy(eigvals)
FA[np.isnan(FA)] = 0
FA[FA>1] = 1
#Lendo máscara segmentação cérebro
mask_out = ni.load(file_bet).get_data().astype(bool)
mask_out = mask_out.transpose(0,2,1)#.copy()
#Lendo máscara corpo caloso e registrando em DTI
tag = np.genfromtxt(file_mask, missing_values=';', skip_header = 4)
seg_mask_t1 = DTII.createMaskSegmentationOriginal(shape, tag)
z, y, x = seg_mask_t1.nonzero()
pontos = np.vstack((z,y,x,np.ones(z.size)))
T_T = np.dot(T3, np.linalg.inv(T))
z, y, x, _ = np.round(np.dot(T_T, pontos)).astype('int')
if np.array([z.min(), y.min(), x.min()]).min() < 0:
return False
seg_mask = np.zeros(FA.shape, dtype='bool')
#z = np.clip(z, 0,255)
#y = np.clip(y, 0,69)
#x = np.clip(x, 0,255)
seg_mask[z,y,x] = True
#Encontrando fatia media no plano sagital
fat_md, FA_mean = DTII.getFissureSlice(eigvals, FA)
wFA = FA*abs(eigvects[0,0]) #weighted FA
return (volume[:,:,::-1,::-1], wFA, FA, MD, fat_md, eigvals, eigvects, seg_mask_t1, seg_mask, mask_out[:,::-1,::-1])
| [
"dtimp.createMaskSegmentationOriginal",
"nibabel.load",
"dtimp.getFissureSlice",
"dtimp.getFractionalAnisotropy",
"numpy.zeros",
"numpy.genfromtxt",
"numpy.isnan",
"numpy.ones",
"numpy.linalg.inv",
"numpy.dot",
"numpy.diag",
"dtimp.loadNiftiDTI"
] | [((715, 736), 'numpy.diag', 'np.diag', (['[1, 1, 2, 1]'], {}), '([1, 1, 2, 1])\n', (722, 736), True, 'import numpy as np\n'), ((742, 758), 'numpy.dot', 'np.dot', (['T', 'scale'], {}), '(T, scale)\n', (748, 758), True, 'import numpy as np\n'), ((826, 867), 'dtimp.loadNiftiDTI', 'DTII.loadNiftiDTI', (['filedir'], {'reorient': '(True)'}), '(filedir, reorient=True)\n', (843, 867), True, 'import dtimp as DTII\n'), ((903, 940), 'dtimp.getFractionalAnisotropy', 'DTII.getFractionalAnisotropy', (['eigvals'], {}), '(eigvals)\n', (931, 940), True, 'import dtimp as DTII\n'), ((1193, 1252), 'numpy.genfromtxt', 'np.genfromtxt', (['file_mask'], {'missing_values': '""";"""', 'skip_header': '(4)'}), "(file_mask, missing_values=';', skip_header=4)\n", (1206, 1252), True, 'import numpy as np\n'), ((1273, 1320), 'dtimp.createMaskSegmentationOriginal', 'DTII.createMaskSegmentationOriginal', (['shape', 'tag'], {}), '(shape, tag)\n', (1308, 1320), True, 'import dtimp as DTII\n'), ((1597, 1629), 'numpy.zeros', 'np.zeros', (['FA.shape'], {'dtype': '"""bool"""'}), "(FA.shape, dtype='bool')\n", (1605, 1629), True, 'import numpy as np\n'), ((1806, 1839), 'dtimp.getFissureSlice', 'DTII.getFissureSlice', (['eigvals', 'FA'], {}), '(eigvals, FA)\n', (1826, 1839), True, 'import dtimp as DTII\n'), ((948, 960), 'numpy.isnan', 'np.isnan', (['FA'], {}), '(FA)\n', (956, 960), True, 'import numpy as np\n'), ((1426, 1442), 'numpy.linalg.inv', 'np.linalg.inv', (['T'], {}), '(T)\n', (1439, 1442), True, 'import numpy as np\n'), ((431, 447), 'nibabel.load', 'ni.load', (['file_T1'], {}), '(file_T1)\n', (438, 447), True, 'import nibabel as ni\n'), ((510, 527), 'nibabel.load', 'ni.load', (['file_DTI'], {}), '(file_DTI)\n', (517, 527), True, 'import nibabel as ni\n'), ((1387, 1402), 'numpy.ones', 'np.ones', (['z.size'], {}), '(z.size)\n', (1394, 1402), True, 'import numpy as np\n'), ((1470, 1489), 'numpy.dot', 'np.dot', (['T_T', 'pontos'], {}), '(T_T, pontos)\n', (1476, 1489), True, 'import numpy as np\n'), ((1038, 1055), 'nibabel.load', 'ni.load', (['file_bet'], {}), '(file_bet)\n', (1045, 1055), True, 'import nibabel as ni\n')] |
"""Tensorflow clustering"""
import tensorflow as tf
from tensorflow.contrib.factorization import KMEANS_PLUS_PLUS_INIT
__author__ = "<NAME> (http://www.vmusco.com)"
from numpy.core.tests.test_mem_overlap import xrange
from tensorflow.python.framework import constant_op
from mlperf.clustering import clusteringtoolkit
from mlperf.clustering.clusteringtoolkit import ClusteringToolkit
from mlperf.tools.static import TENSORFLOW_TOOLKIT
class TensorFlow(clusteringtoolkit.ClusteringToolkit):
def toolkit_name(self):
return TENSORFLOW_TOOLKIT
@staticmethod
def _train_kpp(input_fn, kmeans, num_iterations=10):
# train
for _ in xrange(num_iterations):
kmeans.train(input_fn)
@staticmethod
def _build_points_and_input_fn(data_without_target):
points = data_without_target.values
def input_fn():
return tf.train.limit_epochs(tf.convert_to_tensor(points, dtype=tf.float32), num_epochs=1)
return points, input_fn
@staticmethod
def _clustering_to_list(points, cluster_indices):
clusters_list = []
for index, point in enumerate(points):
cluster_index = cluster_indices[index]
clusters_list.append([index, cluster_index])
return clusters_list
@staticmethod
def _centroids_to_list(model):
centers_list = []
for row in model.cluster_centers():
centers_list.append(row.tolist())
return centers_list
# https://www.tensorflow.org/api_docs/python/tf/contrib/factorization/KMeansClustering
def run_kmeans(self, nb_clusters, src_file, data_without_target, dataset_name, initial_clusters_file,
initial_clusters, run_number, run_info=None, nb_iterations=None):
import tensorflow as tf
output_file, centroids_file = self._prepare_files(dataset_name, run_info, True)
if self.seed is not None:
tf.set_random_seed(self.seed)
kmeans = tf.contrib.factorization.KMeansClustering(num_clusters=nb_clusters,
initial_clusters=initial_clusters, use_mini_batch=False)
points, input_fn = TensorFlow._build_points_and_input_fn(data_without_target)
TensorFlow._train_kpp(input_fn, kmeans, 10 if nb_iterations is None else nb_iterations)
cluster_indices = list(kmeans.predict_cluster_index(input_fn))
ClusteringToolkit._save_clustering(TensorFlow._clustering_to_list(points, cluster_indices), output_file)
ClusteringToolkit._save_centroids(TensorFlow._centroids_to_list(kmeans), centroids_file)
return output_file, {"centroids": centroids_file}
def run_kmeans_plus_plus(self, nb_clusters, src_file, data_without_target, dataset_name, run_number, run_info=None,
nb_iterations=None):
import tensorflow as tf
output_file, centroids_file = self._prepare_files(dataset_name, run_info, True)
if self.seed is not None:
tf.set_random_seed(self.seed)
kmeans = tf.contrib.factorization.KMeansClustering(num_clusters=nb_clusters,
initial_clusters=KMEANS_PLUS_PLUS_INIT, use_mini_batch=False)
points, input_fn = TensorFlow._build_points_and_input_fn(data_without_target)
TensorFlow._train_kpp(input_fn, kmeans, 10 if nb_iterations is None else nb_iterations)
cluster_indices = list(kmeans.predict_cluster_index(input_fn))
ClusteringToolkit._save_clustering(TensorFlow._clustering_to_list(points, cluster_indices), output_file)
ClusteringToolkit._save_centroids(TensorFlow._centroids_to_list(kmeans), centroids_file)
return output_file, {"centroids": centroids_file}
def run_gaussian(self, nb_clusters, src_file, data_without_target, dataset_name, run_number, run_info=None):
import tensorflow as tf
output_file, centroids_file = self._prepare_files(dataset_name, run_info, True)
if self.seed is not None:
tf.set_random_seed(self.seed)
points = data_without_target.values
def get_input_fn():
def input_fn():
return constant_op.constant(points.astype(np.float32)), None
return input_fn
gmm = tf.contrib.factorization.GMM(num_clusters=nb_clusters)
gmm.fit(input_fn=get_input_fn(), steps=1)
cluster_indices = list(gmm.predict_assignments())
ClusteringToolkit._save_clustering(TensorFlow._clustering_to_list(points, cluster_indices), output_file)
ClusteringToolkit._save_centroids(TensorFlow._centroids_to_list(gmm), centroids_file)
return output_file, {"centroids": centroids_file}
def run_gaussian_initial_starting_points(self, nb_clusters, src_file, data_without_target, dataset_name,
initial_clusters_file, initial_clusters, run_number, run_info=None):
import tensorflow as tf
output_file, centroids_file = self._prepare_files(dataset_name, run_info, True)
if self.seed is not None:
tf.set_random_seed(self.seed)
points = data_without_target.values
def get_input_fn():
def input_fn():
return constant_op.constant(points.astype(np.float32)), None
return input_fn
gmm = tf.contrib.factorization.GMM(num_clusters=nb_clusters, initial_clusters=initial_clusters)
gmm.fit(input_fn=get_input_fn(), steps=1)
cluster_indices = list(gmm.predict_assignments())
ClusteringToolkit._save_clustering(TensorFlow._clustering_to_list(points, cluster_indices), output_file)
ClusteringToolkit._save_centroids(TensorFlow._centroids_to_list(gmm), centroids_file)
return output_file, {"centroids": centroids_file}
| [
"tensorflow.convert_to_tensor",
"tensorflow.contrib.factorization.KMeansClustering",
"tensorflow.set_random_seed",
"numpy.core.tests.test_mem_overlap.xrange",
"tensorflow.contrib.factorization.GMM"
] | [((666, 688), 'numpy.core.tests.test_mem_overlap.xrange', 'xrange', (['num_iterations'], {}), '(num_iterations)\n', (672, 688), False, 'from numpy.core.tests.test_mem_overlap import xrange\n'), ((1987, 2115), 'tensorflow.contrib.factorization.KMeansClustering', 'tf.contrib.factorization.KMeansClustering', ([], {'num_clusters': 'nb_clusters', 'initial_clusters': 'initial_clusters', 'use_mini_batch': '(False)'}), '(num_clusters=nb_clusters,\n initial_clusters=initial_clusters, use_mini_batch=False)\n', (2028, 2115), True, 'import tensorflow as tf\n'), ((3080, 3213), 'tensorflow.contrib.factorization.KMeansClustering', 'tf.contrib.factorization.KMeansClustering', ([], {'num_clusters': 'nb_clusters', 'initial_clusters': 'KMEANS_PLUS_PLUS_INIT', 'use_mini_batch': '(False)'}), '(num_clusters=nb_clusters,\n initial_clusters=KMEANS_PLUS_PLUS_INIT, use_mini_batch=False)\n', (3121, 3213), True, 'import tensorflow as tf\n'), ((4327, 4381), 'tensorflow.contrib.factorization.GMM', 'tf.contrib.factorization.GMM', ([], {'num_clusters': 'nb_clusters'}), '(num_clusters=nb_clusters)\n', (4355, 4381), True, 'import tensorflow as tf\n'), ((5402, 5496), 'tensorflow.contrib.factorization.GMM', 'tf.contrib.factorization.GMM', ([], {'num_clusters': 'nb_clusters', 'initial_clusters': 'initial_clusters'}), '(num_clusters=nb_clusters, initial_clusters=\n initial_clusters)\n', (5430, 5496), True, 'import tensorflow as tf\n'), ((1939, 1968), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['self.seed'], {}), '(self.seed)\n', (1957, 1968), True, 'import tensorflow as tf\n'), ((3032, 3061), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['self.seed'], {}), '(self.seed)\n', (3050, 3061), True, 'import tensorflow as tf\n'), ((4074, 4103), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['self.seed'], {}), '(self.seed)\n', (4092, 4103), True, 'import tensorflow as tf\n'), ((5149, 5178), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['self.seed'], {}), '(self.seed)\n', (5167, 5178), True, 'import tensorflow as tf\n'), ((911, 957), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['points'], {'dtype': 'tf.float32'}), '(points, dtype=tf.float32)\n', (931, 957), True, 'import tensorflow as tf\n')] |
__author__ = 'rvuine'
import math
from abc import ABCMeta, abstractmethod
class StepOperator(metaclass=ABCMeta):
"""
A step operator will be executed once per net step on all nodes.
"""
@property
@abstractmethod
def priority(self):
"""
Returns a numerical priority value used to determine step operator order execution.
Lower priority operators will be executed first.
The lowest possible value 0 and 1 are reserved for the Propagate and Calculate operators to ensure all step
operators will be executed after propagation and node function calculation.
"""
pass # pragma: no cover
@abstractmethod
def execute(self, nodenet, nodes, netapi):
"""
Actually execute the operator.
"""
pass # pragma: no cover
class Propagate(StepOperator):
"""
Every node net needs a propagate operator
"""
@property
def priority(self):
return 0
@abstractmethod
def execute(self, nodenet, nodes, netapi):
pass # pragma: no cover
class Calculate(StepOperator):
"""
Every node net needs a calculate operator
"""
@property
def priority(self):
return 1
def execute(self, nodenet, nodes, netapi):
pass # pragma: no cover
def gentle_sigmoid(x):
return 2 * ((1 / (1 + math.exp(-0.5 * x))) - 0.5)
class DoernerianEmotionalModulators(StepOperator):
"""
Implementation a doernerian emotional model based on global node net modulators.
The following base values can and should be set from the node net:
base_sum_importance_of_intentions - Sum of importance of all current intentions
base_sum_urgency_of_intentions - Sum of urgency of all current intentions
base_competence_for_intention - Competence for currently selected intention
base_importance_of_intention - Importance of currently selected intention
base_urgency_of_intention - Importance of currently selected intention
base_number_of_active_motives - Number of currently active motives
base_number_of_expected_events - Number of expected events in last cycle
base_number_of_unexpected_events - Number of unexpected events in last cycle
base_urge_change - Sum of changes to urges in last cycle
base_age_influence_on_competence - Influence factor of node net age on competence (0: no influence)
The following emotional parameters will be calculated:
emo_pleasure - Pleasure (LUL in Dörner)
emo_activation - General activation (ARAS in Dörner)
emo_securing_rate - Tendency to check/re-check the environment
emo_resolution - Thoroughness of perception
emo_selection_threshold - Tendency to change selected motive
emo_competence - Assumed predictability of events
This code is experimental, various magic numbers / parameters will probably have to be
introduced to make it work.
"""
writeable_modulators = [
'base_sum_importance_of_intentions',
'base_sum_urgency_of_intentions',
'base_competence_for_intention',
'base_importance_of_intention',
'base_urgency_of_intention',
'base_number_of_active_motives',
'base_number_of_expected_events',
'base_number_of_unexpected_events',
'base_urge_change',
'base_age_influence_on_competence',
'base_porret_decay_factor']
readable_modulators = [
'emo_pleasure',
'emo_activation',
'emo_securing_rate',
'emo_resolution',
'emo_selection_threshold',
'emo_competence']
@property
def priority(self):
return 1000
def execute(self, nodenet, nodes, netapi):
COMPETENCE_DECAY_FACTOR = 0.1
JOY_DECAY_FACTOR = 0.01
base_sum_importance_of_intentions = netapi.get_modulator("base_sum_importance_of_intentions")
base_sum_urgency_of_intentions = netapi.get_modulator("base_sum_urgency_of_intentions")
base_competence_for_intention = netapi.get_modulator("base_competence_for_intention")
base_importance_of_intention = netapi.get_modulator("base_importance_of_intention")
base_urgency_of_intention = netapi.get_modulator("base_urgency_of_intention")
base_number_of_active_motives = netapi.get_modulator("base_number_of_active_motives")
base_number_of_unexpected_events = netapi.get_modulator("base_number_of_unexpected_events")
base_number_of_expected_events = netapi.get_modulator("base_number_of_expected_events")
base_urge_change = netapi.get_modulator("base_urge_change")
base_age = netapi.get_modulator("base_age")
base_age_influence_on_competence = netapi.get_modulator("base_age_influence_on_competence")
base_unexpectedness_prev = netapi.get_modulator("base_unexpectedness")
base_sum_of_urges = netapi.get_modulator("base_sum_of_urges")
emo_competence_prev = netapi.get_modulator("emo_competence")
emo_sustaining_joy_prev = netapi.get_modulator("emo_sustaining_joy")
base_age += 1
emo_activation = max(0, ((base_sum_importance_of_intentions + base_sum_urgency_of_intentions) /
((base_number_of_active_motives * 2) + 1)) + base_urge_change)
base_unexpectedness = max(min(base_unexpectedness_prev + gentle_sigmoid((base_number_of_unexpected_events - base_number_of_expected_events) / 10), 1), 0)
fear = 0 # todo: understand the formula in Principles 185
emo_securing_rate = (((1 - base_competence_for_intention) -
(0.5 * base_urgency_of_intention * base_importance_of_intention)) +
fear +
base_unexpectedness)
emo_resolution = 1 - emo_activation
emo_selection_threshold = emo_activation
pleasure_from_expectation = gentle_sigmoid((base_number_of_expected_events - base_number_of_unexpected_events) / 10)
pleasure_from_satisfaction = gentle_sigmoid(base_urge_change * -3)
emo_pleasure = pleasure_from_expectation + pleasure_from_satisfaction # ignoring fear and hope for now
emo_valence = 0.5 - base_urge_change - base_sum_of_urges # base_urge_change is inverse
if emo_pleasure != 0:
if math.copysign(1, emo_pleasure) == math.copysign(1, emo_sustaining_joy_prev):
if abs(emo_pleasure) >= abs(emo_sustaining_joy_prev):
emo_sustaining_joy = emo_pleasure
else:
emo_sustaining_joy = emo_sustaining_joy_prev
else:
emo_sustaining_joy = emo_pleasure
else:
if abs(emo_sustaining_joy_prev) < JOY_DECAY_FACTOR:
emo_sustaining_joy = 0
else:
emo_sustaining_joy = emo_sustaining_joy_prev - math.copysign(JOY_DECAY_FACTOR, emo_sustaining_joy_prev)
pleasurefactor = 1 if emo_pleasure >= 0 else -1
divisorbaseline = 1 if emo_pleasure >= 0 else 2
youthful_exuberance_term = 1 # base_age_influence_on_competence * (1 + (1 / math.sqrt(2 * base_age)))
emo_competence = (((emo_competence_prev) + (emo_pleasure * youthful_exuberance_term)) /
(divisorbaseline + (pleasurefactor * emo_competence_prev * COMPETENCE_DECAY_FACTOR)))
emo_competence = max(min(emo_competence, 0.99), 0.01)
# setting technical parameters
nodenet.set_modulator("base_age", base_age)
nodenet.set_modulator("base_unexpectedness", base_unexpectedness)
# resetting per-cycle base parameters
nodenet.set_modulator("base_number_of_expected_events", 0)
nodenet.set_modulator("base_number_of_unexpected_events", 0)
nodenet.set_modulator("base_urge_change", 0)
# nodenet.set_modulator("base_porret_decay_factor", 1)
# setting emotional parameters
nodenet.set_modulator("emo_pleasure", emo_pleasure)
nodenet.set_modulator("emo_activation", emo_activation)
nodenet.set_modulator("emo_securing_rate", emo_securing_rate)
nodenet.set_modulator("emo_resolution", emo_resolution)
nodenet.set_modulator("emo_selection_threshold", emo_selection_threshold)
nodenet.set_modulator("emo_competence", emo_competence)
nodenet.set_modulator("emo_sustaining_joy", emo_sustaining_joy)
nodenet.set_modulator("emo_valence", emo_valence)
class CalculateFlowmodules(StepOperator):
@property
def priority(self):
return 0
def __init__(self, nodenet):
self.nodenet = nodenet
def value_guard(self, value, source, name):
if value is None:
return None
if self.nodenet.runner_config.get('runner_infguard'):
if type(value) == list:
for val in value:
self._guard(val, source, name)
else:
self._guard(value, source, name)
return value
def _guard(self, value, source, name):
import numpy as np
if np.isnan(np.sum(value)):
raise ValueError("NAN value in flow datected: %s" % self.format_error(source, name))
elif np.isinf(np.sum(value)):
raise ValueError("INF value in flow datected: %s" % self.format_error(source, name))
def format_error(self, source, name):
if type(source) == dict:
if len(source['members']) == 1:
msg = "output %s of %s" % (name, source['members'][0])
else:
msg = "output %s of graph %s" % (name, str(source['members']))
else:
msg = "output %s of %s" % (name, str(source))
return msg
| [
"math.copysign",
"math.exp",
"numpy.sum"
] | [((9408, 9421), 'numpy.sum', 'np.sum', (['value'], {}), '(value)\n', (9414, 9421), True, 'import numpy as np\n'), ((6638, 6668), 'math.copysign', 'math.copysign', (['(1)', 'emo_pleasure'], {}), '(1, emo_pleasure)\n', (6651, 6668), False, 'import math\n'), ((6672, 6713), 'math.copysign', 'math.copysign', (['(1)', 'emo_sustaining_joy_prev'], {}), '(1, emo_sustaining_joy_prev)\n', (6685, 6713), False, 'import math\n'), ((9543, 9556), 'numpy.sum', 'np.sum', (['value'], {}), '(value)\n', (9549, 9556), True, 'import numpy as np\n'), ((1363, 1381), 'math.exp', 'math.exp', (['(-0.5 * x)'], {}), '(-0.5 * x)\n', (1371, 1381), False, 'import math\n'), ((7192, 7248), 'math.copysign', 'math.copysign', (['JOY_DECAY_FACTOR', 'emo_sustaining_joy_prev'], {}), '(JOY_DECAY_FACTOR, emo_sustaining_joy_prev)\n', (7205, 7248), False, 'import math\n')] |
import argparse
import copy
import json
import pickle
import pprint
import os
import sys
from tqdm import tqdm
from typing import *
from my_pybullet_envs import utils
import numpy as np
import torch
import math
import my_pybullet_envs
from system import policy, openrave
import pybullet as p
import time
import inspect
from my_pybullet_envs.inmoov_arm_obj_imaginary_sessions import (
ImaginaryArmObjSession,
)
from my_pybullet_envs.inmoov_shadow_demo_env_v4 import (
InmoovShadowHandDemoEnvV4,
)
from my_pybullet_envs.inmoov_shadow_hand_v2 import (
InmoovShadowNew,
)
currentdir = os.path.dirname(
os.path.abspath(inspect.getfile(inspect.currentframe()))
)
homedir = os.path.expanduser("~")
# TODO: main module depends on the following code/model:
# demo env: especially observation # change obs vec (note diffTar)
# the settings of inmoov hand v2 # init thumb 0.0 vs 0.1
# obj sizes & frame representation & friction & obj xy range
# frame skip
# vision delay
"""Parse arguments"""
sys.path.append("a2c_ppo_acktr")
parser = argparse.ArgumentParser(description="RL")
parser.add_argument("--seed", type=int, default=101) # only keep np.random
parser.add_argument("--use_height", type=int, default=0)
parser.add_argument("--test_placing", type=int, default=0)
parser.add_argument("--long_move", type=int, default=0)
parser.add_argument("--non-det", type=int, default=0)
parser.add_argument("--render", type=int, default=0)
parser.add_argument("--sleep", type=int, default=0)
args = parser.parse_args()
np.random.seed(args.seed)
args.det = not args.non_det
"""Configurations."""
USE_GV5 = False # is false, use gv6
DUMMY_SLEEP = bool(args.sleep)
WITH_REACHING = True
WITH_RETRACT = True
USE_HEIGHT_INFO = bool(args.use_height)
TEST_PLACING = bool(args.test_placing) # if false, test stacking
ADD_SURROUNDING_OBJS = True
LONG_MOVE = bool(args.long_move)
SURROUNDING_OBJS_MAX_NUM = 4
GRASP_SPH_ON = True
ADD_WHITE_NOISE = True
RENDER = bool(args.render)
CLOSE_THRES = 0.25
NUM_TRIALS = 300
GRASP_END_STEP = 35
PLACE_END_STEP = 70
INIT_NOISE = True
DET_CONTACT = 0 # 0 false, 1 true
OBJ_MU = 1.0
FLOOR_MU = 1.0
HAND_MU = 1.0
OBJ_MASS = 3.5
IS_CUDA = True
DEVICE = "cuda" if IS_CUDA else "cpu"
if USE_GV5:
GRASP_PI = "0313_2_n_25_45"
GRASP_DIR = "./trained_models_%s/ppo/" % "0313_2_n"
PLACE_PI = "0313_2_placeco_0316_1" # 50ms
PLACE_DIR = "./trained_models_%s/ppo/" % PLACE_PI
GRASP_PI_ENV_NAME = "InmoovHandGraspBulletEnv-v5"
PLACE_PI_ENV_NAME = "InmoovHandPlaceBulletEnv-v9"
INIT_FIN_Q = np.array([0.4, 0.4, 0.4] * 3 + [0.4, 0.4, 0.4] + [0.0, 1.0, 0.1, 0.5, 0.0])
else:
# use gv6
if USE_HEIGHT_INFO:
GRASP_PI = "0404_0_n_20_40"
GRASP_DIR = "./trained_models_%s/ppo/" % "0404_0_n"
PLACE_PI = "0404_0_n_place_0404_0"
PLACE_DIR = "./trained_models_%s/ppo/" % PLACE_PI
else:
GRASP_PI = "0411_0_n_25_45"
GRASP_DIR = "./trained_models_%s/ppo/" % "0411_0_n"
PLACE_PI = "0411_0_n_place_0411_0"
PLACE_DIR = "./trained_models_%s/ppo/" % PLACE_PI
# GRASP_PI = "0426_0_n_25_45"
# GRASP_DIR = "./trained_models_%s/ppo/" % "0426_0_n"
#
# PLACE_PI = "0426_0_n_place_0426_0"
# PLACE_DIR = "./trained_models_%s/ppo/" % PLACE_PI
GRASP_PI_ENV_NAME = "InmoovHandGraspBulletEnv-v6"
PLACE_PI_ENV_NAME = "InmoovHandPlaceBulletEnv-v9"
INIT_FIN_Q = np.array([0.4, 0.4, 0.4] * 3 + [0.4, 0.4, 0.4] + [0.0, 1.0, 0.1, 0.5, 0.1])
if GRASP_SPH_ON:
GRASP_SPH_PI = "0422_sph_n_25_45" # TODO: 0420
GRASP_SPH_DIR = "./trained_models_%s/ppo/" % "0422_sph_n"
PLACE_SPH_PI = "0422_sph_n_place_0422_sph"
PLACE_SPH_DIR = "./trained_models_%s/ppo/" % PLACE_SPH_PI
USE_VISION_DELAY = True
VISION_DELAY = 2
PLACING_CONTROL_SKIP = 6
GRASPING_CONTROL_SKIP = 6
def planning(trajectory, restore_fingers=False):
# TODO: total traj length 300+5 now
max_force = env_core.robot.maxForce
last_tar_arm_q = env_core.robot.get_q_dq(env_core.robot.arm_dofs)[0]
init_tar_fin_q = env_core.robot.tar_fin_q
init_fin_q = env_core.robot.get_q_dq(env_core.robot.fin_actdofs)[0]
env_core.robot.tar_arm_q = trajectory[-1] # TODO: important!
print("init_tar_fin_q")
print(["{0:0.3f}".format(n) for n in init_tar_fin_q])
print("init_fin_q")
print(["{0:0.3f}".format(n) for n in init_fin_q])
for idx in range(len(trajectory) + 5):
if idx > len(trajectory) - 1:
tar_arm_q = trajectory[-1]
else:
tar_arm_q = trajectory[idx]
tar_arm_vel = (tar_arm_q - last_tar_arm_q) / utils.TS
p.setJointMotorControlArray(
bodyIndex=env_core.robot.arm_id,
jointIndices=env_core.robot.arm_dofs,
controlMode=p.POSITION_CONTROL,
targetPositions=list(tar_arm_q),
targetVelocities=list(tar_arm_vel),
forces=[max_force * 5] * len(env_core.robot.arm_dofs))
if restore_fingers and idx >= len(trajectory) * 0.1: # TODO: hardcoded
blending = np.clip((idx - len(trajectory) * 0.1) / (len(trajectory) * 0.6), 0.0, 1.0)
cur_fin_q = env_core.robot.get_q_dq(env_core.robot.fin_actdofs)[0]
tar_fin_q = env_core.robot.init_fin_q * blending + cur_fin_q * (1-blending)
else:
# try to keep fin q close to init_fin_q (keep finger pose)
# add at most offset 0.05 in init_tar_fin_q direction so that grasp is tight
tar_fin_q = np.clip(init_tar_fin_q, init_fin_q - 0.05, init_fin_q + 0.05)
# clip to joint limit
tar_fin_q = np.clip(tar_fin_q,
env_core.robot.ll[env_core.robot.fin_actdofs],
env_core.robot.ul[env_core.robot.fin_actdofs])
p.setJointMotorControlArray(
bodyIndex=env_core.robot.arm_id,
jointIndices=env_core.robot.fin_actdofs,
controlMode=p.POSITION_CONTROL,
targetPositions=list(tar_fin_q),
forces=[max_force] * len(env_core.robot.fin_actdofs))
p.setJointMotorControlArray(
bodyIndex=env_core.robot.arm_id,
jointIndices=env_core.robot.fin_zerodofs,
controlMode=p.POSITION_CONTROL,
targetPositions=[0.0]*len(env_core.robot.fin_zerodofs),
forces=[max_force / 4.0] * len(env_core.robot.fin_zerodofs))
diff = np.linalg.norm(env_core.robot.get_q_dq(env_core.robot.arm_dofs)[0]
- tar_arm_q)
if idx == len(trajectory) + 4:
print("diff final", diff)
print("vel final", np.linalg.norm(env_core.robot.get_q_dq(env_core.robot.arm_dofs)[1]))
print("fin dofs")
print(["{0:0.3f}".format(n) for n in env_core.robot.get_q_dq(env_core.robot.fin_actdofs)[0]])
print("cur_fin_tar_q")
print(["{0:0.3f}".format(n) for n in env_core.robot.tar_fin_q])
for _ in range(1):
p.stepSimulation()
if DUMMY_SLEEP:
time.sleep(utils.TS * 0.6)
last_tar_arm_q = tar_arm_q
def get_relative_state_for_reset(oid):
obj_pos, obj_quat = p.getBasePositionAndOrientation(oid) # w2o
hand_pos, hand_quat = env_core.robot.get_link_pos_quat(
env_core.robot.ee_id
) # w2p
inv_h_p, inv_h_q = p.invertTransform(hand_pos, hand_quat) # p2w
o_p_hf, o_q_hf = p.multiplyTransforms(
inv_h_p, inv_h_q, obj_pos, obj_quat
) # p2w*w2o
fin_q, _ = env_core.robot.get_q_dq(env_core.robot.all_findofs)
relative_state = {
"obj_pos_in_palm": o_p_hf,
"obj_quat_in_palm": o_q_hf,
"all_fin_q": fin_q,
"fin_tar_q": env_core.robot.tar_fin_q,
}
return relative_state
def sample_obj_dict(is_thicker=False, whole_table_top=False, only_sph=False):
# a dict containing obj info
# "shape", "radius", "height", "position", "orientation", "mass", "mu"
min_r = utils.HALF_W_MIN_BTM if is_thicker else utils.HALF_W_MIN
if whole_table_top:
x_min = utils.X_MIN
x_max = utils.X_MAX
y_min = utils.Y_MIN
y_max = utils.Y_MAX
else:
x_min = utils.TX_MIN
x_max = utils.TX_MAX
y_min = utils.TY_MIN
y_max = utils.TY_MAX
if GRASP_SPH_ON:
shape = utils.SHAPE_IND_TO_NAME_MAP[np.random.randint(3) - 1] # -1(sph)/0/1
else:
shape = utils.SHAPE_IND_TO_NAME_MAP[np.random.randint(2)]
if only_sph:
shape = utils.SHAPE_IND_TO_NAME_MAP[-1]
obj_dict = {
"shape": shape,
"radius": np.random.uniform(min_r, utils.HALF_W_MAX),
"height": np.random.uniform(utils.H_MIN, utils.H_MAX),
"position": [
np.random.uniform(x_min, x_max),
np.random.uniform(y_min, y_max),
0.0
],
"orientation": p.getQuaternionFromEuler(
[0., 0., np.random.uniform(low=0, high=2.0 * math.pi)]
),
"mass": OBJ_MASS,
"mu": OBJ_MU,
}
if obj_dict["shape"] == "box":
obj_dict["radius"] *= 0.8
elif GRASP_SPH_ON and obj_dict['shape'] == "sphere":
obj_dict['height'] *= 0.75
obj_dict['radius'] = None
obj_dict["position"][2] = obj_dict["height"] / 2.0
return obj_dict
def load_obj_and_construct_state(obj_dicts_list):
state = {}
# load surrounding first
for idx in range(2, len(obj_dicts_list)):
bullet_id = utils.create_sym_prim_shape_helper_new(obj_dicts_list[idx])
state[bullet_id] = obj_dicts_list[idx]
bottom_id = None
# ignore btm if placing on tabletop
if not TEST_PLACING:
obj_dicts_list[1]['color'] = 'green'
bottom_id = utils.create_sym_prim_shape_helper_new(obj_dicts_list[1])
state[bottom_id] = obj_dicts_list[1]
# TODO:tmp load grasp obj last
obj_dicts_list[0]['color'] = 'red'
topobj_id = utils.create_sym_prim_shape_helper_new(obj_dicts_list[0])
state[topobj_id] = obj_dicts_list[0]
return state, topobj_id, bottom_id
def construct_obj_array_for_openrave(obj_dicts_list):
arr = []
for idx, obj_dict in enumerate(obj_dicts_list):
if idx == 1 and TEST_PLACING:
# ignore btm if placing on tabletop
continue
# grasp obj should be at first
arr.append(obj_dict["position"][:2] + [0., 0.])
return np.array(arr)
def get_grasp_policy_obs_tensor(tx, ty, half_height, is_box):
if USE_GV5:
assert USE_HEIGHT_INFO
obs = env_core.get_robot_contact_txty_halfh_obs_nodup(tx, ty, half_height)
else:
if USE_HEIGHT_INFO:
obs = env_core.get_robot_contact_txtytz_halfh_shape_obs_no_dup(tx, ty, 0.0, half_height, is_box)
else:
obs = env_core.get_robot_contact_txty_shape_obs_no_dup(tx, ty, is_box)
obs = policy.wrap_obs(obs, IS_CUDA)
return obs
def get_stack_policy_obs_tensor(tx, ty, tz, t_half_height, is_box, t_pos, t_up, b_pos, b_up):
if USE_HEIGHT_INFO:
obs = env_core.get_robot_contact_txtytz_halfh_shape_2obj6dUp_obs_nodup_from_up(
tx, ty, tz, t_half_height, is_box, t_pos, t_up, b_pos, b_up
)
else:
obs = env_core.get_robot_contact_txty_shape_2obj6dUp_obs_nodup_from_up(
tx, ty, is_box, t_pos, t_up, b_pos, b_up
)
# if TEST_PLACING:
# obs.extend([1.0])
# else:
# obs.extend([-1.0])
obs = policy.wrap_obs(obs, IS_CUDA)
return obs
def is_close(obj_dict_a, obj_dict_b, dist=CLOSE_THRES):
xa, ya = obj_dict_a["position"][0], obj_dict_a["position"][1]
xb, yb = obj_dict_b["position"][0], obj_dict_b["position"][1]
return (xa - xb)**2 + (ya - yb)**2 < dist**2
def get_stacking_obs(
obj_state: dict,
top_oid: int,
btm_oid: int,
):
"""Retrieves stacking observations.
Args:
obj_state: world obj state dict of dicts
top_oid: The object ID of the top object.
btm_oid: The object ID of the bottom object.
Returns:
top_pos: The xyz position of the top object.
top_up: The up vector of the top object.
btm_pos: The xyz position of the bottom object.
btm_up: The up vector of the bottom object.
top_half_height: Half of the height of the top object.
"""
top_pos, top_quat = p.getBasePositionAndOrientation(top_oid)
if GRASP_SPH_ON and obj_state[top_oid]["shape"] == "sphere":
top_quat = [0., 0, 0, 1]
if btm_oid is None:
btm_pos, btm_quat = [0.0, 0, 0], [0.0, 0, 0, 1]
else:
btm_pos, btm_quat = p.getBasePositionAndOrientation(btm_oid)
top_up = utils.quat_to_upv(top_quat)
btm_up = utils.quat_to_upv(btm_quat)
top_half_height = obj_state[top_oid]["height"] / 2
if ADD_WHITE_NOISE:
top_pos = utils.perturb(np.random, top_pos, r=0.02)
btm_pos = utils.perturb(np.random, btm_pos, r=0.02)
top_up = utils.perturb(np.random, top_up, r=0.03)
btm_up = utils.perturb(np.random, btm_up, r=0.03)
top_half_height = utils.perturb_scalar(np.random, top_half_height, r=0.01)
return top_pos, top_up, btm_pos, btm_up, top_half_height
def gen_surrounding_objs(obj_dicts_list):
# gen objs and modifies obj_dicts_list accordingly
if ADD_SURROUNDING_OBJS:
num_obj = np.random.randint(SURROUNDING_OBJS_MAX_NUM) + 1 # 1,2,3,4
retries = 0
while len(obj_dicts_list) - 2 < num_obj and retries < 50:
new_obj_dict = sample_obj_dict(whole_table_top=True)
is_close_arr = [is_close(new_obj_dict, obj_dict) for obj_dict in obj_dicts_list]
if not any(is_close_arr):
obj_dicts_list.append(new_obj_dict)
retries += 1
return obj_dicts_list
success_count = 0
openrave_success_count = 0
"""Pre-calculation & Loading"""
g_actor_critic, _, _, _ = policy.load(
GRASP_DIR, GRASP_PI_ENV_NAME, IS_CUDA
)
p_actor_critic, _, recurrent_hidden_states, masks = policy.load(
PLACE_DIR, PLACE_PI_ENV_NAME, IS_CUDA
)
if GRASP_SPH_ON:
sph_g_actor_critic, _, _, _ = policy.load(
GRASP_SPH_DIR, GRASP_PI_ENV_NAME, IS_CUDA
)
sph_p_actor_critic, _, _, _ = policy.load(
PLACE_SPH_DIR, PLACE_PI_ENV_NAME, IS_CUDA
)
o_pos_pf_ave, o_quat_pf_ave, _ = \
utils.read_grasp_final_states_from_pickle(GRASP_PI)
p_pos_of_ave, p_quat_of_ave = p.invertTransform(
o_pos_pf_ave, o_quat_pf_ave
)
if GRASP_SPH_ON:
sph_o_pos_pf_ave, sph_o_quat_pf_ave, _ = \
utils.read_grasp_final_states_from_pickle(GRASP_SPH_PI)
sph_p_pos_of_ave, sph_p_quat_of_ave = p.invertTransform(
sph_o_pos_pf_ave, sph_o_quat_pf_ave
)
"""Start Bullet session."""
if RENDER:
p.connect(p.GUI)
else:
p.connect(p.DIRECT)
for trial in range(NUM_TRIALS):
"""Sample two/N objects"""
all_dicts = []
while True:
top_dict = sample_obj_dict(only_sph=False)
btm_dict = sample_obj_dict(is_thicker=True)
g_tx, g_ty = top_dict["position"][0], top_dict["position"][1]
p_tx, p_ty, p_tz = btm_dict["position"][0], btm_dict["position"][1], btm_dict["height"]
t_half_height = top_dict["height"]/2
if ADD_WHITE_NOISE:
g_tx += np.random.uniform(low=-0.015, high=0.015)
g_ty += np.random.uniform(low=-0.015, high=0.015)
t_half_height += np.random.uniform(low=-0.01, high=0.01)
p_tx += np.random.uniform(low=-0.015, high=0.015)
p_ty += np.random.uniform(low=-0.015, high=0.015)
p_tz += np.random.uniform(low=-0.015, high=0.015)
if TEST_PLACING:
# overwrite ptz
p_tz = 0.0
# if GRASP_SPH_ON
top_shape = utils.NAME_TO_SHAPE_IND_MAP[top_dict["shape"]] # -1(sph)/0/1
# else
# is_box = int(top_dict["shape"] == "box") # 0/1
dist = CLOSE_THRES*2.0 if LONG_MOVE else CLOSE_THRES
if is_close(top_dict, btm_dict, dist=dist):
continue # discard & re-sample
else:
all_dicts = [top_dict, btm_dict]
gen_surrounding_objs(all_dicts)
del top_dict, btm_dict
break
"""Imaginary arm session to get q_reach"""
if USE_GV5:
sess = ImaginaryArmObjSession()
Qreach = np.array(sess.get_most_comfortable_q_and_refangle(g_tx, g_ty)[0])
del sess
else:
# maybe not necessary to create table and robot twice. Decide later
desired_obj_pos = [g_tx, g_ty, 0.0]
table_id = utils.create_table(FLOOR_MU)
robot = InmoovShadowNew(
init_noise=False,
timestep=utils.TS,
np_random=np.random,
)
Qreach = utils.get_n_optimal_init_arm_qs(robot, utils.PALM_POS_OF_INIT,
p.getQuaternionFromEuler(utils.PALM_EULER_OF_INIT),
desired_obj_pos, table_id, wrist_gain=3.0)[0]
p.resetSimulation()
if USE_HEIGHT_INFO:
desired_obj_pos = [p_tx, p_ty, utils.PLACE_START_CLEARANCE + p_tz]
else:
if TEST_PLACING:
desired_obj_pos = [p_tx, p_ty, utils.PLACE_START_CLEARANCE + 0.0]
else:
desired_obj_pos = [p_tx, p_ty, utils.PLACE_START_CLEARANCE + utils.H_MAX]
table_id = utils.create_table(FLOOR_MU)
robot = InmoovShadowNew(
init_noise=False,
timestep=utils.TS,
np_random=np.random,
)
if GRASP_SPH_ON and top_shape == -1: # sphere has no "up vector"
_, desired_obj_quat = p.multiplyTransforms(
[0, 0, 0],
p.getQuaternionFromEuler(utils.PALM_EULER_OF_INIT),
[0, 0, 0],
sph_o_quat_pf_ave
)
Qdestin = utils.get_n_optimal_init_arm_qs(
robot, sph_p_pos_of_ave, sph_p_quat_of_ave, desired_obj_pos, table_id, desired_obj_quat=desired_obj_quat
)[0]
else:
desired_obj_quat = [0., 0, 0, 1] # box or cyl be upright
Qdestin = utils.get_n_optimal_init_arm_qs(
robot, p_pos_of_ave, p_quat_of_ave, desired_obj_pos, table_id, desired_obj_quat=desired_obj_quat
)[0]
del table_id, robot, desired_obj_pos
p.resetSimulation()
"""Clean up the simulation, since this is only imaginary."""
"""Setup Bullet world."""
""" Create table, robot, bottom obj, top obj"""
p.setPhysicsEngineParameter(numSolverIterations=utils.BULLET_CONTACT_ITER)
p.setPhysicsEngineParameter(deterministicOverlappingPairs=DET_CONTACT)
p.setTimeStep(utils.TS)
p.setGravity(0, 0, -utils.GRAVITY)
table_id = utils.create_table(FLOOR_MU)
env_core = InmoovShadowHandDemoEnvV4(
np_random=np.random,
init_noise=INIT_NOISE,
timestep=utils.TS,
withVel=False,
diffTar=True,
robot_mu=HAND_MU,
control_skip=GRASPING_CONTROL_SKIP,
sleep=DUMMY_SLEEP
)
env_core.change_init_fin_q(INIT_FIN_Q)
objs, top_id, btm_id = load_obj_and_construct_state(all_dicts)
OBJECTS = construct_obj_array_for_openrave(all_dicts)
"""Prepare for grasping. Reach for the object."""
print(f"Qreach: {Qreach}")
if WITH_REACHING:
env_core.robot.reset_with_certain_arm_q([0.0] * 7)
reach_save_path = homedir + "/container_data/PB_REACH.npz"
reach_read_path = homedir + "/container_data/OR_REACH.npz"
Traj_reach = openrave.get_traj_from_openrave_container(OBJECTS, None, Qreach, reach_save_path, reach_read_path)
if Traj_reach is None or len(Traj_reach) == 0:
p.resetSimulation()
print("*******", success_count * 1.0 / (trial + 1))
continue # reaching failed
else:
planning(Traj_reach)
print("arm q", env_core.robot.get_q_dq(env_core.robot.arm_dofs)[0])
else:
env_core.robot.reset_with_certain_arm_q(Qreach)
# input("press enter")
g_obs = get_grasp_policy_obs_tensor(g_tx, g_ty, t_half_height, top_shape)
"""Grasp"""
control_steps = 0
for i in range(GRASP_END_STEP):
with torch.no_grad():
if GRASP_SPH_ON and top_shape == -1:
value, action, _, recurrent_hidden_states = sph_g_actor_critic.act(
g_obs, recurrent_hidden_states, masks, deterministic=args.det
)
else:
value, action, _, recurrent_hidden_states = g_actor_critic.act(
g_obs, recurrent_hidden_states, masks, deterministic=args.det
)
env_core.step(policy.unwrap_action(action, IS_CUDA))
g_obs = get_grasp_policy_obs_tensor(g_tx, g_ty, t_half_height, top_shape)
# print(g_obs)
# print(action)
# print(control_steps)
# control_steps += 1
# input("press enter g_obs")
masks.fill_(1.0)
# pose_saver.get_poses()
final_g_obs = copy.copy(g_obs)
del g_obs, g_tx, g_ty, t_half_height
state = get_relative_state_for_reset(top_id)
print("after grasping", state)
# state = get_relative_state_for_reset(top_id)
# print("after grasping", state)
# print("arm q", env_core.robot.get_q_dq(env_core.robot.arm_dofs)[0])
# # input("after grasping")
"""Send move command to OpenRAVE"""
Qmove_init = env_core.robot.get_q_dq(env_core.robot.arm_dofs)[0]
print(f"Qmove_init: {Qmove_init}")
print(f"Qdestin: {Qdestin}")
move_save_path = homedir + "/container_data/PB_MOVE.npz"
move_read_path = homedir + "/container_data/OR_MOVE.npz"
Traj_move = openrave.get_traj_from_openrave_container(OBJECTS, Qmove_init, Qdestin, move_save_path, move_read_path)
"""Execute planned moving trajectory"""
if Traj_move is None or len(Traj_move) == 0:
p.resetSimulation()
print("*******", success_count * 1.0 / (trial + 1))
continue # transporting failed
else:
planning(Traj_move)
print("arm q", env_core.robot.get_q_dq(env_core.robot.arm_dofs)[0])
# input("after moving")
print("palm", env_core.robot.get_link_pos_quat(env_core.robot.ee_id))
# pose_saver.get_poses()
# print(f"Pose before placing")
# pprint.pprint(pose_saver.poses[-1])
#
# input("ready to place")
# ##### fake: reset###
# # reset only arm but not obj/finger
# # reset obj/finger but not arm
# # reset finger vel/obj vel only
# # reset obj but not arm/finger -- good
# # reset obj vel but not pos -- somewhat good
# # reset obj but not arm/finger
#
# # # TODO:tmp
# # state = get_relative_state_for_reset(top_id)
# # print("after grasping", state)
#
# o_pos_pf = state['obj_pos_in_palm']
# o_quat_pf = state['obj_quat_in_palm']
# all_fin_q_init = state['all_fin_q']
# tar_fin_q_init = state['fin_tar_q']
# # env_core.robot.reset_with_certain_arm_q_finger_states(Qdestin, all_fin_q_init, tar_fin_q_init)
# # env_core.robot.reset_only_certain_finger_states(all_fin_q_init, tar_fin_q_init)
#
# p_pos, p_quat = env_core.robot.get_link_pos_quat(env_core.robot.ee_id)
# o_pos, o_quat = p.multiplyTransforms(p_pos, p_quat, o_pos_pf, o_quat_pf)
# p.resetBasePositionAndOrientation(top_id, o_pos, o_quat)
# p.stepSimulation()
# # env_core.robot.reset_with_certain_arm_q_finger_states(Qdestin, all_fin_q_init, tar_fin_q_init)
# # env_core.robot.reset_only_certain_finger_states(all_fin_q_init, tar_fin_q_init)
# p.resetBasePositionAndOrientation(top_id, o_pos, o_quat)
# p.stepSimulation()
# #####
# # input("reset")
"""Prepare for placing"""
env_core.change_control_skip_scaling(c_skip=PLACING_CONTROL_SKIP)
t_pos, t_up, b_pos, b_up, t_half_height = get_stacking_obs(
obj_state=objs,
top_oid=top_id,
btm_oid=btm_id,
)
l_t_pos, l_t_up, l_b_pos, l_b_up, l_t_half_height = (
t_pos,
t_up,
b_pos,
b_up,
t_half_height,
)
# an ugly hack to force Bullet compute forward kinematics
_ = get_stack_policy_obs_tensor(
p_tx, p_ty, p_tz, t_half_height, top_shape, t_pos, t_up, b_pos, b_up
)
p_obs = get_stack_policy_obs_tensor(
p_tx, p_ty, p_tz, t_half_height, top_shape, t_pos, t_up, b_pos, b_up
)
# print("pobs", p_obs)
# input("ready to place")
"""Execute placing"""
print(f"Executing placing...")
for i in tqdm(range(PLACE_END_STEP)):
with torch.no_grad():
if GRASP_SPH_ON and top_shape == -1:
value, action, _, recurrent_hidden_states = sph_p_actor_critic.act(
p_obs, recurrent_hidden_states, masks, deterministic=args.det
)
else:
value, action, _, recurrent_hidden_states = p_actor_critic.act(
p_obs, recurrent_hidden_states, masks, deterministic=args.det
)
env_core.step(policy.unwrap_action(action, IS_CUDA))
if (i + 1) % VISION_DELAY == 0:
l_t_pos, l_t_up, l_b_pos, l_b_up, l_t_half_height = (
t_pos,
t_up,
b_pos,
b_up,
t_half_height,
)
t_pos, t_up, b_pos, b_up, t_half_height = get_stacking_obs(
obj_state=objs,
top_oid=top_id,
btm_oid=btm_id,
)
p_obs = get_stack_policy_obs_tensor(
p_tx, p_ty, p_tz, l_t_half_height, top_shape, l_t_pos, l_t_up, l_b_pos, l_b_up
)
# print(action)
# print(p_obs)
# input("press enter g_obs")
masks.fill_(1.0)
# pose_saver.get_poses()
# print(f"Pose after placing")
# pprint.pprint(pose_saver.poses[-1])
if WITH_RETRACT:
print(f"Starting release trajectory")
Qretract_init = env_core.robot.get_q_dq(env_core.robot.arm_dofs)[0]
retract_save_path = homedir + "/container_data/PB_RETRACT.npz"
retract_read_path = homedir + "/container_data/OR_RETRACT.npz"
OBJECTS[0, :] = np.array([p_tx, p_ty, p_tz, 0.0]) # note: p_tz is 0 for placing
Traj_reach = openrave.get_traj_from_openrave_container(
OBJECTS, Qretract_init, None, retract_save_path, retract_read_path
)
if Traj_reach is None or len(Traj_reach) == 0:
p.resetSimulation()
print("*******", success_count * 1.0 / (trial + 1))
continue # retracting failed
else:
planning(Traj_reach, restore_fingers=True)
t_pos, t_quat = p.getBasePositionAndOrientation(top_id)
if t_pos[2] - p_tz > 0.05 and (t_pos[0] - p_tx)**2 + (t_pos[1] - p_ty)**2 < 0.1**2:
# TODO: ptz noisy a very rough check
success_count += 1
openrave_success_count += 1
p.resetSimulation()
print("*******", success_count * 1.0 / (trial+1), trial+1)
print("******* w/o OR", success_count * 1.0 / openrave_success_count, openrave_success_count)
p.disconnect()
print("*******total", success_count * 1.0 / NUM_TRIALS)
print("*******total w/o OR", success_count * 1.0 / openrave_success_count)
f = open("final_stats.txt", "a")
f.write(f"*******total: {success_count * 1.0 / NUM_TRIALS:.3f})")
f.write(f"*******total w/o OR: {success_count * 1.0 / openrave_success_count:.3f})")
f.write("\n")
f.close()
| [
"my_pybullet_envs.utils.create_table",
"my_pybullet_envs.inmoov_shadow_hand_v2.InmoovShadowNew",
"my_pybullet_envs.inmoov_shadow_demo_env_v4.InmoovShadowHandDemoEnvV4",
"numpy.random.seed",
"argparse.ArgumentParser",
"pybullet.resetSimulation",
"my_pybullet_envs.utils.perturb",
"numpy.clip",
"numpy.... | [((690, 713), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (708, 713), False, 'import os\n'), ((1017, 1049), 'sys.path.append', 'sys.path.append', (['"""a2c_ppo_acktr"""'], {}), "('a2c_ppo_acktr')\n", (1032, 1049), False, 'import sys\n'), ((1059, 1100), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""RL"""'}), "(description='RL')\n", (1082, 1100), False, 'import argparse\n'), ((1537, 1562), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (1551, 1562), True, 'import numpy as np\n'), ((13898, 13948), 'system.policy.load', 'policy.load', (['GRASP_DIR', 'GRASP_PI_ENV_NAME', 'IS_CUDA'], {}), '(GRASP_DIR, GRASP_PI_ENV_NAME, IS_CUDA)\n', (13909, 13948), False, 'from system import policy, openrave\n'), ((14007, 14057), 'system.policy.load', 'policy.load', (['PLACE_DIR', 'PLACE_PI_ENV_NAME', 'IS_CUDA'], {}), '(PLACE_DIR, PLACE_PI_ENV_NAME, IS_CUDA)\n', (14018, 14057), False, 'from system import policy, openrave\n'), ((14328, 14379), 'my_pybullet_envs.utils.read_grasp_final_states_from_pickle', 'utils.read_grasp_final_states_from_pickle', (['GRASP_PI'], {}), '(GRASP_PI)\n', (14369, 14379), False, 'from my_pybullet_envs import utils\n'), ((14411, 14457), 'pybullet.invertTransform', 'p.invertTransform', (['o_pos_pf_ave', 'o_quat_pf_ave'], {}), '(o_pos_pf_ave, o_quat_pf_ave)\n', (14428, 14457), True, 'import pybullet as p\n'), ((27042, 27056), 'pybullet.disconnect', 'p.disconnect', ([], {}), '()\n', (27054, 27056), True, 'import pybullet as p\n'), ((2568, 2643), 'numpy.array', 'np.array', (['([0.4, 0.4, 0.4] * 3 + [0.4, 0.4, 0.4] + [0.0, 1.0, 0.1, 0.5, 0.0])'], {}), '([0.4, 0.4, 0.4] * 3 + [0.4, 0.4, 0.4] + [0.0, 1.0, 0.1, 0.5, 0.0])\n', (2576, 2643), True, 'import numpy as np\n'), ((3438, 3513), 'numpy.array', 'np.array', (['([0.4, 0.4, 0.4] * 3 + [0.4, 0.4, 0.4] + [0.0, 1.0, 0.1, 0.5, 0.1])'], {}), '([0.4, 0.4, 0.4] * 3 + [0.4, 0.4, 0.4] + [0.0, 1.0, 0.1, 0.5, 0.1])\n', (3446, 3513), True, 'import numpy as np\n'), ((7195, 7231), 'pybullet.getBasePositionAndOrientation', 'p.getBasePositionAndOrientation', (['oid'], {}), '(oid)\n', (7226, 7231), True, 'import pybullet as p\n'), ((7364, 7402), 'pybullet.invertTransform', 'p.invertTransform', (['hand_pos', 'hand_quat'], {}), '(hand_pos, hand_quat)\n', (7381, 7402), True, 'import pybullet as p\n'), ((7431, 7488), 'pybullet.multiplyTransforms', 'p.multiplyTransforms', (['inv_h_p', 'inv_h_q', 'obj_pos', 'obj_quat'], {}), '(inv_h_p, inv_h_q, obj_pos, obj_quat)\n', (7451, 7488), True, 'import pybullet as p\n'), ((9928, 9985), 'my_pybullet_envs.utils.create_sym_prim_shape_helper_new', 'utils.create_sym_prim_shape_helper_new', (['obj_dicts_list[0]'], {}), '(obj_dicts_list[0])\n', (9966, 9985), False, 'from my_pybullet_envs import utils\n'), ((10400, 10413), 'numpy.array', 'np.array', (['arr'], {}), '(arr)\n', (10408, 10413), True, 'import numpy as np\n'), ((10862, 10891), 'system.policy.wrap_obs', 'policy.wrap_obs', (['obs', 'IS_CUDA'], {}), '(obs, IS_CUDA)\n', (10877, 10891), False, 'from system import policy, openrave\n'), ((11468, 11497), 'system.policy.wrap_obs', 'policy.wrap_obs', (['obs', 'IS_CUDA'], {}), '(obs, IS_CUDA)\n', (11483, 11497), False, 'from system import policy, openrave\n'), ((12359, 12399), 'pybullet.getBasePositionAndOrientation', 'p.getBasePositionAndOrientation', (['top_oid'], {}), '(top_oid)\n', (12390, 12399), True, 'import pybullet as p\n'), ((12671, 12698), 'my_pybullet_envs.utils.quat_to_upv', 'utils.quat_to_upv', (['top_quat'], {}), '(top_quat)\n', (12688, 12698), False, 'from my_pybullet_envs import utils\n'), ((12712, 12739), 'my_pybullet_envs.utils.quat_to_upv', 'utils.quat_to_upv', (['btm_quat'], {}), '(btm_quat)\n', (12729, 12739), False, 'from my_pybullet_envs import utils\n'), ((14116, 14170), 'system.policy.load', 'policy.load', (['GRASP_SPH_DIR', 'GRASP_PI_ENV_NAME', 'IS_CUDA'], {}), '(GRASP_SPH_DIR, GRASP_PI_ENV_NAME, IS_CUDA)\n', (14127, 14170), False, 'from system import policy, openrave\n'), ((14219, 14273), 'system.policy.load', 'policy.load', (['PLACE_SPH_DIR', 'PLACE_PI_ENV_NAME', 'IS_CUDA'], {}), '(PLACE_SPH_DIR, PLACE_PI_ENV_NAME, IS_CUDA)\n', (14230, 14273), False, 'from system import policy, openrave\n'), ((14537, 14592), 'my_pybullet_envs.utils.read_grasp_final_states_from_pickle', 'utils.read_grasp_final_states_from_pickle', (['GRASP_SPH_PI'], {}), '(GRASP_SPH_PI)\n', (14578, 14592), False, 'from my_pybullet_envs import utils\n'), ((14635, 14689), 'pybullet.invertTransform', 'p.invertTransform', (['sph_o_pos_pf_ave', 'sph_o_quat_pf_ave'], {}), '(sph_o_pos_pf_ave, sph_o_quat_pf_ave)\n', (14652, 14689), True, 'import pybullet as p\n'), ((14748, 14764), 'pybullet.connect', 'p.connect', (['p.GUI'], {}), '(p.GUI)\n', (14757, 14764), True, 'import pybullet as p\n'), ((14775, 14794), 'pybullet.connect', 'p.connect', (['p.DIRECT'], {}), '(p.DIRECT)\n', (14784, 14794), True, 'import pybullet as p\n'), ((17358, 17386), 'my_pybullet_envs.utils.create_table', 'utils.create_table', (['FLOOR_MU'], {}), '(FLOOR_MU)\n', (17376, 17386), False, 'from my_pybullet_envs import utils\n'), ((17400, 17473), 'my_pybullet_envs.inmoov_shadow_hand_v2.InmoovShadowNew', 'InmoovShadowNew', ([], {'init_noise': '(False)', 'timestep': 'utils.TS', 'np_random': 'np.random'}), '(init_noise=False, timestep=utils.TS, np_random=np.random)\n', (17415, 17473), False, 'from my_pybullet_envs.inmoov_shadow_hand_v2 import InmoovShadowNew\n'), ((18257, 18276), 'pybullet.resetSimulation', 'p.resetSimulation', ([], {}), '()\n', (18274, 18276), True, 'import pybullet as p\n'), ((18430, 18504), 'pybullet.setPhysicsEngineParameter', 'p.setPhysicsEngineParameter', ([], {'numSolverIterations': 'utils.BULLET_CONTACT_ITER'}), '(numSolverIterations=utils.BULLET_CONTACT_ITER)\n', (18457, 18504), True, 'import pybullet as p\n'), ((18509, 18579), 'pybullet.setPhysicsEngineParameter', 'p.setPhysicsEngineParameter', ([], {'deterministicOverlappingPairs': 'DET_CONTACT'}), '(deterministicOverlappingPairs=DET_CONTACT)\n', (18536, 18579), True, 'import pybullet as p\n'), ((18584, 18607), 'pybullet.setTimeStep', 'p.setTimeStep', (['utils.TS'], {}), '(utils.TS)\n', (18597, 18607), True, 'import pybullet as p\n'), ((18612, 18646), 'pybullet.setGravity', 'p.setGravity', (['(0)', '(0)', '(-utils.GRAVITY)'], {}), '(0, 0, -utils.GRAVITY)\n', (18624, 18646), True, 'import pybullet as p\n'), ((18663, 18691), 'my_pybullet_envs.utils.create_table', 'utils.create_table', (['FLOOR_MU'], {}), '(FLOOR_MU)\n', (18681, 18691), False, 'from my_pybullet_envs import utils\n'), ((18708, 18906), 'my_pybullet_envs.inmoov_shadow_demo_env_v4.InmoovShadowHandDemoEnvV4', 'InmoovShadowHandDemoEnvV4', ([], {'np_random': 'np.random', 'init_noise': 'INIT_NOISE', 'timestep': 'utils.TS', 'withVel': '(False)', 'diffTar': '(True)', 'robot_mu': 'HAND_MU', 'control_skip': 'GRASPING_CONTROL_SKIP', 'sleep': 'DUMMY_SLEEP'}), '(np_random=np.random, init_noise=INIT_NOISE,\n timestep=utils.TS, withVel=False, diffTar=True, robot_mu=HAND_MU,\n control_skip=GRASPING_CONTROL_SKIP, sleep=DUMMY_SLEEP)\n', (18733, 18906), False, 'from my_pybullet_envs.inmoov_shadow_demo_env_v4 import InmoovShadowHandDemoEnvV4\n'), ((20956, 20972), 'copy.copy', 'copy.copy', (['g_obs'], {}), '(g_obs)\n', (20965, 20972), False, 'import copy\n'), ((21614, 21721), 'system.openrave.get_traj_from_openrave_container', 'openrave.get_traj_from_openrave_container', (['OBJECTS', 'Qmove_init', 'Qdestin', 'move_save_path', 'move_read_path'], {}), '(OBJECTS, Qmove_init, Qdestin,\n move_save_path, move_read_path)\n', (21655, 21721), False, 'from system import policy, openrave\n'), ((26623, 26662), 'pybullet.getBasePositionAndOrientation', 'p.getBasePositionAndOrientation', (['top_id'], {}), '(top_id)\n', (26654, 26662), True, 'import pybullet as p\n'), ((26860, 26879), 'pybullet.resetSimulation', 'p.resetSimulation', ([], {}), '()\n', (26877, 26879), True, 'import pybullet as p\n'), ((5640, 5757), 'numpy.clip', 'np.clip', (['tar_fin_q', 'env_core.robot.ll[env_core.robot.fin_actdofs]', 'env_core.robot.ul[env_core.robot.fin_actdofs]'], {}), '(tar_fin_q, env_core.robot.ll[env_core.robot.fin_actdofs], env_core.\n robot.ul[env_core.robot.fin_actdofs])\n', (5647, 5757), True, 'import numpy as np\n'), ((8613, 8655), 'numpy.random.uniform', 'np.random.uniform', (['min_r', 'utils.HALF_W_MAX'], {}), '(min_r, utils.HALF_W_MAX)\n', (8630, 8655), True, 'import numpy as np\n'), ((8675, 8718), 'numpy.random.uniform', 'np.random.uniform', (['utils.H_MIN', 'utils.H_MAX'], {}), '(utils.H_MIN, utils.H_MAX)\n', (8692, 8718), True, 'import numpy as np\n'), ((9475, 9534), 'my_pybullet_envs.utils.create_sym_prim_shape_helper_new', 'utils.create_sym_prim_shape_helper_new', (['obj_dicts_list[idx]'], {}), '(obj_dicts_list[idx])\n', (9513, 9534), False, 'from my_pybullet_envs import utils\n'), ((9734, 9791), 'my_pybullet_envs.utils.create_sym_prim_shape_helper_new', 'utils.create_sym_prim_shape_helper_new', (['obj_dicts_list[1]'], {}), '(obj_dicts_list[1])\n', (9772, 9791), False, 'from my_pybullet_envs import utils\n'), ((12616, 12656), 'pybullet.getBasePositionAndOrientation', 'p.getBasePositionAndOrientation', (['btm_oid'], {}), '(btm_oid)\n', (12647, 12656), True, 'import pybullet as p\n'), ((12839, 12880), 'my_pybullet_envs.utils.perturb', 'utils.perturb', (['np.random', 'top_pos'], {'r': '(0.02)'}), '(np.random, top_pos, r=0.02)\n', (12852, 12880), False, 'from my_pybullet_envs import utils\n'), ((12899, 12940), 'my_pybullet_envs.utils.perturb', 'utils.perturb', (['np.random', 'btm_pos'], {'r': '(0.02)'}), '(np.random, btm_pos, r=0.02)\n', (12912, 12940), False, 'from my_pybullet_envs import utils\n'), ((12958, 12998), 'my_pybullet_envs.utils.perturb', 'utils.perturb', (['np.random', 'top_up'], {'r': '(0.03)'}), '(np.random, top_up, r=0.03)\n', (12971, 12998), False, 'from my_pybullet_envs import utils\n'), ((13016, 13056), 'my_pybullet_envs.utils.perturb', 'utils.perturb', (['np.random', 'btm_up'], {'r': '(0.03)'}), '(np.random, btm_up, r=0.03)\n', (13029, 13056), False, 'from my_pybullet_envs import utils\n'), ((13083, 13139), 'my_pybullet_envs.utils.perturb_scalar', 'utils.perturb_scalar', (['np.random', 'top_half_height'], {'r': '(0.01)'}), '(np.random, top_half_height, r=0.01)\n', (13103, 13139), False, 'from my_pybullet_envs import utils\n'), ((16282, 16306), 'my_pybullet_envs.inmoov_arm_obj_imaginary_sessions.ImaginaryArmObjSession', 'ImaginaryArmObjSession', ([], {}), '()\n', (16304, 16306), False, 'from my_pybullet_envs.inmoov_arm_obj_imaginary_sessions import ImaginaryArmObjSession\n'), ((16557, 16585), 'my_pybullet_envs.utils.create_table', 'utils.create_table', (['FLOOR_MU'], {}), '(FLOOR_MU)\n', (16575, 16585), False, 'from my_pybullet_envs import utils\n'), ((16603, 16676), 'my_pybullet_envs.inmoov_shadow_hand_v2.InmoovShadowNew', 'InmoovShadowNew', ([], {'init_noise': '(False)', 'timestep': 'utils.TS', 'np_random': 'np.random'}), '(init_noise=False, timestep=utils.TS, np_random=np.random)\n', (16618, 16676), False, 'from my_pybullet_envs.inmoov_shadow_hand_v2 import InmoovShadowNew\n'), ((17009, 17028), 'pybullet.resetSimulation', 'p.resetSimulation', ([], {}), '()\n', (17026, 17028), True, 'import pybullet as p\n'), ((19462, 19564), 'system.openrave.get_traj_from_openrave_container', 'openrave.get_traj_from_openrave_container', (['OBJECTS', 'None', 'Qreach', 'reach_save_path', 'reach_read_path'], {}), '(OBJECTS, None, Qreach,\n reach_save_path, reach_read_path)\n', (19503, 19564), False, 'from system import policy, openrave\n'), ((21821, 21840), 'pybullet.resetSimulation', 'p.resetSimulation', ([], {}), '()\n', (21838, 21840), True, 'import pybullet as p\n'), ((26115, 26148), 'numpy.array', 'np.array', (['[p_tx, p_ty, p_tz, 0.0]'], {}), '([p_tx, p_ty, p_tz, 0.0])\n', (26123, 26148), True, 'import numpy as np\n'), ((26207, 26320), 'system.openrave.get_traj_from_openrave_container', 'openrave.get_traj_from_openrave_container', (['OBJECTS', 'Qretract_init', 'None', 'retract_save_path', 'retract_read_path'], {}), '(OBJECTS, Qretract_init, None,\n retract_save_path, retract_read_path)\n', (26248, 26320), False, 'from system import policy, openrave\n'), ((653, 675), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (673, 675), False, 'import inspect\n'), ((5527, 5588), 'numpy.clip', 'np.clip', (['init_tar_fin_q', '(init_fin_q - 0.05)', '(init_fin_q + 0.05)'], {}), '(init_tar_fin_q, init_fin_q - 0.05, init_fin_q + 0.05)\n', (5534, 5588), True, 'import numpy as np\n'), ((7012, 7030), 'pybullet.stepSimulation', 'p.stepSimulation', ([], {}), '()\n', (7028, 7030), True, 'import pybullet as p\n'), ((7067, 7093), 'time.sleep', 'time.sleep', (['(utils.TS * 0.6)'], {}), '(utils.TS * 0.6)\n', (7077, 7093), False, 'import time\n'), ((8466, 8486), 'numpy.random.randint', 'np.random.randint', (['(2)'], {}), '(2)\n', (8483, 8486), True, 'import numpy as np\n'), ((8754, 8785), 'numpy.random.uniform', 'np.random.uniform', (['x_min', 'x_max'], {}), '(x_min, x_max)\n', (8771, 8785), True, 'import numpy as np\n'), ((8799, 8830), 'numpy.random.uniform', 'np.random.uniform', (['y_min', 'y_max'], {}), '(y_min, y_max)\n', (8816, 8830), True, 'import numpy as np\n'), ((13348, 13391), 'numpy.random.randint', 'np.random.randint', (['SURROUNDING_OBJS_MAX_NUM'], {}), '(SURROUNDING_OBJS_MAX_NUM)\n', (13365, 13391), True, 'import numpy as np\n'), ((15260, 15301), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-0.015)', 'high': '(0.015)'}), '(low=-0.015, high=0.015)\n', (15277, 15301), True, 'import numpy as np\n'), ((15322, 15363), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-0.015)', 'high': '(0.015)'}), '(low=-0.015, high=0.015)\n', (15339, 15363), True, 'import numpy as np\n'), ((15393, 15432), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-0.01)', 'high': '(0.01)'}), '(low=-0.01, high=0.01)\n', (15410, 15432), True, 'import numpy as np\n'), ((15453, 15494), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-0.015)', 'high': '(0.015)'}), '(low=-0.015, high=0.015)\n', (15470, 15494), True, 'import numpy as np\n'), ((15515, 15556), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-0.015)', 'high': '(0.015)'}), '(low=-0.015, high=0.015)\n', (15532, 15556), True, 'import numpy as np\n'), ((15577, 15618), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-0.015)', 'high': '(0.015)'}), '(low=-0.015, high=0.015)\n', (15594, 15618), True, 'import numpy as np\n'), ((17666, 17716), 'pybullet.getQuaternionFromEuler', 'p.getQuaternionFromEuler', (['utils.PALM_EULER_OF_INIT'], {}), '(utils.PALM_EULER_OF_INIT)\n', (17690, 17716), True, 'import pybullet as p\n'), ((17799, 17940), 'my_pybullet_envs.utils.get_n_optimal_init_arm_qs', 'utils.get_n_optimal_init_arm_qs', (['robot', 'sph_p_pos_of_ave', 'sph_p_quat_of_ave', 'desired_obj_pos', 'table_id'], {'desired_obj_quat': 'desired_obj_quat'}), '(robot, sph_p_pos_of_ave, sph_p_quat_of_ave,\n desired_obj_pos, table_id, desired_obj_quat=desired_obj_quat)\n', (17830, 17940), False, 'from my_pybullet_envs import utils\n'), ((18056, 18189), 'my_pybullet_envs.utils.get_n_optimal_init_arm_qs', 'utils.get_n_optimal_init_arm_qs', (['robot', 'p_pos_of_ave', 'p_quat_of_ave', 'desired_obj_pos', 'table_id'], {'desired_obj_quat': 'desired_obj_quat'}), '(robot, p_pos_of_ave, p_quat_of_ave,\n desired_obj_pos, table_id, desired_obj_quat=desired_obj_quat)\n', (18087, 18189), False, 'from my_pybullet_envs import utils\n'), ((19629, 19648), 'pybullet.resetSimulation', 'p.resetSimulation', ([], {}), '()\n', (19646, 19648), True, 'import pybullet as p\n'), ((20141, 20156), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (20154, 20156), False, 'import torch\n'), ((20612, 20649), 'system.policy.unwrap_action', 'policy.unwrap_action', (['action', 'IS_CUDA'], {}), '(action, IS_CUDA)\n', (20632, 20649), False, 'from system import policy, openrave\n'), ((24501, 24516), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (24514, 24516), False, 'import torch\n'), ((24972, 25009), 'system.policy.unwrap_action', 'policy.unwrap_action', (['action', 'IS_CUDA'], {}), '(action, IS_CUDA)\n', (24992, 25009), False, 'from system import policy, openrave\n'), ((26407, 26426), 'pybullet.resetSimulation', 'p.resetSimulation', ([], {}), '()\n', (26424, 26426), True, 'import pybullet as p\n'), ((8370, 8390), 'numpy.random.randint', 'np.random.randint', (['(3)'], {}), '(3)\n', (8387, 8390), True, 'import numpy as np\n'), ((8929, 8973), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(0)', 'high': '(2.0 * math.pi)'}), '(low=0, high=2.0 * math.pi)\n', (8946, 8973), True, 'import numpy as np\n'), ((16853, 16903), 'pybullet.getQuaternionFromEuler', 'p.getQuaternionFromEuler', (['utils.PALM_EULER_OF_INIT'], {}), '(utils.PALM_EULER_OF_INIT)\n', (16877, 16903), True, 'import pybullet as p\n')] |
"""
Plotting routines for visualizing chemical diversity of datasets
"""
import os
import sys
import pandas as pd
import numpy as np
import seaborn as sns
import umap
from scipy.stats.kde import gaussian_kde
from scipy.cluster.hierarchy import linkage
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import logging
import argparse
from rdkit import Chem
from rdkit.Chem import AllChem, Draw
from atomsci.ddm.utils import struct_utils
from atomsci.ddm.pipeline import dist_metrics as dm
from atomsci.ddm.pipeline import chem_diversity as cd
from atomsci.ddm.pipeline import parameter_parser as parse
from atomsci.ddm.pipeline import model_datasets as md
from atomsci.ddm.pipeline import featurization as feat
from atomsci.ddm.utils import datastore_functions as dsf
#matplotlib.style.use('ggplot')
matplotlib.rc('xtick', labelsize=12)
matplotlib.rc('ytick', labelsize=12)
matplotlib.rc('axes', labelsize=12)
logging.basicConfig(format='%(asctime)-15s %(message)s')
ndist_max = 1000000
#------------------------------------------------------------------------------------------------------------------
def plot_dataset_dist_distr(dataset, feat_type, dist_metric, task_name, **metric_kwargs):
"""
Generate a density plot showing the distribution of distances between dataset feature
vectors, using the specified feature type and distance metric.
"""
log = logging.getLogger('ATOM')
num_cmpds = dataset.X.shape[0]
if num_cmpds > 50000:
log.warning("Dataset has %d compounds, too big to calculate distance matrix" % num_cmpds)
return
log.warning("Starting distance matrix calculation for %d compounds" % num_cmpds)
dists = cd.calc_dist_diskdataset(feat_type, dist_metric, dataset, calc_type='all', **metric_kwargs)
log.warning("Finished calculation of %d distances" % len(dists))
if len(dists) > ndist_max:
# Sample a subset of the distances so KDE doesn't take so long
dist_sample = np.random.choice(dists, size=ndist_max)
else:
dist_sample = dists
dist_pdf = gaussian_kde(dist_sample)
x_plt = np.linspace(min(dist_sample), max(dist_sample), 500)
y_plt = dist_pdf(x_plt)
fig, ax = plt.subplots(figsize=(8.0,8.0))
ax.plot(x_plt, y_plt, color='forestgreen')
ax.set_xlabel('%s distance' % dist_metric)
ax.set_ylabel('Density')
ax.set_title("%s dataset\nDistribution of %s distances between %s feature vectors" % (
task_name, dist_metric, feat_type))
return dists
#------------------------------------------------------------------------------------------------------------------
def diversity_plots(dset_key, datastore=True, bucket='gsk_ml', title_prefix=None, ecfp_radius=4, out_dir=None,
id_col='compound_id', smiles_col='rdkit_smiles', is_base_smiles=False, response_col=None, max_for_mcs=300):
"""
Plot visualizations of diversity for an arbitrary table of compounds. At minimum, the file should contain
columns for a compound ID and a SMILES string.
"""
# Load table of compound names, IDs and SMILES strings
if datastore:
cmpd_df = dsf.retrieve_dataset_by_datasetkey(dset_key, bucket)
else:
cmpd_df = pd.read_csv(dset_key, index_col=False)
cmpd_df = cmpd_df.drop_duplicates(subset=smiles_col)
file_prefix = os.path.splitext(os.path.basename(dset_key))[0]
if title_prefix is None:
title_prefix = file_prefix.replace('_', ' ')
compound_ids = cmpd_df[id_col].values
smiles_strs = cmpd_df[smiles_col].values
ncmpds = len(smiles_strs)
# Strip salts, canonicalize SMILES strings and create RDKit Mol objects
if is_base_smiles:
base_mols = np.array([Chem.MolFromSmiles(s) for s in smiles_strs])
else:
print("Canonicalizing %d molecules..." % ncmpds)
base_mols = np.array([struct_utils.base_mol_from_smiles(smiles) for smiles in smiles_strs])
for i, mol in enumerate(base_mols):
if mol is None:
print('Unable to get base molecule for compound %d = %s' % (i, compound_ids[i]))
print("Done")
has_good_smiles = np.array([mol is not None for mol in base_mols])
base_mols = base_mols[has_good_smiles]
cmpd_df = cmpd_df[has_good_smiles]
ncmpds = cmpd_df.shape[0]
compound_ids = cmpd_df[id_col].values
responses = None
if response_col is not None:
responses = cmpd_df[response_col].values
if set(responses) == set([0,1]):
response_type = 'binary'
colorpal = {0 : 'forestgreen', 1 : 'red'}
else:
response_type = 'continuous'
colorpal = sns.blend_palette(['red', 'green', 'blue'], 12, as_cmap=True)
# Generate ECFP fingerprints
print("Computing fingerprints...")
fps = [AllChem.GetMorganFingerprintAsBitVect(mol, ecfp_radius, 1024) for mol in base_mols if mol is not None]
print("Done")
if ncmpds <= max_for_mcs:
# Get MCS distance matrix and draw a heatmap
print("Computing MCS distance matrix...")
mcs_dist = dm.mcs(base_mols)
print("Done")
cmpd1 = []
cmpd2 = []
dist = []
ind1 = []
ind2 = []
for i in range(ncmpds-1):
for j in range(i+1, ncmpds):
cmpd1.append(compound_ids[i])
cmpd2.append(compound_ids[j])
dist.append(mcs_dist[i,j])
ind1.append(i)
ind2.append(j)
dist_df = pd.DataFrame({'compound_1' : cmpd1, 'compound_2' : cmpd2, 'dist' : dist,
'i' : ind1, 'j' : ind2})
dist_df = dist_df.sort_values(by='dist')
print(dist_df.head(10))
if out_dir is not None:
dist_df.to_csv('%s/%s_mcs_dist_table.csv' % (out_dir, file_prefix), index=False)
for k in range(10):
mol_i = base_mols[dist_df.i.values[k]]
mol_j = base_mols[dist_df.j.values[k]]
img_file_i = '%s/%d_%s.png' % (out_dir, k, compound_ids[dist_df.i.values[k]])
img_file_j = '%s/%d_%s.png' % (out_dir, k, compound_ids[dist_df.j.values[k]])
Draw.MolToFile(mol_i, img_file_i, size=(500,500), fitImage=False)
Draw.MolToFile(mol_j, img_file_j, size=(500,500), fitImage=False)
mcs_linkage = linkage(mcs_dist, method='complete')
mcs_df = pd.DataFrame(mcs_dist, columns=compound_ids, index=compound_ids)
if out_dir is not None:
pdf_path = '%s/%s_mcs_clustermap.pdf' % (out_dir, file_prefix)
pdf = PdfPages(pdf_path)
g = sns.clustermap(mcs_df, row_linkage=mcs_linkage, col_linkage=mcs_linkage, figsize=(12,12), cmap='plasma')
if out_dir is not None:
pdf.savefig(g.fig)
pdf.close()
# Draw a UMAP projection based on MCS distance
mapper = umap.UMAP(n_neighbors=20, min_dist=0.1, n_components=2, metric='precomputed', random_state=17)
reps = mapper.fit_transform(mcs_dist)
rep_df = pd.DataFrame.from_records(reps, columns=['x', 'y'])
rep_df['compound_id'] = compound_ids
if out_dir is not None:
pdf_path = '%s/%s_mcs_umap_proj.pdf' % (out_dir, file_prefix)
pdf = PdfPages(pdf_path)
fig, ax = plt.subplots(figsize=(12,12))
if responses is None:
sns.scatterplot(x='x', y='y', data=rep_df, ax=ax)
else:
rep_df['response'] = responses
sns.scatterplot(x='x', y='y', hue='response', palette=colorpal,
data=rep_df, ax=ax)
ax.set_title("%s, 2D projection based on MCS distance" % title_prefix)
if out_dir is not None:
pdf.savefig(fig)
pdf.close()
rep_df.to_csv('%s/%s_mcs_umap_proj.csv' % (out_dir, file_prefix), index=False)
# Get Tanimoto distance matrix
print("Computing Tanimoto distance matrix...")
tani_dist = dm.tanimoto(fps)
print("Done")
# Draw a UMAP projection based on Tanimoto distance
mapper = umap.UMAP(n_neighbors=20, min_dist=0.1, n_components=2, metric='precomputed', random_state=17)
reps = mapper.fit_transform(tani_dist)
rep_df = pd.DataFrame.from_records(reps, columns=['x', 'y'])
rep_df['compound_id'] = compound_ids
if out_dir is not None:
pdf_path = '%s/%s_tani_umap_proj.pdf' % (out_dir, file_prefix)
pdf = PdfPages(pdf_path)
fig, ax = plt.subplots(figsize=(12,12))
if responses is None:
sns.scatterplot(x='x', y='y', data=rep_df, ax=ax)
else:
rep_df['response'] = responses
sns.scatterplot(x='x', y='y', hue='response', palette=colorpal,
data=rep_df, ax=ax)
ax.set_title("%s, 2D projection based on Tanimoto distance" % title_prefix)
if out_dir is not None:
pdf.savefig(fig)
pdf.close()
# Draw a cluster heatmap based on Tanimoto distance
tani_linkage = linkage(tani_dist, method='complete')
tani_df = pd.DataFrame(tani_dist, columns=compound_ids, index=compound_ids)
if out_dir is not None:
pdf_path = '%s/%s_tanimoto_clustermap.pdf' % (out_dir, file_prefix)
pdf = PdfPages(pdf_path)
g = sns.clustermap(tani_df, row_linkage=tani_linkage, col_linkage=tani_linkage, figsize=(12,12), cmap='plasma')
if out_dir is not None:
pdf.savefig(g.fig)
pdf.close()
#------------------------------------------------------------------------------------------------------------------
def sa200_diversity_plots(ecfp_radius=6):
"""
Plot visualizations of diversity for the 208 compounds selected for phenotypic assays.
"""
sa200_file = '/ds/projdata/gsk_data/ExperimentalDesign/AS200_TS_12Oct18.csv'
out_dir = '/usr/local/data/sa200'
file_prefix = 'sa200'
title_prefix = 'Phenotypic assay compound set'
diversity_plots(sa200_file, datastore=False, bucket=None, title_prefix=title_prefix, out_dir=out_dir, ecfp_radius=ecfp_radius,
smiles_col='canonical_smiles')
#------------------------------------------------------------------------------------------------------------------
def bsep_diversity_plots(ecfp_radius=6):
"""
Plot visualizations of diversity for the compounds in the BSEP PIC50 dataset.
"""
dset_key = 'singletask_liability_datasets/ABCB11_Bile_Salt_Export_Pump_BSEP_membrane_vesicles_Imaging_PIC50.csv'
out_dir = '/usr/local/data/bsep'
os.makedirs(out_dir, exist_ok=True)
title_prefix = 'ABCB11_Bile_Salt_Export_Pump_BSEP_membrane_vesicles_Imaging_PIC50 compound set'
diversity_plots(dset_key, datastore=True, bucket='gsk_ml', title_prefix=title_prefix, out_dir=out_dir, ecfp_radius=ecfp_radius)
#------------------------------------------------------------------------------------------------------------------
def obach_diversity_plots(ecfp_radius=6):
"""
Plot visualizations of diversity for the compounds in the Obach, Lombardo et al PK dataset
"""
# TODO: Put this dataset in the datastore where everybody else can see it
cmpd_file = '/usr/local/data/diversity_plots/obach/LombardoSupplemental_Data_rdsmiles.csv'
out_dir = '/usr/local/data/diversity_plots/obach'
os.makedirs(out_dir, exist_ok=True)
file_prefix = 'obach'
title_prefix = 'Obach PK compound set'
id_col = 'Name'
smiles_col='rdkit_smiles'
# Load table of compound names, IDs and SMILES strings
cmpd_df = pd.read_csv(cmpd_file, index_col=False)
compound_ids = cmpd_df[id_col].values
smiles_strs = cmpd_df[smiles_col].values
ncmpds = len(smiles_strs)
# Strip salts, canonicalize SMILES strings and create RDKit Mol objects
print("Canonicalizing molecules...")
base_mols = [struct_utils.base_mol_from_smiles(smiles) for smiles in smiles_strs]
for i, mol in enumerate(base_mols):
if mol is None:
print('Unable to get base molecule for compound %d = %s' % (i, compound_ids[i]))
base_smiles = [Chem.MolToSmiles(mol) for mol in base_mols]
print("Done")
# Generate ECFP fingerprints
print("Computing fingerprints...")
fps = [AllChem.GetMorganFingerprintAsBitVect(mol, ecfp_radius, 1024) for mol in base_mols if mol is not None]
print("Done")
# Get Tanimoto distance matrix
print("Computing Tanimoto distance matrix...")
tani_dist = dm.tanimoto(fps)
print("Done")
# Draw a UMAP projection based on Tanimoto distance
mapper = umap.UMAP(n_neighbors=10, n_components=2, metric='precomputed', random_state=17)
reps = mapper.fit_transform(tani_dist)
rep_df = pd.DataFrame.from_records(reps, columns=['x', 'y'])
rep_df['compound_id'] = compound_ids
if out_dir is not None:
pdf_path = '%s/%s_tani_umap_proj.pdf' % (out_dir, file_prefix)
pdf = PdfPages(pdf_path)
fig, ax = plt.subplots(figsize=(12,12))
sns.scatterplot(x='x', y='y', data=rep_df, ax=ax)
ax.set_title("%s, 2D projection based on Tanimoto distance" % title_prefix)
main_rep_df = rep_df[(rep_df.x > -20) & (rep_df.y > -20)]
fig, ax = plt.subplots(figsize=(12,12))
sns.scatterplot(x='x', y='y', data=main_rep_df, ax=ax)
ax.set_title("%s, main portion, 2D projection based on Tanimoto distance" % title_prefix)
if out_dir is not None:
pdf.savefig(fig)
pdf.close()
# Draw a cluster heatmap based on Tanimoto distance
tani_linkage = linkage(tani_dist, method='complete')
tani_df = pd.DataFrame(tani_dist, columns=compound_ids, index=compound_ids)
if out_dir is not None:
pdf_path = '%s/%s_tanimoto_clustermap.pdf' % (out_dir, file_prefix)
pdf = PdfPages(pdf_path)
g = sns.clustermap(tani_df, row_linkage=tani_linkage, col_linkage=tani_linkage, figsize=(12,12), cmap='plasma')
if out_dir is not None:
pdf.savefig(g.fig)
pdf.close()
#------------------------------------------------------------------------------------------------------------------
def solubility_diversity_plots(ecfp_radius=6):
"""
Plot visualizations of diversity for the compounds in the Delaney and GSK aqueous solubility datasets
"""
data_dir = '/ds/data/gsk_data/GSK_datasets/solubility'
cmpd_file = '%s/delaney-processed.csv' % data_dir
out_dir = '/usr/local/data/diversity_plots/solubility'
os.makedirs(out_dir, exist_ok=True)
file_prefix = 'delaney'
title_prefix = 'Delaney solubility compound set'
diversity_plots(cmpd_file, file_prefix, title_prefix, out_dir=out_dir, ecfp_radius=ecfp_radius, id_col='Compound ID')
cmpd_file = '%s/ATOM_GSK_Solubility_Aqueous.csv' % data_dir
title_prefix = 'GSK Aqueous Solubility compound set'
file_prefix = 'gsk_aq_sol'
diversity_plots(cmpd_file, file_prefix, title_prefix, out_dir=out_dir, ecfp_radius=ecfp_radius, id_col='compound_id')
#------------------------------------------------------------------------------------------------------------------
def compare_solubility_datasets(ecfp_radius=6):
"""
Plot projections of Delaney and GSK solubility datasets using the same UMAP projectors.
"""
data_dir = '/ds/data/gsk_data/GSK_datasets/solubility'
del_cmpd_file = '%s/delaney-processed.csv' % data_dir
out_dir = '/usr/local/data/diversity_plots/solubility'
smiles_col='rdkit_smiles'
del_id_col = 'Compound ID'
# Load table of compound names, IDs and SMILES strings
del_cmpd_df = pd.read_csv(del_cmpd_file, index_col=False)
del_compound_ids = del_cmpd_df[del_id_col].values
del_smiles_strs = del_cmpd_df[smiles_col].values
# Strip salts, canonicalize SMILES strings and create RDKit Mol objects
base_mols = [struct_utils.base_mol_from_smiles(smiles) for smiles in del_smiles_strs]
for i, mol in enumerate(base_mols):
if mol is None:
print('Unable to get base molecule for compound %d = %s' % (i, del_compound_ids[i]))
base_smiles = [Chem.MolToSmiles(mol) for mol in base_mols]
del_fps = [AllChem.GetMorganFingerprintAsBitVect(mol, ecfp_radius, 1024) for mol in base_mols if mol is not None]
gsk_cmpd_file = '%s/ATOM_GSK_Solubility_Aqueous.csv' % data_dir
gsk_cmpd_df = pd.read_csv(gsk_cmpd_file, index_col=False)
gsk_smiles_strs = gsk_cmpd_df[smiles_col].values
gsk_id_col = 'compound_id'
# Check for common structures between datasets
dup_smiles = list(set(gsk_smiles_strs) & set(del_smiles_strs))
print("GSK and Delaney compound sets have %d SMILES strings in common" % len(dup_smiles))
if len(dup_smiles) > 0:
gsk_cmpd_df = gsk_cmpd_df[~gsk_cmpd_df.rdkit_smiles.isin(dup_smiles)]
gsk_smiles_strs = gsk_cmpd_df[smiles_col].values
gsk_compound_ids = gsk_cmpd_df[gsk_id_col].values
base_mols = [struct_utils.base_mol_from_smiles(smiles) for smiles in gsk_smiles_strs]
for i, mol in enumerate(base_mols):
if mol is None:
print('Unable to get base molecule for compound %d = %s' % (i, del_compound_ids[i]))
base_smiles = [Chem.MolToSmiles(mol) for mol in base_mols]
gsk_fps = [AllChem.GetMorganFingerprintAsBitVect(mol, ecfp_radius, 1024) for mol in base_mols if mol is not None]
# Train a UMAP projector with Delaney set, then use it to project both data sets
del_mapper = umap.UMAP(n_neighbors=10, n_components=2, metric='jaccard', random_state=17)
del_reps = del_mapper.fit_transform(del_fps)
gsk_reps = del_mapper.transform(gsk_fps)
del_rep_df = pd.DataFrame.from_records(del_reps, columns=['x', 'y'])
del_rep_df['compound_id'] = del_compound_ids
del_rep_df['dataset'] = 'Delaney'
gsk_rep_df = pd.DataFrame.from_records(gsk_reps, columns=['x', 'y'])
gsk_rep_df['compound_id'] = gsk_compound_ids
gsk_rep_df['dataset'] = 'GSK Aq Sol'
rep_df = pd.concat((del_rep_df, gsk_rep_df), ignore_index=True)
dataset_pal = {'Delaney' : 'forestgreen', 'GSK Aq Sol' : 'orange'}
pdf_path = '%s/delaney_gsk_aq_sol_umap_proj.pdf' % out_dir
pdf = PdfPages(pdf_path)
fig, ax = plt.subplots(figsize=(12,12))
g = sns.scatterplot(x='x', y='y', ax=ax, hue='dataset', style='dataset', palette=dataset_pal, data=rep_df)
ax.set_title("Solubility dataset fingerprints, UMAP projection trained on Delaney data", fontdict={'fontsize' : 12})
pdf.savefig(fig)
pdf.close()
# Train a UMAP projector with GSK set, then use it to project both data sets
gsk_mapper = umap.UMAP(n_neighbors=10, n_components=2, metric='jaccard', random_state=17)
gsk_reps = gsk_mapper.fit_transform(gsk_fps)
del_reps = gsk_mapper.transform(del_fps)
del_rep_df = pd.DataFrame.from_records(del_reps, columns=['x', 'y'])
del_rep_df['compound_id'] = del_compound_ids
del_rep_df['dataset'] = 'Delaney'
gsk_rep_df = pd.DataFrame.from_records(gsk_reps, columns=['x', 'y'])
gsk_rep_df['compound_id'] = gsk_compound_ids
gsk_rep_df['dataset'] = 'GSK Aq Sol'
rep_df = pd.concat((gsk_rep_df, del_rep_df), ignore_index=True)
dataset_pal = {'Delaney' : 'forestgreen', 'GSK Aq Sol' : 'orange'}
pdf_path = '%s/gsk_aq_sol_delaney_umap_proj.pdf' % out_dir
pdf = PdfPages(pdf_path)
fig, ax = plt.subplots(figsize=(12,12))
g = sns.scatterplot(x='x', y='y', ax=ax, hue='dataset', style='dataset', palette=dataset_pal, data=rep_df)
ax.set_title("Solubility dataset fingerprints, UMAP projection trained on GSK aqueous solubility data", fontdict={'fontsize' : 12})
pdf.savefig(fig)
pdf.close()
#------------------------------------------------------------------------------------------------------------------
def compare_obach_gsk_aq_sol(ecfp_radius=6):
"""
Plot projections of Obach and GSK solubility datasets using the same UMAP projectors.
"""
obach_cmpd_file = '/usr/local/data/diversity_plots/obach/LombardoSupplemental_Data_rdsmiles.csv'
out_dir = '/usr/local/data/diversity_plots/obach'
obach_id_col = 'Name'
smiles_col='rdkit_smiles'
# Load table of compound names, IDs and SMILES strings
obach_cmpd_df = pd.read_csv(obach_cmpd_file, index_col=False)
# Sample the same number of compounds as in the GSK set
obach_cmpd_df = obach_cmpd_df.sample(n=732, axis=0)
obach_compound_ids = obach_cmpd_df[obach_id_col].values
obach_smiles_strs = obach_cmpd_df[smiles_col].values
# Strip salts, canonicalize SMILES strings and create RDKit Mol objects
base_mols = [struct_utils.base_mol_from_smiles(smiles) for smiles in obach_smiles_strs]
for i, mol in enumerate(base_mols):
if mol is None:
print('Unable to get base molecule for compound %d = %s' % (i, obach_compound_ids[i]))
base_smiles = [Chem.MolToSmiles(mol) for mol in base_mols]
obach_fps = [AllChem.GetMorganFingerprintAsBitVect(mol, ecfp_radius, 1024) for mol in base_mols if mol is not None]
# Load the GSK dataset
gsk_data_dir = '/ds/data/gsk_data/GSK_datasets/solubility'
gsk_cmpd_file = '%s/ATOM_GSK_Solubility_Aqueous.csv' % gsk_data_dir
gsk_cmpd_df = pd.read_csv(gsk_cmpd_file, index_col=False)
gsk_smiles_strs = gsk_cmpd_df[smiles_col].values
gsk_id_col = 'compound_id'
# Check for common structures between datasets
dup_smiles = list(set(gsk_smiles_strs) & set(obach_smiles_strs))
print("GSK and Obach compound sets have %d SMILES strings in common" % len(dup_smiles))
if len(dup_smiles) > 0:
gsk_cmpd_df = gsk_cmpd_df[~gsk_cmpd_df.rdkit_smiles.isin(dup_smiles)]
gsk_smiles_strs = gsk_cmpd_df[smiles_col].values
gsk_compound_ids = gsk_cmpd_df[gsk_id_col].values
base_mols = [struct_utils.base_mol_from_smiles(smiles) for smiles in gsk_smiles_strs]
for i, mol in enumerate(base_mols):
if mol is None:
print('Unable to get base molecule for compound %d = %s' % (i, obach_compound_ids[i]))
base_smiles = [Chem.MolToSmiles(mol) for mol in base_mols]
gsk_fps = [AllChem.GetMorganFingerprintAsBitVect(mol, ecfp_radius, 1024) for mol in base_mols if mol is not None]
# Train a UMAP projector with Obach set, then use it to project both data sets
obach_mapper = umap.UMAP(n_neighbors=10, n_components=2, metric='jaccard', random_state=17)
obach_reps = obach_mapper.fit_transform(obach_fps)
gsk_reps = obach_mapper.transform(gsk_fps)
obach_rep_df = pd.DataFrame.from_records(obach_reps, columns=['x', 'y'])
obach_rep_df['compound_id'] = obach_compound_ids
obach_rep_df['dataset'] = 'Obach'
gsk_rep_df = pd.DataFrame.from_records(gsk_reps, columns=['x', 'y'])
gsk_rep_df['compound_id'] = gsk_compound_ids
gsk_rep_df['dataset'] = 'GSK Aq Sol'
rep_df = pd.concat((obach_rep_df, gsk_rep_df), ignore_index=True)
#main_rep_df = rep_df[(rep_df.x > -20) & (rep_df.y > -20)]
dataset_pal = {'Obach' : 'blue', 'GSK Aq Sol' : 'orange'}
pdf_path = '%s/obach_gsk_aq_sol_umap_proj.pdf' % out_dir
pdf = PdfPages(pdf_path)
fig, ax = plt.subplots(figsize=(12,12))
g = sns.scatterplot(x='x', y='y', ax=ax, hue='dataset', style='dataset', palette=dataset_pal, data=rep_df)
ax.set_title("Obach and GSK solubility dataset fingerprints, UMAP projection trained on Obach data", fontdict={'fontsize' : 12})
pdf.savefig(fig)
pdf.close()
#------------------------------------------------------------------------------------------------------------------
def liability_dset_diversity(bucket='gsk_ml', feat_type='descriptors', dist_metric='cosine', **metric_kwargs):
"""
Load datasets from datastore, featurize them, and plot distributions of their inter-compound
distances.
"""
log = logging.getLogger('ATOM')
ds_client = dsf.config_client()
ds_table = dsf.search_datasets_by_key_value(key='param', value=['PIC50','PEC50'], operator='in',
bucket=bucket, client=ds_client)
dset_keys = ds_table.dataset_key.values
metadata = ds_table.metadata.values
split = 'random'
task_names = []
num_cmpds = []
for i, dset_key in enumerate(dset_keys):
md_dict = dsf.metadata_to_dict(metadata[i])
task_name = md_dict['task_name']
num_cmpds = md_dict['CMPD_COUNT'][0]
log.warning("Loading dataset for %s, %d compounds" % (task_name, num_cmpds))
dset_df = dsf.retrieve_dataset_by_datasetkey(dset_key, bucket, ds_client)
dataset_dir = os.path.dirname(dset_key)
dataset_file = os.path.basename(dset_key)
if feat_type == 'descriptors':
params = argparse.Namespace(dataset_dir=dataset_dir,
dataset_file=dataset_file,
y=task_name,
bucket=bucket,
descriptor_key='all_GSK_Compound_2D_3D_MOE_Descriptors_Scaled_With_Smiles_And_Inchi',
descriptor_type='MOE',
splitter=split,
id_col='compound_id',
smiles_col='rdkit_smiles',
featurizer='descriptors',
prediction_type='regression',
system='twintron-blue',
datastore=True,
transformers=True)
elif feat_type == 'ECFP':
params = argparse.Namespace(dataset_dir=dataset_dir,
dataset_file=dataset_file,
y=task_name,
bucket=bucket,
splitter=split,
id_col='compound_id',
smiles_col='rdkit_smiles',
featurizer='ECFP',
prediction_type='regression',
system='twintron-blue',
datastore=True,
ecfp_radius=2, ecfp_size=1024,
transformers=True)
else:
log.error("Feature type %s not supported" % feat_type)
return
log.warning("Featurizing data with %s featurizer" % feat_type)
model_dataset = md.MinimalDataset(params)
model_dataset.get_featurized_data(dset_df)
num_cmpds = model_dataset.dataset.X.shape[0]
if num_cmpds > 50000:
log.warning("Too many compounds to compute distance matrix: %d" % num_cmpds)
continue
plot_dataset_dist_distr(model_dataset.dataset, feat_type, dist_metric, task_name, **metric_kwargs)
# ------------------------------------------------------------------------------------------------------------------
def get_dset_diversity(dset_key, ds_client, bucket='gsk_ml', feat_type='descriptors', dist_metric='cosine',
**metric_kwargs):
"""
Load datasets from datastore, featurize them, and plot distributions of their inter-compound
distances.
"""
log = logging.getLogger('ATOM')
dset_df = dsf.retrieve_dataset_by_datasetkey(dset_key, bucket, ds_client)
if feat_type == 'descriptors':
params = parse.wrapper(dict(
dataset_key=dset_key,
bucket=bucket,
descriptor_key='/ds/projdata/gsk_data/GSK_Descriptors/GSK_2D_3D_MOE_Descriptors_By_Variant_ID_With_Base_RDKit_SMILES.feather',
descriptor_type='moe',
featurizer='descriptors',
system='twintron-blue',
datastore=True,
transformers=True))
elif feat_type == 'ECFP':
params = parse.wrapper(dict(
dataset_key=dset_key,
bucket=bucket,
featurizer='ECFP',
system='twintron-blue',
datastore=True,
ecfp_radius=2,
ecfp_size=1024,
transformers=True))
else:
log.error("Feature type %s not supported" % feat_type)
return
metadata = dsf.get_keyval(dataset_key=dset_key, bucket=bucket)
if 'id_col' in metadata.keys():
params.id_col = metadata['id_col']
if 'param' in metadata.keys():
params.response_cols = [metadata['param']]
elif 'response_col' in metadata.keys():
params.response_cols = [metadata['response_col']]
elif 'response_cols' in metadata.keys():
params.response_cols = metadata['response_cols']
if 'smiles_col' in metadata.keys():
params.smiles_col = metadata['smiles_col']
if 'class_number' in metadata.keys():
params.class_number = metadata['class_number']
params.dataset_name = dset_key.split('/')[-1].rstrip('.csv')
log.warning("Featurizing data with %s featurizer" % feat_type)
featurization = feat.create_featurization(params)
model_dataset = md.MinimalDataset(params, featurization)
model_dataset.get_featurized_data(dset_df)
num_cmpds = model_dataset.dataset.X.shape[0]
if num_cmpds > 50000:
log.warning("Too many compounds to compute distance matrix: %d" % num_cmpds)
return
# plot_dataset_dist_distr(model_dataset.dataset, feat_type, dist_metric, params.response_cols, **metric_kwargs)
dists = cd.calc_dist_diskdataset('descriptors', dist_metric, model_dataset.dataset, calc_type='all')
import scipy
dists = scipy.spatial.distance.squareform(dists)
res_dir = '/ds/projdata/gsk_data/model_analysis/'
plt_dir = '%s/Plots' % res_dir
file_prefix = dset_key.split('/')[-1].rstrip('.csv')
mcs_linkage = linkage(dists, method='complete')
pdf_path = '%s/%s_mcs_clustermap.pdf' % (plt_dir, file_prefix)
pdf = PdfPages(pdf_path)
g = sns.clustermap(dists, row_linkage=mcs_linkage, col_linkage=mcs_linkage, figsize=(12, 12), cmap='plasma')
if plt_dir is not None:
pdf.savefig(g.fig)
pdf.close()
return dists
| [
"argparse.Namespace",
"matplotlib.backends.backend_pdf.PdfPages",
"matplotlib.rc",
"atomsci.ddm.utils.struct_utils.base_mol_from_smiles",
"pandas.read_csv",
"scipy.cluster.hierarchy.linkage",
"atomsci.ddm.utils.datastore_functions.config_client",
"rdkit.Chem.MolToSmiles",
"atomsci.ddm.pipeline.model... | [((859, 895), 'matplotlib.rc', 'matplotlib.rc', (['"""xtick"""'], {'labelsize': '(12)'}), "('xtick', labelsize=12)\n", (872, 895), False, 'import matplotlib\n'), ((896, 932), 'matplotlib.rc', 'matplotlib.rc', (['"""ytick"""'], {'labelsize': '(12)'}), "('ytick', labelsize=12)\n", (909, 932), False, 'import matplotlib\n'), ((933, 968), 'matplotlib.rc', 'matplotlib.rc', (['"""axes"""'], {'labelsize': '(12)'}), "('axes', labelsize=12)\n", (946, 968), False, 'import matplotlib\n'), ((970, 1026), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)-15s %(message)s"""'}), "(format='%(asctime)-15s %(message)s')\n", (989, 1026), False, 'import logging\n'), ((1438, 1463), 'logging.getLogger', 'logging.getLogger', (['"""ATOM"""'], {}), "('ATOM')\n", (1455, 1463), False, 'import logging\n'), ((1735, 1830), 'atomsci.ddm.pipeline.chem_diversity.calc_dist_diskdataset', 'cd.calc_dist_diskdataset', (['feat_type', 'dist_metric', 'dataset'], {'calc_type': '"""all"""'}), "(feat_type, dist_metric, dataset, calc_type='all',\n **metric_kwargs)\n", (1759, 1830), True, 'from atomsci.ddm.pipeline import chem_diversity as cd\n'), ((2114, 2139), 'scipy.stats.kde.gaussian_kde', 'gaussian_kde', (['dist_sample'], {}), '(dist_sample)\n', (2126, 2139), False, 'from scipy.stats.kde import gaussian_kde\n'), ((2247, 2279), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(8.0, 8.0)'}), '(figsize=(8.0, 8.0))\n', (2259, 2279), True, 'import matplotlib.pyplot as plt\n'), ((4190, 4240), 'numpy.array', 'np.array', (['[(mol is not None) for mol in base_mols]'], {}), '([(mol is not None) for mol in base_mols])\n', (4198, 4240), True, 'import numpy as np\n'), ((8030, 8046), 'atomsci.ddm.pipeline.dist_metrics.tanimoto', 'dm.tanimoto', (['fps'], {}), '(fps)\n', (8041, 8046), True, 'from atomsci.ddm.pipeline import dist_metrics as dm\n'), ((8134, 8233), 'umap.UMAP', 'umap.UMAP', ([], {'n_neighbors': '(20)', 'min_dist': '(0.1)', 'n_components': '(2)', 'metric': '"""precomputed"""', 'random_state': '(17)'}), "(n_neighbors=20, min_dist=0.1, n_components=2, metric=\n 'precomputed', random_state=17)\n", (8143, 8233), False, 'import umap\n'), ((8285, 8336), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', (['reps'], {'columns': "['x', 'y']"}), "(reps, columns=['x', 'y'])\n", (8310, 8336), True, 'import pandas as pd\n'), ((8524, 8554), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(12, 12)'}), '(figsize=(12, 12))\n', (8536, 8554), True, 'import matplotlib.pyplot as plt\n'), ((9032, 9069), 'scipy.cluster.hierarchy.linkage', 'linkage', (['tani_dist'], {'method': '"""complete"""'}), "(tani_dist, method='complete')\n", (9039, 9069), False, 'from scipy.cluster.hierarchy import linkage\n'), ((9084, 9149), 'pandas.DataFrame', 'pd.DataFrame', (['tani_dist'], {'columns': 'compound_ids', 'index': 'compound_ids'}), '(tani_dist, columns=compound_ids, index=compound_ids)\n', (9096, 9149), True, 'import pandas as pd\n'), ((9295, 9407), 'seaborn.clustermap', 'sns.clustermap', (['tani_df'], {'row_linkage': 'tani_linkage', 'col_linkage': 'tani_linkage', 'figsize': '(12, 12)', 'cmap': '"""plasma"""'}), "(tani_df, row_linkage=tani_linkage, col_linkage=tani_linkage,\n figsize=(12, 12), cmap='plasma')\n", (9309, 9407), True, 'import seaborn as sns\n'), ((10539, 10574), 'os.makedirs', 'os.makedirs', (['out_dir'], {'exist_ok': '(True)'}), '(out_dir, exist_ok=True)\n', (10550, 10574), False, 'import os\n'), ((11309, 11344), 'os.makedirs', 'os.makedirs', (['out_dir'], {'exist_ok': '(True)'}), '(out_dir, exist_ok=True)\n', (11320, 11344), False, 'import os\n'), ((11540, 11579), 'pandas.read_csv', 'pd.read_csv', (['cmpd_file'], {'index_col': '(False)'}), '(cmpd_file, index_col=False)\n', (11551, 11579), True, 'import pandas as pd\n'), ((12447, 12463), 'atomsci.ddm.pipeline.dist_metrics.tanimoto', 'dm.tanimoto', (['fps'], {}), '(fps)\n', (12458, 12463), True, 'from atomsci.ddm.pipeline import dist_metrics as dm\n'), ((12551, 12636), 'umap.UMAP', 'umap.UMAP', ([], {'n_neighbors': '(10)', 'n_components': '(2)', 'metric': '"""precomputed"""', 'random_state': '(17)'}), "(n_neighbors=10, n_components=2, metric='precomputed', random_state=17\n )\n", (12560, 12636), False, 'import umap\n'), ((12688, 12739), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', (['reps'], {'columns': "['x', 'y']"}), "(reps, columns=['x', 'y'])\n", (12713, 12739), True, 'import pandas as pd\n'), ((12927, 12957), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(12, 12)'}), '(figsize=(12, 12))\n', (12939, 12957), True, 'import matplotlib.pyplot as plt\n'), ((12961, 13010), 'seaborn.scatterplot', 'sns.scatterplot', ([], {'x': '"""x"""', 'y': '"""y"""', 'data': 'rep_df', 'ax': 'ax'}), "(x='x', y='y', data=rep_df, ax=ax)\n", (12976, 13010), True, 'import seaborn as sns\n'), ((13168, 13198), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(12, 12)'}), '(figsize=(12, 12))\n', (13180, 13198), True, 'import matplotlib.pyplot as plt\n'), ((13202, 13256), 'seaborn.scatterplot', 'sns.scatterplot', ([], {'x': '"""x"""', 'y': '"""y"""', 'data': 'main_rep_df', 'ax': 'ax'}), "(x='x', y='y', data=main_rep_df, ax=ax)\n", (13217, 13256), True, 'import seaborn as sns\n'), ((13497, 13534), 'scipy.cluster.hierarchy.linkage', 'linkage', (['tani_dist'], {'method': '"""complete"""'}), "(tani_dist, method='complete')\n", (13504, 13534), False, 'from scipy.cluster.hierarchy import linkage\n'), ((13549, 13614), 'pandas.DataFrame', 'pd.DataFrame', (['tani_dist'], {'columns': 'compound_ids', 'index': 'compound_ids'}), '(tani_dist, columns=compound_ids, index=compound_ids)\n', (13561, 13614), True, 'import pandas as pd\n'), ((13760, 13872), 'seaborn.clustermap', 'sns.clustermap', (['tani_df'], {'row_linkage': 'tani_linkage', 'col_linkage': 'tani_linkage', 'figsize': '(12, 12)', 'cmap': '"""plasma"""'}), "(tani_df, row_linkage=tani_linkage, col_linkage=tani_linkage,\n figsize=(12, 12), cmap='plasma')\n", (13774, 13872), True, 'import seaborn as sns\n'), ((14407, 14442), 'os.makedirs', 'os.makedirs', (['out_dir'], {'exist_ok': '(True)'}), '(out_dir, exist_ok=True)\n', (14418, 14442), False, 'import os\n'), ((15508, 15551), 'pandas.read_csv', 'pd.read_csv', (['del_cmpd_file'], {'index_col': '(False)'}), '(del_cmpd_file, index_col=False)\n', (15519, 15551), True, 'import pandas as pd\n'), ((16256, 16299), 'pandas.read_csv', 'pd.read_csv', (['gsk_cmpd_file'], {'index_col': '(False)'}), '(gsk_cmpd_file, index_col=False)\n', (16267, 16299), True, 'import pandas as pd\n'), ((17344, 17420), 'umap.UMAP', 'umap.UMAP', ([], {'n_neighbors': '(10)', 'n_components': '(2)', 'metric': '"""jaccard"""', 'random_state': '(17)'}), "(n_neighbors=10, n_components=2, metric='jaccard', random_state=17)\n", (17353, 17420), False, 'import umap\n'), ((17532, 17587), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', (['del_reps'], {'columns': "['x', 'y']"}), "(del_reps, columns=['x', 'y'])\n", (17557, 17587), True, 'import pandas as pd\n'), ((17692, 17747), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', (['gsk_reps'], {'columns': "['x', 'y']"}), "(gsk_reps, columns=['x', 'y'])\n", (17717, 17747), True, 'import pandas as pd\n'), ((17851, 17905), 'pandas.concat', 'pd.concat', (['(del_rep_df, gsk_rep_df)'], {'ignore_index': '(True)'}), '((del_rep_df, gsk_rep_df), ignore_index=True)\n', (17860, 17905), True, 'import pandas as pd\n'), ((18050, 18068), 'matplotlib.backends.backend_pdf.PdfPages', 'PdfPages', (['pdf_path'], {}), '(pdf_path)\n', (18058, 18068), False, 'from matplotlib.backends.backend_pdf import PdfPages\n'), ((18083, 18113), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(12, 12)'}), '(figsize=(12, 12))\n', (18095, 18113), True, 'import matplotlib.pyplot as plt\n'), ((18121, 18227), 'seaborn.scatterplot', 'sns.scatterplot', ([], {'x': '"""x"""', 'y': '"""y"""', 'ax': 'ax', 'hue': '"""dataset"""', 'style': '"""dataset"""', 'palette': 'dataset_pal', 'data': 'rep_df'}), "(x='x', y='y', ax=ax, hue='dataset', style='dataset',\n palette=dataset_pal, data=rep_df)\n", (18136, 18227), True, 'import seaborn as sns\n'), ((18481, 18557), 'umap.UMAP', 'umap.UMAP', ([], {'n_neighbors': '(10)', 'n_components': '(2)', 'metric': '"""jaccard"""', 'random_state': '(17)'}), "(n_neighbors=10, n_components=2, metric='jaccard', random_state=17)\n", (18490, 18557), False, 'import umap\n'), ((18669, 18724), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', (['del_reps'], {'columns': "['x', 'y']"}), "(del_reps, columns=['x', 'y'])\n", (18694, 18724), True, 'import pandas as pd\n'), ((18829, 18884), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', (['gsk_reps'], {'columns': "['x', 'y']"}), "(gsk_reps, columns=['x', 'y'])\n", (18854, 18884), True, 'import pandas as pd\n'), ((18988, 19042), 'pandas.concat', 'pd.concat', (['(gsk_rep_df, del_rep_df)'], {'ignore_index': '(True)'}), '((gsk_rep_df, del_rep_df), ignore_index=True)\n', (18997, 19042), True, 'import pandas as pd\n'), ((19187, 19205), 'matplotlib.backends.backend_pdf.PdfPages', 'PdfPages', (['pdf_path'], {}), '(pdf_path)\n', (19195, 19205), False, 'from matplotlib.backends.backend_pdf import PdfPages\n'), ((19220, 19250), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(12, 12)'}), '(figsize=(12, 12))\n', (19232, 19250), True, 'import matplotlib.pyplot as plt\n'), ((19258, 19364), 'seaborn.scatterplot', 'sns.scatterplot', ([], {'x': '"""x"""', 'y': '"""y"""', 'ax': 'ax', 'hue': '"""dataset"""', 'style': '"""dataset"""', 'palette': 'dataset_pal', 'data': 'rep_df'}), "(x='x', y='y', ax=ax, hue='dataset', style='dataset',\n palette=dataset_pal, data=rep_df)\n", (19273, 19364), True, 'import seaborn as sns\n'), ((20096, 20141), 'pandas.read_csv', 'pd.read_csv', (['obach_cmpd_file'], {'index_col': '(False)'}), '(obach_cmpd_file, index_col=False)\n', (20107, 20141), True, 'import pandas as pd\n'), ((21071, 21114), 'pandas.read_csv', 'pd.read_csv', (['gsk_cmpd_file'], {'index_col': '(False)'}), '(gsk_cmpd_file, index_col=False)\n', (21082, 21114), True, 'import pandas as pd\n'), ((22161, 22237), 'umap.UMAP', 'umap.UMAP', ([], {'n_neighbors': '(10)', 'n_components': '(2)', 'metric': '"""jaccard"""', 'random_state': '(17)'}), "(n_neighbors=10, n_components=2, metric='jaccard', random_state=17)\n", (22170, 22237), False, 'import umap\n'), ((22359, 22416), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', (['obach_reps'], {'columns': "['x', 'y']"}), "(obach_reps, columns=['x', 'y'])\n", (22384, 22416), True, 'import pandas as pd\n'), ((22525, 22580), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', (['gsk_reps'], {'columns': "['x', 'y']"}), "(gsk_reps, columns=['x', 'y'])\n", (22550, 22580), True, 'import pandas as pd\n'), ((22684, 22740), 'pandas.concat', 'pd.concat', (['(obach_rep_df, gsk_rep_df)'], {'ignore_index': '(True)'}), '((obach_rep_df, gsk_rep_df), ignore_index=True)\n', (22693, 22740), True, 'import pandas as pd\n'), ((22937, 22955), 'matplotlib.backends.backend_pdf.PdfPages', 'PdfPages', (['pdf_path'], {}), '(pdf_path)\n', (22945, 22955), False, 'from matplotlib.backends.backend_pdf import PdfPages\n'), ((22970, 23000), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(12, 12)'}), '(figsize=(12, 12))\n', (22982, 23000), True, 'import matplotlib.pyplot as plt\n'), ((23008, 23114), 'seaborn.scatterplot', 'sns.scatterplot', ([], {'x': '"""x"""', 'y': '"""y"""', 'ax': 'ax', 'hue': '"""dataset"""', 'style': '"""dataset"""', 'palette': 'dataset_pal', 'data': 'rep_df'}), "(x='x', y='y', ax=ax, hue='dataset', style='dataset',\n palette=dataset_pal, data=rep_df)\n", (23023, 23114), True, 'import seaborn as sns\n'), ((23647, 23672), 'logging.getLogger', 'logging.getLogger', (['"""ATOM"""'], {}), "('ATOM')\n", (23664, 23672), False, 'import logging\n'), ((23689, 23708), 'atomsci.ddm.utils.datastore_functions.config_client', 'dsf.config_client', ([], {}), '()\n', (23706, 23708), True, 'from atomsci.ddm.utils import datastore_functions as dsf\n'), ((23724, 23847), 'atomsci.ddm.utils.datastore_functions.search_datasets_by_key_value', 'dsf.search_datasets_by_key_value', ([], {'key': '"""param"""', 'value': "['PIC50', 'PEC50']", 'operator': '"""in"""', 'bucket': 'bucket', 'client': 'ds_client'}), "(key='param', value=['PIC50', 'PEC50'],\n operator='in', bucket=bucket, client=ds_client)\n", (23756, 23847), True, 'from atomsci.ddm.utils import datastore_functions as dsf\n'), ((2020, 2059), 'numpy.random.choice', 'np.random.choice', (['dists'], {'size': 'ndist_max'}), '(dists, size=ndist_max)\n', (2036, 2059), True, 'import numpy as np\n'), ((3193, 3245), 'atomsci.ddm.utils.datastore_functions.retrieve_dataset_by_datasetkey', 'dsf.retrieve_dataset_by_datasetkey', (['dset_key', 'bucket'], {}), '(dset_key, bucket)\n', (3227, 3245), True, 'from atomsci.ddm.utils import datastore_functions as dsf\n'), ((3274, 3312), 'pandas.read_csv', 'pd.read_csv', (['dset_key'], {'index_col': '(False)'}), '(dset_key, index_col=False)\n', (3285, 3312), True, 'import pandas as pd\n'), ((4856, 4917), 'rdkit.Chem.AllChem.GetMorganFingerprintAsBitVect', 'AllChem.GetMorganFingerprintAsBitVect', (['mol', 'ecfp_radius', '(1024)'], {}), '(mol, ecfp_radius, 1024)\n', (4893, 4917), False, 'from rdkit.Chem import AllChem, Draw\n'), ((5130, 5147), 'atomsci.ddm.pipeline.dist_metrics.mcs', 'dm.mcs', (['base_mols'], {}), '(base_mols)\n', (5136, 5147), True, 'from atomsci.ddm.pipeline import dist_metrics as dm\n'), ((5552, 5648), 'pandas.DataFrame', 'pd.DataFrame', (["{'compound_1': cmpd1, 'compound_2': cmpd2, 'dist': dist, 'i': ind1, 'j': ind2}"], {}), "({'compound_1': cmpd1, 'compound_2': cmpd2, 'dist': dist, 'i':\n ind1, 'j': ind2})\n", (5564, 5648), True, 'import pandas as pd\n'), ((6409, 6445), 'scipy.cluster.hierarchy.linkage', 'linkage', (['mcs_dist'], {'method': '"""complete"""'}), "(mcs_dist, method='complete')\n", (6416, 6445), False, 'from scipy.cluster.hierarchy import linkage\n'), ((6463, 6527), 'pandas.DataFrame', 'pd.DataFrame', (['mcs_dist'], {'columns': 'compound_ids', 'index': 'compound_ids'}), '(mcs_dist, columns=compound_ids, index=compound_ids)\n', (6475, 6527), True, 'import pandas as pd\n'), ((6684, 6793), 'seaborn.clustermap', 'sns.clustermap', (['mcs_df'], {'row_linkage': 'mcs_linkage', 'col_linkage': 'mcs_linkage', 'figsize': '(12, 12)', 'cmap': '"""plasma"""'}), "(mcs_df, row_linkage=mcs_linkage, col_linkage=mcs_linkage,\n figsize=(12, 12), cmap='plasma')\n", (6698, 6793), True, 'import seaborn as sns\n'), ((6953, 7052), 'umap.UMAP', 'umap.UMAP', ([], {'n_neighbors': '(20)', 'min_dist': '(0.1)', 'n_components': '(2)', 'metric': '"""precomputed"""', 'random_state': '(17)'}), "(n_neighbors=20, min_dist=0.1, n_components=2, metric=\n 'precomputed', random_state=17)\n", (6962, 7052), False, 'import umap\n'), ((7111, 7162), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', (['reps'], {'columns': "['x', 'y']"}), "(reps, columns=['x', 'y'])\n", (7136, 7162), True, 'import pandas as pd\n'), ((7369, 7399), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(12, 12)'}), '(figsize=(12, 12))\n', (7381, 7399), True, 'import matplotlib.pyplot as plt\n'), ((8491, 8509), 'matplotlib.backends.backend_pdf.PdfPages', 'PdfPages', (['pdf_path'], {}), '(pdf_path)\n', (8499, 8509), False, 'from matplotlib.backends.backend_pdf import PdfPages\n'), ((8588, 8637), 'seaborn.scatterplot', 'sns.scatterplot', ([], {'x': '"""x"""', 'y': '"""y"""', 'data': 'rep_df', 'ax': 'ax'}), "(x='x', y='y', data=rep_df, ax=ax)\n", (8603, 8637), True, 'import seaborn as sns\n'), ((8695, 8782), 'seaborn.scatterplot', 'sns.scatterplot', ([], {'x': '"""x"""', 'y': '"""y"""', 'hue': '"""response"""', 'palette': 'colorpal', 'data': 'rep_df', 'ax': 'ax'}), "(x='x', y='y', hue='response', palette=colorpal, data=rep_df,\n ax=ax)\n", (8710, 8782), True, 'import seaborn as sns\n'), ((9268, 9286), 'matplotlib.backends.backend_pdf.PdfPages', 'PdfPages', (['pdf_path'], {}), '(pdf_path)\n', (9276, 9286), False, 'from matplotlib.backends.backend_pdf import PdfPages\n'), ((11832, 11873), 'atomsci.ddm.utils.struct_utils.base_mol_from_smiles', 'struct_utils.base_mol_from_smiles', (['smiles'], {}), '(smiles)\n', (11865, 11873), False, 'from atomsci.ddm.utils import struct_utils\n'), ((12077, 12098), 'rdkit.Chem.MolToSmiles', 'Chem.MolToSmiles', (['mol'], {}), '(mol)\n', (12093, 12098), False, 'from rdkit import Chem\n'), ((12223, 12284), 'rdkit.Chem.AllChem.GetMorganFingerprintAsBitVect', 'AllChem.GetMorganFingerprintAsBitVect', (['mol', 'ecfp_radius', '(1024)'], {}), '(mol, ecfp_radius, 1024)\n', (12260, 12284), False, 'from rdkit.Chem import AllChem, Draw\n'), ((12894, 12912), 'matplotlib.backends.backend_pdf.PdfPages', 'PdfPages', (['pdf_path'], {}), '(pdf_path)\n', (12902, 12912), False, 'from matplotlib.backends.backend_pdf import PdfPages\n'), ((13733, 13751), 'matplotlib.backends.backend_pdf.PdfPages', 'PdfPages', (['pdf_path'], {}), '(pdf_path)\n', (13741, 13751), False, 'from matplotlib.backends.backend_pdf import PdfPages\n'), ((15753, 15794), 'atomsci.ddm.utils.struct_utils.base_mol_from_smiles', 'struct_utils.base_mol_from_smiles', (['smiles'], {}), '(smiles)\n', (15786, 15794), False, 'from atomsci.ddm.utils import struct_utils\n'), ((16006, 16027), 'rdkit.Chem.MolToSmiles', 'Chem.MolToSmiles', (['mol'], {}), '(mol)\n', (16022, 16027), False, 'from rdkit import Chem\n'), ((16065, 16126), 'rdkit.Chem.AllChem.GetMorganFingerprintAsBitVect', 'AllChem.GetMorganFingerprintAsBitVect', (['mol', 'ecfp_radius', '(1024)'], {}), '(mol, ecfp_radius, 1024)\n', (16102, 16126), False, 'from rdkit.Chem import AllChem, Draw\n'), ((16826, 16867), 'atomsci.ddm.utils.struct_utils.base_mol_from_smiles', 'struct_utils.base_mol_from_smiles', (['smiles'], {}), '(smiles)\n', (16859, 16867), False, 'from atomsci.ddm.utils import struct_utils\n'), ((17079, 17100), 'rdkit.Chem.MolToSmiles', 'Chem.MolToSmiles', (['mol'], {}), '(mol)\n', (17095, 17100), False, 'from rdkit import Chem\n'), ((17138, 17199), 'rdkit.Chem.AllChem.GetMorganFingerprintAsBitVect', 'AllChem.GetMorganFingerprintAsBitVect', (['mol', 'ecfp_radius', '(1024)'], {}), '(mol, ecfp_radius, 1024)\n', (17175, 17199), False, 'from rdkit.Chem import AllChem, Draw\n'), ((20469, 20510), 'atomsci.ddm.utils.struct_utils.base_mol_from_smiles', 'struct_utils.base_mol_from_smiles', (['smiles'], {}), '(smiles)\n', (20502, 20510), False, 'from atomsci.ddm.utils import struct_utils\n'), ((20726, 20747), 'rdkit.Chem.MolToSmiles', 'Chem.MolToSmiles', (['mol'], {}), '(mol)\n', (20742, 20747), False, 'from rdkit import Chem\n'), ((20787, 20848), 'rdkit.Chem.AllChem.GetMorganFingerprintAsBitVect', 'AllChem.GetMorganFingerprintAsBitVect', (['mol', 'ecfp_radius', '(1024)'], {}), '(mol, ecfp_radius, 1024)\n', (20824, 20848), False, 'from rdkit.Chem import AllChem, Draw\n'), ((21641, 21682), 'atomsci.ddm.utils.struct_utils.base_mol_from_smiles', 'struct_utils.base_mol_from_smiles', (['smiles'], {}), '(smiles)\n', (21674, 21682), False, 'from atomsci.ddm.utils import struct_utils\n'), ((21896, 21917), 'rdkit.Chem.MolToSmiles', 'Chem.MolToSmiles', (['mol'], {}), '(mol)\n', (21912, 21917), False, 'from rdkit import Chem\n'), ((21955, 22016), 'rdkit.Chem.AllChem.GetMorganFingerprintAsBitVect', 'AllChem.GetMorganFingerprintAsBitVect', (['mol', 'ecfp_radius', '(1024)'], {}), '(mol, ecfp_radius, 1024)\n', (21992, 22016), False, 'from rdkit.Chem import AllChem, Draw\n'), ((24099, 24132), 'atomsci.ddm.utils.datastore_functions.metadata_to_dict', 'dsf.metadata_to_dict', (['metadata[i]'], {}), '(metadata[i])\n', (24119, 24132), True, 'from atomsci.ddm.utils import datastore_functions as dsf\n'), ((24322, 24385), 'atomsci.ddm.utils.datastore_functions.retrieve_dataset_by_datasetkey', 'dsf.retrieve_dataset_by_datasetkey', (['dset_key', 'bucket', 'ds_client'], {}), '(dset_key, bucket, ds_client)\n', (24356, 24385), True, 'from atomsci.ddm.utils import datastore_functions as dsf\n'), ((24408, 24433), 'os.path.dirname', 'os.path.dirname', (['dset_key'], {}), '(dset_key)\n', (24423, 24433), False, 'import os\n'), ((24457, 24483), 'os.path.basename', 'os.path.basename', (['dset_key'], {}), '(dset_key)\n', (24473, 24483), False, 'import os\n'), ((26188, 26213), 'atomsci.ddm.pipeline.model_datasets.MinimalDataset', 'md.MinimalDataset', (['params'], {}), '(params)\n', (26205, 26213), True, 'from atomsci.ddm.pipeline import model_datasets as md\n'), ((27002, 27027), 'logging.getLogger', 'logging.getLogger', (['"""ATOM"""'], {}), "('ATOM')\n", (27019, 27027), False, 'import logging\n'), ((27051, 27114), 'atomsci.ddm.utils.datastore_functions.retrieve_dataset_by_datasetkey', 'dsf.retrieve_dataset_by_datasetkey', (['dset_key', 'bucket', 'ds_client'], {}), '(dset_key, bucket, ds_client)\n', (27085, 27114), True, 'from atomsci.ddm.utils import datastore_functions as dsf\n'), ((28070, 28121), 'atomsci.ddm.utils.datastore_functions.get_keyval', 'dsf.get_keyval', ([], {'dataset_key': 'dset_key', 'bucket': 'bucket'}), '(dataset_key=dset_key, bucket=bucket)\n', (28084, 28121), True, 'from atomsci.ddm.utils import datastore_functions as dsf\n'), ((28906, 28939), 'atomsci.ddm.pipeline.featurization.create_featurization', 'feat.create_featurization', (['params'], {}), '(params)\n', (28931, 28939), True, 'from atomsci.ddm.pipeline import featurization as feat\n'), ((28964, 29004), 'atomsci.ddm.pipeline.model_datasets.MinimalDataset', 'md.MinimalDataset', (['params', 'featurization'], {}), '(params, featurization)\n', (28981, 29004), True, 'from atomsci.ddm.pipeline import model_datasets as md\n'), ((29383, 29479), 'atomsci.ddm.pipeline.chem_diversity.calc_dist_diskdataset', 'cd.calc_dist_diskdataset', (['"""descriptors"""', 'dist_metric', 'model_dataset.dataset'], {'calc_type': '"""all"""'}), "('descriptors', dist_metric, model_dataset.dataset,\n calc_type='all')\n", (29407, 29479), True, 'from atomsci.ddm.pipeline import chem_diversity as cd\n'), ((29513, 29553), 'scipy.spatial.distance.squareform', 'scipy.spatial.distance.squareform', (['dists'], {}), '(dists)\n', (29546, 29553), False, 'import scipy\n'), ((29734, 29767), 'scipy.cluster.hierarchy.linkage', 'linkage', (['dists'], {'method': '"""complete"""'}), "(dists, method='complete')\n", (29741, 29767), False, 'from scipy.cluster.hierarchy import linkage\n'), ((29853, 29871), 'matplotlib.backends.backend_pdf.PdfPages', 'PdfPages', (['pdf_path'], {}), '(pdf_path)\n', (29861, 29871), False, 'from matplotlib.backends.backend_pdf import PdfPages\n'), ((29884, 29992), 'seaborn.clustermap', 'sns.clustermap', (['dists'], {'row_linkage': 'mcs_linkage', 'col_linkage': 'mcs_linkage', 'figsize': '(12, 12)', 'cmap': '"""plasma"""'}), "(dists, row_linkage=mcs_linkage, col_linkage=mcs_linkage,\n figsize=(12, 12), cmap='plasma')\n", (29898, 29992), True, 'import seaborn as sns\n'), ((3405, 3431), 'os.path.basename', 'os.path.basename', (['dset_key'], {}), '(dset_key)\n', (3421, 3431), False, 'import os\n'), ((4708, 4769), 'seaborn.blend_palette', 'sns.blend_palette', (["['red', 'green', 'blue']", '(12)'], {'as_cmap': '(True)'}), "(['red', 'green', 'blue'], 12, as_cmap=True)\n", (4725, 4769), True, 'import seaborn as sns\n'), ((6653, 6671), 'matplotlib.backends.backend_pdf.PdfPages', 'PdfPages', (['pdf_path'], {}), '(pdf_path)\n', (6661, 6671), False, 'from matplotlib.backends.backend_pdf import PdfPages\n'), ((7332, 7350), 'matplotlib.backends.backend_pdf.PdfPages', 'PdfPages', (['pdf_path'], {}), '(pdf_path)\n', (7340, 7350), False, 'from matplotlib.backends.backend_pdf import PdfPages\n'), ((7441, 7490), 'seaborn.scatterplot', 'sns.scatterplot', ([], {'x': '"""x"""', 'y': '"""y"""', 'data': 'rep_df', 'ax': 'ax'}), "(x='x', y='y', data=rep_df, ax=ax)\n", (7456, 7490), True, 'import seaborn as sns\n'), ((7560, 7647), 'seaborn.scatterplot', 'sns.scatterplot', ([], {'x': '"""x"""', 'y': '"""y"""', 'hue': '"""response"""', 'palette': 'colorpal', 'data': 'rep_df', 'ax': 'ax'}), "(x='x', y='y', hue='response', palette=colorpal, data=rep_df,\n ax=ax)\n", (7575, 7647), True, 'import seaborn as sns\n'), ((24544, 24954), 'argparse.Namespace', 'argparse.Namespace', ([], {'dataset_dir': 'dataset_dir', 'dataset_file': 'dataset_file', 'y': 'task_name', 'bucket': 'bucket', 'descriptor_key': '"""all_GSK_Compound_2D_3D_MOE_Descriptors_Scaled_With_Smiles_And_Inchi"""', 'descriptor_type': '"""MOE"""', 'splitter': 'split', 'id_col': '"""compound_id"""', 'smiles_col': '"""rdkit_smiles"""', 'featurizer': '"""descriptors"""', 'prediction_type': '"""regression"""', 'system': '"""twintron-blue"""', 'datastore': '(True)', 'transformers': '(True)'}), "(dataset_dir=dataset_dir, dataset_file=dataset_file, y=\n task_name, bucket=bucket, descriptor_key=\n 'all_GSK_Compound_2D_3D_MOE_Descriptors_Scaled_With_Smiles_And_Inchi',\n descriptor_type='MOE', splitter=split, id_col='compound_id', smiles_col\n ='rdkit_smiles', featurizer='descriptors', prediction_type='regression',\n system='twintron-blue', datastore=True, transformers=True)\n", (24562, 24954), False, 'import argparse\n'), ((3764, 3785), 'rdkit.Chem.MolFromSmiles', 'Chem.MolFromSmiles', (['s'], {}), '(s)\n', (3782, 3785), False, 'from rdkit import Chem\n'), ((3906, 3947), 'atomsci.ddm.utils.struct_utils.base_mol_from_smiles', 'struct_utils.base_mol_from_smiles', (['smiles'], {}), '(smiles)\n', (3939, 3947), False, 'from atomsci.ddm.utils import struct_utils\n'), ((6234, 6300), 'rdkit.Chem.Draw.MolToFile', 'Draw.MolToFile', (['mol_i', 'img_file_i'], {'size': '(500, 500)', 'fitImage': '(False)'}), '(mol_i, img_file_i, size=(500, 500), fitImage=False)\n', (6248, 6300), False, 'from rdkit.Chem import AllChem, Draw\n'), ((6316, 6382), 'rdkit.Chem.Draw.MolToFile', 'Draw.MolToFile', (['mol_j', 'img_file_j'], {'size': '(500, 500)', 'fitImage': '(False)'}), '(mol_j, img_file_j, size=(500, 500), fitImage=False)\n', (6330, 6382), False, 'from rdkit.Chem import AllChem, Draw\n'), ((25352, 25672), 'argparse.Namespace', 'argparse.Namespace', ([], {'dataset_dir': 'dataset_dir', 'dataset_file': 'dataset_file', 'y': 'task_name', 'bucket': 'bucket', 'splitter': 'split', 'id_col': '"""compound_id"""', 'smiles_col': '"""rdkit_smiles"""', 'featurizer': '"""ECFP"""', 'prediction_type': '"""regression"""', 'system': '"""twintron-blue"""', 'datastore': '(True)', 'ecfp_radius': '(2)', 'ecfp_size': '(1024)', 'transformers': '(True)'}), "(dataset_dir=dataset_dir, dataset_file=dataset_file, y=\n task_name, bucket=bucket, splitter=split, id_col='compound_id',\n smiles_col='rdkit_smiles', featurizer='ECFP', prediction_type=\n 'regression', system='twintron-blue', datastore=True, ecfp_radius=2,\n ecfp_size=1024, transformers=True)\n", (25370, 25672), False, 'import argparse\n')] |
# coding: utf-8
# Copyright 2018 <NAME>
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
import importlib
import numpy
import torch
import pytest
def make_arg(**kwargs):
defaults = dict(
elayers_sd=1,
elayers=2,
subsample="1_2_2_1_1",
etype="vggblstmp",
eunits=100,
eprojs=100,
dtype="lstm",
dlayers=1,
dunits=300,
atype="location",
aconv_chans=10,
aconv_filts=100,
mtlalpha=0.5,
lsm_type="",
lsm_weight=0.0,
sampling_probability=0.0,
adim=320,
dropout_rate=0.0,
dropout_rate_decoder=0.0,
nbest=5,
beam_size=3,
penalty=0.5,
maxlenratio=1.0,
minlenratio=0.0,
ctc_weight=0.2,
verbose=2,
char_list=["a", "i", "u", "e", "o"],
outdir=None,
ctc_type="warpctc",
num_spkrs=1,
spa=False
)
defaults.update(kwargs)
return argparse.Namespace(**defaults)
def init_torch_weight_const(m, val):
for p in m.parameters():
p.data.fill_(val)
def init_chainer_weight_const(m, val):
for p in m.params():
p.data[:] = val
@pytest.mark.parametrize(("etype", "dtype", "num_spkrs", "spa", "m_str", "text_idx1"), [
("vggblstmp", "lstm", 2, True, "espnet.nets.pytorch_backend.e2e_asr_mix", 0),
("vggbgrup", "gru", 2, True, "espnet.nets.pytorch_backend.e2e_asr_mix", 1),
])
def test_recognition_results_multi_outputs(etype, dtype, num_spkrs, spa, m_str, text_idx1):
const = 1e-4
numpy.random.seed(1)
seq_true_texts = ([["uiuiuiuiuiuiuiuio", "uiuiuiuiuiuiuiuio"],
["uiuiuiuiuiuiuiuio", "uiuiuiuiuiuiuiuio"]])
# ctc_weight: 0.5 (hybrid CTC/attention), cannot be 0.0 (attention) or 1.0 (CTC)
for text_idx2, ctc_weight in enumerate([0.5]):
seq_true_text_sd = seq_true_texts[text_idx1]
args = make_arg(etype=etype, ctc_weight=ctc_weight, num_spkrs=num_spkrs, spa=spa)
m = importlib.import_module(m_str)
model = m.E2E(40, 5, args)
if "pytorch" in m_str:
init_torch_weight_const(model, const)
else:
init_chainer_weight_const(model, const)
data = [
("aaa", dict(feat=numpy.random.randn(100, 40).astype(
numpy.float32), token=seq_true_text_sd))
]
in_data = data[0][1]["feat"]
nbest_hyps = model.recognize(in_data, args, args.char_list)
seq_hat_text_sd = []
for i in range(num_spkrs):
y_hat = nbest_hyps[i][0]['yseq'][1:]
seq_hat = [args.char_list[int(idx)] for idx in y_hat]
seq_hat_text = "".join(seq_hat).replace('<space>', ' ')
seq_hat_text_sd.append(seq_hat_text)
seq_true_text_sd = data[0][1]["token"]
assert seq_hat_text_sd == seq_true_text_sd
@pytest.mark.parametrize(("etype", "dtype", "num_spkrs", "m_str", "data_idx"), [
("vggblstmp", "lstm", 2, "espnet.nets.pytorch_backend.e2e_asr_mix", 0),
])
def test_pit_process(etype, dtype, num_spkrs, m_str, data_idx):
bs = 10
m = importlib.import_module(m_str)
losses_2 = torch.ones([bs, 4], dtype=torch.float32)
for i in range(bs):
losses_2[i][i % 4] = 0
true_losses_2 = torch.ones(bs, dtype=torch.float32) / 2
perm_choices_2 = [[0, 1], [1, 0], [1, 0], [0, 1]]
true_perm_2 = []
for i in range(bs):
true_perm_2.append(perm_choices_2[i % 4])
true_perm_2 = torch.tensor(true_perm_2).long()
losses = [losses_2]
true_losses = [torch.mean(true_losses_2)]
true_perm = [true_perm_2]
args = make_arg(etype=etype, num_spkrs=num_spkrs)
model = m.E2E(40, 5, args)
min_loss, min_perm = model.pit.pit_process(losses[data_idx])
assert min_loss == true_losses[data_idx]
assert torch.equal(min_perm, true_perm[data_idx])
| [
"argparse.Namespace",
"torch.ones",
"torch.mean",
"numpy.random.seed",
"importlib.import_module",
"numpy.random.randn",
"torch.equal",
"pytest.mark.parametrize",
"torch.tensor"
] | [((1225, 1479), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["('etype', 'dtype', 'num_spkrs', 'spa', 'm_str', 'text_idx1')", "[('vggblstmp', 'lstm', 2, True, 'espnet.nets.pytorch_backend.e2e_asr_mix', \n 0), ('vggbgrup', 'gru', 2, True,\n 'espnet.nets.pytorch_backend.e2e_asr_mix', 1)]"], {}), "(('etype', 'dtype', 'num_spkrs', 'spa', 'm_str',\n 'text_idx1'), [('vggblstmp', 'lstm', 2, True,\n 'espnet.nets.pytorch_backend.e2e_asr_mix', 0), ('vggbgrup', 'gru', 2, \n True, 'espnet.nets.pytorch_backend.e2e_asr_mix', 1)])\n", (1248, 1479), False, 'import pytest\n'), ((2911, 3072), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["('etype', 'dtype', 'num_spkrs', 'm_str', 'data_idx')", "[('vggblstmp', 'lstm', 2, 'espnet.nets.pytorch_backend.e2e_asr_mix', 0)]"], {}), "(('etype', 'dtype', 'num_spkrs', 'm_str', 'data_idx'\n ), [('vggblstmp', 'lstm', 2, 'espnet.nets.pytorch_backend.e2e_asr_mix', 0)]\n )\n", (2934, 3072), False, 'import pytest\n'), ((1007, 1037), 'argparse.Namespace', 'argparse.Namespace', ([], {}), '(**defaults)\n', (1025, 1037), False, 'import argparse\n'), ((1591, 1611), 'numpy.random.seed', 'numpy.random.seed', (['(1)'], {}), '(1)\n', (1608, 1611), False, 'import numpy\n'), ((3154, 3184), 'importlib.import_module', 'importlib.import_module', (['m_str'], {}), '(m_str)\n', (3177, 3184), False, 'import importlib\n'), ((3201, 3241), 'torch.ones', 'torch.ones', (['[bs, 4]'], {'dtype': 'torch.float32'}), '([bs, 4], dtype=torch.float32)\n', (3211, 3241), False, 'import torch\n'), ((3866, 3908), 'torch.equal', 'torch.equal', (['min_perm', 'true_perm[data_idx]'], {}), '(min_perm, true_perm[data_idx])\n', (3877, 3908), False, 'import torch\n'), ((2040, 2070), 'importlib.import_module', 'importlib.import_module', (['m_str'], {}), '(m_str)\n', (2063, 2070), False, 'import importlib\n'), ((3317, 3352), 'torch.ones', 'torch.ones', (['bs'], {'dtype': 'torch.float32'}), '(bs, dtype=torch.float32)\n', (3327, 3352), False, 'import torch\n'), ((3601, 3626), 'torch.mean', 'torch.mean', (['true_losses_2'], {}), '(true_losses_2)\n', (3611, 3626), False, 'import torch\n'), ((3524, 3549), 'torch.tensor', 'torch.tensor', (['true_perm_2'], {}), '(true_perm_2)\n', (3536, 3549), False, 'import torch\n'), ((2302, 2329), 'numpy.random.randn', 'numpy.random.randn', (['(100)', '(40)'], {}), '(100, 40)\n', (2320, 2329), False, 'import numpy\n')] |
import os
from pathlib import Path
from tempfile import tempdir
import numpy as np
import pytest
from numpy.testing import assert_allclose, assert_almost_equal
from ross.disk_element import DiskElement, DiskElement6DoF
from ross.materials import steel
@pytest.fixture
def disk():
return DiskElement(0, 0.07, 0.05, 0.32956)
def test_index(disk):
assert disk.dof_local_index().x_0 == 0
assert disk.dof_local_index().y_0 == 1
assert disk.dof_local_index().alpha_0 == 2
assert disk.dof_local_index().beta_0 == 3
def test_mass_matrix_disk(disk):
# fmt: off
Md1 = np.array([[0.07, 0., 0., 0.],
[0., 0.07, 0., 0.],
[0., 0., 0.05, 0.],
[0., 0., 0., 0.05]])
# fmt: on
assert_almost_equal(disk.M(), Md1, decimal=5)
def test_gyroscopic_matrix_disk(disk):
# fmt: off
Gd1 = np.array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.32956],
[0., 0., -0.32956, 0.]])
# fmt: on
assert_almost_equal(disk.G(), Gd1, decimal=5)
@pytest.fixture
def disk_from_geometry():
return DiskElement.from_geometry(0, steel, 0.07, 0.05, 0.28)
def test_save_load(disk, disk_from_geometry):
file = Path(tempdir) / "disk.toml"
disk.save(file)
disk_loaded = DiskElement.load(file)
assert disk == disk_loaded
def test_mass_matrix_disk1(disk_from_geometry):
# fmt: off
Md1 = np.array([[ 32.58973, 0. , 0. , 0. ],
[ 0. , 32.58973, 0. , 0. ],
[ 0. , 0. , 0.17809, 0. ],
[ 0. , 0. , 0. , 0.17809]])
# fmt: on
assert_almost_equal(disk_from_geometry.M(), Md1, decimal=5)
def test_gyroscopic_matrix_disk1(disk_from_geometry):
# fmt: off
Gd1 = np.array([[ 0. , 0. , 0. , 0. ],
[ 0. , 0. , 0. , 0. ],
[ 0. , 0. , 0. , 0.32956],
[ 0. , 0. , -0.32956, 0. ]])
# fmt: on
assert_almost_equal(disk_from_geometry.G(), Gd1, decimal=5)
def test_from_table():
for file_name in ["/data/shaft_us.xls", "/data/shaft_si.xls"]:
file_name = os.path.dirname(os.path.realpath(__file__)) + file_name
disks = DiskElement.from_table(file_name, sheet_name="More")
assert_allclose(disks[1].m, 6.90999178227835)
assert_allclose(disks[1].Ip, 0.0469996988106328, atol=1.6e-07)
assert_allclose(disks[1].Id, 0.0249998397928898, atol=1.6e-07)
@pytest.fixture
def disk_6dof():
return DiskElement6DoF(0, 32.58973, 0.17809, 0.32956)
def test_index_6dof(disk_6dof):
assert disk_6dof.dof_local_index().x_0 == 0
assert disk_6dof.dof_local_index().y_0 == 1
assert disk_6dof.dof_local_index().z_0 == 2
assert disk_6dof.dof_local_index().alpha_0 == 3
assert disk_6dof.dof_local_index().beta_0 == 4
assert disk_6dof.dof_local_index().theta_0 == 5
def test_mass_matrix_disk_6dof(disk_6dof):
# fmt: off
Md1 = np.array([[32.58973, 0., 0., 0., 0., 0. ],
[0., 32.58973, 0., 0., 0., 0. ],
[0., 0., 32.58973, 0., 0., 0. ],
[0., 0., 0., 0.17809, 0., 0. ],
[0., 0., 0., 0., 0.17809, 0. ],
[0., 0., 0., 0, 0., 0.32956]])
# fmt: on
assert_almost_equal(disk_6dof.M(), Md1, decimal=5)
def test_gyroscopic_matrix_disk_6dof(disk_6dof):
# fmt: off
Gd1 = np.array([
[ 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0.32956, 0],
[ 0, 0, 0, -0.32956, 0, 0],
[ 0, 0, 0, 0, 0, 0]])
# fmt: on
assert_almost_equal(disk_6dof.G(), Gd1, decimal=5)
@pytest.fixture
def disk_from_geometry_6dof():
return DiskElement6DoF.from_geometry(0, steel, 0.07, 0.05, 0.28)
def test_mass_matrix_disk1_6dof(disk_from_geometry_6dof):
# fmt: off
Md1 = np.array([[32.58973, 0., 0., 0., 0., 0. ],
[0., 32.58973, 0., 0., 0., 0. ],
[0., 0., 32.58973, 0., 0., 0. ],
[0., 0., 0., 0.17809, 0., 0. ],
[0., 0., 0., 0., 0.17809, 0. ],
[0., 0., 0., 0, 0., 0.32956]])
# fmt: on
M_class = disk_from_geometry_6dof.M()
assert_almost_equal(M_class, Md1, decimal=5)
def test_gyroscopic_matrix_disk1_6dof(disk_from_geometry_6dof):
# fmt: off
Gd1 = np.array([
[ 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0.32956, 0],
[ 0, 0, 0, -0.32956, 0, 0],
[ 0, 0, 0, 0, 0, 0]])
# fmt: on
assert_almost_equal(disk_from_geometry_6dof.G(), Gd1, decimal=5)
def test_from_table_6dof():
for file_name in ["/data/shaft_us.xls", "/data/shaft_si.xls"]:
file_name = os.path.dirname(os.path.realpath(__file__)) + file_name
disks = DiskElement6DoF.from_table(file_name, sheet_name="More")
assert_allclose(disks[1].m, 6.90999178227835)
assert_allclose(disks[1].Ip, 0.0469996988106328, atol=1.6e-07)
assert_allclose(disks[1].Id, 0.0249998397928898, atol=1.6e-07)
| [
"ross.disk_element.DiskElement6DoF.from_table",
"ross.disk_element.DiskElement.load",
"ross.disk_element.DiskElement.from_geometry",
"ross.disk_element.DiskElement6DoF.from_geometry",
"numpy.testing.assert_almost_equal",
"os.path.realpath",
"ross.disk_element.DiskElement",
"ross.disk_element.DiskEleme... | [((295, 330), 'ross.disk_element.DiskElement', 'DiskElement', (['(0)', '(0.07)', '(0.05)', '(0.32956)'], {}), '(0, 0.07, 0.05, 0.32956)\n', (306, 330), False, 'from ross.disk_element import DiskElement, DiskElement6DoF\n'), ((594, 701), 'numpy.array', 'np.array', (['[[0.07, 0.0, 0.0, 0.0], [0.0, 0.07, 0.0, 0.0], [0.0, 0.0, 0.05, 0.0], [0.0,\n 0.0, 0.0, 0.05]]'], {}), '([[0.07, 0.0, 0.0, 0.0], [0.0, 0.07, 0.0, 0.0], [0.0, 0.0, 0.05, \n 0.0], [0.0, 0.0, 0.0, 0.05]])\n', (602, 701), True, 'import numpy as np\n'), ((876, 988), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.32956], [0.0,\n 0.0, -0.32956, 0.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, \n 0.32956], [0.0, 0.0, -0.32956, 0.0]])\n', (884, 988), True, 'import numpy as np\n'), ((1150, 1203), 'ross.disk_element.DiskElement.from_geometry', 'DiskElement.from_geometry', (['(0)', 'steel', '(0.07)', '(0.05)', '(0.28)'], {}), '(0, steel, 0.07, 0.05, 0.28)\n', (1175, 1203), False, 'from ross.disk_element import DiskElement, DiskElement6DoF\n'), ((1329, 1351), 'ross.disk_element.DiskElement.load', 'DiskElement.load', (['file'], {}), '(file)\n', (1345, 1351), False, 'from ross.disk_element import DiskElement, DiskElement6DoF\n'), ((1458, 1579), 'numpy.array', 'np.array', (['[[32.58973, 0.0, 0.0, 0.0], [0.0, 32.58973, 0.0, 0.0], [0.0, 0.0, 0.17809, \n 0.0], [0.0, 0.0, 0.0, 0.17809]]'], {}), '([[32.58973, 0.0, 0.0, 0.0], [0.0, 32.58973, 0.0, 0.0], [0.0, 0.0, \n 0.17809, 0.0], [0.0, 0.0, 0.0, 0.17809]])\n', (1466, 1579), True, 'import numpy as np\n'), ((1872, 1984), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.32956], [0.0,\n 0.0, -0.32956, 0.0]]'], {}), '([[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, \n 0.32956], [0.0, 0.0, -0.32956, 0.0]])\n', (1880, 1984), True, 'import numpy as np\n'), ((2669, 2715), 'ross.disk_element.DiskElement6DoF', 'DiskElement6DoF', (['(0)', '(32.58973)', '(0.17809)', '(0.32956)'], {}), '(0, 32.58973, 0.17809, 0.32956)\n', (2684, 2715), False, 'from ross.disk_element import DiskElement, DiskElement6DoF\n'), ((3119, 3360), 'numpy.array', 'np.array', (['[[32.58973, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 32.58973, 0.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 32.58973, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.17809, 0.0, 0.0],\n [0.0, 0.0, 0.0, 0.0, 0.17809, 0.0], [0.0, 0.0, 0.0, 0, 0.0, 0.32956]]'], {}), '([[32.58973, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 32.58973, 0.0, 0.0, \n 0.0, 0.0], [0.0, 0.0, 32.58973, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.17809,\n 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.17809, 0.0], [0.0, 0.0, 0.0, 0, 0.0, \n 0.32956]])\n', (3127, 3360), True, 'import numpy as np\n'), ((3719, 3866), 'numpy.array', 'np.array', (['[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, \n 0.32956, 0], [0, 0, 0, -0.32956, 0, 0], [0, 0, 0, 0, 0, 0]]'], {}), '([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0,\n 0, 0, 0.32956, 0], [0, 0, 0, -0.32956, 0, 0], [0, 0, 0, 0, 0, 0]])\n', (3727, 3866), True, 'import numpy as np\n'), ((4149, 4206), 'ross.disk_element.DiskElement6DoF.from_geometry', 'DiskElement6DoF.from_geometry', (['(0)', 'steel', '(0.07)', '(0.05)', '(0.28)'], {}), '(0, steel, 0.07, 0.05, 0.28)\n', (4178, 4206), False, 'from ross.disk_element import DiskElement, DiskElement6DoF\n'), ((4292, 4533), 'numpy.array', 'np.array', (['[[32.58973, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 32.58973, 0.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 32.58973, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.17809, 0.0, 0.0],\n [0.0, 0.0, 0.0, 0.0, 0.17809, 0.0], [0.0, 0.0, 0.0, 0, 0.0, 0.32956]]'], {}), '([[32.58973, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 32.58973, 0.0, 0.0, \n 0.0, 0.0], [0.0, 0.0, 32.58973, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.17809,\n 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.17809, 0.0], [0.0, 0.0, 0.0, 0, 0.0, \n 0.32956]])\n', (4300, 4533), True, 'import numpy as np\n'), ((4808, 4852), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['M_class', 'Md1'], {'decimal': '(5)'}), '(M_class, Md1, decimal=5)\n', (4827, 4852), False, 'from numpy.testing import assert_allclose, assert_almost_equal\n'), ((4944, 5091), 'numpy.array', 'np.array', (['[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, \n 0.32956, 0], [0, 0, 0, -0.32956, 0, 0], [0, 0, 0, 0, 0, 0]]'], {}), '([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0,\n 0, 0, 0.32956, 0], [0, 0, 0, -0.32956, 0, 0], [0, 0, 0, 0, 0, 0]])\n', (4952, 5091), True, 'import numpy as np\n'), ((1263, 1276), 'pathlib.Path', 'Path', (['tempdir'], {}), '(tempdir)\n', (1267, 1276), False, 'from pathlib import Path\n'), ((2373, 2425), 'ross.disk_element.DiskElement.from_table', 'DiskElement.from_table', (['file_name'], {'sheet_name': '"""More"""'}), "(file_name, sheet_name='More')\n", (2395, 2425), False, 'from ross.disk_element import DiskElement, DiskElement6DoF\n'), ((2435, 2480), 'numpy.testing.assert_allclose', 'assert_allclose', (['disks[1].m', '(6.90999178227835)'], {}), '(disks[1].m, 6.90999178227835)\n', (2450, 2480), False, 'from numpy.testing import assert_allclose, assert_almost_equal\n'), ((2489, 2551), 'numpy.testing.assert_allclose', 'assert_allclose', (['disks[1].Ip', '(0.0469996988106328)'], {'atol': '(1.6e-07)'}), '(disks[1].Ip, 0.0469996988106328, atol=1.6e-07)\n', (2504, 2551), False, 'from numpy.testing import assert_allclose, assert_almost_equal\n'), ((2560, 2622), 'numpy.testing.assert_allclose', 'assert_allclose', (['disks[1].Id', '(0.0249998397928898)'], {'atol': '(1.6e-07)'}), '(disks[1].Id, 0.0249998397928898, atol=1.6e-07)\n', (2575, 2622), False, 'from numpy.testing import assert_allclose, assert_almost_equal\n'), ((5516, 5572), 'ross.disk_element.DiskElement6DoF.from_table', 'DiskElement6DoF.from_table', (['file_name'], {'sheet_name': '"""More"""'}), "(file_name, sheet_name='More')\n", (5542, 5572), False, 'from ross.disk_element import DiskElement, DiskElement6DoF\n'), ((5582, 5627), 'numpy.testing.assert_allclose', 'assert_allclose', (['disks[1].m', '(6.90999178227835)'], {}), '(disks[1].m, 6.90999178227835)\n', (5597, 5627), False, 'from numpy.testing import assert_allclose, assert_almost_equal\n'), ((5636, 5698), 'numpy.testing.assert_allclose', 'assert_allclose', (['disks[1].Ip', '(0.0469996988106328)'], {'atol': '(1.6e-07)'}), '(disks[1].Ip, 0.0469996988106328, atol=1.6e-07)\n', (5651, 5698), False, 'from numpy.testing import assert_allclose, assert_almost_equal\n'), ((5707, 5769), 'numpy.testing.assert_allclose', 'assert_allclose', (['disks[1].Id', '(0.0249998397928898)'], {'atol': '(1.6e-07)'}), '(disks[1].Id, 0.0249998397928898, atol=1.6e-07)\n', (5722, 5769), False, 'from numpy.testing import assert_allclose, assert_almost_equal\n'), ((2317, 2343), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (2333, 2343), False, 'import os\n'), ((5460, 5486), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (5476, 5486), False, 'import os\n')] |
import numpy as np
import cv2 as cv
import numba
from numba import jit
from skimage.measure import regionprops
def draw_boxes(image, labels):
props = regionprops(labels)
for prop in props:
cv_coords = np.flip(prop.coords, 1)
rect = cv.minAreaRect(cv_coords)
box = cv.boxPoints(rect)
box = np.int0(box)
cv.drawContours(image, [box], 0, (0, 255, 0), 1)
def texture_channel_generation(image):
l, a, b = cv.split(image)
def imshow_components(labels):
# Map component labels to hue val
label_hue = np.uint8(179*labels/np.max(labels))
blank_ch = 255*np.ones_like(label_hue)
labeled_img = cv.merge([label_hue, blank_ch, blank_ch])
# cvt to BGR for display
labeled_img = cv.cvtColor(labeled_img, cv.COLOR_HSV2BGR)
return labeled_img
def create_sum_image(image, conv_flag=cv.COLOR_BGR2YCrCb):
img = cv.cvtColor(image, conv_flag)
l, a, b = cv.split(img)
scalar = np.bincount(a.reshape(-1, 1).ravel()).argmax()
ad = cv.absdiff(a, np.array([scalar], dtype=np.float))
scalar = np.bincount(b.reshape(-1, 1).ravel()).argmax()
bd = cv.absdiff(b, np.array([scalar], dtype=np.float))
sum_image = cv.add(ad, bd)
return sum_image
def create_2D_image(image, conv_flag=cv.COLOR_BGR2YCrCb):
img = cv.cvtColor(image, conv_flag)
l, a, b = cv.split(img)
return np.dstack((a, b))
def get_saturation(image, conv_flag=cv.COLOR_BGR2HSV):
hsv = cv.cvtColor(image, conv_flag)
_, s, _ = cv.split(hsv)
return s
@jit(nopython=True)
def get_image(values, thresh):
(H,W) = values.shape[:2]
image = np.zeros((H,W), dtype=np.uint8)
for y in range(0, H):
for x in range(0, W):
if values[y, x] > thresh:
image[y, x] = 255
return image
def show_images(results):
shape = results[0].shape
### Print results
vertical_stack = []
for i in range(0, len(results), 2):
if (i + 1) < len(results):
numpy_horizontal = np.hstack((results[i], results[i + 1]))
else:
numpy_horizontal = np.hstack((results[i], np.zeros(shape, dtype='uint8')))
vertical_stack.append(numpy_horizontal)
numpy_horizontal_concat = np.vstack(vertical_stack)
cv.namedWindow('image' , cv.WINDOW_NORMAL)
cv.imshow('image', numpy_horizontal_concat)
cv.waitKey(0)
cv.destroyAllWindows()
def show_image(image):
cv.namedWindow('image' , cv.WINDOW_NORMAL)
cv.imshow('image', image)
cv.waitKey(0)
cv.destroyAllWindows()
def convert(image):
return cv.cvtColor(image, cv.COLOR_GRAY2BGR)
| [
"cv2.boxPoints",
"cv2.minAreaRect",
"cv2.imshow",
"skimage.measure.regionprops",
"cv2.cvtColor",
"numpy.max",
"cv2.split",
"cv2.drawContours",
"cv2.destroyAllWindows",
"numpy.dstack",
"numpy.int0",
"numpy.ones_like",
"cv2.waitKey",
"numpy.hstack",
"cv2.merge",
"cv2.add",
"numpy.vstac... | [((1530, 1548), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (1533, 1548), False, 'from numba import jit\n'), ((156, 175), 'skimage.measure.regionprops', 'regionprops', (['labels'], {}), '(labels)\n', (167, 175), False, 'from skimage.measure import regionprops\n'), ((456, 471), 'cv2.split', 'cv.split', (['image'], {}), '(image)\n', (464, 471), True, 'import cv2 as cv\n'), ((656, 697), 'cv2.merge', 'cv.merge', (['[label_hue, blank_ch, blank_ch]'], {}), '([label_hue, blank_ch, blank_ch])\n', (664, 697), True, 'import cv2 as cv\n'), ((746, 788), 'cv2.cvtColor', 'cv.cvtColor', (['labeled_img', 'cv.COLOR_HSV2BGR'], {}), '(labeled_img, cv.COLOR_HSV2BGR)\n', (757, 788), True, 'import cv2 as cv\n'), ((884, 913), 'cv2.cvtColor', 'cv.cvtColor', (['image', 'conv_flag'], {}), '(image, conv_flag)\n', (895, 913), True, 'import cv2 as cv\n'), ((928, 941), 'cv2.split', 'cv.split', (['img'], {}), '(img)\n', (936, 941), True, 'import cv2 as cv\n'), ((1196, 1210), 'cv2.add', 'cv.add', (['ad', 'bd'], {}), '(ad, bd)\n', (1202, 1210), True, 'import cv2 as cv\n'), ((1302, 1331), 'cv2.cvtColor', 'cv.cvtColor', (['image', 'conv_flag'], {}), '(image, conv_flag)\n', (1313, 1331), True, 'import cv2 as cv\n'), ((1346, 1359), 'cv2.split', 'cv.split', (['img'], {}), '(img)\n', (1354, 1359), True, 'import cv2 as cv\n'), ((1371, 1388), 'numpy.dstack', 'np.dstack', (['(a, b)'], {}), '((a, b))\n', (1380, 1388), True, 'import numpy as np\n'), ((1456, 1485), 'cv2.cvtColor', 'cv.cvtColor', (['image', 'conv_flag'], {}), '(image, conv_flag)\n', (1467, 1485), True, 'import cv2 as cv\n'), ((1500, 1513), 'cv2.split', 'cv.split', (['hsv'], {}), '(hsv)\n', (1508, 1513), True, 'import cv2 as cv\n'), ((1621, 1653), 'numpy.zeros', 'np.zeros', (['(H, W)'], {'dtype': 'np.uint8'}), '((H, W), dtype=np.uint8)\n', (1629, 1653), True, 'import numpy as np\n'), ((2228, 2253), 'numpy.vstack', 'np.vstack', (['vertical_stack'], {}), '(vertical_stack)\n', (2237, 2253), True, 'import numpy as np\n'), ((2259, 2300), 'cv2.namedWindow', 'cv.namedWindow', (['"""image"""', 'cv.WINDOW_NORMAL'], {}), "('image', cv.WINDOW_NORMAL)\n", (2273, 2300), True, 'import cv2 as cv\n'), ((2306, 2349), 'cv2.imshow', 'cv.imshow', (['"""image"""', 'numpy_horizontal_concat'], {}), "('image', numpy_horizontal_concat)\n", (2315, 2349), True, 'import cv2 as cv\n'), ((2354, 2367), 'cv2.waitKey', 'cv.waitKey', (['(0)'], {}), '(0)\n', (2364, 2367), True, 'import cv2 as cv\n'), ((2372, 2394), 'cv2.destroyAllWindows', 'cv.destroyAllWindows', ([], {}), '()\n', (2392, 2394), True, 'import cv2 as cv\n'), ((2424, 2465), 'cv2.namedWindow', 'cv.namedWindow', (['"""image"""', 'cv.WINDOW_NORMAL'], {}), "('image', cv.WINDOW_NORMAL)\n", (2438, 2465), True, 'import cv2 as cv\n'), ((2471, 2496), 'cv2.imshow', 'cv.imshow', (['"""image"""', 'image'], {}), "('image', image)\n", (2480, 2496), True, 'import cv2 as cv\n'), ((2501, 2514), 'cv2.waitKey', 'cv.waitKey', (['(0)'], {}), '(0)\n', (2511, 2514), True, 'import cv2 as cv\n'), ((2519, 2541), 'cv2.destroyAllWindows', 'cv.destroyAllWindows', ([], {}), '()\n', (2539, 2541), True, 'import cv2 as cv\n'), ((2574, 2611), 'cv2.cvtColor', 'cv.cvtColor', (['image', 'cv.COLOR_GRAY2BGR'], {}), '(image, cv.COLOR_GRAY2BGR)\n', (2585, 2611), True, 'import cv2 as cv\n'), ((219, 242), 'numpy.flip', 'np.flip', (['prop.coords', '(1)'], {}), '(prop.coords, 1)\n', (226, 242), True, 'import numpy as np\n'), ((258, 283), 'cv2.minAreaRect', 'cv.minAreaRect', (['cv_coords'], {}), '(cv_coords)\n', (272, 283), True, 'import cv2 as cv\n'), ((298, 316), 'cv2.boxPoints', 'cv.boxPoints', (['rect'], {}), '(rect)\n', (310, 316), True, 'import cv2 as cv\n'), ((331, 343), 'numpy.int0', 'np.int0', (['box'], {}), '(box)\n', (338, 343), True, 'import numpy as np\n'), ((352, 400), 'cv2.drawContours', 'cv.drawContours', (['image', '[box]', '(0)', '(0, 255, 0)', '(1)'], {}), '(image, [box], 0, (0, 255, 0), 1)\n', (367, 400), True, 'import cv2 as cv\n'), ((614, 637), 'numpy.ones_like', 'np.ones_like', (['label_hue'], {}), '(label_hue)\n', (626, 637), True, 'import numpy as np\n'), ((1025, 1059), 'numpy.array', 'np.array', (['[scalar]'], {'dtype': 'np.float'}), '([scalar], dtype=np.float)\n', (1033, 1059), True, 'import numpy as np\n'), ((1144, 1178), 'numpy.array', 'np.array', (['[scalar]'], {'dtype': 'np.float'}), '([scalar], dtype=np.float)\n', (1152, 1178), True, 'import numpy as np\n'), ((579, 593), 'numpy.max', 'np.max', (['labels'], {}), '(labels)\n', (585, 593), True, 'import numpy as np\n'), ((2008, 2047), 'numpy.hstack', 'np.hstack', (['(results[i], results[i + 1])'], {}), '((results[i], results[i + 1]))\n', (2017, 2047), True, 'import numpy as np\n'), ((2116, 2146), 'numpy.zeros', 'np.zeros', (['shape'], {'dtype': '"""uint8"""'}), "(shape, dtype='uint8')\n", (2124, 2146), True, 'import numpy as np\n')] |
from pyaudio import PyAudio, paInt16
import wave
# set up loggers
import logging
logging.basicConfig()
logger = logging.getLogger(name=__name__)
# only show errors or warnings until userdefine log level is set up
logger.setLevel(logging.INFO)
try:
import numpy as np
except:
logger.warning(
"Could not load numpy. The program code will be much slower without it. ")
from math import sin, pi
class PySine(object):
BITRATE = 96000.
def __init__(self):
self.pyaudio = PyAudio()
self.frames = None
try:
self.stream = self.pyaudio.open(
format=self.pyaudio.get_format_from_width(1),
channels=1,
rate=int(self.BITRATE),
output=True)
except:
logger.error(
"No audio output is available. Mocking audio stream to simulate one...")
# output stream simulation with magicmock
try:
from mock import MagicMock
except: # python > 3.3
from unittest.mock import MagicMock
from time import sleep
self.stream = MagicMock()
def write(array):
duration = len(array)/float(self.BITRATE)
sleep(duration)
self.stream.write = write
def __del__(self):
self.stream.stop_stream()
self.stream.close()
self.pyaudio.terminate()
def sine(self, frequency=440.0, duration=1.0):
points = int(self.BITRATE * duration)
try:
times = np.linspace(0, duration, points, endpoint=False)
data = np.array((np.sin(times*frequency*2*np.pi) + 1.0)
* 127.5, dtype=np.int8).tostring()
if not self.frames:
self.frames = data
else:
self.frames += data
except: # do it without numpy
data = ''
omega = 2.0*pi*frequency/self.BITRATE
for i in range(points):
data += chr(int(127.5*(1.0+sin(float(i)*omega))))
self.frames.append(data)
if not self.frames:
self.frames = b''.join(self.frames)
else:
self.frames += b''.join(self.frames)
self.stream.write(data)
def save(self, filename):
wf = wave.open(filename, 'wb')
wf.setnchannels(1)
wf.setsampwidth(1)
wf.setframerate(self.BITRATE)
wf.writeframes(self.frames)
wf.close()
PYSINE = PySine()
def sine(frequency=440.0, duration=1.0):
return PYSINE.sine(frequency=frequency, duration=duration)
| [
"wave.open",
"unittest.mock.MagicMock",
"logging.basicConfig",
"time.sleep",
"numpy.sin",
"numpy.linspace",
"pyaudio.PyAudio",
"logging.getLogger"
] | [((81, 102), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (100, 102), False, 'import logging\n'), ((112, 144), 'logging.getLogger', 'logging.getLogger', ([], {'name': '__name__'}), '(name=__name__)\n', (129, 144), False, 'import logging\n'), ((505, 514), 'pyaudio.PyAudio', 'PyAudio', ([], {}), '()\n', (512, 514), False, 'from pyaudio import PyAudio, paInt16\n'), ((2361, 2386), 'wave.open', 'wave.open', (['filename', '"""wb"""'], {}), "(filename, 'wb')\n", (2370, 2386), False, 'import wave\n'), ((1574, 1622), 'numpy.linspace', 'np.linspace', (['(0)', 'duration', 'points'], {'endpoint': '(False)'}), '(0, duration, points, endpoint=False)\n', (1585, 1622), True, 'import numpy as np\n'), ((1153, 1164), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (1162, 1164), False, 'from unittest.mock import MagicMock\n'), ((1270, 1285), 'time.sleep', 'sleep', (['duration'], {}), '(duration)\n', (1275, 1285), False, 'from time import sleep\n'), ((1652, 1689), 'numpy.sin', 'np.sin', (['(times * frequency * 2 * np.pi)'], {}), '(times * frequency * 2 * np.pi)\n', (1658, 1689), True, 'import numpy as np\n')] |
import itertools
import json
import os
import numpy as np
import pybullet as p
from bddl.object_taxonomy import ObjectTaxonomy
from pynput import keyboard
import igibson
from igibson.objects.articulated_object import URDFObject
from igibson.objects.visual_marker import VisualMarker
from igibson.scenes.empty_scene import EmptyScene
from igibson.simulator import Simulator
from igibson.utils.assets_utils import download_assets
download_assets()
ABILITY_NAME = "cleaningTool"
SYNSETS = [
"alarm.n.02",
"printer.n.03",
"facsimile.n.02",
"scanner.n.02",
"modem.n.01",
]
CATEGORIES = [
"broom",
"carpet_sweeper",
"scraper",
"scrub_brush",
"toothbrush",
"vacuum",
]
MODE = "synset" # "ability, "category"
LINK_NAME = "toggle_button"
IS_CUBOID = False
SKIP_EXISTING = False
OBJECT_TAXONOMY = ObjectTaxonomy()
def get_categories():
dir = os.path.join(igibson.ig_dataset_path, "objects")
return [cat for cat in os.listdir(dir) if os.path.isdir(get_category_directory(cat))]
def get_category_directory(category):
return os.path.join(igibson.ig_dataset_path, "objects", category)
def get_obj(folder):
return URDFObject(os.path.join(folder, os.path.basename(folder) + ".urdf"), name="obj", model_path=folder)
def get_metadata_filename(objdir):
return os.path.join(objdir, "misc", "metadata.json")
def get_corner_positions(base, rotation, size):
quat = p.getQuaternionFromEuler(rotation)
options = [-1, 1]
outputs = []
for pos in itertools.product(options, options, options):
res = p.multiplyTransforms(base, quat, np.array(pos) * size / 2.0, [0, 0, 0, 1])
outputs.append(res)
return outputs
def main():
# Collect the relevant categories.
categories = CATEGORIES
if MODE == "ability":
categories = []
for cat in get_categories():
# Check that the category has this label.
klass = OBJECT_TAXONOMY.get_class_name_from_igibson_category(cat)
if not klass:
continue
if not OBJECT_TAXONOMY.has_ability(klass, ABILITY_NAME):
continue
categories.append(cat)
elif MODE == "synset":
categories = []
for synset in SYNSETS:
categories.extend(OBJECT_TAXONOMY.get_igibson_categories(synset))
categories = set(categories) & set(get_categories())
print("%d categories: %s" % (len(categories), ", ".join(categories)))
# Now collect the actual objects.
objects = []
objects_by_category = {}
for cat in categories:
cd = get_category_directory(cat)
objects_by_category[cat] = []
for objdir in os.listdir(cd):
objdirfull = os.path.join(cd, objdir)
objects.append(objdirfull)
objects_by_category[cat].append(objdirfull)
print("%d objects.\n" % len(objects))
for cat in categories:
cd = get_category_directory(cat)
for objdir in os.listdir(cd):
objdirfull = os.path.join(cd, objdir)
mfn = get_metadata_filename(objdirfull)
with open(mfn, "r") as mf:
meta = json.load(mf)
offset = np.array([0.0, 0.0, 0.0])
size = np.array([0.0, 0.0, 0.0])
rotation = np.array([0.0, 0.0, 0.0])
existing = False
if "links" in meta and LINK_NAME in meta["links"]:
print("%s/%s already has the requested link." % (cat, objdir))
if SKIP_EXISTING:
continue
existing = True
offset = np.array(meta["links"][LINK_NAME]["xyz"])
if IS_CUBOID:
size = np.array(meta["links"][LINK_NAME]["size"])
rotation = np.array(meta["links"][LINK_NAME]["rpy"])
s = Simulator(mode="gui")
scene = EmptyScene()
s.import_scene(scene)
obj = get_obj(objdirfull)
s.import_object(obj)
obj_pos = np.array([0.0, 0.0, 1.0])
obj.set_position(obj_pos)
dim = max(obj.bounding_box)
marker_size = dim / 100.0
steps = [dim * 0.1, dim * 0.01, dim * 0.001]
rot_steps = [np.deg2rad(1), np.deg2rad(5), np.deg2rad(10)]
m = VisualMarker(radius=marker_size, rgba_color=[0, 0, 1, 0.5])
s.import_object(m)
if IS_CUBOID:
initial_poses = get_corner_positions(obj_pos + offset, rotation, size)
markers = [VisualMarker(radius=marker_size, rgba_color=[0, 1, 0, 0.5]) for _ in initial_poses]
[s.import_object(m) for m in markers]
for marker, (pos, orn) in zip(markers, initial_poses):
marker.set_position_orientation(pos, orn)
# if existing:
# e = VisualMarker(radius=0.02, rgba_color=[1, 0, 0, 0.5])
# s.import_object(e)
# e.set_position(obj_pos + offset)
step_size = steps[1]
rot_step_size = rot_steps[1]
done = False
while not done:
with keyboard.Events() as events:
for event in events:
if (
event is None
or not isinstance(event, keyboard.Events.Press)
or not hasattr(event.key, "char")
):
continue
if event.key.char == "w":
print("Moving forward one")
offset += np.array([0, 1, 0]) * step_size
elif event.key.char == "a":
print("Moving left one")
offset += np.array([-1, 0, 0]) * step_size
elif event.key.char == "s":
print("Moving back one")
offset += np.array([0, -1, 0]) * step_size
elif event.key.char == "d":
print("Moving right one")
offset += np.array([1, 0, 0]) * step_size
elif event.key.char == "q":
print("Moving up one")
offset += np.array([0, 0, 1]) * step_size
elif event.key.char == "z":
print("Moving down one")
offset += np.array([0, 0, -1]) * step_size
elif event.key.char == "1":
print("Sizing forward one")
size += np.array([0, 1, 0]) * step_size
elif event.key.char == "2":
print("Sizing back one")
size += np.array([0, -1, 0]) * step_size
elif event.key.char == "4":
print("Sizing left one")
size += np.array([-1, 0, 0]) * step_size
elif event.key.char == "5":
print("Sizing right one")
size += np.array([1, 0, 0]) * step_size
elif event.key.char == "7":
print("Sizing up one")
size += np.array([0, 0, 1]) * step_size
elif event.key.char == "8":
print("Sizing down one")
size += np.array([0, 0, -1]) * step_size
elif event.key.char == "t":
print("Rotation +X one")
rotation += np.array([1, 0, 0]) * rot_step_size
elif event.key.char == "y":
print("Rotation -X one")
rotation += np.array([-1, 0, 0]) * rot_step_size
elif event.key.char == "u":
print("Rotation +Y one")
rotation += np.array([0, 1, 0]) * rot_step_size
elif event.key.char == "i":
print("Rotation -Y one")
rotation += np.array([0, -1, 0]) * rot_step_size
elif event.key.char == "o":
print("Rotation +Z one")
rotation += np.array([0, 0, 1]) * rot_step_size
elif event.key.char == "p":
print("Rotation -Z one")
rotation += np.array([0, 0, -1]) * rot_step_size
elif event.key.char == "h":
print("Step to 0.1")
step_size = steps[0]
rot_step_size = rot_steps[0]
elif event.key.char == "j":
print("Step to 0.01")
step_size = steps[1]
rot_step_size = rot_steps[1]
elif event.key.char == "k":
print("Step to 0.001")
step_size = steps[2]
rot_step_size = rot_steps[2]
elif event.key.char == "b":
print("Updating box to match bounding box.")
offset = np.array([0.0, 0.0, 0.0])
rotation = np.array([0.0, 0.0, 0.0])
size = np.array(obj.bounding_box, dtype=float)
elif event.key.char == "c":
done = True
break
print("New position:", offset)
m.set_position(obj_pos + offset)
if IS_CUBOID:
print("New rotation:", rotation)
print("New size:", size)
print("")
poses = get_corner_positions(obj_pos + offset, rotation, size)
for marker, (pos, orn) in zip(markers, poses):
marker.set_position_orientation(pos, orn)
# Record it into the meta file.
if "links" not in meta:
meta["links"] = dict()
dynamics_info = p.getDynamicsInfo(obj.get_body_id(), -1)
inertial_pos, inertial_orn = dynamics_info[3], dynamics_info[4]
rel_position, rel_orn = p.multiplyTransforms(
offset, p.getQuaternionFromEuler(rotation), inertial_pos, inertial_orn
)
if IS_CUBOID:
meta["links"][LINK_NAME] = {
"geometry": "box",
"size": list(size),
"xyz": list(rel_position),
"rpy": list(p.getEulerFromQuaternion(rel_orn)),
}
else:
meta["links"][LINK_NAME] = {"geometry": None, "size": None, "xyz": list(rel_position), "rpy": None}
with open(mfn, "w") as mf:
json.dump(meta, mf)
print("Updated %s" % mfn)
input("Hit enter to continue.")
s.disconnect()
if __name__ == "__main__":
main()
| [
"igibson.utils.assets_utils.download_assets",
"pybullet.getQuaternionFromEuler",
"json.dump",
"json.load",
"pynput.keyboard.Events",
"os.path.basename",
"numpy.deg2rad",
"bddl.object_taxonomy.ObjectTaxonomy",
"igibson.simulator.Simulator",
"numpy.array",
"itertools.product",
"pybullet.getEuler... | [((431, 448), 'igibson.utils.assets_utils.download_assets', 'download_assets', ([], {}), '()\n', (446, 448), False, 'from igibson.utils.assets_utils import download_assets\n'), ((838, 854), 'bddl.object_taxonomy.ObjectTaxonomy', 'ObjectTaxonomy', ([], {}), '()\n', (852, 854), False, 'from bddl.object_taxonomy import ObjectTaxonomy\n'), ((889, 937), 'os.path.join', 'os.path.join', (['igibson.ig_dataset_path', '"""objects"""'], {}), "(igibson.ig_dataset_path, 'objects')\n", (901, 937), False, 'import os\n'), ((1079, 1137), 'os.path.join', 'os.path.join', (['igibson.ig_dataset_path', '"""objects"""', 'category'], {}), "(igibson.ig_dataset_path, 'objects', category)\n", (1091, 1137), False, 'import os\n'), ((1320, 1365), 'os.path.join', 'os.path.join', (['objdir', '"""misc"""', '"""metadata.json"""'], {}), "(objdir, 'misc', 'metadata.json')\n", (1332, 1365), False, 'import os\n'), ((1427, 1461), 'pybullet.getQuaternionFromEuler', 'p.getQuaternionFromEuler', (['rotation'], {}), '(rotation)\n', (1451, 1461), True, 'import pybullet as p\n'), ((1516, 1560), 'itertools.product', 'itertools.product', (['options', 'options', 'options'], {}), '(options, options, options)\n', (1533, 1560), False, 'import itertools\n'), ((2689, 2703), 'os.listdir', 'os.listdir', (['cd'], {}), '(cd)\n', (2699, 2703), False, 'import os\n'), ((2984, 2998), 'os.listdir', 'os.listdir', (['cd'], {}), '(cd)\n', (2994, 2998), False, 'import os\n'), ((965, 980), 'os.listdir', 'os.listdir', (['dir'], {}), '(dir)\n', (975, 980), False, 'import os\n'), ((2730, 2754), 'os.path.join', 'os.path.join', (['cd', 'objdir'], {}), '(cd, objdir)\n', (2742, 2754), False, 'import os\n'), ((3025, 3049), 'os.path.join', 'os.path.join', (['cd', 'objdir'], {}), '(cd, objdir)\n', (3037, 3049), False, 'import os\n'), ((3201, 3226), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (3209, 3226), True, 'import numpy as np\n'), ((3246, 3271), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (3254, 3271), True, 'import numpy as np\n'), ((3295, 3320), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (3303, 3320), True, 'import numpy as np\n'), ((3847, 3868), 'igibson.simulator.Simulator', 'Simulator', ([], {'mode': '"""gui"""'}), "(mode='gui')\n", (3856, 3868), False, 'from igibson.simulator import Simulator\n'), ((3889, 3901), 'igibson.scenes.empty_scene.EmptyScene', 'EmptyScene', ([], {}), '()\n', (3899, 3901), False, 'from igibson.scenes.empty_scene import EmptyScene\n'), ((4029, 4054), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 1.0])\n', (4037, 4054), True, 'import numpy as np\n'), ((4317, 4376), 'igibson.objects.visual_marker.VisualMarker', 'VisualMarker', ([], {'radius': 'marker_size', 'rgba_color': '[0, 0, 1, 0.5]'}), '(radius=marker_size, rgba_color=[0, 0, 1, 0.5])\n', (4329, 4376), False, 'from igibson.objects.visual_marker import VisualMarker\n'), ((1204, 1228), 'os.path.basename', 'os.path.basename', (['folder'], {}), '(folder)\n', (1220, 1228), False, 'import os\n'), ((3165, 3178), 'json.load', 'json.load', (['mf'], {}), '(mf)\n', (3174, 3178), False, 'import json\n'), ((3615, 3656), 'numpy.array', 'np.array', (["meta['links'][LINK_NAME]['xyz']"], {}), "(meta['links'][LINK_NAME]['xyz'])\n", (3623, 3656), True, 'import numpy as np\n'), ((4254, 4267), 'numpy.deg2rad', 'np.deg2rad', (['(1)'], {}), '(1)\n', (4264, 4267), True, 'import numpy as np\n'), ((4269, 4282), 'numpy.deg2rad', 'np.deg2rad', (['(5)'], {}), '(5)\n', (4279, 4282), True, 'import numpy as np\n'), ((4284, 4298), 'numpy.deg2rad', 'np.deg2rad', (['(10)'], {}), '(10)\n', (4294, 4298), True, 'import numpy as np\n'), ((10658, 10692), 'pybullet.getQuaternionFromEuler', 'p.getQuaternionFromEuler', (['rotation'], {}), '(rotation)\n', (10682, 10692), True, 'import pybullet as p\n'), ((11209, 11228), 'json.dump', 'json.dump', (['meta', 'mf'], {}), '(meta, mf)\n', (11218, 11228), False, 'import json\n'), ((1609, 1622), 'numpy.array', 'np.array', (['pos'], {}), '(pos)\n', (1617, 1622), True, 'import numpy as np\n'), ((3714, 3756), 'numpy.array', 'np.array', (["meta['links'][LINK_NAME]['size']"], {}), "(meta['links'][LINK_NAME]['size'])\n", (3722, 3756), True, 'import numpy as np\n'), ((3788, 3829), 'numpy.array', 'np.array', (["meta['links'][LINK_NAME]['rpy']"], {}), "(meta['links'][LINK_NAME]['rpy'])\n", (3796, 3829), True, 'import numpy as np\n'), ((4548, 4607), 'igibson.objects.visual_marker.VisualMarker', 'VisualMarker', ([], {'radius': 'marker_size', 'rgba_color': '[0, 1, 0, 0.5]'}), '(radius=marker_size, rgba_color=[0, 1, 0, 0.5])\n', (4560, 4607), False, 'from igibson.objects.visual_marker import VisualMarker\n'), ((5159, 5176), 'pynput.keyboard.Events', 'keyboard.Events', ([], {}), '()\n', (5174, 5176), False, 'from pynput import keyboard\n'), ((10965, 10998), 'pybullet.getEulerFromQuaternion', 'p.getEulerFromQuaternion', (['rel_orn'], {}), '(rel_orn)\n', (10989, 10998), True, 'import pybullet as p\n'), ((5647, 5666), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (5655, 5666), True, 'import numpy as np\n'), ((5822, 5842), 'numpy.array', 'np.array', (['[-1, 0, 0]'], {}), '([-1, 0, 0])\n', (5830, 5842), True, 'import numpy as np\n'), ((5998, 6018), 'numpy.array', 'np.array', (['[0, -1, 0]'], {}), '([0, -1, 0])\n', (6006, 6018), True, 'import numpy as np\n'), ((6175, 6194), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (6183, 6194), True, 'import numpy as np\n'), ((6348, 6367), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (6356, 6367), True, 'import numpy as np\n'), ((6523, 6543), 'numpy.array', 'np.array', (['[0, 0, -1]'], {}), '([0, 0, -1])\n', (6531, 6543), True, 'import numpy as np\n'), ((6700, 6719), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (6708, 6719), True, 'import numpy as np\n'), ((6873, 6893), 'numpy.array', 'np.array', (['[0, -1, 0]'], {}), '([0, -1, 0])\n', (6881, 6893), True, 'import numpy as np\n'), ((7047, 7067), 'numpy.array', 'np.array', (['[-1, 0, 0]'], {}), '([-1, 0, 0])\n', (7055, 7067), True, 'import numpy as np\n'), ((7222, 7241), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (7230, 7241), True, 'import numpy as np\n'), ((7393, 7412), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (7401, 7412), True, 'import numpy as np\n'), ((7566, 7586), 'numpy.array', 'np.array', (['[0, 0, -1]'], {}), '([0, 0, -1])\n', (7574, 7586), True, 'import numpy as np\n'), ((7744, 7763), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (7752, 7763), True, 'import numpy as np\n'), ((7925, 7945), 'numpy.array', 'np.array', (['[-1, 0, 0]'], {}), '([-1, 0, 0])\n', (7933, 7945), True, 'import numpy as np\n'), ((8107, 8126), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (8115, 8126), True, 'import numpy as np\n'), ((8288, 8308), 'numpy.array', 'np.array', (['[0, -1, 0]'], {}), '([0, -1, 0])\n', (8296, 8308), True, 'import numpy as np\n'), ((8470, 8489), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (8478, 8489), True, 'import numpy as np\n'), ((8651, 8671), 'numpy.array', 'np.array', (['[0, 0, -1]'], {}), '([0, 0, -1])\n', (8659, 8671), True, 'import numpy as np\n'), ((9474, 9499), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (9482, 9499), True, 'import numpy as np\n'), ((9539, 9564), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (9547, 9564), True, 'import numpy as np\n'), ((9600, 9639), 'numpy.array', 'np.array', (['obj.bounding_box'], {'dtype': 'float'}), '(obj.bounding_box, dtype=float)\n', (9608, 9639), True, 'import numpy as np\n')] |
import cv2
import numpy as np
BLUE_RGB = (255, 0, 0)
WHITE_RGB = (255, 255, 255)
def create_mask(img):
lower_color = np.array([0, 0, 0], np.uint8)
upper_color = np.array([200, 255, 200], np.uint8)
# Get an Histogram based on the color saturation of the image
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Create a mask based on the lower_color and upper_color
return cv2.inRange(hsv, lower_color, upper_color)
def erode_mask(mask):
# Create a kernel matrix
kernel = np.ones((5, 5), "uint8")
# Erode the mask using the kernel
return cv2.erode(mask, kernel, iterations=1)
def bitwise(eroded_mask, img):
return cv2.bitwise_and(img, img, mask=eroded_mask)
def get_contours(eroded_mask):
# Return the contourns of the objects detected with the eroded mask
(_, contours, _) = cv2.findContours(eroded_mask, cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
return contours
def create_coutours(img):
return get_contours(erode_mask(create_mask(img)))
def get_area_from_contour(contour):
# Get area from contour
return cv2.contourArea(contour)
def draw_rectangular_contour(img, contour, area):
# Get the rectangle bounding the contour
x, y, w, h = cv2.boundingRect(contour)
# Add the rectangle on the img
img = cv2.rectangle(img, (x, y), (x + w, y + h), BLUE_RGB, 2)
# Write Area and its (x, y) coordinates
cv2.putText(img, "Area {}".format(area), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, BLUE_RGB)
return img
def get_mass_center(contour):
# Get the mass center
mass_center = cv2.moments(contour)
x = int(mass_center['m10'] / mass_center['m00'])
y = int(mass_center['m01'] / mass_center['m00'])
return x, y
def draw_center(img, contour):
cx, cy = get_mass_center(contour)
# Add the rectangle on the img
img = cv2.circle(img, (cx, cy), 7, WHITE_RGB, -1)
return img
def show_image(img, title="image rendered"):
# Show the image on a separate window
cv2.imshow(title, img)
def escape_on_q(cap):
# Need to press Q on the image
if cv2.waitKey(10) & 0xFF == ord('q'):
cap.release()
cv2.destroyAllWindows()
| [
"cv2.contourArea",
"cv2.circle",
"cv2.bitwise_and",
"cv2.cvtColor",
"cv2.destroyAllWindows",
"cv2.waitKey",
"cv2.moments",
"cv2.imshow",
"numpy.ones",
"numpy.array",
"cv2.rectangle",
"cv2.erode",
"cv2.boundingRect",
"cv2.inRange",
"cv2.findContours"
] | [((124, 153), 'numpy.array', 'np.array', (['[0, 0, 0]', 'np.uint8'], {}), '([0, 0, 0], np.uint8)\n', (132, 153), True, 'import numpy as np\n'), ((172, 207), 'numpy.array', 'np.array', (['[200, 255, 200]', 'np.uint8'], {}), '([200, 255, 200], np.uint8)\n', (180, 207), True, 'import numpy as np\n'), ((285, 321), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2HSV'], {}), '(img, cv2.COLOR_BGR2HSV)\n', (297, 321), False, 'import cv2\n'), ((394, 436), 'cv2.inRange', 'cv2.inRange', (['hsv', 'lower_color', 'upper_color'], {}), '(hsv, lower_color, upper_color)\n', (405, 436), False, 'import cv2\n'), ((503, 527), 'numpy.ones', 'np.ones', (['(5, 5)', '"""uint8"""'], {}), "((5, 5), 'uint8')\n", (510, 527), True, 'import numpy as np\n'), ((578, 615), 'cv2.erode', 'cv2.erode', (['mask', 'kernel'], {'iterations': '(1)'}), '(mask, kernel, iterations=1)\n', (587, 615), False, 'import cv2\n'), ((660, 703), 'cv2.bitwise_and', 'cv2.bitwise_and', (['img', 'img'], {'mask': 'eroded_mask'}), '(img, img, mask=eroded_mask)\n', (675, 703), False, 'import cv2\n'), ((832, 901), 'cv2.findContours', 'cv2.findContours', (['eroded_mask', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(eroded_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n', (848, 901), False, 'import cv2\n'), ((1121, 1145), 'cv2.contourArea', 'cv2.contourArea', (['contour'], {}), '(contour)\n', (1136, 1145), False, 'import cv2\n'), ((1260, 1285), 'cv2.boundingRect', 'cv2.boundingRect', (['contour'], {}), '(contour)\n', (1276, 1285), False, 'import cv2\n'), ((1331, 1386), 'cv2.rectangle', 'cv2.rectangle', (['img', '(x, y)', '(x + w, y + h)', 'BLUE_RGB', '(2)'], {}), '(img, (x, y), (x + w, y + h), BLUE_RGB, 2)\n', (1344, 1386), False, 'import cv2\n'), ((1617, 1637), 'cv2.moments', 'cv2.moments', (['contour'], {}), '(contour)\n', (1628, 1637), False, 'import cv2\n'), ((1877, 1920), 'cv2.circle', 'cv2.circle', (['img', '(cx, cy)', '(7)', 'WHITE_RGB', '(-1)'], {}), '(img, (cx, cy), 7, WHITE_RGB, -1)\n', (1887, 1920), False, 'import cv2\n'), ((2030, 2052), 'cv2.imshow', 'cv2.imshow', (['title', 'img'], {}), '(title, img)\n', (2040, 2052), False, 'import cv2\n'), ((2185, 2208), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (2206, 2208), False, 'import cv2\n'), ((2119, 2134), 'cv2.waitKey', 'cv2.waitKey', (['(10)'], {}), '(10)\n', (2130, 2134), False, 'import cv2\n')] |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 7 12:43:38 2022
@author: Paul
"""
import pandas as pd
import chemcoord as cc
import os
import numpy as np
from scipy.constants import Planck
from scipy.spatial.transform import Rotation as R
def anglebetweenvec (vec1, vec2):
vec1 = vec1/np.linalg.norm(vec1)
vec2 = vec2/np.linalg.norm(vec2)
cp=np.cross(vec1,vec2)
dp=np.dot(vec1,vec2)
# sine_ang=np.linalg.norm(cp)
cosine_ang=dp
ssc = np.array([[0,-cp[2],cp[1]],[cp[2],0,-cp[0]],[-cp[1],cp[0],0]])
rot_mat = np.identity(3)+ssc+np.dot(ssc,ssc)/(1+cosine_ang)
ff=R.from_matrix(rot_mat)
eul=ff.as_euler('zyz',degrees='True')
return eul
nuctable=pd.read_excel('NMR_freq_table.xlsx')
gyr_ratio_MHz_T=nuctable["GyrHz"];
name_nuc=nuctable["Name"];
nuc_symb=nuctable["Symbol"]
cur_dir = os.getcwd()
xyz_dir = os.chdir('amino_acids_xyz')
gly = cc.Cartesian.read_xyz('Glycine.xyz', start_index=1)
coord_gly = gly[['x','y','z']].to_numpy()
gyr_gly_atom=np.array([])
atom_name_list=gly['atom'].to_numpy()
l=nuc_symb.to_numpy()
for i in range(0, np.shape(coord_gly)[0]):
gyr_gly_atom=np.append(gyr_gly_atom, gyr_ratio_MHz_T.iloc[np.where(l==atom_name_list[i])].to_numpy())
dist=np.zeros([np.shape(coord_gly)[0],np.shape(coord_gly)[0]])
dip=np.zeros([np.shape(coord_gly)[0],np.shape(coord_gly)[0]])
for i in range(0, np.shape(coord_gly)[0]):
gyr1=gyr_gly_atom[i]*1e6
for j in range(i+1, np.shape(coord_gly)[0]):
dist[i][j]=np.sqrt(np.sum((coord_gly[i]-coord_gly[j])**2))
gyr2=gyr_gly_atom[j]*1e6
dip[i][j]=-1e-7*(gyr1*gyr2*Planck)/((dist[i][j]*1e-10) ** 3);
#with open('dipole_gly.txt' , ''
#np.set_printoptions(formatter={'float': lambda x: "{0:0.3f}".format(x)})
np.set_printoptions(precision=3)
for i in range(0, np.shape(coord_gly)[0]):
for j in range(i+1, np.shape(coord_gly)[0]):
eulo=np.round(anglebetweenvec(coord_gly[i], coord_gly[j]),2)
print(i+1,j+1,np.round(dip[i][j],2),*eulo)
| [
"chemcoord.Cartesian.read_xyz",
"numpy.set_printoptions",
"numpy.sum",
"os.getcwd",
"numpy.cross",
"numpy.identity",
"pandas.read_excel",
"numpy.shape",
"numpy.where",
"numpy.array",
"numpy.linalg.norm",
"scipy.spatial.transform.Rotation.from_matrix",
"numpy.dot",
"numpy.round",
"os.chdi... | [((696, 732), 'pandas.read_excel', 'pd.read_excel', (['"""NMR_freq_table.xlsx"""'], {}), "('NMR_freq_table.xlsx')\n", (709, 732), True, 'import pandas as pd\n'), ((834, 845), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (843, 845), False, 'import os\n'), ((856, 883), 'os.chdir', 'os.chdir', (['"""amino_acids_xyz"""'], {}), "('amino_acids_xyz')\n", (864, 883), False, 'import os\n'), ((892, 943), 'chemcoord.Cartesian.read_xyz', 'cc.Cartesian.read_xyz', (['"""Glycine.xyz"""'], {'start_index': '(1)'}), "('Glycine.xyz', start_index=1)\n", (913, 943), True, 'import chemcoord as cc\n'), ((1000, 1012), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1008, 1012), True, 'import numpy as np\n'), ((1756, 1788), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(3)'}), '(precision=3)\n', (1775, 1788), True, 'import numpy as np\n'), ((356, 376), 'numpy.cross', 'np.cross', (['vec1', 'vec2'], {}), '(vec1, vec2)\n', (364, 376), True, 'import numpy as np\n'), ((383, 401), 'numpy.dot', 'np.dot', (['vec1', 'vec2'], {}), '(vec1, vec2)\n', (389, 401), True, 'import numpy as np\n'), ((462, 532), 'numpy.array', 'np.array', (['[[0, -cp[2], cp[1]], [cp[2], 0, -cp[0]], [-cp[1], cp[0], 0]]'], {}), '([[0, -cp[2], cp[1]], [cp[2], 0, -cp[0]], [-cp[1], cp[0], 0]])\n', (470, 532), True, 'import numpy as np\n'), ((596, 618), 'scipy.spatial.transform.Rotation.from_matrix', 'R.from_matrix', (['rot_mat'], {}), '(rot_mat)\n', (609, 618), True, 'from scipy.spatial.transform import Rotation as R\n'), ((291, 311), 'numpy.linalg.norm', 'np.linalg.norm', (['vec1'], {}), '(vec1)\n', (305, 311), True, 'import numpy as np\n'), ((328, 348), 'numpy.linalg.norm', 'np.linalg.norm', (['vec2'], {}), '(vec2)\n', (342, 348), True, 'import numpy as np\n'), ((1091, 1110), 'numpy.shape', 'np.shape', (['coord_gly'], {}), '(coord_gly)\n', (1099, 1110), True, 'import numpy as np\n'), ((1367, 1386), 'numpy.shape', 'np.shape', (['coord_gly'], {}), '(coord_gly)\n', (1375, 1386), True, 'import numpy as np\n'), ((1807, 1826), 'numpy.shape', 'np.shape', (['coord_gly'], {}), '(coord_gly)\n', (1815, 1826), True, 'import numpy as np\n'), ((539, 553), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (550, 553), True, 'import numpy as np\n'), ((558, 574), 'numpy.dot', 'np.dot', (['ssc', 'ssc'], {}), '(ssc, ssc)\n', (564, 574), True, 'import numpy as np\n'), ((1239, 1258), 'numpy.shape', 'np.shape', (['coord_gly'], {}), '(coord_gly)\n', (1247, 1258), True, 'import numpy as np\n'), ((1262, 1281), 'numpy.shape', 'np.shape', (['coord_gly'], {}), '(coord_gly)\n', (1270, 1281), True, 'import numpy as np\n'), ((1301, 1320), 'numpy.shape', 'np.shape', (['coord_gly'], {}), '(coord_gly)\n', (1309, 1320), True, 'import numpy as np\n'), ((1324, 1343), 'numpy.shape', 'np.shape', (['coord_gly'], {}), '(coord_gly)\n', (1332, 1343), True, 'import numpy as np\n'), ((1445, 1464), 'numpy.shape', 'np.shape', (['coord_gly'], {}), '(coord_gly)\n', (1453, 1464), True, 'import numpy as np\n'), ((1497, 1539), 'numpy.sum', 'np.sum', (['((coord_gly[i] - coord_gly[j]) ** 2)'], {}), '((coord_gly[i] - coord_gly[j]) ** 2)\n', (1503, 1539), True, 'import numpy as np\n'), ((1856, 1875), 'numpy.shape', 'np.shape', (['coord_gly'], {}), '(coord_gly)\n', (1864, 1875), True, 'import numpy as np\n'), ((1972, 1994), 'numpy.round', 'np.round', (['dip[i][j]', '(2)'], {}), '(dip[i][j], 2)\n', (1980, 1994), True, 'import numpy as np\n'), ((1178, 1210), 'numpy.where', 'np.where', (['(l == atom_name_list[i])'], {}), '(l == atom_name_list[i])\n', (1186, 1210), True, 'import numpy as np\n')] |
# Author: <NAME> <<EMAIL>>
"""
Calculate Segmentation metrics:
- GlobalAccuracy
- MeanAccuracy
- Mean MeanIoU
"""
import numpy as np
from data_io import imread
def cal_semantic_metrics(pred_list, gt_list, thresh_step=0.01, num_cls=2):
final_accuracy_all = []
for thresh in np.arange(0.0, 1.0, thresh_step):
print(thresh)
global_accuracy_cur = []
statistics = []
for pred, gt in zip(pred_list, gt_list):
gt_img = (gt/255).astype('uint8')
pred_img = (pred/255 > thresh).astype('uint8')
# calculate each image
global_accuracy_cur.append(cal_global_acc(pred_img, gt_img))
statistics.append(get_statistics(pred_img, gt_img, num_cls))
# get global accuracy with corresponding threshold: (TP+TN)/all_pixels
global_acc = np.sum([v[0] for v in global_accuracy_cur])/np.sum([v[1] for v in global_accuracy_cur])
# get tp, fp, fn
counts = []
for i in range(num_cls):
tp = np.sum([v[i][0] for v in statistics])
fp = np.sum([v[i][1] for v in statistics])
fn = np.sum([v[i][2] for v in statistics])
counts.append([tp, fp, fn])
# calculate mean accuracy
mean_acc = np.sum([v[0]/(v[0]+v[2]) for v in counts])/num_cls
# calculate mean iou
mean_iou_acc = np.sum([v[0]/(np.sum(v)) for v in counts])/num_cls
final_accuracy_all.append([thresh, global_acc, mean_acc, mean_iou_acc])
return final_accuracy_all
def cal_global_acc(pred, gt):
"""
acc = (TP+TN)/all_pixels
"""
h,w = gt.shape
return [np.sum(pred==gt), float(h*w)]
def get_statistics(pred, gt, num_cls=2):
"""
return tp, fp, fn
"""
h,w = gt.shape
statistics = []
for i in range(num_cls):
tp = np.sum((pred==i)&(gt==i))
fp = np.sum((pred==i)&(gt!=i))
fn = np.sum((pred!=i)&(gt==i))
statistics.append([tp, fp, fn])
return statistics
| [
"numpy.arange",
"numpy.sum"
] | [((288, 320), 'numpy.arange', 'np.arange', (['(0.0)', '(1.0)', 'thresh_step'], {}), '(0.0, 1.0, thresh_step)\n', (297, 320), True, 'import numpy as np\n'), ((1662, 1680), 'numpy.sum', 'np.sum', (['(pred == gt)'], {}), '(pred == gt)\n', (1668, 1680), True, 'import numpy as np\n'), ((1853, 1884), 'numpy.sum', 'np.sum', (['((pred == i) & (gt == i))'], {}), '((pred == i) & (gt == i))\n', (1859, 1884), True, 'import numpy as np\n'), ((1892, 1923), 'numpy.sum', 'np.sum', (['((pred == i) & (gt != i))'], {}), '((pred == i) & (gt != i))\n', (1898, 1923), True, 'import numpy as np\n'), ((1931, 1962), 'numpy.sum', 'np.sum', (['((pred != i) & (gt == i))'], {}), '((pred != i) & (gt == i))\n', (1937, 1962), True, 'import numpy as np\n'), ((856, 899), 'numpy.sum', 'np.sum', (['[v[0] for v in global_accuracy_cur]'], {}), '([v[0] for v in global_accuracy_cur])\n', (862, 899), True, 'import numpy as np\n'), ((900, 943), 'numpy.sum', 'np.sum', (['[v[1] for v in global_accuracy_cur]'], {}), '([v[1] for v in global_accuracy_cur])\n', (906, 943), True, 'import numpy as np\n'), ((1048, 1085), 'numpy.sum', 'np.sum', (['[v[i][0] for v in statistics]'], {}), '([v[i][0] for v in statistics])\n', (1054, 1085), True, 'import numpy as np\n'), ((1103, 1140), 'numpy.sum', 'np.sum', (['[v[i][1] for v in statistics]'], {}), '([v[i][1] for v in statistics])\n', (1109, 1140), True, 'import numpy as np\n'), ((1158, 1195), 'numpy.sum', 'np.sum', (['[v[i][2] for v in statistics]'], {}), '([v[i][2] for v in statistics])\n', (1164, 1195), True, 'import numpy as np\n'), ((1290, 1338), 'numpy.sum', 'np.sum', (['[(v[0] / (v[0] + v[2])) for v in counts]'], {}), '([(v[0] / (v[0] + v[2])) for v in counts])\n', (1296, 1338), True, 'import numpy as np\n'), ((1407, 1416), 'numpy.sum', 'np.sum', (['v'], {}), '(v)\n', (1413, 1416), True, 'import numpy as np\n')] |
import structured_map_ranking_loss
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from confidnet.utils import misc
class SelfConfidMSELoss(nn.modules.loss._Loss):
def __init__(self, config_args, device):
self.nb_classes = config_args["data"]["num_classes"]
self.task = config_args["training"]["task"]
self.weighting = config_args["training"]["loss"]["weighting"]
self.device = device
super().__init__()
def forward(self, input, target):
probs = F.softmax(input[0], dim=1)
confidence = torch.sigmoid(input[1]).squeeze()
# Apply optional weighting
weights = torch.ones_like(target).type(torch.FloatTensor).to(self.device)
weights[(probs.argmax(dim=1) != target)] *= self.weighting
labels_hot = misc.one_hot_embedding(target, self.nb_classes).to(self.device)
# Segmentation special case
if self.task == "segmentation":
labels_hot = labels_hot.permute(0, 3, 1, 2)
loss = weights * (confidence - (probs * labels_hot).sum(dim=1)) ** 2
return torch.mean(loss)
class SteepSlopeLoss(nn.modules.loss._Loss):
def __init__(self, config_args, device):
self.nb_classes = config_args["data"]["num_classes"]
self.task = config_args["training"]["task"]
self.weighting = config_args["training"]["loss"]["weighting"]
self.device = device
self.hyperparam = [1.0, 1.0]
self.db = 0.0
if config_args["training"]["loss"]["hyperparam"]:
self.hyperparam = [config_args["training"]["loss"]["hyperparam"][0], config_args["training"]["loss"]["hyperparam"][1]]
super().__init__()
def forward(self, input, target):
probs = F.softmax(input[0], dim=1)
# confidence = torch.sigmoid(input[1]).squeeze()
x = input[1].squeeze()
gt = (probs.argmax(dim=1) == target).float()
alpha_neg, alpha_pos = self.hyperparam[0], self.hyperparam[1]
# Apply optional weighting
# weights = torch.ones_like(target).type(torch.FloatTensor).to(self.device)
# weights[(probs.argmax(dim=1) != target)] *= self.weighting
# labels_hot = misc.one_hot_embedding(target, self.nb_classes).to(self.device)
# Segmentation special case
if self.task == "segmentation":
labels_hot = labels_hot.permute(0, 3, 1, 2)
# loss = weights * (confidence - (probs * labels_hot).sum(dim=1)) ** 2
loss_neg = torch.exp(alpha_neg*x/(1+torch.abs(x))) - np.exp(-alpha_neg)
loss_pos = torch.exp(-alpha_pos*x/(1+torch.abs(x))) - np.exp(-alpha_pos)
loss = gt*loss_pos + (1-gt)*loss_neg
return torch.mean(loss)
class SelfConfidTCPRLoss(nn.modules.loss._Loss):
def __init__(self, config_args, device):
self.nb_classes = config_args["data"]["num_classes"]
self.task = config_args["training"]["task"]
self.weighting = config_args["training"]["loss"]["weighting"]
self.device = device
super().__init__()
def forward(self, input, target):
probs = F.softmax(input[0], dim=1)
maxprob = probs.max(dim=1)[0]
confidence = torch.sigmoid(input[1]).squeeze()
# Apply optional weighting
weights = torch.ones_like(target).type(torch.FloatTensor).to(self.device)
weights[(probs.argmax(dim=1) != target)] *= self.weighting
labels_hot = misc.one_hot_embedding(target, self.nb_classes).to(self.device)
# Segmentation special case
if self.task == "segmentation":
labels_hot = labels_hot.permute(0, 3, 1, 2)
loss = weights * (confidence - (probs * labels_hot).sum(dim=1) / maxprob) ** 2
return torch.mean(loss)
class SelfConfidBCELoss(nn.modules.loss._Loss):
def __init__(self, device, config_args):
self.nb_classes = config_args["data"]["num_classes"]
self.weighting = config_args["training"]["loss"]["weighting"]
self.device = device
super().__init__()
def forward(self, input, target):
confidence = input[1].squeeze(dim=1)
weights = torch.ones_like(target).type(torch.FloatTensor).to(self.device)
weights[(input[0].argmax(dim=1) != target)] *= self.weighting
return nn.BCEWithLogitsLoss(weight=weights)(
confidence, (input[0].argmax(dim=1) == target).float()
)
class FocalLoss(nn.modules.loss._Loss):
def __init__(self, config_args, device):
super().__init__()
self.alpha = config_args["training"]["loss"].get("alpha", 0.25)
self.gamma = config_args["training"]["loss"].get("gamma", 5)
def forward(self, input, target):
confidence = input[1].squeeze(dim=1)
BCE_loss = F.binary_cross_entropy_with_logits(
confidence, (input[0].argmax(dim=1) == target).float(), reduction="none"
)
pt = torch.exp(-BCE_loss)
loss = self.alpha * (1 - pt) ** self.gamma * BCE_loss
return torch.mean(loss)
class StructuredMAPRankingLossFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, input, target, mask):
loss, ranking_lai = structured_map_ranking_loss.forward(input, target, mask)
ctx.save_for_backward(input, target, mask, ranking_lai)
return loss
@staticmethod
def backward(ctx, grad_output):
input, target, mask, ranking_lai = ctx.saved_variables
grad_input = structured_map_ranking_loss.backward(
grad_output, input, target, mask, ranking_lai
)
return grad_input, None, None
class StructuredMAPRankingLoss(nn.modules.loss._Loss):
def __init__(self, device, config_args):
self.nb_classes = config_args["data"]["num_classes"]
self.device = device
super().__init__()
def forward(self, input, target):
confidence = input[1]
mask = torch.ones_like(target).unsqueeze(dim=1)
return StructuredMAPRankingLossFunction.apply(
confidence,
(input[0].argmax(dim=1) == target).float().unsqueeze(dim=1),
mask.to(dtype=torch.uint8),
)
class OODConfidenceLoss(nn.modules.loss._Loss):
def __init__(self, device, config_args):
self.nb_classes = config_args["data"]["num_classes"]
self.task = config_args["training"]["task"]
self.device = device
self.half_random = config_args["training"]["loss"]["half_random"]
self.beta = config_args["training"]["loss"]["beta"]
self.lbda = config_args["training"]["loss"]["lbda"]
self.lbda_control = config_args["training"]["loss"]["lbda_control"]
self.loss_nll, self.loss_confid = None, None
super().__init__()
def forward(self, input, target):
probs = F.softmax(input[0], dim=1)
confidence = torch.sigmoid(input[1])
# Make sure we don't have any numerical instability
eps = 1e-12
probs = torch.clamp(probs, 0.0 + eps, 1.0 - eps)
confidence = torch.clamp(confidence, 0.0 + eps, 1.0 - eps)
if self.half_random:
# Randomly set half of the confidences to 1 (i.e. no hints)
b = torch.bernoulli(torch.Tensor(confidence.size()).uniform_(0, 1)).to(self.device)
conf = confidence * b + (1 - b)
else:
conf = confidence
labels_hot = misc.one_hot_embedding(target, self.nb_classes).to(self.device)
# Segmentation special case
if self.task == "segmentation":
labels_hot = labels_hot.permute(0, 3, 1, 2)
probs_interpol = torch.log(conf * probs + (1 - conf) * labels_hot)
self.loss_nll = nn.NLLLoss()(probs_interpol, target)
self.loss_confid = torch.mean(-(torch.log(confidence)))
total_loss = self.loss_nll + self.lbda * self.loss_confid
# Update lbda
if self.lbda_control:
if self.loss_confid >= self.beta:
self.lbda /= 0.99
else:
self.lbda /= 1.01
return total_loss
# PYTORCH LOSSES LISTS
PYTORCH_LOSS = {"cross_entropy": nn.CrossEntropyLoss}
# CUSTOM LOSSES LISTS
CUSTOM_LOSS = {
"steep": SteepSlopeLoss,
"selfconfid_mse": SelfConfidMSELoss,
"selfconfid_tcpr": SelfConfidTCPRLoss,
"selfconfid_bce": SelfConfidBCELoss,
"focal": FocalLoss,
"ranking": StructuredMAPRankingLoss,
"ood_confidence": OODConfidenceLoss,
}
| [
"torch.mean",
"torch.ones_like",
"structured_map_ranking_loss.backward",
"torch.nn.BCEWithLogitsLoss",
"torch.log",
"torch.nn.functional.softmax",
"torch.nn.NLLLoss",
"torch.exp",
"torch.sigmoid",
"torch.clamp",
"confidnet.utils.misc.one_hot_embedding",
"numpy.exp",
"torch.abs",
"structure... | [((544, 570), 'torch.nn.functional.softmax', 'F.softmax', (['input[0]'], {'dim': '(1)'}), '(input[0], dim=1)\n', (553, 570), True, 'import torch.nn.functional as F\n'), ((1119, 1135), 'torch.mean', 'torch.mean', (['loss'], {}), '(loss)\n', (1129, 1135), False, 'import torch\n'), ((1769, 1795), 'torch.nn.functional.softmax', 'F.softmax', (['input[0]'], {'dim': '(1)'}), '(input[0], dim=1)\n', (1778, 1795), True, 'import torch.nn.functional as F\n'), ((2717, 2733), 'torch.mean', 'torch.mean', (['loss'], {}), '(loss)\n', (2727, 2733), False, 'import torch\n'), ((3124, 3150), 'torch.nn.functional.softmax', 'F.softmax', (['input[0]'], {'dim': '(1)'}), '(input[0], dim=1)\n', (3133, 3150), True, 'import torch.nn.functional as F\n'), ((3747, 3763), 'torch.mean', 'torch.mean', (['loss'], {}), '(loss)\n', (3757, 3763), False, 'import torch\n'), ((4914, 4934), 'torch.exp', 'torch.exp', (['(-BCE_loss)'], {}), '(-BCE_loss)\n', (4923, 4934), False, 'import torch\n'), ((5012, 5028), 'torch.mean', 'torch.mean', (['loss'], {}), '(loss)\n', (5022, 5028), False, 'import torch\n'), ((5185, 5241), 'structured_map_ranking_loss.forward', 'structured_map_ranking_loss.forward', (['input', 'target', 'mask'], {}), '(input, target, mask)\n', (5220, 5241), False, 'import structured_map_ranking_loss\n'), ((5465, 5552), 'structured_map_ranking_loss.backward', 'structured_map_ranking_loss.backward', (['grad_output', 'input', 'target', 'mask', 'ranking_lai'], {}), '(grad_output, input, target, mask,\n ranking_lai)\n', (5501, 5552), False, 'import structured_map_ranking_loss\n'), ((6797, 6823), 'torch.nn.functional.softmax', 'F.softmax', (['input[0]'], {'dim': '(1)'}), '(input[0], dim=1)\n', (6806, 6823), True, 'import torch.nn.functional as F\n'), ((6845, 6868), 'torch.sigmoid', 'torch.sigmoid', (['input[1]'], {}), '(input[1])\n', (6858, 6868), False, 'import torch\n'), ((6966, 7006), 'torch.clamp', 'torch.clamp', (['probs', '(0.0 + eps)', '(1.0 - eps)'], {}), '(probs, 0.0 + eps, 1.0 - eps)\n', (6977, 7006), False, 'import torch\n'), ((7028, 7073), 'torch.clamp', 'torch.clamp', (['confidence', '(0.0 + eps)', '(1.0 - eps)'], {}), '(confidence, 0.0 + eps, 1.0 - eps)\n', (7039, 7073), False, 'import torch\n'), ((7603, 7652), 'torch.log', 'torch.log', (['(conf * probs + (1 - conf) * labels_hot)'], {}), '(conf * probs + (1 - conf) * labels_hot)\n', (7612, 7652), False, 'import torch\n'), ((2556, 2574), 'numpy.exp', 'np.exp', (['(-alpha_neg)'], {}), '(-alpha_neg)\n', (2562, 2574), True, 'import numpy as np\n'), ((2637, 2655), 'numpy.exp', 'np.exp', (['(-alpha_pos)'], {}), '(-alpha_pos)\n', (2643, 2655), True, 'import numpy as np\n'), ((4297, 4333), 'torch.nn.BCEWithLogitsLoss', 'nn.BCEWithLogitsLoss', ([], {'weight': 'weights'}), '(weight=weights)\n', (4317, 4333), True, 'import torch.nn as nn\n'), ((7677, 7689), 'torch.nn.NLLLoss', 'nn.NLLLoss', ([], {}), '()\n', (7687, 7689), True, 'import torch.nn as nn\n'), ((592, 615), 'torch.sigmoid', 'torch.sigmoid', (['input[1]'], {}), '(input[1])\n', (605, 615), False, 'import torch\n'), ((831, 878), 'confidnet.utils.misc.one_hot_embedding', 'misc.one_hot_embedding', (['target', 'self.nb_classes'], {}), '(target, self.nb_classes)\n', (853, 878), False, 'from confidnet.utils import misc\n'), ((3210, 3233), 'torch.sigmoid', 'torch.sigmoid', (['input[1]'], {}), '(input[1])\n', (3223, 3233), False, 'import torch\n'), ((3449, 3496), 'confidnet.utils.misc.one_hot_embedding', 'misc.one_hot_embedding', (['target', 'self.nb_classes'], {}), '(target, self.nb_classes)\n', (3471, 3496), False, 'from confidnet.utils import misc\n'), ((5912, 5935), 'torch.ones_like', 'torch.ones_like', (['target'], {}), '(target)\n', (5927, 5935), False, 'import torch\n'), ((7382, 7429), 'confidnet.utils.misc.one_hot_embedding', 'misc.one_hot_embedding', (['target', 'self.nb_classes'], {}), '(target, self.nb_classes)\n', (7404, 7429), False, 'from confidnet.utils import misc\n'), ((7754, 7775), 'torch.log', 'torch.log', (['confidence'], {}), '(confidence)\n', (7763, 7775), False, 'import torch\n'), ((679, 702), 'torch.ones_like', 'torch.ones_like', (['target'], {}), '(target)\n', (694, 702), False, 'import torch\n'), ((2539, 2551), 'torch.abs', 'torch.abs', (['x'], {}), '(x)\n', (2548, 2551), False, 'import torch\n'), ((2620, 2632), 'torch.abs', 'torch.abs', (['x'], {}), '(x)\n', (2629, 2632), False, 'import torch\n'), ((3297, 3320), 'torch.ones_like', 'torch.ones_like', (['target'], {}), '(target)\n', (3312, 3320), False, 'import torch\n'), ((4148, 4171), 'torch.ones_like', 'torch.ones_like', (['target'], {}), '(target)\n', (4163, 4171), False, 'import torch\n')] |
"""
dynophores.tests.fixures
Fixures to be used in unit testing.
"""
from pathlib import Path
import pytest
import numpy as np
from dynophores import Dynophore, SuperFeature, EnvPartner, ChemicalFeatureCloud3D
PATH_TEST_DATA = Path(__name__).parent / "dynophores" / "tests" / "data"
@pytest.fixture(scope="module")
def envpartner():
envpartner_dict = {
"id": "ILE-10-A[169,171,172]",
"residue_name": "ILE",
"residue_number": 10,
"chain": "A",
"atom_numbers": [169, 171, 172],
"occurrences": np.array([0, 0, 1]),
"distances": np.array([6.0, 6.0, 3.0]),
}
envpartner = EnvPartner(**envpartner_dict)
return envpartner
@pytest.fixture(scope="module")
def chemicalfeaturecloud3d():
cloud_dict = {
"id": "H[4599,4602,4601,4608,4609,4600]",
"center": np.array([1, 1, 1]),
"points": np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]]),
}
cloud = ChemicalFeatureCloud3D(**cloud_dict)
return cloud
@pytest.fixture(scope="module")
def superfeature():
envpartner1_dict = {
"id": "ILE-10-A[169,171,172]",
"residue_name": "ILE",
"residue_number": 10,
"chain": "A",
"atom_numbers": [169, 171, 172],
"occurrences": np.array([0, 0, 1]),
"distances": np.array([6.0, 6.0, 3.0]),
}
envpartner2_dict = {
"id": "VAL-18-A[275,276,277]",
"residue_name": "VAL",
"residue_number": 18,
"chain": "A",
"atom_numbers": [275, 276, 277],
"occurrences": np.array([0, 1, 0]),
"distances": np.array([6.0, 4.0, 4.0]),
}
cloud_dict = {
"id": "H[4599,4602,4601,4608,4609,4600]",
"center": np.array([1, 1, 1]),
"points": np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]]),
}
superfeature_dict = {
"id": "H[4599,4602,4601,4608,4609,4600]",
"feature_type": "H",
"atom_numbers": [4599, 4602, 4601, 4608, 4609, 4600],
"occurrences": np.array([0, 1, 1]),
"envpartners": {
envpartner1_dict["id"]: EnvPartner(**envpartner1_dict),
envpartner2_dict["id"]: EnvPartner(**envpartner2_dict),
},
"cloud": ChemicalFeatureCloud3D(**cloud_dict),
}
superfeature = SuperFeature(**superfeature_dict)
return superfeature
@pytest.fixture(scope="module")
def dynophore():
dynophore = Dynophore.from_dir(PATH_TEST_DATA / "out")
return dynophore
| [
"dynophores.EnvPartner",
"dynophores.Dynophore.from_dir",
"pytest.fixture",
"pathlib.Path",
"numpy.array",
"dynophores.ChemicalFeatureCloud3D",
"dynophores.SuperFeature"
] | [((291, 321), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (305, 321), False, 'import pytest\n'), ((699, 729), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (713, 729), False, 'import pytest\n'), ((1010, 1040), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1024, 1040), False, 'import pytest\n'), ((2342, 2372), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (2356, 2372), False, 'import pytest\n'), ((644, 673), 'dynophores.EnvPartner', 'EnvPartner', ([], {}), '(**envpartner_dict)\n', (654, 673), False, 'from dynophores import Dynophore, SuperFeature, EnvPartner, ChemicalFeatureCloud3D\n'), ((953, 989), 'dynophores.ChemicalFeatureCloud3D', 'ChemicalFeatureCloud3D', ([], {}), '(**cloud_dict)\n', (975, 989), False, 'from dynophores import Dynophore, SuperFeature, EnvPartner, ChemicalFeatureCloud3D\n'), ((2281, 2314), 'dynophores.SuperFeature', 'SuperFeature', ([], {}), '(**superfeature_dict)\n', (2293, 2314), False, 'from dynophores import Dynophore, SuperFeature, EnvPartner, ChemicalFeatureCloud3D\n'), ((2407, 2449), 'dynophores.Dynophore.from_dir', 'Dynophore.from_dir', (["(PATH_TEST_DATA / 'out')"], {}), "(PATH_TEST_DATA / 'out')\n", (2425, 2449), False, 'from dynophores import Dynophore, SuperFeature, EnvPartner, ChemicalFeatureCloud3D\n'), ((551, 570), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (559, 570), True, 'import numpy as np\n'), ((593, 618), 'numpy.array', 'np.array', (['[6.0, 6.0, 3.0]'], {}), '([6.0, 6.0, 3.0])\n', (601, 618), True, 'import numpy as np\n'), ((848, 867), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (856, 867), True, 'import numpy as np\n'), ((887, 933), 'numpy.array', 'np.array', (['[[-1, -1, -1], [0, 0, 0], [1, 1, 1]]'], {}), '([[-1, -1, -1], [0, 0, 0], [1, 1, 1]])\n', (895, 933), True, 'import numpy as np\n'), ((1273, 1292), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (1281, 1292), True, 'import numpy as np\n'), ((1315, 1340), 'numpy.array', 'np.array', (['[6.0, 6.0, 3.0]'], {}), '([6.0, 6.0, 3.0])\n', (1323, 1340), True, 'import numpy as np\n'), ((1560, 1579), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (1568, 1579), True, 'import numpy as np\n'), ((1602, 1627), 'numpy.array', 'np.array', (['[6.0, 4.0, 4.0]'], {}), '([6.0, 4.0, 4.0])\n', (1610, 1627), True, 'import numpy as np\n'), ((1723, 1742), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (1731, 1742), True, 'import numpy as np\n'), ((1762, 1808), 'numpy.array', 'np.array', (['[[-1, -1, -1], [0, 0, 0], [1, 1, 1]]'], {}), '([[-1, -1, -1], [0, 0, 0], [1, 1, 1]])\n', (1770, 1808), True, 'import numpy as np\n'), ((2007, 2026), 'numpy.array', 'np.array', (['[0, 1, 1]'], {}), '([0, 1, 1])\n', (2015, 2026), True, 'import numpy as np\n'), ((2217, 2253), 'dynophores.ChemicalFeatureCloud3D', 'ChemicalFeatureCloud3D', ([], {}), '(**cloud_dict)\n', (2239, 2253), False, 'from dynophores import Dynophore, SuperFeature, EnvPartner, ChemicalFeatureCloud3D\n'), ((2089, 2119), 'dynophores.EnvPartner', 'EnvPartner', ([], {}), '(**envpartner1_dict)\n', (2099, 2119), False, 'from dynophores import Dynophore, SuperFeature, EnvPartner, ChemicalFeatureCloud3D\n'), ((2157, 2187), 'dynophores.EnvPartner', 'EnvPartner', ([], {}), '(**envpartner2_dict)\n', (2167, 2187), False, 'from dynophores import Dynophore, SuperFeature, EnvPartner, ChemicalFeatureCloud3D\n'), ((232, 246), 'pathlib.Path', 'Path', (['__name__'], {}), '(__name__)\n', (236, 246), False, 'from pathlib import Path\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.