code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import mysql.connector
import json
import numpy as np
cnx = mysql.connector.connect(user='shohdi', password='<PASSWORD>',
host='127.0.0.1',
database='forex_db')
cnx._open_connection()
cursor = cnx.cursor()
#cursor.execute('create table numpy(id int primary key , arr TEXT)')
a = np.random.rand(3,2)
print(a)
b = a.tolist()
b = json.dumps(b)
cursor.execute("insert into numpy (id,arr) VALUES (1,'"+b+"');")
#Fetching 1st row from the table
cursor.execute('select * from numpy;')
result = cursor.fetchall()
#print(result)
#print(len(result))
#print(result[0][1])
c = json.loads( result[0][1])
c = np.array(c,np.float)
print(c)
cnx.close() | [
"numpy.random.rand",
"numpy.array",
"json.loads",
"json.dumps"
] | [((344, 364), 'numpy.random.rand', 'np.random.rand', (['(3)', '(2)'], {}), '(3, 2)\n', (358, 364), True, 'import numpy as np\n'), ((392, 405), 'json.dumps', 'json.dumps', (['b'], {}), '(b)\n', (402, 405), False, 'import json\n'), ((634, 658), 'json.loads', 'json.loads', (['result[0][1]'], {}), '(result[0][1])\n', (644, 658), False, 'import json\n'), ((664, 685), 'numpy.array', 'np.array', (['c', 'np.float'], {}), '(c, np.float)\n', (672, 685), True, 'import numpy as np\n')] |
import ast
import json
import logging
import math
import os
import random
import h5py
from dataclasses import dataclass
import braceexpand
import numpy as np
import pandas as pd
import torch
import torchvision.datasets as datasets
import webdataset as wds
from PIL import Image
from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler
from torch.utils.data.distributed import DistributedSampler
from functools import partial
import soundfile as sf
import librosa
import io
import torchaudio
import torchaudio.functional as F
from pathlib import Path
import wget
import random
from open_clip import tokenize
try:
import horovod.torch as hvd
except ImportError:
hvd = None
from open_clip import tokenize
# initizlied the audioset map
_AUDIOSET_MAP_PATH = os.path.join(Path(__file__).parent, "audioset_textmap.npy")
_AUDIOSET_MAP = np.load(_AUDIOSET_MAP_PATH, allow_pickle=True)
def int16_to_float32(x):
return (x / 32767.).astype(np.float32)
# For Toy Dataset
class ToyDataset(Dataset):
def __init__(self, index_path, ipc, config, eval_mode = False):
"""Toy Dataset for testing the audioset input with text labels
Parameters
----------
index_path: str
the link to the h5 file of each audio
idc: str
the link to the npy file, the number of samples in each class
config: dict
the audio cfg file
eval_model (bool): to indicate if the dataset is a testing dataset
"""
self.audio_cfg = config["audio_cfg"]
self.text_cfg = config["text_cfg"]
self.fp = h5py.File(index_path, "r")
self.ipc = np.load(ipc, allow_pickle=True)
self.total_size = len(self.fp["audio_name"])
self.classes_num = self.audio_cfg["class_num"]
self.eval_mode = eval_mode
if not eval_mode:
self.generate_queue()
else:
self.queue = []
for i in range(self.total_size):
target = self.fp["target"][i]
if np.sum(target) > 0:
self.queue.append(i)
self.total_size = len(self.queue)
logging.info("total dataset size: %d" %(self.total_size))
logging.info("class num: %d" %(self.classes_num))
def time_shifting(self, x):
frame_num = len(x)
shift_len = random.randint(0, frame_num - 1)
new_sample = np.concatenate([x[shift_len:], x[:shift_len]], axis = 0)
return new_sample
def generate_queue(self):
self.queue = []
while len(self.queue) < self.total_size:
class_set = [*range(self.classes_num)]
random.shuffle(class_set)
self.queue += [self.ipc[d][random.randint(0, len(self.ipc[d]) - 1)] for d in class_set]
self.queue = self.queue[:self.total_size]
logging.info("queue regenerated:%s" %(self.queue[-5:]))
def crop_wav(self, x):
crop_size = self.audio_cfg["crop_size"]
crop_pos = random.randint(0, len(x) - crop_size - 1)
return x[crop_pos:crop_pos + crop_size]
def prompt_text(self, target):
events = _AUDIOSET_MAP[np.where(target > 0)]
event_text = "The sounds of " + ", ".join(events[:-1]) + " and " + events[-1]
text = tokenize(event_text)[0]
return text
def __getitem__(self, index):
"""Load waveform, text, and target of an audio clip
Parameters
----------
index: int
the index number
Return
------
output: dict {
"hdf5_path": str,
"index_in_hdf5": int,
"audio_name": str,
"waveform": list (audio_length,),
"target": list (class_num, ),
"text": torch.tensor (context_length,)
}
the output dictionary
"""
s_index = self.queue[index]
audio_name = self.fp["audio_name"][s_index].decode()
# Hardcode here CHANGE
hdf5_path = self.fp["hdf5_path"][s_index].decode().replace("/home/tiger/DB/knut/data/audioset/hdf5s/waveforms", "/mnt/audio_clip/test/data")
r_idx = self.fp["index_in_hdf5"][s_index]
target = self.fp["target"][s_index].astype(np.float32)
text = self.prompt_text(target)
with h5py.File(hdf5_path, "r") as f:
waveform = int16_to_float32(f["waveform"][r_idx])[:self.audio_cfg["clip_samples"]]
assert len(waveform) == self.audio_cfg["clip_samples"], "The sample length is not match"
# Time shift
# if (self.config.enable_time_shift) and (not self.eval_mode):
# waveform = self.time_shifting(waveform)
# # Label Enhance
# if (self.config.crop_size is not None) and (not self.eval_mode):
# waveform = self.crop_wav(waveform)
# # the label enhance rate is fixed 0.5
# if (self.config.enable_label_enhance) and (not self.eval_mode) and random.random() < 0.5:
# kidx = np.where(target)[0]
# for k in kidx:
# for add_key in self.class_map[k][1]:
# target[add_key] = 1.0
# if len(self.class_map[k][2]) > 0:
# add_key = random.choice(self.class_map[k][2])
# target[add_key] = 1.0
# missing the text input
data_dict = {
"hdf5_path": hdf5_path,
"index_in_hdf5": r_idx,
"audio_name": audio_name,
"waveform": waveform,
"target": target,
"text": text
}
return data_dict
def __len__(self):
return self.total_size
class CsvDataset(Dataset):
def __init__(self, input_filename, transforms, img_key, caption_key, sep="\t"):
logging.debug(f"Loading csv data from {input_filename}.")
df = pd.read_csv(input_filename, sep=sep)
self.images = df[img_key].tolist()
self.captions = df[caption_key].tolist()
self.transforms = transforms
logging.debug("Done loading data.")
def __len__(self):
return len(self.captions)
def __getitem__(self, idx):
images = self.transforms(Image.open(str(self.images[idx])))
texts = tokenize([str(self.captions[idx])])[0]
return images, texts
@dataclass
class DataInfo:
dataloader: DataLoader
sampler: DistributedSampler
def preprocess_txt(text):
return tokenize([str(text)])[0]
def get_dataset_size(shards, sizefilepath_=None, is_local=True):
if not is_local:
if os.path.exists('sizes.json'):
os.remove('sizes.json')
if not sizefilepath_ is None:
wget.download(sizefilepath_, 'sizes.json')
else:
wget.download(os.path.join(os.path.dirname(shards[0]), "sizes.json"), 'sizes.json')
sizefilepath_ = 'sizes.json'
if isinstance(shards, list):
size_list = []
for s in shards:
size_list.append(get_dataset_size(s, sizefilepath_=sizefilepath_, is_local=True)[0])
else:
shards_list = list(braceexpand.braceexpand(shards))
dir_path = os.path.dirname(shards)
if not sizefilepath_ is None:
sizes = json.load(open(sizefilepath_, "r"))
total_size = sum([int(sizes[os.path.basename(shard)]) for shard in shards_list])
else:
sizes_filename = os.path.join(dir_path, "sizes.json")
len_filename = os.path.join(dir_path, "__len__")
if os.path.exists(sizes_filename):
sizes = json.load(open(sizes_filename, "r"))
total_size = sum([int(sizes[os.path.basename(shard)]) for shard in shards_list])
elif os.path.exists(len_filename):
# FIXME this used to be eval(open(...)) but that seemed rather unsafe
total_size = ast.literal_eval(open(len_filename, "r").read())
else:
raise Exception("Cannot find sizes file for dataset. Please specify the path to the file.")
# total_size = None # num samples undefined
# some common dataset sizes (at time of authors last download)
# cc3m-train: 2905954
# cc12m: 10968539
# LAION-400m: 407332084
num_shards = len(shards_list)
if isinstance(shards, list):
return sum(size_list), len(shards)
else:
return total_size, num_shards
def get_imagenet(args, preprocess_fns, split):
assert split in ["train", "val", "v2"]
is_train = split == "train"
preprocess_train, preprocess_val = preprocess_fns
if split == "v2":
from imagenetv2_pytorch import ImageNetV2Dataset
dataset = ImageNetV2Dataset(location=args.imagenet_v2, transform=preprocess_val)
else:
if is_train:
data_path = args.imagenet_train
preprocess_fn = preprocess_train
else:
data_path = args.imagenet_val
preprocess_fn = preprocess_val
assert data_path
dataset = datasets.ImageFolder(data_path, transform=preprocess_fn)
if is_train:
idxs = np.zeros(len(dataset.targets))
target_array = np.array(dataset.targets)
k = 50
for c in range(1000):
m = target_array == c
n = len(idxs[m])
arr = np.zeros(n)
arr[:k] = 1
np.random.shuffle(arr)
idxs[m] = arr
idxs = idxs.astype("int")
sampler = SubsetRandomSampler(np.where(idxs)[0])
else:
sampler = None
dataloader = torch.utils.data.DataLoader(
dataset,
batch_size=args.batch_size,
num_workers=args.workers,
sampler=sampler,
)
return DataInfo(dataloader, sampler)
def count_samples(dataloader):
os.environ["WDS_EPOCH"] = "0"
n_elements, n_batches = 0, 0
for images, texts in dataloader:
n_batches += 1
n_elements += len(images)
assert len(images) == len(texts)
return n_elements, n_batches
def filter_no_caption(sample):
return "txt" in sample
def log_and_continue(exn):
"""Call in an exception handler to ignore any exception, isssue a warning, and continue."""
logging.warning(f"Handling webdataset error ({repr(exn)}). Ignoring.")
return True
_SHARD_SHUFFLE_SIZE = 2000
_SHARD_SHUFFLE_INITIAL = 500
_SAMPLE_SHUFFLE_SIZE = 5000
_SAMPLE_SHUFFLE_INITIAL = 1000
def sample_prop(sizefile, inputs, proportion, is_local=True):
"""
Sample a proportion of the data.
"""
file_path_dict = {os.path.split(inputs[i])[1]:os.path.split(inputs[i])[0] for i in range(len(inputs))}
sampled_filepath_dict = {}
sampled_size_dict = {}
if not is_local:
if os.path.exists('sizes.json'):
os.remove('sizes.json')
wget.download(sizefile, 'sizes.json')
sizefile = 'sizes.json'
with open(sizefile,'r', encoding='UTF-8') as f:
load_dict = json.load(f)
L = int(len(file_path_dict)*proportion)
subkeys = random.sample(file_path_dict.keys(), L)
for k in subkeys:
sampled_size_dict[k] = load_dict[k]
sampled_filepath_dict[k] = file_path_dict[k]
return sum(sampled_size_dict.values()), L, [os.path.join(v,k) for k,v in sampled_filepath_dict.items()], sampled_size_dict
def preprocess(
sample,
audio_ext,
text_ext,
samplerate,
mono,
max_len,
dtype,
res_type,
resample_method="TorchAudio",
):
"""
Preprocess a single sample for wdsdataloader.
"""
#keys = list(sample.keys())
#for k in keys:
# if (audio_ext in k) and (audio_ext!=k): # if the key is not extention of audio, something like 'xxxxx.flac'
# sample[audio_ext] = sample[k]
# del sample[k]
# if (text_ext in k) and (text_ext!=k): # if the key is not extention of audio, something like 'xxxxx.json'
# sample[text_ext] = sample[k]
# del sample[k]
audio_data, orig_sr = sf.read(io.BytesIO(sample[audio_ext]))
# if samplerate is not None:
# if resample_method == "TorchAudio_":
# audio_data = F.resample(
# torch.tensor(audio_data).unsqueeze(0),
# orig_sr,
# 32000,
# lowpass_filter_width=64,
# rolloff=0.9475937167399596,
# resampling_method="kaiser_window",
# ).squeeze(0)
# elif resample_method == "librosa":
# audio_data = librosa.resample(
# audio_data, orig_sr=orig_sr, target_sr=samplerate, res_type=res_type
# )
# elif resample_method is None or resample_method == "None" or resample_method == "TorchAudio":
# pass
# else:
# raise ValueError(f"Unknown resample method: {resample_method}")
if len(audio_data) > max_len: # random clip if too long
overflow = len(audio_data) - max_len
idx = np.random.randint(0, overflow + 1)
audio_data = audio_data[idx : idx + max_len]
#if np.random.rand() > 0.5:
# audio_data = audio_data[idx : idx + max_len]
#else:
# audio_data = audio_data[
# len(audio_data) + 1 - idx - max_len : len(audio_data) + 1 - idx
# ]
else: # padding if too short
audio_data = np.pad(
audio_data,
(0, max_len - len(audio_data)),
mode="constant",
constant_values=0,
)
#if mono: # convert to mono
# audio_data = librosa.to_mono(audio_data)
sample["waveform"] = torch.tensor(audio_data).float()
del sample[audio_ext]
texts = json.loads(sample[text_ext].decode('utf-8'))["text"]
if isinstance(texts, list) and isinstance(texts[0], str) and len(texts) > 1:
texts = random.choice(texts)
sample["raw_text"] = texts
sample["text"] = tokenize(texts)
del sample[text_ext]
sample["audio_name"] = sample["__key__"].split("/")[-1]+"."+audio_ext
sample["text_name"] = sample["__key__"].split("/")[-1]+"."+text_ext
sample["audio_orig_sr"] = orig_sr
return sample
# def get_wds_dataset(args, preprocess_img, is_train):
def get_wds_dataset(
args,
model_cfg,
is_train,
audio_ext="flac",
text_ext="json",
samplerate=32000,
mono=True,
max_len=1000000,
dtype="float64",
res_type="kaiser_best",
proportion=1.0,
sizefilepath_=None,
is_local=None,
resample_method=None,
):
"""
Get a dataset for wdsdataloader.
"""
if is_local is None and (not args.remotedata is None):
is_local = not args.remotedata
input_shards = args.train_data if is_train else args.val_data
assert input_shards is not None
if not sizefilepath_ is None:
sizefilepath = sizefilepath_
else:
sizefilepath = os.path.join(os.path.dirname(input_shards[0]), "sizes.json")
if proportion!=1.0:
num_samples, num_shards, input_shards, _ = sample_prop(sizefilepath, input_shards, proportion, is_local=is_local)
else:
num_samples, num_shards = get_dataset_size(input_shards, sizefilepath_=sizefilepath_, is_local=is_local)
if not num_samples:
if is_train:
num_samples = args.train_num_samples
if not num_samples:
raise RuntimeError(
'Currently, number of dataset samples must be specified for training dataset. '
'Please specify via `--train-num-samples` if no dataset length info present.')
else:
num_samples = args.val_num_samples or 0 # eval will just exhaust the iterator if not specified
pipeline = [wds.SimpleShardList(input_shards)]
# at this point we have an iterator over all the shards
if is_train:
pipeline.extend([
wds.detshuffle(bufsize=_SHARD_SHUFFLE_SIZE, initial=_SHARD_SHUFFLE_INITIAL, seed=args.seed),
wds.split_by_node,
wds.split_by_worker,
# at this point, we have an iterator over the shards assigned to each worker at each node
wds.tarfile_to_samples(handler=log_and_continue),
wds.shuffle(
bufsize=_SAMPLE_SHUFFLE_SIZE,
initial=_SAMPLE_SHUFFLE_INITIAL,
rng=random.Random(args.seed)),
#wds.repeatedly, # FIXME determine if this is beneficial
])
else:
pipeline.extend([
wds.split_by_worker,
# at this point, we have an iterator over the shards assigned to each worker
wds.tarfile_to_samples(handler=log_and_continue),
])
pipeline.extend([
wds.map(
partial(
preprocess,
audio_ext=audio_ext,
text_ext=text_ext,
samplerate=samplerate,
mono=mono,
max_len=max_len,
dtype=dtype,
res_type=res_type,
resample_method=args.resample_method,
)
),
wds.to_tuple("__url__", "__key__", "waveform", "text", "raw_text", "audio_name", "text_name", "audio_orig_sr"),
wds.batched(args.batch_size, partial=not is_train),
])
dataset = wds.DataPipeline(*pipeline)
if is_train:
# roll over and repeat a few samples to get same number of full batches on each node
global_batch_size = args.batch_size * args.world_size
num_batches = math.ceil(num_samples / global_batch_size)
num_workers = max(1, args.workers)
num_worker_batches = math.ceil(num_batches / num_workers) # per dataloader worker
num_batches = num_worker_batches * num_workers
num_samples = num_batches * global_batch_size
dataset = dataset.with_epoch(num_worker_batches) # each worker is iterating over this
else:
# last batches are partial, eval is done on single (master) node
num_batches = math.ceil(num_samples / args.batch_size)
dataloader = wds.WebLoader(dataset, batch_size=None, shuffle=False, num_workers=args.workers)
# FIXME not clear which approach is better, with_epoch before vs after dataloader?
# hoping to resolve via https://github.com/webdataset/webdataset/issues/169
# if is_train:
# # roll over and repeat a few samples to get same number of full batches on each node
# global_batch_size = args.batch_size * args.world_size
# num_batches = math.ceil(num_samples / global_batch_size)
# num_workers = max(1, args.workers)
# num_batches = math.ceil(num_batches / num_workers) * num_workers
# num_samples = num_batches * global_batch_size
# dataloader = dataloader.with_epoch(num_batches)
# else:
# # last batches are partial, eval is done on single (master) node
# num_batches = math.ceil(num_samples / args.batch_size)
# add meta-data to dataloader instance for convenience
dataloader.num_batches = num_batches
dataloader.num_samples = num_samples
return DataInfo(dataloader, None)
def wds_batch_list2dict(batch, keys=["__url__", "__key__", "waveform", "text", "raw_text", "audio_name", "text_name", "audio_orig_sr"]):
"""
Return a dictionary of the batch, with keys as the names of the fields.
"""
assert len(keys) == len(batch), "batch must have same number of keys as keys argument"
return {keys[i]: batch[i] for i in range(len(batch))}
def get_csv_dataset(args, preprocess_fn, is_train):
input_filename = args.train_data if is_train else args.val_data
assert input_filename
dataset = CsvDataset(
input_filename,
preprocess_fn,
img_key=args.csv_img_key,
caption_key=args.csv_caption_key,
sep=args.csv_separator)
num_samples = len(dataset)
sampler = DistributedSampler(dataset) if args.distributed and is_train else None
shuffle = is_train and sampler is None
dataloader = DataLoader(
dataset,
batch_size=args.batch_size,
shuffle=shuffle,
num_workers=args.workers,
pin_memory=True,
sampler=sampler,
drop_last=is_train,
)
dataloader.num_samples = num_samples
dataloader.num_batches = len(dataloader)
return DataInfo(dataloader, sampler)
def get_toy_dataset(args, model_cfg, is_train):
index_path = args.train_data if is_train else args.val_data
ipc_path = args.train_ipc if is_train else args.val_ipc
assert index_path and ipc_path
eval_mode = not is_train
dataset = ToyDataset(
index_path,
ipc_path,
model_cfg,
eval_mode=eval_mode
)
num_samples = len(dataset)
sampler = DistributedSampler(dataset, shuffle=False) if args.distributed and is_train else None
dataloader = DataLoader(
dataset,
batch_size=args.batch_size,
shuffle=False,
num_workers=args.workers,
sampler=sampler,
drop_last=is_train,
)
dataloader.num_samples = num_samples
dataloader.num_batches = len(dataloader)
return DataInfo(dataloader, sampler)
def get_dataset_fn(data_path, dataset_type):
if dataset_type == "webdataset":
return get_wds_dataset
elif dataset_type == "csv":
return get_csv_dataset
elif dataset_type == "auto":
ext = data_path.split(".")[-1]
if ext in ["csv", "tsv"]:
return get_csv_dataset
elif ext in ["tar"]:
return get_wds_dataset
else:
raise ValueError(
f"Tried to figure out dataset type, but failed for extention {ext}."
)
elif dataset_type == "toy":
return get_toy_dataset
else:
raise ValueError(f"Unsupported dataset type: {dataset_type}")
def get_data(args, model_cfg):
# deprecated for audio
# preprocess_train, preprocess_val = preprocess_fns
data = {}
# need to CHANGE when using the formal webdataset
# if args.train_data:
# data["train"] = get_dataset_fn(args.train_data, args.dataset_type)(
# args, preprocess_train, is_train=True
# )
# if args.val_data:
# data["val"] = get_dataset_fn(args.val_data, args.dataset_type)(
# args, preprocess_val, is_train=False
# )
# if args.imagenet_val is not None:
# data["imagenet-val"] = get_imagenet(args, preprocess_fns, "val")
# if args.imagenet_v2 is not None:
# data["imagenet-v2"] = get_imagenet(args, preprocess_fns, "v2")
if args.train_data:
data["train"] = get_dataset_fn(args.train_data, args.dataset_type)(
args, model_cfg, is_train=True
)
if args.val_data:
data["val"] = get_dataset_fn(args.val_data, args.dataset_type)(
args, model_cfg, is_train=False
)
return data
| [
"webdataset.tarfile_to_samples",
"numpy.load",
"os.remove",
"numpy.sum",
"open_clip.tokenize",
"pandas.read_csv",
"random.shuffle",
"webdataset.batched",
"pathlib.Path",
"numpy.random.randint",
"webdataset.to_tuple",
"os.path.join",
"random.randint",
"torch.utils.data.DataLoader",
"rando... | [((855, 901), 'numpy.load', 'np.load', (['_AUDIOSET_MAP_PATH'], {'allow_pickle': '(True)'}), '(_AUDIOSET_MAP_PATH, allow_pickle=True)\n', (862, 901), True, 'import numpy as np\n'), ((9665, 9776), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': 'args.batch_size', 'num_workers': 'args.workers', 'sampler': 'sampler'}), '(dataset, batch_size=args.batch_size,\n num_workers=args.workers, sampler=sampler)\n', (9692, 9776), False, 'import torch\n'), ((13962, 13977), 'open_clip.tokenize', 'tokenize', (['texts'], {}), '(texts)\n', (13970, 13977), False, 'from open_clip import tokenize\n'), ((17325, 17352), 'webdataset.DataPipeline', 'wds.DataPipeline', (['*pipeline'], {}), '(*pipeline)\n', (17341, 17352), True, 'import webdataset as wds\n'), ((18092, 18177), 'webdataset.WebLoader', 'wds.WebLoader', (['dataset'], {'batch_size': 'None', 'shuffle': '(False)', 'num_workers': 'args.workers'}), '(dataset, batch_size=None, shuffle=False, num_workers=args.workers\n )\n', (18105, 18177), True, 'import webdataset as wds\n'), ((20038, 20191), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'batch_size': 'args.batch_size', 'shuffle': 'shuffle', 'num_workers': 'args.workers', 'pin_memory': '(True)', 'sampler': 'sampler', 'drop_last': 'is_train'}), '(dataset, batch_size=args.batch_size, shuffle=shuffle,\n num_workers=args.workers, pin_memory=True, sampler=sampler, drop_last=\n is_train)\n', (20048, 20191), False, 'from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler\n'), ((20879, 21009), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'batch_size': 'args.batch_size', 'shuffle': '(False)', 'num_workers': 'args.workers', 'sampler': 'sampler', 'drop_last': 'is_train'}), '(dataset, batch_size=args.batch_size, shuffle=False, num_workers=\n args.workers, sampler=sampler, drop_last=is_train)\n', (20889, 21009), False, 'from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler\n'), ((792, 806), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (796, 806), False, 'from pathlib import Path\n'), ((1642, 1668), 'h5py.File', 'h5py.File', (['index_path', '"""r"""'], {}), "(index_path, 'r')\n", (1651, 1668), False, 'import h5py\n'), ((1688, 1719), 'numpy.load', 'np.load', (['ipc'], {'allow_pickle': '(True)'}), '(ipc, allow_pickle=True)\n', (1695, 1719), True, 'import numpy as np\n'), ((2191, 2247), 'logging.info', 'logging.info', (["('total dataset size: %d' % self.total_size)"], {}), "('total dataset size: %d' % self.total_size)\n", (2203, 2247), False, 'import logging\n'), ((2257, 2305), 'logging.info', 'logging.info', (["('class num: %d' % self.classes_num)"], {}), "('class num: %d' % self.classes_num)\n", (2269, 2305), False, 'import logging\n'), ((2387, 2419), 'random.randint', 'random.randint', (['(0)', '(frame_num - 1)'], {}), '(0, frame_num - 1)\n', (2401, 2419), False, 'import random\n'), ((2441, 2495), 'numpy.concatenate', 'np.concatenate', (['[x[shift_len:], x[:shift_len]]'], {'axis': '(0)'}), '([x[shift_len:], x[:shift_len]], axis=0)\n', (2455, 2495), True, 'import numpy as np\n'), ((2891, 2945), 'logging.info', 'logging.info', (["('queue regenerated:%s' % self.queue[-5:])"], {}), "('queue regenerated:%s' % self.queue[-5:])\n", (2903, 2945), False, 'import logging\n'), ((5860, 5917), 'logging.debug', 'logging.debug', (['f"""Loading csv data from {input_filename}."""'], {}), "(f'Loading csv data from {input_filename}.')\n", (5873, 5917), False, 'import logging\n'), ((5931, 5967), 'pandas.read_csv', 'pd.read_csv', (['input_filename'], {'sep': 'sep'}), '(input_filename, sep=sep)\n', (5942, 5967), True, 'import pandas as pd\n'), ((6106, 6141), 'logging.debug', 'logging.debug', (['"""Done loading data."""'], {}), "('Done loading data.')\n", (6119, 6141), False, 'import logging\n'), ((6637, 6665), 'os.path.exists', 'os.path.exists', (['"""sizes.json"""'], {}), "('sizes.json')\n", (6651, 6665), False, 'import os\n'), ((7210, 7233), 'os.path.dirname', 'os.path.dirname', (['shards'], {}), '(shards)\n', (7225, 7233), False, 'import os\n'), ((8795, 8865), 'imagenetv2_pytorch.ImageNetV2Dataset', 'ImageNetV2Dataset', ([], {'location': 'args.imagenet_v2', 'transform': 'preprocess_val'}), '(location=args.imagenet_v2, transform=preprocess_val)\n', (8812, 8865), False, 'from imagenetv2_pytorch import ImageNetV2Dataset\n'), ((9129, 9185), 'torchvision.datasets.ImageFolder', 'datasets.ImageFolder', (['data_path'], {'transform': 'preprocess_fn'}), '(data_path, transform=preprocess_fn)\n', (9149, 9185), True, 'import torchvision.datasets as datasets\n'), ((9273, 9298), 'numpy.array', 'np.array', (['dataset.targets'], {}), '(dataset.targets)\n', (9281, 9298), True, 'import numpy as np\n'), ((10828, 10856), 'os.path.exists', 'os.path.exists', (['"""sizes.json"""'], {}), "('sizes.json')\n", (10842, 10856), False, 'import os\n'), ((10902, 10939), 'wget.download', 'wget.download', (['sizefile', '"""sizes.json"""'], {}), "(sizefile, 'sizes.json')\n", (10915, 10939), False, 'import wget\n'), ((11044, 11056), 'json.load', 'json.load', (['f'], {}), '(f)\n', (11053, 11056), False, 'import json\n'), ((12085, 12114), 'io.BytesIO', 'io.BytesIO', (['sample[audio_ext]'], {}), '(sample[audio_ext])\n', (12095, 12114), False, 'import io\n'), ((13027, 13061), 'numpy.random.randint', 'np.random.randint', (['(0)', '(overflow + 1)'], {}), '(0, overflow + 1)\n', (13044, 13061), True, 'import numpy as np\n'), ((13889, 13909), 'random.choice', 'random.choice', (['texts'], {}), '(texts)\n', (13902, 13909), False, 'import random\n'), ((15771, 15804), 'webdataset.SimpleShardList', 'wds.SimpleShardList', (['input_shards'], {}), '(input_shards)\n', (15790, 15804), True, 'import webdataset as wds\n'), ((17547, 17589), 'math.ceil', 'math.ceil', (['(num_samples / global_batch_size)'], {}), '(num_samples / global_batch_size)\n', (17556, 17589), False, 'import math\n'), ((17662, 17698), 'math.ceil', 'math.ceil', (['(num_batches / num_workers)'], {}), '(num_batches / num_workers)\n', (17671, 17698), False, 'import math\n'), ((18033, 18073), 'math.ceil', 'math.ceil', (['(num_samples / args.batch_size)'], {}), '(num_samples / args.batch_size)\n', (18042, 18073), False, 'import math\n'), ((19906, 19933), 'torch.utils.data.distributed.DistributedSampler', 'DistributedSampler', (['dataset'], {}), '(dataset)\n', (19924, 19933), False, 'from torch.utils.data.distributed import DistributedSampler\n'), ((20775, 20817), 'torch.utils.data.distributed.DistributedSampler', 'DistributedSampler', (['dataset'], {'shuffle': '(False)'}), '(dataset, shuffle=False)\n', (20793, 20817), False, 'from torch.utils.data.distributed import DistributedSampler\n'), ((2698, 2723), 'random.shuffle', 'random.shuffle', (['class_set'], {}), '(class_set)\n', (2712, 2723), False, 'import random\n'), ((3199, 3219), 'numpy.where', 'np.where', (['(target > 0)'], {}), '(target > 0)\n', (3207, 3219), True, 'import numpy as np\n'), ((3322, 3342), 'open_clip.tokenize', 'tokenize', (['event_text'], {}), '(event_text)\n', (3330, 3342), False, 'from open_clip import tokenize\n'), ((4388, 4413), 'h5py.File', 'h5py.File', (['hdf5_path', '"""r"""'], {}), "(hdf5_path, 'r')\n", (4397, 4413), False, 'import h5py\n'), ((6679, 6702), 'os.remove', 'os.remove', (['"""sizes.json"""'], {}), "('sizes.json')\n", (6688, 6702), False, 'import os\n'), ((6753, 6795), 'wget.download', 'wget.download', (['sizefilepath_', '"""sizes.json"""'], {}), "(sizefilepath_, 'sizes.json')\n", (6766, 6795), False, 'import wget\n'), ((7158, 7189), 'braceexpand.braceexpand', 'braceexpand.braceexpand', (['shards'], {}), '(shards)\n', (7181, 7189), False, 'import braceexpand\n'), ((7464, 7500), 'os.path.join', 'os.path.join', (['dir_path', '"""sizes.json"""'], {}), "(dir_path, 'sizes.json')\n", (7476, 7500), False, 'import os\n'), ((7528, 7561), 'os.path.join', 'os.path.join', (['dir_path', '"""__len__"""'], {}), "(dir_path, '__len__')\n", (7540, 7561), False, 'import os\n'), ((7577, 7607), 'os.path.exists', 'os.path.exists', (['sizes_filename'], {}), '(sizes_filename)\n', (7591, 7607), False, 'import os\n'), ((9425, 9436), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (9433, 9436), True, 'import numpy as np\n'), ((9473, 9495), 'numpy.random.shuffle', 'np.random.shuffle', (['arr'], {}), '(arr)\n', (9490, 9495), True, 'import numpy as np\n'), ((10653, 10677), 'os.path.split', 'os.path.split', (['inputs[i]'], {}), '(inputs[i])\n', (10666, 10677), False, 'import os\n'), ((10681, 10705), 'os.path.split', 'os.path.split', (['inputs[i]'], {}), '(inputs[i])\n', (10694, 10705), False, 'import os\n'), ((10870, 10893), 'os.remove', 'os.remove', (['"""sizes.json"""'], {}), "('sizes.json')\n", (10879, 10893), False, 'import os\n'), ((11322, 11340), 'os.path.join', 'os.path.join', (['v', 'k'], {}), '(v, k)\n', (11334, 11340), False, 'import os\n'), ((13668, 13692), 'torch.tensor', 'torch.tensor', (['audio_data'], {}), '(audio_data)\n', (13680, 13692), False, 'import torch\n'), ((14944, 14976), 'os.path.dirname', 'os.path.dirname', (['input_shards[0]'], {}), '(input_shards[0])\n', (14959, 14976), False, 'import os\n'), ((17131, 17245), 'webdataset.to_tuple', 'wds.to_tuple', (['"""__url__"""', '"""__key__"""', '"""waveform"""', '"""text"""', '"""raw_text"""', '"""audio_name"""', '"""text_name"""', '"""audio_orig_sr"""'], {}), "('__url__', '__key__', 'waveform', 'text', 'raw_text',\n 'audio_name', 'text_name', 'audio_orig_sr')\n", (17143, 17245), True, 'import webdataset as wds\n'), ((17251, 17301), 'webdataset.batched', 'wds.batched', (['args.batch_size'], {'partial': '(not is_train)'}), '(args.batch_size, partial=not is_train)\n', (17262, 17301), True, 'import webdataset as wds\n'), ((7784, 7812), 'os.path.exists', 'os.path.exists', (['len_filename'], {}), '(len_filename)\n', (7798, 7812), False, 'import os\n'), ((9595, 9609), 'numpy.where', 'np.where', (['idxs'], {}), '(idxs)\n', (9603, 9609), True, 'import numpy as np\n'), ((15921, 16016), 'webdataset.detshuffle', 'wds.detshuffle', ([], {'bufsize': '_SHARD_SHUFFLE_SIZE', 'initial': '_SHARD_SHUFFLE_INITIAL', 'seed': 'args.seed'}), '(bufsize=_SHARD_SHUFFLE_SIZE, initial=_SHARD_SHUFFLE_INITIAL,\n seed=args.seed)\n', (15935, 16016), True, 'import webdataset as wds\n'), ((16192, 16240), 'webdataset.tarfile_to_samples', 'wds.tarfile_to_samples', ([], {'handler': 'log_and_continue'}), '(handler=log_and_continue)\n', (16214, 16240), True, 'import webdataset as wds\n'), ((16660, 16708), 'webdataset.tarfile_to_samples', 'wds.tarfile_to_samples', ([], {'handler': 'log_and_continue'}), '(handler=log_and_continue)\n', (16682, 16708), True, 'import webdataset as wds\n'), ((16772, 16961), 'functools.partial', 'partial', (['preprocess'], {'audio_ext': 'audio_ext', 'text_ext': 'text_ext', 'samplerate': 'samplerate', 'mono': 'mono', 'max_len': 'max_len', 'dtype': 'dtype', 'res_type': 'res_type', 'resample_method': 'args.resample_method'}), '(preprocess, audio_ext=audio_ext, text_ext=text_ext, samplerate=\n samplerate, mono=mono, max_len=max_len, dtype=dtype, res_type=res_type,\n resample_method=args.resample_method)\n', (16779, 16961), False, 'from functools import partial\n'), ((2076, 2090), 'numpy.sum', 'np.sum', (['target'], {}), '(target)\n', (2082, 2090), True, 'import numpy as np\n'), ((6849, 6875), 'os.path.dirname', 'os.path.dirname', (['shards[0]'], {}), '(shards[0])\n', (6864, 6875), False, 'import os\n'), ((16382, 16406), 'random.Random', 'random.Random', (['args.seed'], {}), '(args.seed)\n', (16395, 16406), False, 'import random\n'), ((7368, 7391), 'os.path.basename', 'os.path.basename', (['shard'], {}), '(shard)\n', (7384, 7391), False, 'import os\n'), ((7714, 7737), 'os.path.basename', 'os.path.basename', (['shard'], {}), '(shard)\n', (7730, 7737), False, 'import os\n')] |
"""
Imageutils unit tests.
"""
from __future__ import division
import unittest
import numpy as np
from astraviso import imageutils as iu
class imageutilstests(unittest.TestCase):
"""
Imageutils unit test class.
"""
def setUp(self):
pass
def tearDown(self):
pass
class test_poisson_noise(imageutilstests):
"""
Test poisson_noise function.
"""
def test_empty_image(self):
"""
Test output value and type.
"""
# Allocate placeholder image
image = np.zeros((512))
# Add noise
noisy_image = iu.poisson_noise(image, 0, 1200, 200)
# Check result
self.assertIsInstance(noisy_image, np.ndarray, "Output type should be ndarray.")
self.assertEqual(noisy_image.shape, image.shape, "Image shape should be preserved.")
self.assertTrue(np.all(noisy_image >= 0), "Image with noise should be strictly positive.")
class test_gaussian_noise(imageutilstests):
"""
Test gaussian_noise function.
"""
def test_empty_image(self):
"""
Test output value and type.
"""
# Allocate placeholder image
image = np.zeros((512))
# Add noise
noisy_image = iu.gaussian_noise(image, 0, 1200, 200)
# Check result
self.assertIsInstance(noisy_image, np.ndarray, "Output type should be ndarray.")
self.assertEqual(noisy_image.shape, image.shape, "Image shape should be preserved.")
class test_vismag2photon(imageutilstests):
"""
Test vismag2photon function.
"""
def test_single(self):
"""
Test output value and type for single input.
"""
# Set up visible magnitudes
vismags = -1
# Convert to photons
photons = iu.vismag2photon(vismags, 1, 1, 1)
# Check output
self.assertIsInstance(photons, float, "Output type should be float.")
self.assertGreater(photons, 0, "Photon count must be positive.")
def test_single(self):
"""
Test output value and type for multiple input.
"""
# Set up visible magnitudes
vismags = np.array([1, 0, -1])
# Convert to photons
photons = iu.vismag2photon(vismags, 1, 1, 1)
# Check output
self.assertEqual(len(photons), len(vismags), "Output size not equal to input.")
self.assertIsInstance(photons, np.ndarray, "Output type should be float.")
self.assertTrue(np.all(photons>0), "Photon counts must be positive.")
self.assertGreater(photons[2], photons[0], "Incorrect output values.")
self.assertEqual(photons[1], 1, "Incorrect output value for input 0.")
class test_apply_constant_qe(imageutilstests):
"""
Test apply_constant_quantum_efficiency function.
"""
def test_zero(self):
"""
Test output value and type for zero QE.
"""
# Convert to photoelectrons
photo_electrons = iu.apply_constant_quantum_efficiency(16*np.ones((16,16)), 0)
# Check output
self.assertIsInstance(photo_electrons, np.ndarray, "Output type should be ndarray.")
self.assertTrue(np.all(photo_electrons==0), "Output values should all be equal to 0.")
def test_positive(self):
"""
Test output value and type for positive QE.
"""
# Convert to photoelectrons
photo_electrons = iu.apply_constant_quantum_efficiency(16*np.ones((16,16)), 0.4)
# Check output
self.assertIsInstance(photo_electrons, np.ndarray, "Output type should be ndarray.")
self.assertTrue(np.all(photo_electrons==6), "Output values should all be equal to 6.")
class test_apply_gaussian_qe(imageutilstests):
"""
Test apply_gaussian_quantum_efficiency function.
"""
def test_zero(self):
"""
Test output value and type for zero QE.
"""
# Create test image
test_image = 16*np.ones((16,16))
# Convert to photoelectrons
photo_electrons = iu.apply_gaussian_quantum_efficiency(test_image, 0, 0)
# Check output
self.assertIsInstance(photo_electrons, np.ndarray, "Output type should be ndarray.")
self.assertTrue(np.all(photo_electrons==0), "Output values should all be equal to 0.")
def test_seed(self):
"""
Test RNG seed capability for Gaussian QE.
"""
# Create test image
test_image = 16*np.ones((16,16))
# Convert to photoelectrons
photo_electrons_1 = iu.apply_gaussian_quantum_efficiency(test_image, 0.2, 0.01, seed=1)
photo_electrons_2 = iu.apply_gaussian_quantum_efficiency(test_image, 0.2, 0.01, seed=1)
# Check output
self.assertIsInstance(photo_electrons_1, np.ndarray, "Output type should be ndarray.")
self.assertIsInstance(photo_electrons_2, np.ndarray, "Output type should be ndarray.")
self.assertTrue(np.all(photo_electrons_1==photo_electrons_2), \
"Seed does not lead to consistent results.")
def test_positive(self):
"""
Check Gaussian QE for negative values.
"""
# Create test image
test_image = 16*np.ones((256,256))
# Convert to photoelectrons
photo_electrons = iu.apply_gaussian_quantum_efficiency(test_image, 0, 1, seed=1)
# Check output
self.assertIsInstance(photo_electrons, np.ndarray, "Output type should be ndarray.")
self.assertTrue(np.all(photo_electrons>=0), "Quantum efficiency must be strictly positive.")
class test_saturate(imageutilstests):
"""
Test saturate function.
"""
def test_no_clipping(self):
"""
Test output value and type for array input and sufficient bit_depth.
"""
# Compute saturated image
saturated = iu.saturate(16*np.ones((16,16)), 8)
# Check output
self.assertIsInstance(saturated, np.ndarray, "Output type should be ndarray.")
self.assertTrue(np.all(saturated==16), "Output values should all be equal to 16.")
def test_clipping(self):
"""
Test output value and type for array input and insufficient bit_depth.
"""
# Compute saturated image
saturated = iu.saturate(16*np.ones((16,16)), 2)
# Check output
self.assertIsInstance(saturated, np.ndarray, "Output type should be ndarray.")
self.assertTrue(np.all(saturated==3), "Output values should all be equal to 3.")
class test_conv2(imageutilstests):
"""
Test conv2 function.
"""
def test_3by3(self):
"""
Test 3x3 convoltuion kernel.
"""
# Create kernel & image
kernel = np.ones((3,3))
image = np.ones((64,64))
# Convolve
result = iu.conv2(image, kernel)
# Check result
self.assertIsInstance(result, np.ndarray, "Output type should be ndarray.")
self.assertEqual(image.shape, result.shape, "Image shape must be preserved.")
self.assertTrue(np.all(result[1:-2,1:-2] == 9), "Incorrect pixel values.")
def test_exceptions(self):
"""
Verify conv2 exceptions.
"""
# Create kernel & image
kernel = np.ones((3,3))
image = np.ones((64,64))
# Test even kernel
with self.assertRaises(ValueError):
iu.conv2(image, np.ones((2,2)))
# Test rectangular kernel
with self.assertRaises(ValueError):
iu.conv2(image, np.ones((2,3)))
| [
"astraviso.imageutils.apply_gaussian_quantum_efficiency",
"astraviso.imageutils.gaussian_noise",
"astraviso.imageutils.poisson_noise",
"numpy.zeros",
"astraviso.imageutils.vismag2photon",
"numpy.ones",
"numpy.array",
"astraviso.imageutils.conv2",
"numpy.all"
] | [((540, 553), 'numpy.zeros', 'np.zeros', (['(512)'], {}), '(512)\n', (548, 553), True, 'import numpy as np\n'), ((599, 636), 'astraviso.imageutils.poisson_noise', 'iu.poisson_noise', (['image', '(0)', '(1200)', '(200)'], {}), '(image, 0, 1200, 200)\n', (615, 636), True, 'from astraviso import imageutils as iu\n'), ((1184, 1197), 'numpy.zeros', 'np.zeros', (['(512)'], {}), '(512)\n', (1192, 1197), True, 'import numpy as np\n'), ((1243, 1281), 'astraviso.imageutils.gaussian_noise', 'iu.gaussian_noise', (['image', '(0)', '(1200)', '(200)'], {}), '(image, 0, 1200, 200)\n', (1260, 1281), True, 'from astraviso import imageutils as iu\n'), ((1792, 1826), 'astraviso.imageutils.vismag2photon', 'iu.vismag2photon', (['vismags', '(1)', '(1)', '(1)'], {}), '(vismags, 1, 1, 1)\n', (1808, 1826), True, 'from astraviso import imageutils as iu\n'), ((2164, 2184), 'numpy.array', 'np.array', (['[1, 0, -1]'], {}), '([1, 0, -1])\n', (2172, 2184), True, 'import numpy as np\n'), ((2233, 2267), 'astraviso.imageutils.vismag2photon', 'iu.vismag2photon', (['vismags', '(1)', '(1)', '(1)'], {}), '(vismags, 1, 1, 1)\n', (2249, 2267), True, 'from astraviso import imageutils as iu\n'), ((4042, 4096), 'astraviso.imageutils.apply_gaussian_quantum_efficiency', 'iu.apply_gaussian_quantum_efficiency', (['test_image', '(0)', '(0)'], {}), '(test_image, 0, 0)\n', (4078, 4096), True, 'from astraviso import imageutils as iu\n'), ((4544, 4611), 'astraviso.imageutils.apply_gaussian_quantum_efficiency', 'iu.apply_gaussian_quantum_efficiency', (['test_image', '(0.2)', '(0.01)'], {'seed': '(1)'}), '(test_image, 0.2, 0.01, seed=1)\n', (4580, 4611), True, 'from astraviso import imageutils as iu\n'), ((4640, 4707), 'astraviso.imageutils.apply_gaussian_quantum_efficiency', 'iu.apply_gaussian_quantum_efficiency', (['test_image', '(0.2)', '(0.01)'], {'seed': '(1)'}), '(test_image, 0.2, 0.01, seed=1)\n', (4676, 4707), True, 'from astraviso import imageutils as iu\n'), ((5360, 5422), 'astraviso.imageutils.apply_gaussian_quantum_efficiency', 'iu.apply_gaussian_quantum_efficiency', (['test_image', '(0)', '(1)'], {'seed': '(1)'}), '(test_image, 0, 1, seed=1)\n', (5396, 5422), True, 'from astraviso import imageutils as iu\n'), ((6789, 6804), 'numpy.ones', 'np.ones', (['(3, 3)'], {}), '((3, 3))\n', (6796, 6804), True, 'import numpy as np\n'), ((6820, 6837), 'numpy.ones', 'np.ones', (['(64, 64)'], {}), '((64, 64))\n', (6827, 6837), True, 'import numpy as np\n'), ((6874, 6897), 'astraviso.imageutils.conv2', 'iu.conv2', (['image', 'kernel'], {}), '(image, kernel)\n', (6882, 6897), True, 'from astraviso import imageutils as iu\n'), ((7314, 7329), 'numpy.ones', 'np.ones', (['(3, 3)'], {}), '((3, 3))\n', (7321, 7329), True, 'import numpy as np\n'), ((7345, 7362), 'numpy.ones', 'np.ones', (['(64, 64)'], {}), '((64, 64))\n', (7352, 7362), True, 'import numpy as np\n'), ((867, 891), 'numpy.all', 'np.all', (['(noisy_image >= 0)'], {}), '(noisy_image >= 0)\n', (873, 891), True, 'import numpy as np\n'), ((2487, 2506), 'numpy.all', 'np.all', (['(photons > 0)'], {}), '(photons > 0)\n', (2493, 2506), True, 'import numpy as np\n'), ((3179, 3207), 'numpy.all', 'np.all', (['(photo_electrons == 0)'], {}), '(photo_electrons == 0)\n', (3185, 3207), True, 'import numpy as np\n'), ((3623, 3651), 'numpy.all', 'np.all', (['(photo_electrons == 6)'], {}), '(photo_electrons == 6)\n', (3629, 3651), True, 'import numpy as np\n'), ((3962, 3979), 'numpy.ones', 'np.ones', (['(16, 16)'], {}), '((16, 16))\n', (3969, 3979), True, 'import numpy as np\n'), ((4238, 4266), 'numpy.all', 'np.all', (['(photo_electrons == 0)'], {}), '(photo_electrons == 0)\n', (4244, 4266), True, 'import numpy as np\n'), ((4462, 4479), 'numpy.ones', 'np.ones', (['(16, 16)'], {}), '((16, 16))\n', (4469, 4479), True, 'import numpy as np\n'), ((4946, 4992), 'numpy.all', 'np.all', (['(photo_electrons_1 == photo_electrons_2)'], {}), '(photo_electrons_1 == photo_electrons_2)\n', (4952, 4992), True, 'import numpy as np\n'), ((5278, 5297), 'numpy.ones', 'np.ones', (['(256, 256)'], {}), '((256, 256))\n', (5285, 5297), True, 'import numpy as np\n'), ((5564, 5592), 'numpy.all', 'np.all', (['(photo_electrons >= 0)'], {}), '(photo_electrons >= 0)\n', (5570, 5592), True, 'import numpy as np\n'), ((6084, 6107), 'numpy.all', 'np.all', (['(saturated == 16)'], {}), '(saturated == 16)\n', (6090, 6107), True, 'import numpy as np\n'), ((6510, 6532), 'numpy.all', 'np.all', (['(saturated == 3)'], {}), '(saturated == 3)\n', (6516, 6532), True, 'import numpy as np\n'), ((7116, 7147), 'numpy.all', 'np.all', (['(result[1:-2, 1:-2] == 9)'], {}), '(result[1:-2, 1:-2] == 9)\n', (7122, 7147), True, 'import numpy as np\n'), ((3017, 3034), 'numpy.ones', 'np.ones', (['(16, 16)'], {}), '((16, 16))\n', (3024, 3034), True, 'import numpy as np\n'), ((3459, 3476), 'numpy.ones', 'np.ones', (['(16, 16)'], {}), '((16, 16))\n', (3466, 3476), True, 'import numpy as np\n'), ((5928, 5945), 'numpy.ones', 'np.ones', (['(16, 16)'], {}), '((16, 16))\n', (5935, 5945), True, 'import numpy as np\n'), ((6354, 6371), 'numpy.ones', 'np.ones', (['(16, 16)'], {}), '((16, 16))\n', (6361, 6371), True, 'import numpy as np\n'), ((7462, 7477), 'numpy.ones', 'np.ones', (['(2, 2)'], {}), '((2, 2))\n', (7469, 7477), True, 'import numpy as np\n'), ((7585, 7600), 'numpy.ones', 'np.ones', (['(2, 3)'], {}), '((2, 3))\n', (7592, 7600), True, 'import numpy as np\n')] |
from __future__ import division
from builtins import object
import numpy as np
from sporco.admm import cbpdn
import sporco_cuda.cbpdn as cucbpdn
import sporco.metric as sm
import sporco.signal as ss
class TestSet01(object):
def setup_method(self, method):
np.random.seed(12345)
def test_01(self):
Nr = 32
Nc = 31
Nd = 5
M = 4
D = np.random.randn(Nd, Nd, M).astype(np.float32)
s = np.random.randn(Nr, Nc).astype(np.float32)
lmbda = 1e-1
opt = cbpdn.ConvBPDN.Options({'Verbose': False, 'MaxMainIter': 50,
'AutoRho': {'Enabled': False}})
b = cbpdn.ConvBPDN(D, s, lmbda, opt)
X1 = b.solve()
X2 = cucbpdn.cbpdn(D, s, lmbda, opt)
assert(sm.mse(X1, X2) < 1e-8)
def test_02(self):
Nr = 32
Nc = 31
Nd = 5
M = 4
D = np.random.randn(Nd, Nd, M).astype(np.float32)
s = np.random.randn(Nr, Nc).astype(np.float32)
lmbda = 1e-1
Wl1 = np.random.randn(1, 1, M).astype(np.float32)
opt = cbpdn.ConvBPDN.Options(
{'Verbose': False, 'MaxMainIter': 50, 'L1Weight': Wl1,
'AutoRho': {'Enabled': False}})
b = cbpdn.ConvBPDN(D, s, lmbda, opt)
X1 = b.solve()
X2 = cucbpdn.cbpdn(D, s, lmbda, opt)
assert(sm.mse(X1, X2) < 1e-8)
def test_03(self):
Nr = 32
Nc = 31
Nd = 5
M = 4
D = np.random.randn(Nd, Nd, M).astype(np.float32)
s = np.random.randn(Nr, Nc).astype(np.float32)
lmbda = 1e-1
Wl1 = np.random.randn(1, 1, M).astype(np.float32)
Wl1[0] = 0.0
opt = cbpdn.ConvBPDN.Options(
{'Verbose': False, 'MaxMainIter': 50, 'L1Weight': Wl1,
'AutoRho': {'Enabled': False}})
b = cbpdn.ConvBPDN(D, s, lmbda, opt)
X1 = b.solve()
X2 = cucbpdn.cbpdn(D, s, lmbda, opt)
assert(sm.mse(X1, X2) < 1e-8)
def test_04(self):
Nr = 32
Nc = 31
Nd = 5
M = 4
D = np.random.randn(Nd, Nd, M).astype(np.float32)
s = np.random.randn(Nr, Nc).astype(np.float32)
lmbda = 1e-1
Wl1 = np.random.randn(Nr, Nc, M).astype(np.float32)
opt = cbpdn.ConvBPDN.Options(
{'Verbose': False, 'MaxMainIter': 50, 'L1Weight': Wl1,
'AutoRho': {'Enabled': False}})
b = cbpdn.ConvBPDN(D, s, lmbda, opt)
X1 = b.solve()
X2 = cucbpdn.cbpdn(D, s, lmbda, opt)
assert(sm.mse(X1, X2) < 1e-6)
def test_05(self):
Nr = 32
Nc = 31
Nd = 5
M = 4
D = np.random.randn(Nd, Nd, M).astype(np.float32)
s = np.random.randn(Nr, Nc).astype(np.float32)
lmbda = 1e-1
mu = 1e-2
opt = cbpdn.ConvBPDNGradReg.Options(
{'Verbose': False, 'MaxMainIter': 50, 'AutoRho':
{'Enabled': False}})
b = cbpdn.ConvBPDNGradReg(D, s, lmbda, mu, opt)
X1 = b.solve()
X2 = cucbpdn.cbpdngrd(D, s, lmbda, mu, opt)
assert(sm.mse(X1, X2) < 1e-8)
def test_06(self):
Nr = 32
Nc = 31
Nd = 5
M = 4
D = np.random.randn(Nd, Nd, M).astype(np.float32)
s = np.random.randn(Nr, Nc).astype(np.float32)
lmbda = 1e-1
mu = 1e-2
Wgrd = np.random.randn(M).astype(np.float32)
opt = cbpdn.ConvBPDNGradReg.Options(
{'Verbose': False, 'MaxMainIter': 50, 'GradWeight': Wgrd,
'AutoRho': {'Enabled': False}})
b = cbpdn.ConvBPDNGradReg(D, s, lmbda, mu, opt)
X1 = b.solve()
X2 = cucbpdn.cbpdngrd(D, s, lmbda, mu, opt)
assert(sm.mse(X1, X2) < 1e-8)
def test_07(self):
Nr = 32
Nc = 31
Nd = 5
M = 4
D = np.random.randn(Nd, Nd, M).astype(np.float32)
s = np.random.randn(Nr, Nc).astype(np.float32)
lmbda = 1e-1
mu = 1e-2
Wl1 = np.random.randn(1, 1, M).astype(np.float32)
opt = cbpdn.ConvBPDNGradReg.Options(
{'Verbose': False, 'MaxMainIter': 50, 'L1Weight': Wl1,
'AutoRho': {'Enabled': False}})
b = cbpdn.ConvBPDNGradReg(D, s, lmbda, mu, opt)
X1 = b.solve()
X2 = cucbpdn.cbpdngrd(D, s, lmbda, mu, opt)
assert(sm.mse(X1, X2) < 1e-8)
def test_08(self):
Nr = 32
Nc = 31
Nd = 5
M = 4
D = np.random.randn(Nd, Nd, M).astype(np.float32)
s = np.random.randn(Nr, Nc).astype(np.float32)
lmbda = 1e-1
mu = 1e-2
Wl1 = np.random.randn(Nr, Nc, M).astype(np.float32)
opt = cbpdn.ConvBPDNGradReg.Options(
{'Verbose': False, 'MaxMainIter': 50, 'L1Weight': Wl1,
'AutoRho': {'Enabled': False}})
b = cbpdn.ConvBPDNGradReg(D, s, lmbda, mu, opt)
X1 = b.solve()
X2 = cucbpdn.cbpdngrd(D, s, lmbda, mu, opt)
assert(sm.mse(X1, X2) < 1e-8)
def test_09(self):
Nr = 32
Nc = 31
Nd = 5
M = 4
D = np.random.randn(Nd, Nd, M).astype(np.float32)
s = np.random.randn(Nr, Nc).astype(np.float32)
lmbda = 1e-1
mu = 1e-2
Wl1 = np.random.randn(Nr, Nc, M).astype(np.float32)
Wgrd = np.random.randn(M).astype(np.float32)
opt = cbpdn.ConvBPDNGradReg.Options(
{'Verbose': False, 'MaxMainIter': 50, 'L1Weight': Wl1,
'GradWeight': Wgrd, 'AutoRho': {'Enabled': False}})
b = cbpdn.ConvBPDNGradReg(D, s, lmbda, mu, opt)
X1 = b.solve()
X2 = cucbpdn.cbpdngrd(D, s, lmbda, mu, opt)
assert(sm.mse(X1, X2) < 1e-8)
def test_10(self):
Nr = 32
Nc = 31
Nd = 5
M = 4
D = np.random.randn(Nd, Nd, M).astype(np.float32)
s = np.random.randn(Nr, Nc).astype(np.float32)
frc = 0.5
msk = ss.rndmask(s.shape, frc, dtype=np.float32)
s *= msk
lmbda = 1e-1
opt = cbpdn.ConvBPDN.Options({'Verbose': False, 'MaxMainIter': 50,
'AutoRho': {'Enabled': False}})
b = cbpdn.AddMaskSim(cbpdn.ConvBPDN, D, s, msk, lmbda, opt=opt)
X1 = b.solve()
X2 = cucbpdn.cbpdnmsk(D, s, msk, lmbda, opt)
assert(sm.mse(X1, X2) < 1e-8)
def test_11(self):
Nr = 32
Nc = 31
Nd = 5
M = 4
D = np.random.randn(Nd, Nd, M).astype(np.float32)
s = np.random.randn(Nr, Nc).astype(np.float32)
frc = 0.5
msk = ss.rndmask(s.shape, frc, dtype=np.float32)
s *= msk
lmbda = 1e-1
# Create a random ℓ1 term weighting array. There is no need to
# extend this array to account for the AMS impulse filter since
# this is taken care of automatically by cucbpdn.cbpdnmsk
Wl1 = np.random.randn(1, 1, M).astype(np.float32)
# Append a zero entry to the L1Weight array, corresponding to
# the impulse filter appended to the dictionary by cbpdn.AddMaskSim,
# since this is not done automatically by cbpdn.AddMaskSim
Wl1i = np.concatenate((Wl1, np.zeros(Wl1.shape[0:-1] + (1,))),
axis=-1)
opt = cbpdn.ConvBPDN.Options({'Verbose': False, 'MaxMainIter': 50,
'AutoRho': {'Enabled': False}})
opt['L1Weight'] = Wl1i
b = cbpdn.AddMaskSim(cbpdn.ConvBPDN, D, s, msk, lmbda, opt=opt)
X1 = b.solve()
opt['L1Weight'] = Wl1
X2 = cucbpdn.cbpdnmsk(D, s, msk, lmbda, opt)
assert(sm.mse(X1, X2) < 1e-8)
def test_12(self):
Nr = 32
Nc = 31
Nd = 5
M = 4
D = np.random.randn(Nd, Nd, M).astype(np.float32)
s = np.random.randn(Nr, Nc).astype(np.float32)
frc = 0.5
msk = ss.rndmask(s.shape, frc, dtype=np.float32)
s *= msk
lmbda = 1e-1
mu = 1e-2
# Since cucbpdn.cbpdngrdmsk automatically ensures that the ℓ2 of
# gradient term is not applied to the AMS impulse filter, while
# cbpdn.AddMaskSim does not, we have to pass a GradWeight array
# with a zero entry corresponding to the AMS impulse filter to
# cbpdn.AddMaskSim
Wgrdi = np.hstack((np.ones(M,), np.zeros((1,))))
opt = cbpdn.ConvBPDNGradReg.Options(
{'Verbose': False, 'MaxMainIter': 50, 'AutoRho':
{'Enabled': False}})
opt['GradWeight'] = Wgrdi
b = cbpdn.AddMaskSim(cbpdn.ConvBPDNGradReg, D, s, msk, lmbda, mu, opt)
X1 = b.solve()
opt['GradWeight'] = 1.0
X2 = cucbpdn.cbpdngrdmsk(D, s, msk, lmbda, mu, opt)
assert(sm.mse(X1, X2) < 1e-8)
def test_13(self):
Nr = 32
Nc = 31
Nd = 5
M = 4
D = np.random.randn(Nd, Nd, M).astype(np.float32)
s = np.random.randn(Nr, Nc).astype(np.float32)
frc = 0.5
msk = ss.rndmask(s.shape, frc, dtype=np.float32)
s *= msk
lmbda = 1e-1
mu = 1e-2
# Create a random ℓ1 term weighting array. There is no need to
# extend this array to account for the AMS impulse filter since
# this is taken care of automatically by cucbpdn.cbpdngrdmsk
Wl1 = np.random.randn(1, 1, M).astype(np.float32)
# Append a zero entry to the L1Weight array, corresponding to
# the impulse filter appended to the dictionary by cbpdn.AddMaskSim,
# since this is not done automatically by cbpdn.AddMaskSim
Wl1i = np.concatenate((Wl1, np.zeros(Wl1.shape[0:-1] + (1,))),
axis=-1)
# Since cucbpdn.cbpdngrdmsk automatically ensures that the ℓ2 of
# gradient term is not applied to the AMS impulse filter, while
# cbpdn.AddMaskSim does not, we have to pass a GradWeight array
# with a zero entry corresponding to the AMS impulse filter to
# cbpdn.AddMaskSim
Wgrdi = np.hstack((np.ones(M,), np.zeros((1,))))
opt = cbpdn.ConvBPDNGradReg.Options(
{'Verbose': False, 'MaxMainIter': 50, 'AutoRho':
{'Enabled': False}})
opt['L1Weight'] = Wl1i
opt['GradWeight'] = Wgrdi
b = cbpdn.AddMaskSim(cbpdn.ConvBPDNGradReg, D, s, msk, lmbda, mu, opt)
X1 = b.solve()
opt['L1Weight'] = Wl1
opt['GradWeight'] = 1.0
X2 = cucbpdn.cbpdngrdmsk(D, s, msk, lmbda, mu, opt)
assert(sm.mse(X1, X2) < 1e-8)
def test_14(self):
Nr = 32
Nc = 31
Nd = 5
M = 4
D = np.random.randn(Nd, Nd, M).astype(np.float32)
s = np.random.randn(Nr, Nc).astype(np.float32)
frc = 0.5
msk = ss.rndmask(s.shape, frc, dtype=np.float32)
s *= msk
lmbda = 1e-1
mu = 1e-2
# Create a random ℓ2 of gradient term weighting array. There is no
# need to extend this array to account for the AMS impulse filter
# since this is taken care of automatically by cucbpdn.cbpdngrdmsk
Wgrd = np.random.randn(M).astype(np.float32)
# Append a zero entry to the GradWeight array, corresponding to
# the impulse filter appended to the dictionary by cbpdn.AddMaskSim,
# since this is not done automatically by cbpdn.AddMaskSim
Wgrdi = np.hstack((Wgrd, np.zeros((1,))))
opt = cbpdn.ConvBPDNGradReg.Options(
{'Verbose': False, 'MaxMainIter': 50, 'AutoRho':
{'Enabled': False}})
opt['GradWeight'] = Wgrdi
b = cbpdn.AddMaskSim(cbpdn.ConvBPDNGradReg, D, s, msk, lmbda, mu, opt)
X1 = b.solve()
opt['GradWeight'] = Wgrd
X2 = cucbpdn.cbpdngrdmsk(D, s, msk, lmbda, mu, opt)
assert(sm.mse(X1, X2) < 1e-8)
| [
"sporco.admm.cbpdn.ConvBPDN",
"numpy.random.seed",
"sporco.admm.cbpdn.ConvBPDN.Options",
"sporco.admm.cbpdn.AddMaskSim",
"numpy.random.randn",
"sporco.admm.cbpdn.ConvBPDNGradReg.Options",
"sporco.signal.rndmask",
"sporco_cuda.cbpdn.cbpdnmsk",
"sporco.metric.mse",
"numpy.zeros",
"sporco_cuda.cbpd... | [((274, 295), 'numpy.random.seed', 'np.random.seed', (['(12345)'], {}), '(12345)\n', (288, 295), True, 'import numpy as np\n'), ((530, 627), 'sporco.admm.cbpdn.ConvBPDN.Options', 'cbpdn.ConvBPDN.Options', (["{'Verbose': False, 'MaxMainIter': 50, 'AutoRho': {'Enabled': False}}"], {}), "({'Verbose': False, 'MaxMainIter': 50, 'AutoRho': {\n 'Enabled': False}})\n", (552, 627), False, 'from sporco.admm import cbpdn\n'), ((673, 705), 'sporco.admm.cbpdn.ConvBPDN', 'cbpdn.ConvBPDN', (['D', 's', 'lmbda', 'opt'], {}), '(D, s, lmbda, opt)\n', (687, 705), False, 'from sporco.admm import cbpdn\n'), ((742, 773), 'sporco_cuda.cbpdn.cbpdn', 'cucbpdn.cbpdn', (['D', 's', 'lmbda', 'opt'], {}), '(D, s, lmbda, opt)\n', (755, 773), True, 'import sporco_cuda.cbpdn as cucbpdn\n'), ((1105, 1218), 'sporco.admm.cbpdn.ConvBPDN.Options', 'cbpdn.ConvBPDN.Options', (["{'Verbose': False, 'MaxMainIter': 50, 'L1Weight': Wl1, 'AutoRho': {\n 'Enabled': False}}"], {}), "({'Verbose': False, 'MaxMainIter': 50, 'L1Weight':\n Wl1, 'AutoRho': {'Enabled': False}})\n", (1127, 1218), False, 'from sporco.admm import cbpdn\n'), ((1253, 1285), 'sporco.admm.cbpdn.ConvBPDN', 'cbpdn.ConvBPDN', (['D', 's', 'lmbda', 'opt'], {}), '(D, s, lmbda, opt)\n', (1267, 1285), False, 'from sporco.admm import cbpdn\n'), ((1322, 1353), 'sporco_cuda.cbpdn.cbpdn', 'cucbpdn.cbpdn', (['D', 's', 'lmbda', 'opt'], {}), '(D, s, lmbda, opt)\n', (1335, 1353), True, 'import sporco_cuda.cbpdn as cucbpdn\n'), ((1706, 1819), 'sporco.admm.cbpdn.ConvBPDN.Options', 'cbpdn.ConvBPDN.Options', (["{'Verbose': False, 'MaxMainIter': 50, 'L1Weight': Wl1, 'AutoRho': {\n 'Enabled': False}}"], {}), "({'Verbose': False, 'MaxMainIter': 50, 'L1Weight':\n Wl1, 'AutoRho': {'Enabled': False}})\n", (1728, 1819), False, 'from sporco.admm import cbpdn\n'), ((1854, 1886), 'sporco.admm.cbpdn.ConvBPDN', 'cbpdn.ConvBPDN', (['D', 's', 'lmbda', 'opt'], {}), '(D, s, lmbda, opt)\n', (1868, 1886), False, 'from sporco.admm import cbpdn\n'), ((1923, 1954), 'sporco_cuda.cbpdn.cbpdn', 'cucbpdn.cbpdn', (['D', 's', 'lmbda', 'opt'], {}), '(D, s, lmbda, opt)\n', (1936, 1954), True, 'import sporco_cuda.cbpdn as cucbpdn\n'), ((2288, 2401), 'sporco.admm.cbpdn.ConvBPDN.Options', 'cbpdn.ConvBPDN.Options', (["{'Verbose': False, 'MaxMainIter': 50, 'L1Weight': Wl1, 'AutoRho': {\n 'Enabled': False}}"], {}), "({'Verbose': False, 'MaxMainIter': 50, 'L1Weight':\n Wl1, 'AutoRho': {'Enabled': False}})\n", (2310, 2401), False, 'from sporco.admm import cbpdn\n'), ((2436, 2468), 'sporco.admm.cbpdn.ConvBPDN', 'cbpdn.ConvBPDN', (['D', 's', 'lmbda', 'opt'], {}), '(D, s, lmbda, opt)\n', (2450, 2468), False, 'from sporco.admm import cbpdn\n'), ((2505, 2536), 'sporco_cuda.cbpdn.cbpdn', 'cucbpdn.cbpdn', (['D', 's', 'lmbda', 'opt'], {}), '(D, s, lmbda, opt)\n', (2518, 2536), True, 'import sporco_cuda.cbpdn as cucbpdn\n'), ((2828, 2931), 'sporco.admm.cbpdn.ConvBPDNGradReg.Options', 'cbpdn.ConvBPDNGradReg.Options', (["{'Verbose': False, 'MaxMainIter': 50, 'AutoRho': {'Enabled': False}}"], {}), "({'Verbose': False, 'MaxMainIter': 50,\n 'AutoRho': {'Enabled': False}})\n", (2857, 2931), False, 'from sporco.admm import cbpdn\n'), ((2966, 3009), 'sporco.admm.cbpdn.ConvBPDNGradReg', 'cbpdn.ConvBPDNGradReg', (['D', 's', 'lmbda', 'mu', 'opt'], {}), '(D, s, lmbda, mu, opt)\n', (2987, 3009), False, 'from sporco.admm import cbpdn\n'), ((3046, 3084), 'sporco_cuda.cbpdn.cbpdngrd', 'cucbpdn.cbpdngrd', (['D', 's', 'lmbda', 'mu', 'opt'], {}), '(D, s, lmbda, mu, opt)\n', (3062, 3084), True, 'import sporco_cuda.cbpdn as cucbpdn\n'), ((3429, 3552), 'sporco.admm.cbpdn.ConvBPDNGradReg.Options', 'cbpdn.ConvBPDNGradReg.Options', (["{'Verbose': False, 'MaxMainIter': 50, 'GradWeight': Wgrd, 'AutoRho': {\n 'Enabled': False}}"], {}), "({'Verbose': False, 'MaxMainIter': 50,\n 'GradWeight': Wgrd, 'AutoRho': {'Enabled': False}})\n", (3458, 3552), False, 'from sporco.admm import cbpdn\n'), ((3587, 3630), 'sporco.admm.cbpdn.ConvBPDNGradReg', 'cbpdn.ConvBPDNGradReg', (['D', 's', 'lmbda', 'mu', 'opt'], {}), '(D, s, lmbda, mu, opt)\n', (3608, 3630), False, 'from sporco.admm import cbpdn\n'), ((3667, 3705), 'sporco_cuda.cbpdn.cbpdngrd', 'cucbpdn.cbpdngrd', (['D', 's', 'lmbda', 'mu', 'opt'], {}), '(D, s, lmbda, mu, opt)\n', (3683, 3705), True, 'import sporco_cuda.cbpdn as cucbpdn\n'), ((4055, 4175), 'sporco.admm.cbpdn.ConvBPDNGradReg.Options', 'cbpdn.ConvBPDNGradReg.Options', (["{'Verbose': False, 'MaxMainIter': 50, 'L1Weight': Wl1, 'AutoRho': {\n 'Enabled': False}}"], {}), "({'Verbose': False, 'MaxMainIter': 50,\n 'L1Weight': Wl1, 'AutoRho': {'Enabled': False}})\n", (4084, 4175), False, 'from sporco.admm import cbpdn\n'), ((4210, 4253), 'sporco.admm.cbpdn.ConvBPDNGradReg', 'cbpdn.ConvBPDNGradReg', (['D', 's', 'lmbda', 'mu', 'opt'], {}), '(D, s, lmbda, mu, opt)\n', (4231, 4253), False, 'from sporco.admm import cbpdn\n'), ((4290, 4328), 'sporco_cuda.cbpdn.cbpdngrd', 'cucbpdn.cbpdngrd', (['D', 's', 'lmbda', 'mu', 'opt'], {}), '(D, s, lmbda, mu, opt)\n', (4306, 4328), True, 'import sporco_cuda.cbpdn as cucbpdn\n'), ((4680, 4800), 'sporco.admm.cbpdn.ConvBPDNGradReg.Options', 'cbpdn.ConvBPDNGradReg.Options', (["{'Verbose': False, 'MaxMainIter': 50, 'L1Weight': Wl1, 'AutoRho': {\n 'Enabled': False}}"], {}), "({'Verbose': False, 'MaxMainIter': 50,\n 'L1Weight': Wl1, 'AutoRho': {'Enabled': False}})\n", (4709, 4800), False, 'from sporco.admm import cbpdn\n'), ((4835, 4878), 'sporco.admm.cbpdn.ConvBPDNGradReg', 'cbpdn.ConvBPDNGradReg', (['D', 's', 'lmbda', 'mu', 'opt'], {}), '(D, s, lmbda, mu, opt)\n', (4856, 4878), False, 'from sporco.admm import cbpdn\n'), ((4915, 4953), 'sporco_cuda.cbpdn.cbpdngrd', 'cucbpdn.cbpdngrd', (['D', 's', 'lmbda', 'mu', 'opt'], {}), '(D, s, lmbda, mu, opt)\n', (4931, 4953), True, 'import sporco_cuda.cbpdn as cucbpdn\n'), ((5358, 5498), 'sporco.admm.cbpdn.ConvBPDNGradReg.Options', 'cbpdn.ConvBPDNGradReg.Options', (["{'Verbose': False, 'MaxMainIter': 50, 'L1Weight': Wl1, 'GradWeight': Wgrd,\n 'AutoRho': {'Enabled': False}}"], {}), "({'Verbose': False, 'MaxMainIter': 50,\n 'L1Weight': Wl1, 'GradWeight': Wgrd, 'AutoRho': {'Enabled': False}})\n", (5387, 5498), False, 'from sporco.admm import cbpdn\n'), ((5533, 5576), 'sporco.admm.cbpdn.ConvBPDNGradReg', 'cbpdn.ConvBPDNGradReg', (['D', 's', 'lmbda', 'mu', 'opt'], {}), '(D, s, lmbda, mu, opt)\n', (5554, 5576), False, 'from sporco.admm import cbpdn\n'), ((5613, 5651), 'sporco_cuda.cbpdn.cbpdngrd', 'cucbpdn.cbpdngrd', (['D', 's', 'lmbda', 'mu', 'opt'], {}), '(D, s, lmbda, mu, opt)\n', (5629, 5651), True, 'import sporco_cuda.cbpdn as cucbpdn\n'), ((5922, 5964), 'sporco.signal.rndmask', 'ss.rndmask', (['s.shape', 'frc'], {'dtype': 'np.float32'}), '(s.shape, frc, dtype=np.float32)\n', (5932, 5964), True, 'import sporco.signal as ss\n'), ((6017, 6114), 'sporco.admm.cbpdn.ConvBPDN.Options', 'cbpdn.ConvBPDN.Options', (["{'Verbose': False, 'MaxMainIter': 50, 'AutoRho': {'Enabled': False}}"], {}), "({'Verbose': False, 'MaxMainIter': 50, 'AutoRho': {\n 'Enabled': False}})\n", (6039, 6114), False, 'from sporco.admm import cbpdn\n'), ((6160, 6219), 'sporco.admm.cbpdn.AddMaskSim', 'cbpdn.AddMaskSim', (['cbpdn.ConvBPDN', 'D', 's', 'msk', 'lmbda'], {'opt': 'opt'}), '(cbpdn.ConvBPDN, D, s, msk, lmbda, opt=opt)\n', (6176, 6219), False, 'from sporco.admm import cbpdn\n'), ((6256, 6295), 'sporco_cuda.cbpdn.cbpdnmsk', 'cucbpdn.cbpdnmsk', (['D', 's', 'msk', 'lmbda', 'opt'], {}), '(D, s, msk, lmbda, opt)\n', (6272, 6295), True, 'import sporco_cuda.cbpdn as cucbpdn\n'), ((6566, 6608), 'sporco.signal.rndmask', 'ss.rndmask', (['s.shape', 'frc'], {'dtype': 'np.float32'}), '(s.shape, frc, dtype=np.float32)\n', (6576, 6608), True, 'import sporco.signal as ss\n'), ((7252, 7349), 'sporco.admm.cbpdn.ConvBPDN.Options', 'cbpdn.ConvBPDN.Options', (["{'Verbose': False, 'MaxMainIter': 50, 'AutoRho': {'Enabled': False}}"], {}), "({'Verbose': False, 'MaxMainIter': 50, 'AutoRho': {\n 'Enabled': False}})\n", (7274, 7349), False, 'from sporco.admm import cbpdn\n'), ((7426, 7485), 'sporco.admm.cbpdn.AddMaskSim', 'cbpdn.AddMaskSim', (['cbpdn.ConvBPDN', 'D', 's', 'msk', 'lmbda'], {'opt': 'opt'}), '(cbpdn.ConvBPDN, D, s, msk, lmbda, opt=opt)\n', (7442, 7485), False, 'from sporco.admm import cbpdn\n'), ((7552, 7591), 'sporco_cuda.cbpdn.cbpdnmsk', 'cucbpdn.cbpdnmsk', (['D', 's', 'msk', 'lmbda', 'opt'], {}), '(D, s, msk, lmbda, opt)\n', (7568, 7591), True, 'import sporco_cuda.cbpdn as cucbpdn\n'), ((7862, 7904), 'sporco.signal.rndmask', 'ss.rndmask', (['s.shape', 'frc'], {'dtype': 'np.float32'}), '(s.shape, frc, dtype=np.float32)\n', (7872, 7904), True, 'import sporco.signal as ss\n'), ((8347, 8450), 'sporco.admm.cbpdn.ConvBPDNGradReg.Options', 'cbpdn.ConvBPDNGradReg.Options', (["{'Verbose': False, 'MaxMainIter': 50, 'AutoRho': {'Enabled': False}}"], {}), "({'Verbose': False, 'MaxMainIter': 50,\n 'AutoRho': {'Enabled': False}})\n", (8376, 8450), False, 'from sporco.admm import cbpdn\n'), ((8519, 8585), 'sporco.admm.cbpdn.AddMaskSim', 'cbpdn.AddMaskSim', (['cbpdn.ConvBPDNGradReg', 'D', 's', 'msk', 'lmbda', 'mu', 'opt'], {}), '(cbpdn.ConvBPDNGradReg, D, s, msk, lmbda, mu, opt)\n', (8535, 8585), False, 'from sporco.admm import cbpdn\n'), ((8654, 8700), 'sporco_cuda.cbpdn.cbpdngrdmsk', 'cucbpdn.cbpdngrdmsk', (['D', 's', 'msk', 'lmbda', 'mu', 'opt'], {}), '(D, s, msk, lmbda, mu, opt)\n', (8673, 8700), True, 'import sporco_cuda.cbpdn as cucbpdn\n'), ((8971, 9013), 'sporco.signal.rndmask', 'ss.rndmask', (['s.shape', 'frc'], {'dtype': 'np.float32'}), '(s.shape, frc, dtype=np.float32)\n', (8981, 9013), True, 'import sporco.signal as ss\n'), ((10050, 10153), 'sporco.admm.cbpdn.ConvBPDNGradReg.Options', 'cbpdn.ConvBPDNGradReg.Options', (["{'Verbose': False, 'MaxMainIter': 50, 'AutoRho': {'Enabled': False}}"], {}), "({'Verbose': False, 'MaxMainIter': 50,\n 'AutoRho': {'Enabled': False}})\n", (10079, 10153), False, 'from sporco.admm import cbpdn\n'), ((10253, 10319), 'sporco.admm.cbpdn.AddMaskSim', 'cbpdn.AddMaskSim', (['cbpdn.ConvBPDNGradReg', 'D', 's', 'msk', 'lmbda', 'mu', 'opt'], {}), '(cbpdn.ConvBPDNGradReg, D, s, msk, lmbda, mu, opt)\n', (10269, 10319), False, 'from sporco.admm import cbpdn\n'), ((10418, 10464), 'sporco_cuda.cbpdn.cbpdngrdmsk', 'cucbpdn.cbpdngrdmsk', (['D', 's', 'msk', 'lmbda', 'mu', 'opt'], {}), '(D, s, msk, lmbda, mu, opt)\n', (10437, 10464), True, 'import sporco_cuda.cbpdn as cucbpdn\n'), ((10735, 10777), 'sporco.signal.rndmask', 'ss.rndmask', (['s.shape', 'frc'], {'dtype': 'np.float32'}), '(s.shape, frc, dtype=np.float32)\n', (10745, 10777), True, 'import sporco.signal as ss\n'), ((11391, 11494), 'sporco.admm.cbpdn.ConvBPDNGradReg.Options', 'cbpdn.ConvBPDNGradReg.Options', (["{'Verbose': False, 'MaxMainIter': 50, 'AutoRho': {'Enabled': False}}"], {}), "({'Verbose': False, 'MaxMainIter': 50,\n 'AutoRho': {'Enabled': False}})\n", (11420, 11494), False, 'from sporco.admm import cbpdn\n'), ((11563, 11629), 'sporco.admm.cbpdn.AddMaskSim', 'cbpdn.AddMaskSim', (['cbpdn.ConvBPDNGradReg', 'D', 's', 'msk', 'lmbda', 'mu', 'opt'], {}), '(cbpdn.ConvBPDNGradReg, D, s, msk, lmbda, mu, opt)\n', (11579, 11629), False, 'from sporco.admm import cbpdn\n'), ((11699, 11745), 'sporco_cuda.cbpdn.cbpdngrdmsk', 'cucbpdn.cbpdngrdmsk', (['D', 's', 'msk', 'lmbda', 'mu', 'opt'], {}), '(D, s, msk, lmbda, mu, opt)\n', (11718, 11745), True, 'import sporco_cuda.cbpdn as cucbpdn\n'), ((789, 803), 'sporco.metric.mse', 'sm.mse', (['X1', 'X2'], {}), '(X1, X2)\n', (795, 803), True, 'import sporco.metric as sm\n'), ((1369, 1383), 'sporco.metric.mse', 'sm.mse', (['X1', 'X2'], {}), '(X1, X2)\n', (1375, 1383), True, 'import sporco.metric as sm\n'), ((1970, 1984), 'sporco.metric.mse', 'sm.mse', (['X1', 'X2'], {}), '(X1, X2)\n', (1976, 1984), True, 'import sporco.metric as sm\n'), ((2552, 2566), 'sporco.metric.mse', 'sm.mse', (['X1', 'X2'], {}), '(X1, X2)\n', (2558, 2566), True, 'import sporco.metric as sm\n'), ((3100, 3114), 'sporco.metric.mse', 'sm.mse', (['X1', 'X2'], {}), '(X1, X2)\n', (3106, 3114), True, 'import sporco.metric as sm\n'), ((3721, 3735), 'sporco.metric.mse', 'sm.mse', (['X1', 'X2'], {}), '(X1, X2)\n', (3727, 3735), True, 'import sporco.metric as sm\n'), ((4344, 4358), 'sporco.metric.mse', 'sm.mse', (['X1', 'X2'], {}), '(X1, X2)\n', (4350, 4358), True, 'import sporco.metric as sm\n'), ((4969, 4983), 'sporco.metric.mse', 'sm.mse', (['X1', 'X2'], {}), '(X1, X2)\n', (4975, 4983), True, 'import sporco.metric as sm\n'), ((5667, 5681), 'sporco.metric.mse', 'sm.mse', (['X1', 'X2'], {}), '(X1, X2)\n', (5673, 5681), True, 'import sporco.metric as sm\n'), ((6311, 6325), 'sporco.metric.mse', 'sm.mse', (['X1', 'X2'], {}), '(X1, X2)\n', (6317, 6325), True, 'import sporco.metric as sm\n'), ((7607, 7621), 'sporco.metric.mse', 'sm.mse', (['X1', 'X2'], {}), '(X1, X2)\n', (7613, 7621), True, 'import sporco.metric as sm\n'), ((8716, 8730), 'sporco.metric.mse', 'sm.mse', (['X1', 'X2'], {}), '(X1, X2)\n', (8722, 8730), True, 'import sporco.metric as sm\n'), ((10480, 10494), 'sporco.metric.mse', 'sm.mse', (['X1', 'X2'], {}), '(X1, X2)\n', (10486, 10494), True, 'import sporco.metric as sm\n'), ((11761, 11775), 'sporco.metric.mse', 'sm.mse', (['X1', 'X2'], {}), '(X1, X2)\n', (11767, 11775), True, 'import sporco.metric as sm\n'), ((394, 420), 'numpy.random.randn', 'np.random.randn', (['Nd', 'Nd', 'M'], {}), '(Nd, Nd, M)\n', (409, 420), True, 'import numpy as np\n'), ((452, 475), 'numpy.random.randn', 'np.random.randn', (['Nr', 'Nc'], {}), '(Nr, Nc)\n', (467, 475), True, 'import numpy as np\n'), ((911, 937), 'numpy.random.randn', 'np.random.randn', (['Nd', 'Nd', 'M'], {}), '(Nd, Nd, M)\n', (926, 937), True, 'import numpy as np\n'), ((969, 992), 'numpy.random.randn', 'np.random.randn', (['Nr', 'Nc'], {}), '(Nr, Nc)\n', (984, 992), True, 'import numpy as np\n'), ((1047, 1071), 'numpy.random.randn', 'np.random.randn', (['(1)', '(1)', 'M'], {}), '(1, 1, M)\n', (1062, 1071), True, 'import numpy as np\n'), ((1491, 1517), 'numpy.random.randn', 'np.random.randn', (['Nd', 'Nd', 'M'], {}), '(Nd, Nd, M)\n', (1506, 1517), True, 'import numpy as np\n'), ((1549, 1572), 'numpy.random.randn', 'np.random.randn', (['Nr', 'Nc'], {}), '(Nr, Nc)\n', (1564, 1572), True, 'import numpy as np\n'), ((1627, 1651), 'numpy.random.randn', 'np.random.randn', (['(1)', '(1)', 'M'], {}), '(1, 1, M)\n', (1642, 1651), True, 'import numpy as np\n'), ((2092, 2118), 'numpy.random.randn', 'np.random.randn', (['Nd', 'Nd', 'M'], {}), '(Nd, Nd, M)\n', (2107, 2118), True, 'import numpy as np\n'), ((2150, 2173), 'numpy.random.randn', 'np.random.randn', (['Nr', 'Nc'], {}), '(Nr, Nc)\n', (2165, 2173), True, 'import numpy as np\n'), ((2228, 2254), 'numpy.random.randn', 'np.random.randn', (['Nr', 'Nc', 'M'], {}), '(Nr, Nc, M)\n', (2243, 2254), True, 'import numpy as np\n'), ((2674, 2700), 'numpy.random.randn', 'np.random.randn', (['Nd', 'Nd', 'M'], {}), '(Nd, Nd, M)\n', (2689, 2700), True, 'import numpy as np\n'), ((2732, 2755), 'numpy.random.randn', 'np.random.randn', (['Nr', 'Nc'], {}), '(Nr, Nc)\n', (2747, 2755), True, 'import numpy as np\n'), ((3222, 3248), 'numpy.random.randn', 'np.random.randn', (['Nd', 'Nd', 'M'], {}), '(Nd, Nd, M)\n', (3237, 3248), True, 'import numpy as np\n'), ((3280, 3303), 'numpy.random.randn', 'np.random.randn', (['Nr', 'Nc'], {}), '(Nr, Nc)\n', (3295, 3303), True, 'import numpy as np\n'), ((3377, 3395), 'numpy.random.randn', 'np.random.randn', (['M'], {}), '(M)\n', (3392, 3395), True, 'import numpy as np\n'), ((3843, 3869), 'numpy.random.randn', 'np.random.randn', (['Nd', 'Nd', 'M'], {}), '(Nd, Nd, M)\n', (3858, 3869), True, 'import numpy as np\n'), ((3901, 3924), 'numpy.random.randn', 'np.random.randn', (['Nr', 'Nc'], {}), '(Nr, Nc)\n', (3916, 3924), True, 'import numpy as np\n'), ((3997, 4021), 'numpy.random.randn', 'np.random.randn', (['(1)', '(1)', 'M'], {}), '(1, 1, M)\n', (4012, 4021), True, 'import numpy as np\n'), ((4466, 4492), 'numpy.random.randn', 'np.random.randn', (['Nd', 'Nd', 'M'], {}), '(Nd, Nd, M)\n', (4481, 4492), True, 'import numpy as np\n'), ((4524, 4547), 'numpy.random.randn', 'np.random.randn', (['Nr', 'Nc'], {}), '(Nr, Nc)\n', (4539, 4547), True, 'import numpy as np\n'), ((4620, 4646), 'numpy.random.randn', 'np.random.randn', (['Nr', 'Nc', 'M'], {}), '(Nr, Nc, M)\n', (4635, 4646), True, 'import numpy as np\n'), ((5091, 5117), 'numpy.random.randn', 'np.random.randn', (['Nd', 'Nd', 'M'], {}), '(Nd, Nd, M)\n', (5106, 5117), True, 'import numpy as np\n'), ((5149, 5172), 'numpy.random.randn', 'np.random.randn', (['Nr', 'Nc'], {}), '(Nr, Nc)\n', (5164, 5172), True, 'import numpy as np\n'), ((5245, 5271), 'numpy.random.randn', 'np.random.randn', (['Nr', 'Nc', 'M'], {}), '(Nr, Nc, M)\n', (5260, 5271), True, 'import numpy as np\n'), ((5306, 5324), 'numpy.random.randn', 'np.random.randn', (['M'], {}), '(M)\n', (5321, 5324), True, 'import numpy as np\n'), ((5789, 5815), 'numpy.random.randn', 'np.random.randn', (['Nd', 'Nd', 'M'], {}), '(Nd, Nd, M)\n', (5804, 5815), True, 'import numpy as np\n'), ((5847, 5870), 'numpy.random.randn', 'np.random.randn', (['Nr', 'Nc'], {}), '(Nr, Nc)\n', (5862, 5870), True, 'import numpy as np\n'), ((6433, 6459), 'numpy.random.randn', 'np.random.randn', (['Nd', 'Nd', 'M'], {}), '(Nd, Nd, M)\n', (6448, 6459), True, 'import numpy as np\n'), ((6491, 6514), 'numpy.random.randn', 'np.random.randn', (['Nr', 'Nc'], {}), '(Nr, Nc)\n', (6506, 6514), True, 'import numpy as np\n'), ((6870, 6894), 'numpy.random.randn', 'np.random.randn', (['(1)', '(1)', 'M'], {}), '(1, 1, M)\n', (6885, 6894), True, 'import numpy as np\n'), ((7164, 7196), 'numpy.zeros', 'np.zeros', (['(Wl1.shape[0:-1] + (1,))'], {}), '(Wl1.shape[0:-1] + (1,))\n', (7172, 7196), True, 'import numpy as np\n'), ((7729, 7755), 'numpy.random.randn', 'np.random.randn', (['Nd', 'Nd', 'M'], {}), '(Nd, Nd, M)\n', (7744, 7755), True, 'import numpy as np\n'), ((7787, 7810), 'numpy.random.randn', 'np.random.randn', (['Nr', 'Nc'], {}), '(Nr, Nc)\n', (7802, 7810), True, 'import numpy as np\n'), ((8303, 8313), 'numpy.ones', 'np.ones', (['M'], {}), '(M)\n', (8310, 8313), True, 'import numpy as np\n'), ((8316, 8330), 'numpy.zeros', 'np.zeros', (['(1,)'], {}), '((1,))\n', (8324, 8330), True, 'import numpy as np\n'), ((8838, 8864), 'numpy.random.randn', 'np.random.randn', (['Nd', 'Nd', 'M'], {}), '(Nd, Nd, M)\n', (8853, 8864), True, 'import numpy as np\n'), ((8896, 8919), 'numpy.random.randn', 'np.random.randn', (['Nr', 'Nc'], {}), '(Nr, Nc)\n', (8911, 8919), True, 'import numpy as np\n'), ((9296, 9320), 'numpy.random.randn', 'np.random.randn', (['(1)', '(1)', 'M'], {}), '(1, 1, M)\n', (9311, 9320), True, 'import numpy as np\n'), ((9590, 9622), 'numpy.zeros', 'np.zeros', (['(Wl1.shape[0:-1] + (1,))'], {}), '(Wl1.shape[0:-1] + (1,))\n', (9598, 9622), True, 'import numpy as np\n'), ((10006, 10016), 'numpy.ones', 'np.ones', (['M'], {}), '(M)\n', (10013, 10016), True, 'import numpy as np\n'), ((10019, 10033), 'numpy.zeros', 'np.zeros', (['(1,)'], {}), '((1,))\n', (10027, 10033), True, 'import numpy as np\n'), ((10602, 10628), 'numpy.random.randn', 'np.random.randn', (['Nd', 'Nd', 'M'], {}), '(Nd, Nd, M)\n', (10617, 10628), True, 'import numpy as np\n'), ((10660, 10683), 'numpy.random.randn', 'np.random.randn', (['Nr', 'Nc'], {}), '(Nr, Nc)\n', (10675, 10683), True, 'import numpy as np\n'), ((11073, 11091), 'numpy.random.randn', 'np.random.randn', (['M'], {}), '(M)\n', (11088, 11091), True, 'import numpy as np\n'), ((11360, 11374), 'numpy.zeros', 'np.zeros', (['(1,)'], {}), '((1,))\n', (11368, 11374), True, 'import numpy as np\n')] |
import numpy as np
import cv2
import face_alignment
# Initialize the chip resolution
chipSize = 300
chipCorners = np.float32([[0,0],
[chipSize,0],
[0,chipSize],
[chipSize,chipSize]])
# Initialize the face alignment tracker
fa = face_alignment.FaceAlignment(face_alignment.LandmarksType._3D, flip_input=True, device="cuda")
# Start the webcam capture, exit with 'q'
cap = cv2.VideoCapture(0)
while(not (cv2.waitKey(1) & 0xFF == ord('q'))):
ret, frame = cap.read()
if(ret):
# Run the face alignment tracker on the webcam image
imagePoints = fa.get_landmarks_from_image(frame)
if(imagePoints is not None):
imagePoints = imagePoints[0]
# Compute the Anchor Landmarks
# This ensures the eyes and chin will not move within the chip
rightEyeMean = np.mean(imagePoints[36:42], axis=0)
leftEyeMean = np.mean(imagePoints[42:47], axis=0)
middleEye = (rightEyeMean + leftEyeMean) * 0.5
chin = imagePoints[8]
#cv2.circle(frame, tuple(rightEyeMean[:2].astype(int)), 30, (255,255,0))
#cv2.circle(frame, tuple(leftEyeMean [:2].astype(int)), 30, (255,0,255))
# Compute the chip center and up/side vectors
mean = ((middleEye * 3) + chin) * 0.25
centered = imagePoints - mean
rightVector = (leftEyeMean - rightEyeMean)
upVector = (chin - middleEye)
# Divide by the length ratio to ensure a square aspect ratio
rightVector /= np.linalg.norm(rightVector) / np.linalg.norm(upVector)
# Compute the corners of the facial chip
imageCorners = np.float32([(mean + ((-rightVector - upVector)))[:2],
(mean + (( rightVector - upVector)))[:2],
(mean + ((-rightVector + upVector)))[:2],
(mean + (( rightVector + upVector)))[:2]])
# Compute the Perspective Homography and Extract the chip from the image
chipMatrix = cv2.getPerspectiveTransform(imageCorners, chipCorners)
chip = cv2.warpPerspective(frame, chipMatrix, (chipSize, chipSize))
cv2.imshow('Webcam View', frame)
cv2.imshow('Chip View', chip)
# When everything is done, release the capture
cap.release()
cv2.destroyAllWindows()
# https://gist.github.com/zalo/fa4396ae7a72b7683888fd9cd1c6d920
# Here's a quickie example for extracting Face Chips using this and OpenCV.
# https://github.com/1adrianb/face-alignment/issues/135
| [
"cv2.warpPerspective",
"face_alignment.FaceAlignment",
"cv2.waitKey",
"cv2.getPerspectiveTransform",
"numpy.float32",
"cv2.imshow",
"cv2.VideoCapture",
"numpy.mean",
"numpy.linalg.norm",
"cv2.destroyAllWindows"
] | [((115, 187), 'numpy.float32', 'np.float32', (['[[0, 0], [chipSize, 0], [0, chipSize], [chipSize, chipSize]]'], {}), '([[0, 0], [chipSize, 0], [0, chipSize], [chipSize, chipSize]])\n', (125, 187), True, 'import numpy as np\n'), ((308, 407), 'face_alignment.FaceAlignment', 'face_alignment.FaceAlignment', (['face_alignment.LandmarksType._3D'], {'flip_input': '(True)', 'device': '"""cuda"""'}), "(face_alignment.LandmarksType._3D, flip_input=\n True, device='cuda')\n", (336, 407), False, 'import face_alignment\n'), ((452, 471), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (468, 471), False, 'import cv2\n'), ((2459, 2482), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (2480, 2482), False, 'import cv2\n'), ((2326, 2358), 'cv2.imshow', 'cv2.imshow', (['"""Webcam View"""', 'frame'], {}), "('Webcam View', frame)\n", (2336, 2358), False, 'import cv2\n'), ((2367, 2396), 'cv2.imshow', 'cv2.imshow', (['"""Chip View"""', 'chip'], {}), "('Chip View', chip)\n", (2377, 2396), False, 'import cv2\n'), ((483, 497), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (494, 497), False, 'import cv2\n'), ((903, 938), 'numpy.mean', 'np.mean', (['imagePoints[36:42]'], {'axis': '(0)'}), '(imagePoints[36:42], axis=0)\n', (910, 938), True, 'import numpy as np\n'), ((966, 1001), 'numpy.mean', 'np.mean', (['imagePoints[42:47]'], {'axis': '(0)'}), '(imagePoints[42:47], axis=0)\n', (973, 1001), True, 'import numpy as np\n'), ((1773, 1952), 'numpy.float32', 'np.float32', (['[(mean + (-rightVector - upVector))[:2], (mean + (rightVector - upVector))[\n :2], (mean + (-rightVector + upVector))[:2], (mean + (rightVector +\n upVector))[:2]]'], {}), '([(mean + (-rightVector - upVector))[:2], (mean + (rightVector -\n upVector))[:2], (mean + (-rightVector + upVector))[:2], (mean + (\n rightVector + upVector))[:2]])\n', (1783, 1952), True, 'import numpy as np\n'), ((2182, 2236), 'cv2.getPerspectiveTransform', 'cv2.getPerspectiveTransform', (['imageCorners', 'chipCorners'], {}), '(imageCorners, chipCorners)\n', (2209, 2236), False, 'import cv2\n'), ((2256, 2316), 'cv2.warpPerspective', 'cv2.warpPerspective', (['frame', 'chipMatrix', '(chipSize, chipSize)'], {}), '(frame, chipMatrix, (chipSize, chipSize))\n', (2275, 2316), False, 'import cv2\n'), ((1637, 1664), 'numpy.linalg.norm', 'np.linalg.norm', (['rightVector'], {}), '(rightVector)\n', (1651, 1664), True, 'import numpy as np\n'), ((1667, 1691), 'numpy.linalg.norm', 'np.linalg.norm', (['upVector'], {}), '(upVector)\n', (1681, 1691), True, 'import numpy as np\n')] |
import numpy as np
import pickle
import os
import torch
from torch.utils.data import TensorDataset
from torchvision.datasets import ImageFolder
import torchvision.transforms as transforms
from sklearn.model_selection import train_test_split
import scipy.io as sio
from vdvae.data.celebahq import CelebAHQDataset
from vdvae.data.imagenet256 import ImageNet256Dataset
from vdvae.data.noise_dataset import NoiseDataset
CIFAR_GROUPS = {
"animals": [2,3,4,5,6,7],
"transportation": [0,1,8,9],
"airplane" : [0],
"automobile" : [1],
"bird" : [2],
"cat" : [3],
"deer" : [4],
"dog" : [5],
"frog" : [6],
"horse" : [7],
"ship" : [8],
"truck" : [9],
"car_truck": [1, 9],
"ship_airplane": [0,8],
"cat_dog": [3,5],
"deer_horse": [4, 7],
"frog_bird": [2, 6]
}
def cuda(x, **kwargs):
if torch.cuda.is_available():
return x.cuda(**kwargs)
else:
return x
def set_up_data(H):
shift_loss = -127.5
scale_loss = 1. / 127.5
# PICK DATASET
if H.dataset == 'imagenet32':
trX, vaX, teX = imagenet32(H.data_root)
H.image_size = 32
H.image_channels = 3
elif H.dataset == 'imagenet64':
trX, vaX, teX = imagenet64(H.data_root)
H.image_size = 64
H.image_channels = 3
elif H.dataset == 'ffhq_256': # data (0,255)
trX, vaX, teX = ffhq256(H.data_root)
H.image_size = 256
H.image_channels = 3
elif H.dataset == 'ffhq_32': # data (0,255)
trX, vaX, teX = ffhq32(H.data_root)
H.image_size = 32
H.image_channels = 3
elif H.dataset == 'ffhq_64': # data (0,255)
trX, vaX, teX = ffhq64(H.data_root)
H.image_size = 64
H.image_channels = 3
elif H.dataset == 'celebahq': # data (0,1)
trX, vaX, teX = celebahq(H.data_root)
H.image_size = 256
H.image_channels = 3
elif H.dataset == 'i256': # data (0,1)
trX, vaX, teX = None, None, None
H.image_size = 256
H.image_channels = 3
elif H.dataset == 'ffhq_1024':
trX, vaX, teX = ffhq1024(H.data_root)
H.image_size = 1024
H.image_channels = 3
elif H.dataset == 'cifar10':
(trX, _), (vaX, _), (teX, _) = cifar10(H.data_root, one_hot=False, group=H.cifar_group)
H.image_size = 32
H.image_channels = 3
elif H.dataset == 'svhn':
trX, vaX, teX = svhn(H.data_root)
H.image_size = 32
H.image_channels = 3
elif H.dataset == 'gaussian_noise':
trX, vaX, teX = None, None, None
H.image_size = 256
H.image_channels = 3
elif H.dataset == 'uniform_noise':
trX, vaX, teX = None, None, None
H.image_size = 256
H.image_channels = 3
else:
raise ValueError('unknown dataset: ', H.dataset)
# get normalization constants
if H.dataset_norm == 'imagenet32':
shift = -116.2373
scale = 1. / 69.37404
elif H.dataset_norm == 'imagenet64':
shift = -115.92961967
scale = 1. / 69.37404
elif H.dataset_norm in ['ffhq_32', 'ffhq_64', 'ffhq_256']: # data (0,255)
shift = -112.8666757481
scale = 1. / 69.84780273
elif H.dataset_norm == 'celebahq': # data (0,1)
shift = -0.4426144146984313 # same as ffhq256 * 255
scale = 1.0 / 0.2743
shift_loss = -0.5
scale_loss = 2.0
elif H.dataset_norm == 'i256': # data (0,1)
shift = -0.4426144146984313 # same as celebahq
scale = 1.0 / 0.2743
shift_loss = -0.5
scale_loss = 2.0
elif H.dataset_norm == 'ffhq_1024':
shift = -0.4387
scale = 1.0 / 0.2743
shift_loss = -0.5
scale_loss = 2.0
elif H.dataset_norm in ['cifar10', 'svhn']:
shift = -120.63838
scale = 1. / 64.16736
elif H.dataset_norm in ['gaussian_noise', 'uniform_noise']:
shift = 0.
scale = 1.
shift_loss = 0.
scale_loss = 1. # shouldn't matter
else:
raise ValueError('unknown dataset_norm: ', H.dataset_norm)
do_low_bit = H.dataset in ['ffhq_256']
if H.test_eval:
print('DOING TEST')
eval_dataset = teX
else:
eval_dataset = vaX
shift = cuda(torch.tensor([shift])).view(1, 1, 1, 1)
scale = cuda(torch.tensor([scale])).view(1, 1, 1, 1)
shift_loss = cuda(torch.tensor([shift_loss])).view(1, 1, 1, 1)
scale_loss = cuda(torch.tensor([scale_loss])).view(1, 1, 1, 1)
if H.dataset == 'ffhq_1024':
train_data = ImageFolder(trX, transforms.ToTensor())
valid_data = ImageFolder(eval_dataset, transforms.ToTensor())
untranspose = True
elif H.dataset == 'celebahq':
train_data = CelebAHQDataset(root_dir=H.data_root, train=True, transform=transforms.ToTensor(), splits=H.train_splits)
valid_data = CelebAHQDataset(root_dir=H.data_root, train=False, transform=transforms.ToTensor(), splits=H.val_splits)
untranspose = True
elif H.dataset == 'i256':
train_data = ImageNet256Dataset(transform=transforms.Compose([
transforms.CenterCrop(256),
transforms.ToTensor()
]))
valid_data = train_data
untranspose = True
elif H.dataset == 'gaussian_noise':
train_data = NoiseDataset(noise_type="gaussian")
valid_data = NoiseDataset(noise_type="gaussian")
untranspose = False
elif H.dataset == 'uniform_noise':
train_data = NoiseDataset(noise_type="uniform")
valid_data = NoiseDataset(noise_type="uniform")
untranspose = False
else:
train_data = TensorDataset(torch.as_tensor(trX))
valid_data = TensorDataset(torch.as_tensor(eval_dataset))
untranspose = False
def preprocess_func(x):
nonlocal shift
nonlocal scale
nonlocal shift_loss
nonlocal scale_loss
nonlocal do_low_bit
nonlocal untranspose
'takes in a data example and returns the preprocessed input'
'as well as the input processed for the loss'
if untranspose:
x[0] = x[0].permute(0, 2, 3, 1)
inp = cuda(x[0], non_blocking=True).float()
out = inp.clone()
inp.add_(shift).mul_(scale)
if do_low_bit:
# 5 bits of precision
out.mul_(1. / 8.).floor_().mul_(8.)
out.add_(shift_loss).mul_(scale_loss)
return inp, out
return H, train_data, valid_data, preprocess_func
def mkdir_p(path):
os.makedirs(path, exist_ok=True)
def flatten(outer):
return [el for inner in outer for el in inner]
def unpickle_cifar10(file):
fo = open(file, 'rb')
data = pickle.load(fo, encoding='bytes')
fo.close()
data = dict(zip([k.decode() for k in data.keys()], data.values()))
return data
def imagenet32(data_root):
trX = np.load(os.path.join(data_root, 'imagenet32-train.npy'), mmap_mode='r')
np.random.seed(42)
tr_va_split_indices = np.random.permutation(trX.shape[0])
train = trX[tr_va_split_indices[:-5000]]
valid = trX[tr_va_split_indices[-5000:]]
test = np.load(os.path.join(data_root, 'imagenet32-valid.npy'), mmap_mode='r')
return train, valid, test
def imagenet64(data_root):
trX = np.load(os.path.join(data_root, 'imagenet64-train.npy'), mmap_mode='r')
np.random.seed(42)
tr_va_split_indices = np.random.permutation(trX.shape[0])
train = trX[tr_va_split_indices[:-5000]]
valid = trX[tr_va_split_indices[-5000:]]
test = np.load(os.path.join(data_root, 'imagenet64-valid.npy'), mmap_mode='r') # this is test.
return train, valid, test
def ffhq1024(data_root):
# we did not significantly tune hyperparameters on ffhq-1024, and so simply evaluate on the test set
return os.path.join(data_root, 'ffhq1024/train'), os.path.join(data_root, 'ffhq1024/valid'), os.path.join(data_root, 'ffhq1024/valid')
def celebahq(data_root):
return os.path.join(data_root, 'img256train'), os.path.join(data_root, 'img256val'), os.path.join(data_root, 'img256val')
def ffhq256(data_root):
trX = np.load(os.path.join(data_root, 'ffhq-256.npy'), mmap_mode='r')
np.random.seed(5)
tr_va_split_indices = np.random.permutation(trX.shape[0])
train = trX[tr_va_split_indices[:-7000]]
valid = trX[tr_va_split_indices[-7000:]]
# we did not significantly tune hyperparameters on ffhq-256, and so simply evaluate on the test set
return train, valid, valid
def ffhq64(data_root):
trX = np.load(os.path.join(data_root, 'ffhq-64.npy'), mmap_mode='r')
np.random.seed(5)
tr_va_split_indices = np.random.permutation(trX.shape[0])
train = trX[tr_va_split_indices[:-7000]]
valid = trX[tr_va_split_indices[-7000:]]
# we did not significantly tune hyperparameters on ffhq-256, and so simply evaluate on the test set
return train, valid, valid
def ffhq32(data_root):
trX = np.load(os.path.join(data_root, 'ffhq-32.npy'), mmap_mode='r')
np.random.seed(5)
tr_va_split_indices = np.random.permutation(trX.shape[0])
train = trX[tr_va_split_indices[:-7000]]
valid = trX[tr_va_split_indices[-7000:]]
# we did not significantly tune hyperparameters on ffhq-256, and so simply evaluate on the test set
return train, valid, valid
def cifar10(data_root, one_hot=True, group=None):
tr_data = [unpickle_cifar10(os.path.join(data_root, 'cifar-10-batches-py/', 'data_batch_%d' % i)) for i in range(1, 6)]
trX = np.vstack(data['data'] for data in tr_data)
trY = np.asarray(flatten([data['labels'] for data in tr_data]))
te_data = unpickle_cifar10(os.path.join(data_root, 'cifar-10-batches-py/', 'test_batch'))
teX = np.asarray(te_data['data'])
teY = np.asarray(te_data['labels'])
trX = trX.reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1)
teX = teX.reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1)
trX, vaX, trY, vaY = train_test_split(trX, trY, test_size=5000, random_state=11172018)
if group is not None:
labels = CIFAR_GROUPS[group]
print("Group", group, labels)
print("Lengths before:", len(trY), len(vaY), len(teY), len(trY) + len(vaY) + len(teY))
tr_mask = np.isin(trY, labels)
va_mask = np.isin(vaY, labels)
te_mask = np.isin(teY, labels)
trX = trX[tr_mask]
trY = trY[tr_mask]
vaX = vaX[va_mask]
vaY = vaY[va_mask]
teX = teX[te_mask]
teY = teY[te_mask]
print("Lengths after:", len(trY), len(vaY), len(teY), len(trY) + len(vaY) + len(teY))
if one_hot:
trY = np.eye(10, dtype=np.float32)[trY]
vaY = np.eye(10, dtype=np.float32)[vaY]
teY = np.eye(10, dtype=np.float32)[teY]
else:
trY = np.reshape(trY, [-1, 1])
vaY = np.reshape(vaY, [-1, 1])
teY = np.reshape(teY, [-1, 1])
return (trX, trY), (vaX, vaY), (teX, teY)
def svhn(data_root):
trX = sio.loadmat(os.path.join(data_root, "train_32x32.mat"))["X"]
teX = sio.loadmat(os.path.join(data_root, "test_32x32.mat"))["X"]
trX = trX.transpose(3,0,1,2)
teX = teX.transpose(3,0,1,2)
trX, vaX = train_test_split(trX, test_size=5000, random_state=11172018)
return trX, vaX, teX
| [
"numpy.isin",
"numpy.random.seed",
"os.makedirs",
"torch.as_tensor",
"sklearn.model_selection.train_test_split",
"numpy.asarray",
"pickle.load",
"torch.cuda.is_available",
"numpy.reshape",
"vdvae.data.noise_dataset.NoiseDataset",
"torchvision.transforms.CenterCrop",
"numpy.random.permutation",... | [((846, 871), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (869, 871), False, 'import torch\n'), ((6497, 6529), 'os.makedirs', 'os.makedirs', (['path'], {'exist_ok': '(True)'}), '(path, exist_ok=True)\n', (6508, 6529), False, 'import os\n'), ((6670, 6703), 'pickle.load', 'pickle.load', (['fo'], {'encoding': '"""bytes"""'}), "(fo, encoding='bytes')\n", (6681, 6703), False, 'import pickle\n'), ((6921, 6939), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (6935, 6939), True, 'import numpy as np\n'), ((6966, 7001), 'numpy.random.permutation', 'np.random.permutation', (['trX.shape[0]'], {}), '(trX.shape[0])\n', (6987, 7001), True, 'import numpy as np\n'), ((7320, 7338), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (7334, 7338), True, 'import numpy as np\n'), ((7365, 7400), 'numpy.random.permutation', 'np.random.permutation', (['trX.shape[0]'], {}), '(trX.shape[0])\n', (7386, 7400), True, 'import numpy as np\n'), ((8149, 8166), 'numpy.random.seed', 'np.random.seed', (['(5)'], {}), '(5)\n', (8163, 8166), True, 'import numpy as np\n'), ((8193, 8228), 'numpy.random.permutation', 'np.random.permutation', (['trX.shape[0]'], {}), '(trX.shape[0])\n', (8214, 8228), True, 'import numpy as np\n'), ((8555, 8572), 'numpy.random.seed', 'np.random.seed', (['(5)'], {}), '(5)\n', (8569, 8572), True, 'import numpy as np\n'), ((8599, 8634), 'numpy.random.permutation', 'np.random.permutation', (['trX.shape[0]'], {}), '(trX.shape[0])\n', (8620, 8634), True, 'import numpy as np\n'), ((8961, 8978), 'numpy.random.seed', 'np.random.seed', (['(5)'], {}), '(5)\n', (8975, 8978), True, 'import numpy as np\n'), ((9005, 9040), 'numpy.random.permutation', 'np.random.permutation', (['trX.shape[0]'], {}), '(trX.shape[0])\n', (9026, 9040), True, 'import numpy as np\n'), ((9452, 9495), 'numpy.vstack', 'np.vstack', (["(data['data'] for data in tr_data)"], {}), "(data['data'] for data in tr_data)\n", (9461, 9495), True, 'import numpy as np\n'), ((9668, 9695), 'numpy.asarray', 'np.asarray', (["te_data['data']"], {}), "(te_data['data'])\n", (9678, 9695), True, 'import numpy as np\n'), ((9706, 9735), 'numpy.asarray', 'np.asarray', (["te_data['labels']"], {}), "(te_data['labels'])\n", (9716, 9735), True, 'import numpy as np\n'), ((9879, 9944), 'sklearn.model_selection.train_test_split', 'train_test_split', (['trX', 'trY'], {'test_size': '(5000)', 'random_state': '(11172018)'}), '(trX, trY, test_size=5000, random_state=11172018)\n', (9895, 9944), False, 'from sklearn.model_selection import train_test_split\n'), ((11096, 11156), 'sklearn.model_selection.train_test_split', 'train_test_split', (['trX'], {'test_size': '(5000)', 'random_state': '(11172018)'}), '(trX, test_size=5000, random_state=11172018)\n', (11112, 11156), False, 'from sklearn.model_selection import train_test_split\n'), ((6853, 6900), 'os.path.join', 'os.path.join', (['data_root', '"""imagenet32-train.npy"""'], {}), "(data_root, 'imagenet32-train.npy')\n", (6865, 6900), False, 'import os\n'), ((7111, 7158), 'os.path.join', 'os.path.join', (['data_root', '"""imagenet32-valid.npy"""'], {}), "(data_root, 'imagenet32-valid.npy')\n", (7123, 7158), False, 'import os\n'), ((7252, 7299), 'os.path.join', 'os.path.join', (['data_root', '"""imagenet64-train.npy"""'], {}), "(data_root, 'imagenet64-train.npy')\n", (7264, 7299), False, 'import os\n'), ((7510, 7557), 'os.path.join', 'os.path.join', (['data_root', '"""imagenet64-valid.npy"""'], {}), "(data_root, 'imagenet64-valid.npy')\n", (7522, 7557), False, 'import os\n'), ((7764, 7805), 'os.path.join', 'os.path.join', (['data_root', '"""ffhq1024/train"""'], {}), "(data_root, 'ffhq1024/train')\n", (7776, 7805), False, 'import os\n'), ((7807, 7848), 'os.path.join', 'os.path.join', (['data_root', '"""ffhq1024/valid"""'], {}), "(data_root, 'ffhq1024/valid')\n", (7819, 7848), False, 'import os\n'), ((7850, 7891), 'os.path.join', 'os.path.join', (['data_root', '"""ffhq1024/valid"""'], {}), "(data_root, 'ffhq1024/valid')\n", (7862, 7891), False, 'import os\n'), ((7930, 7968), 'os.path.join', 'os.path.join', (['data_root', '"""img256train"""'], {}), "(data_root, 'img256train')\n", (7942, 7968), False, 'import os\n'), ((7970, 8006), 'os.path.join', 'os.path.join', (['data_root', '"""img256val"""'], {}), "(data_root, 'img256val')\n", (7982, 8006), False, 'import os\n'), ((8008, 8044), 'os.path.join', 'os.path.join', (['data_root', '"""img256val"""'], {}), "(data_root, 'img256val')\n", (8020, 8044), False, 'import os\n'), ((8089, 8128), 'os.path.join', 'os.path.join', (['data_root', '"""ffhq-256.npy"""'], {}), "(data_root, 'ffhq-256.npy')\n", (8101, 8128), False, 'import os\n'), ((8496, 8534), 'os.path.join', 'os.path.join', (['data_root', '"""ffhq-64.npy"""'], {}), "(data_root, 'ffhq-64.npy')\n", (8508, 8534), False, 'import os\n'), ((8902, 8940), 'os.path.join', 'os.path.join', (['data_root', '"""ffhq-32.npy"""'], {}), "(data_root, 'ffhq-32.npy')\n", (8914, 8940), False, 'import os\n'), ((9595, 9656), 'os.path.join', 'os.path.join', (['data_root', '"""cifar-10-batches-py/"""', '"""test_batch"""'], {}), "(data_root, 'cifar-10-batches-py/', 'test_batch')\n", (9607, 9656), False, 'import os\n'), ((10161, 10181), 'numpy.isin', 'np.isin', (['trY', 'labels'], {}), '(trY, labels)\n', (10168, 10181), True, 'import numpy as np\n'), ((10200, 10220), 'numpy.isin', 'np.isin', (['vaY', 'labels'], {}), '(vaY, labels)\n', (10207, 10220), True, 'import numpy as np\n'), ((10239, 10259), 'numpy.isin', 'np.isin', (['teY', 'labels'], {}), '(teY, labels)\n', (10246, 10259), True, 'import numpy as np\n'), ((10702, 10726), 'numpy.reshape', 'np.reshape', (['trY', '[-1, 1]'], {}), '(trY, [-1, 1])\n', (10712, 10726), True, 'import numpy as np\n'), ((10741, 10765), 'numpy.reshape', 'np.reshape', (['vaY', '[-1, 1]'], {}), '(vaY, [-1, 1])\n', (10751, 10765), True, 'import numpy as np\n'), ((10780, 10804), 'numpy.reshape', 'np.reshape', (['teY', '[-1, 1]'], {}), '(teY, [-1, 1])\n', (10790, 10804), True, 'import numpy as np\n'), ((4546, 4567), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (4565, 4567), True, 'import torchvision.transforms as transforms\n'), ((4616, 4637), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (4635, 4637), True, 'import torchvision.transforms as transforms\n'), ((9350, 9418), 'os.path.join', 'os.path.join', (['data_root', '"""cifar-10-batches-py/"""', "('data_batch_%d' % i)"], {}), "(data_root, 'cifar-10-batches-py/', 'data_batch_%d' % i)\n", (9362, 9418), False, 'import os\n'), ((10548, 10576), 'numpy.eye', 'np.eye', (['(10)'], {'dtype': 'np.float32'}), '(10, dtype=np.float32)\n', (10554, 10576), True, 'import numpy as np\n'), ((10596, 10624), 'numpy.eye', 'np.eye', (['(10)'], {'dtype': 'np.float32'}), '(10, dtype=np.float32)\n', (10602, 10624), True, 'import numpy as np\n'), ((10644, 10672), 'numpy.eye', 'np.eye', (['(10)'], {'dtype': 'np.float32'}), '(10, dtype=np.float32)\n', (10650, 10672), True, 'import numpy as np\n'), ((10896, 10938), 'os.path.join', 'os.path.join', (['data_root', '"""train_32x32.mat"""'], {}), "(data_root, 'train_32x32.mat')\n", (10908, 10938), False, 'import os\n'), ((10967, 11008), 'os.path.join', 'os.path.join', (['data_root', '"""test_32x32.mat"""'], {}), "(data_root, 'test_32x32.mat')\n", (10979, 11008), False, 'import os\n'), ((4242, 4263), 'torch.tensor', 'torch.tensor', (['[shift]'], {}), '([shift])\n', (4254, 4263), False, 'import torch\n'), ((4299, 4320), 'torch.tensor', 'torch.tensor', (['[scale]'], {}), '([scale])\n', (4311, 4320), False, 'import torch\n'), ((4361, 4387), 'torch.tensor', 'torch.tensor', (['[shift_loss]'], {}), '([shift_loss])\n', (4373, 4387), False, 'import torch\n'), ((4428, 4454), 'torch.tensor', 'torch.tensor', (['[scale_loss]'], {}), '([scale_loss])\n', (4440, 4454), False, 'import torch\n'), ((4782, 4803), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (4801, 4803), True, 'import torchvision.transforms as transforms\n'), ((4910, 4931), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (4929, 4931), True, 'import torchvision.transforms as transforms\n'), ((5288, 5323), 'vdvae.data.noise_dataset.NoiseDataset', 'NoiseDataset', ([], {'noise_type': '"""gaussian"""'}), "(noise_type='gaussian')\n", (5300, 5323), False, 'from vdvae.data.noise_dataset import NoiseDataset\n'), ((5345, 5380), 'vdvae.data.noise_dataset.NoiseDataset', 'NoiseDataset', ([], {'noise_type': '"""gaussian"""'}), "(noise_type='gaussian')\n", (5357, 5380), False, 'from vdvae.data.noise_dataset import NoiseDataset\n'), ((5469, 5503), 'vdvae.data.noise_dataset.NoiseDataset', 'NoiseDataset', ([], {'noise_type': '"""uniform"""'}), "(noise_type='uniform')\n", (5481, 5503), False, 'from vdvae.data.noise_dataset import NoiseDataset\n'), ((5525, 5559), 'vdvae.data.noise_dataset.NoiseDataset', 'NoiseDataset', ([], {'noise_type': '"""uniform"""'}), "(noise_type='uniform')\n", (5537, 5559), False, 'from vdvae.data.noise_dataset import NoiseDataset\n'), ((5633, 5653), 'torch.as_tensor', 'torch.as_tensor', (['trX'], {}), '(trX)\n', (5648, 5653), False, 'import torch\n'), ((5690, 5719), 'torch.as_tensor', 'torch.as_tensor', (['eval_dataset'], {}), '(eval_dataset)\n', (5705, 5719), False, 'import torch\n'), ((5094, 5120), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(256)'], {}), '(256)\n', (5115, 5120), True, 'import torchvision.transforms as transforms\n'), ((5134, 5155), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (5153, 5155), True, 'import torchvision.transforms as transforms\n')] |
from __future__ import print_function
import unittest
import numpy
import irbasis
from irbasis_util.regression import *
class TestMethods(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestMethods, self).__init__(*args, **kwargs)
def test_lsqr(self):
numpy.random.seed(100)
N1, N2 = 1000, 100
# Small regularization parameter
alpha = 1e-5
# Columns of A decay exponentially
exp_dump = numpy.array([numpy.exp(-20*i/(1.*N2)) for i in range(N2)])
A = numpy.random.rand(N1*N2) + 1J * numpy.random.rand(N1*N2)
A = A.reshape((N1, N2))
A = A[:, :] * exp_dump[None, :]
y = numpy.random.rand(N1) + 1J * numpy.random.rand(N1)
# Use precondition to "cancel out" the exponential decay of the columns of A.
precond = 1/numpy.sqrt(exp_dump**2 + alpha)
x_svd = ridge_complex(A, y, alpha, solver='svd')
x_lsqr = ridge_complex(A, y, alpha, solver='lsqr')
x_lsqr_precond = ridge_complex(A, y, alpha, solver='lsqr', precond=precond)
# Without preconditioning LSQR nearly fails for a small value of alpha
# Preconditioning improves accuracy a lot!
print(numpy.amax(numpy.abs(x_svd-x_lsqr)))
self.assertTrue(numpy.allclose(x_svd, x_lsqr, atol = 1e-1))
self.assertTrue(numpy.allclose(x_svd, x_lsqr_precond, atol = 1e-7))
if __name__ == '__main__':
unittest.main()
| [
"unittest.main",
"numpy.random.seed",
"numpy.abs",
"numpy.allclose",
"numpy.exp",
"numpy.random.rand",
"numpy.sqrt"
] | [((1440, 1455), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1453, 1455), False, 'import unittest\n'), ((302, 324), 'numpy.random.seed', 'numpy.random.seed', (['(100)'], {}), '(100)\n', (319, 324), False, 'import numpy\n'), ((550, 576), 'numpy.random.rand', 'numpy.random.rand', (['(N1 * N2)'], {}), '(N1 * N2)\n', (567, 576), False, 'import numpy\n'), ((691, 712), 'numpy.random.rand', 'numpy.random.rand', (['N1'], {}), '(N1)\n', (708, 712), False, 'import numpy\n'), ((849, 882), 'numpy.sqrt', 'numpy.sqrt', (['(exp_dump ** 2 + alpha)'], {}), '(exp_dump ** 2 + alpha)\n', (859, 882), False, 'import numpy\n'), ((1288, 1327), 'numpy.allclose', 'numpy.allclose', (['x_svd', 'x_lsqr'], {'atol': '(0.1)'}), '(x_svd, x_lsqr, atol=0.1)\n', (1302, 1327), False, 'import numpy\n'), ((1356, 1405), 'numpy.allclose', 'numpy.allclose', (['x_svd', 'x_lsqr_precond'], {'atol': '(1e-07)'}), '(x_svd, x_lsqr_precond, atol=1e-07)\n', (1370, 1405), False, 'import numpy\n'), ((492, 523), 'numpy.exp', 'numpy.exp', (['(-20 * i / (1.0 * N2))'], {}), '(-20 * i / (1.0 * N2))\n', (501, 523), False, 'import numpy\n'), ((582, 608), 'numpy.random.rand', 'numpy.random.rand', (['(N1 * N2)'], {}), '(N1 * N2)\n', (599, 608), False, 'import numpy\n'), ((720, 741), 'numpy.random.rand', 'numpy.random.rand', (['N1'], {}), '(N1)\n', (737, 741), False, 'import numpy\n'), ((1238, 1263), 'numpy.abs', 'numpy.abs', (['(x_svd - x_lsqr)'], {}), '(x_svd - x_lsqr)\n', (1247, 1263), False, 'import numpy\n')] |
import io
import sys
import uuid
import zipfile
import collections
import numpy as np
from .. import util
from .. import graph
from ..constants import log
try:
import networkx as nx
except BaseException as E:
# create a dummy module which will raise the ImportError
# or other exception only when someone tries to use networkx
from ..exceptions import ExceptionModule
nx = ExceptionModule(E)
def load_3MF(file_obj,
postprocess=True,
**kwargs):
"""
Load a 3MF formatted file into a Trimesh scene.
Parameters
------------
file_obj : file-like
Contains 3MF formatted data
Returns
------------
kwargs : dict
Constructor arguments for `trimesh.Scene`
"""
# dict, {name in archive: BytesIo}
archive = util.decompress(file_obj, file_type='zip')
# get model file
model = archive['3D/3dmodel.model']
# read root attributes only from XML first
event, root = next(etree.iterparse(model, tag=('{*}model'), events=('start',)))
# collect unit information from the tree
if 'unit' in root.attrib:
metadata = {'units': root.attrib['unit']}
else:
# the default units, defined by the specification
metadata = {'units': 'millimeters'}
# { mesh id : mesh name}
id_name = {}
# { mesh id: (n,3) float vertices}
v_seq = {}
# { mesh id: (n,3) int faces}
f_seq = {}
# components are objects that contain other objects
# {id : [other ids]}
components = collections.defaultdict(list)
# load information about the scene graph
# each instance is a single geometry
build_items = []
consumed_names = set()
# iterate the XML object and build elements with an LXML iterator
# loaded elements are cleared to avoid ballooning memory
model.seek(0)
for event, obj in etree.iterparse(model, tag=('{*}object', '{*}build')):
# parse objects
if 'object' in obj.tag:
# id is mandatory
index = obj.attrib['id']
# start with stored name
name = obj.attrib.get('name', str(index))
# apparently some exporters name multiple meshes
# the same thing so check to see if it's been used
if name in consumed_names:
name = name + str(index)
consumed_names.add(name)
# store name reference on the index
id_name[index] = name
# if the object has actual geometry data parse here
for mesh in obj.iter('{*}mesh'):
vertices = mesh.find('{*}vertices')
v_seq[index] = np.array([[i.attrib['x'],
i.attrib['y'],
i.attrib['z']] for
i in vertices.iter('{*}vertex')],
dtype=np.float64)
vertices.clear()
vertices.getparent().remove(vertices)
faces = mesh.find('{*}triangles')
f_seq[index] = np.array([[i.attrib['v1'],
i.attrib['v2'],
i.attrib['v3']] for
i in faces.iter('{*}triangle')],
dtype=np.int64)
faces.clear()
faces.getparent().remove(faces)
# components are references to other geometries
for c in obj.iter('{*}component'):
mesh_index = c.attrib['objectid']
transform = _attrib_to_transform(c.attrib)
components[index].append((mesh_index, transform))
# parse build
if 'build' in obj.tag:
# scene graph information stored here, aka "build" the scene
for item in obj.iter('{*}item'):
# get a transform from the item's attributes
transform = _attrib_to_transform(item.attrib)
# the index of the geometry this item instantiates
build_items.append((item.attrib['objectid'], transform))
# free resources
obj.clear()
obj.getparent().remove(obj)
del obj
# have one mesh per 3MF object
# one mesh per geometry ID, store as kwargs for the object
meshes = {}
for gid in v_seq.keys():
name = id_name[gid]
meshes[name] = {'vertices': v_seq[gid],
'faces': f_seq[gid],
'metadata': metadata.copy()}
meshes[name].update(kwargs)
# turn the item / component representation into
# a MultiDiGraph to compound our pain
g = nx.MultiDiGraph()
# build items are the only things that exist according to 3MF
# so we accomplish that by linking them to the base frame
for gid, tf in build_items:
g.add_edge('world', gid, matrix=tf)
# components are instances which need to be linked to base
# frame by a build_item
for start, group in components.items():
for i, (gid, tf) in enumerate(group):
g.add_edge(start, gid, matrix=tf)
# turn the graph into kwargs for a scene graph
# flatten the scene structure and simplify to
# a single unique node per instance
graph_args = []
parents = collections.defaultdict(set)
for path in graph.multigraph_paths(G=g,
source='world'):
# collect all the transform on the path
transforms = graph.multigraph_collect(G=g,
traversal=path,
attrib='matrix')
# combine them into a single transform
if len(transforms) == 1:
transform = transforms[0]
else:
transform = util.multi_dot(transforms)
# the last element of the path should be the geometry
last = path[-1][0]
# if someone included an undefined component, skip it
if last not in id_name:
log.debug('id {} included but not defined!'.format(last))
continue
# frame names unique
name = id_name[last] + util.unique_id()
# index in meshes
geom = id_name[last]
# collect parents if we want to combine later
if len(path) > 2:
parent = path[-2][0]
parents[parent].add(last)
graph_args.append({'frame_from': 'world',
'frame_to': name,
'matrix': transform,
'geometry': geom})
# solidworks will export each body as its own mesh with the part
# name as the parent so optionally rename and combine these bodies
if postprocess and all('body' in i.lower() for i in meshes.keys()):
# don't rename by default
rename = {k: k for k in meshes.keys()}
for parent, mesh_name in parents.items():
# only handle the case where a parent has a single child
# if there are multiple children we would do a combine op
if len(mesh_name) != 1:
continue
# rename the part
rename[id_name[next(iter(mesh_name))]] = id_name[parent].split(
'(')[0]
# apply the rename operation meshes
meshes = {rename[k]: m for k, m in meshes.items()}
# rename geometry references in the scene graph
for arg in graph_args:
if 'geometry' in arg:
arg['geometry'] = rename[arg['geometry']]
# construct the kwargs to load the scene
kwargs = {'base_frame': 'world',
'graph': graph_args,
'geometry': meshes,
'metadata': metadata}
return kwargs
def export_3MF(mesh,
batch_size=4096,
compression=zipfile.ZIP_DEFLATED,
compresslevel=5):
"""
Converts a Trimesh object into a 3MF file.
Parameters
---------
mesh trimesh.trimesh
Mesh or Scene to export.
batch_size : int
Number of nodes to write per batch.
compression : zipfile.ZIP_*
Type of zip compression to use in this export.
compresslevel : int
For Python > 3.7 specify the 0-9 compression level.
Returns
---------
export : bytes
Represents geometry as a 3MF file.
"""
if sys.version_info < (3, 6):
# Python only added 'w' mode to `zipfile` in Python 3.6
# and it is not worth the effort to work around
raise NotImplementedError(
"3MF export requires Python >= 3.6")
from ..scene.scene import Scene
if not isinstance(mesh, Scene):
mesh = Scene(mesh)
geometry = mesh.geometry
graph = mesh.graph.to_networkx()
base_frame = mesh.graph.base_frame
# xml namespaces
model_nsmap = {
None: "http://schemas.microsoft.com/3dmanufacturing/core/2015/02",
"m": "http://schemas.microsoft.com/3dmanufacturing/material/2015/02",
"p": "http://schemas.microsoft.com/3dmanufacturing/production/2015/06",
"b": "http://schemas.microsoft.com/3dmanufacturing/beamlattice/2017/02",
"s": "http://schemas.microsoft.com/3dmanufacturing/slice/2015/07",
"sc": "http://schemas.microsoft.com/3dmanufacturing/securecontent/2019/04",
}
rels_nsmap = {
None: "http://schemas.openxmlformats.org/package/2006/relationships"
}
# model ids
def model_id(x, models=[]):
if x not in models:
models.append(x)
return str(models.index(x) + 1)
# 3mf archive dict {path: BytesIO}
file_obj = io.BytesIO()
# specify the parameters for the zip container
zip_kwargs = {'compression': compression}
# compresslevel was added in Python 3.7
if sys.version_info >= (3, 7):
zip_kwargs['compresslevel'] = compresslevel
with zipfile.ZipFile(file_obj, mode='w', **zip_kwargs) as z:
# 3dmodel.model
with z.open("3D/3dmodel.model", mode='w') as f, etree.xmlfile(
f, encoding="utf-8"
) as xf:
xf.write_declaration()
# stream elements
with xf.element("model", {"unit": "millimeter"}, nsmap=model_nsmap):
# objects with mesh data and/or references to other objects
with xf.element("resources"):
# stream objects with actual mesh data
for i, (name, m) in enumerate(geometry.items()):
# attributes for object
attribs = {
"id": model_id(name),
"name": name,
"type": "model",
"p:UUID": str(uuid.uuid4())
}
with xf.element("object", **attribs):
with xf.element("mesh"):
with xf.element("vertices"):
# vertex nodes are writed directly to the file
# so make sure lxml's buffer is flushed
xf.flush()
for i in range(0, len(m.vertices), batch_size):
batch = m.vertices[i: i + batch_size]
fragment = (
'<vertex x="{}" y="{}" z="{}" />'
* len(batch)
)
f.write(
fragment.format(*batch.flatten()).encode(
"utf-8"
)
)
with xf.element("triangles"):
xf.flush()
for i in range(0, len(m.faces), batch_size):
batch = m.faces[i: i + batch_size]
fragment = (
'<triangle v1="{}" v2="{}" v3="{}" />'
* len(batch)
)
f.write(
fragment.format(*batch.flatten()).encode(
"utf-8"
)
)
# stream components
for node in graph.nodes:
if node == base_frame or node.startswith("camera"):
continue
if len(graph[node]) == 0:
continue
attribs = {
"id": model_id(node),
"name": node,
"type": "model",
"p:UUID": str(uuid.uuid4())
}
with xf.element("object", **attribs):
with xf.element("components"):
for next, data in graph[node].items():
transform = " ".join(
str(i)
for i in np.array(data["matrix"])[
:3, :4
].T.flatten()
)
xf.write(
etree.Element(
"component",
{
"objectid": model_id(data["geometry"])
if "geometry" in data
else model_id(next),
"transform": transform,
},
)
)
# stream build (objects on base_frame)
with xf.element("build", {"p:UUID": str(uuid.uuid4())}):
for node, data in graph[base_frame].items():
if node.startswith("camera"):
continue
transform = " ".join(
str(i) for i in np.array(data["matrix"])[:3, :4].T.flatten()
)
uuid_tag = "{{{}}}UUID".format(model_nsmap['p'])
xf.write(
etree.Element(
"item",
{
"objectid": model_id(node),
"transform": transform,
uuid_tag: str(uuid.uuid4())
},
nsmap=model_nsmap
)
)
# .rels
with z.open("_rels/.rels", "w") as f, etree.xmlfile(f, encoding="utf-8") as xf:
xf.write_declaration()
# stream elements
with xf.element("Relationships", nsmap=rels_nsmap):
rt = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"
xf.write(
etree.Element(
"Relationship",
Type=rt,
Target="/3D/3dmodel.model",
Id="rel0",
)
)
# [Content_Types].xml
with z.open("[Content_Types].xml", "w") as f, etree.xmlfile(
f, encoding="utf-8"
) as xf:
xf.write_declaration()
# xml namespaces
nsmap = {
None: "http://schemas.openxmlformats.org/package/2006/content-types"
}
# stream elements
types = [
("jpeg", "image/jpeg"),
("jpg", "image/jpeg"),
("model", "application/vnd.ms-package.3dmanufacturing-3dmodel+xml"),
("png", "image/png"),
("rels", "application/vnd.openxmlformats-package.relationships+xml"),
(
"texture",
"application/vnd.ms-package.3dmanufacturing-3dmodeltexture",
),
]
with xf.element("Types", nsmap=nsmap):
for ext, ctype in types:
xf.write(etree.Element("Default", Extension=ext, ContentType=ctype))
return file_obj.getvalue()
def _attrib_to_transform(attrib):
"""
Extract a homogeneous transform from a dictionary.
Parameters
------------
attrib: dict, optionally containing 'transform'
Returns
------------
transform: (4, 4) float, homogeonous transformation
"""
transform = np.eye(4, dtype=np.float64)
if 'transform' in attrib:
# wangle their transform format
values = np.array(
attrib['transform'].split(),
dtype=np.float64).reshape((4, 3)).T
transform[:3, :4] = values
return transform
# do import here to keep lxml a soft dependency
try:
from lxml import etree
_three_loaders = {'3mf': load_3MF}
except ImportError:
_three_loaders = {}
| [
"io.BytesIO",
"uuid.uuid4",
"zipfile.ZipFile",
"lxml.etree.Element",
"networkx.MultiDiGraph",
"lxml.etree.xmlfile",
"collections.defaultdict",
"lxml.etree.iterparse",
"numpy.array",
"numpy.eye"
] | [((1526, 1555), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (1549, 1555), False, 'import collections\n'), ((1862, 1915), 'lxml.etree.iterparse', 'etree.iterparse', (['model'], {'tag': "('{*}object', '{*}build')"}), "(model, tag=('{*}object', '{*}build'))\n", (1877, 1915), False, 'from lxml import etree\n'), ((4722, 4739), 'networkx.MultiDiGraph', 'nx.MultiDiGraph', ([], {}), '()\n', (4737, 4739), True, 'import networkx as nx\n'), ((5347, 5375), 'collections.defaultdict', 'collections.defaultdict', (['set'], {}), '(set)\n', (5370, 5375), False, 'import collections\n'), ((9669, 9681), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (9679, 9681), False, 'import io\n'), ((17267, 17294), 'numpy.eye', 'np.eye', (['(4)'], {'dtype': 'np.float64'}), '(4, dtype=np.float64)\n', (17273, 17294), True, 'import numpy as np\n'), ((980, 1037), 'lxml.etree.iterparse', 'etree.iterparse', (['model'], {'tag': '"""{*}model"""', 'events': "('start',)"}), "(model, tag='{*}model', events=('start',))\n", (995, 1037), False, 'from lxml import etree\n'), ((9921, 9970), 'zipfile.ZipFile', 'zipfile.ZipFile', (['file_obj'], {'mode': '"""w"""'}), "(file_obj, mode='w', **zip_kwargs)\n", (9936, 9970), False, 'import zipfile\n'), ((10057, 10091), 'lxml.etree.xmlfile', 'etree.xmlfile', (['f'], {'encoding': '"""utf-8"""'}), "(f, encoding='utf-8')\n", (10070, 10091), False, 'from lxml import etree\n'), ((15405, 15439), 'lxml.etree.xmlfile', 'etree.xmlfile', (['f'], {'encoding': '"""utf-8"""'}), "(f, encoding='utf-8')\n", (15418, 15439), False, 'from lxml import etree\n'), ((16006, 16040), 'lxml.etree.xmlfile', 'etree.xmlfile', (['f'], {'encoding': '"""utf-8"""'}), "(f, encoding='utf-8')\n", (16019, 16040), False, 'from lxml import etree\n'), ((15706, 15783), 'lxml.etree.Element', 'etree.Element', (['"""Relationship"""'], {'Type': 'rt', 'Target': '"""/3D/3dmodel.model"""', 'Id': '"""rel0"""'}), "('Relationship', Type=rt, Target='/3D/3dmodel.model', Id='rel0')\n", (15719, 15783), False, 'from lxml import etree\n'), ((16880, 16938), 'lxml.etree.Element', 'etree.Element', (['"""Default"""'], {'Extension': 'ext', 'ContentType': 'ctype'}), "('Default', Extension=ext, ContentType=ctype)\n", (16893, 16938), False, 'from lxml import etree\n'), ((10785, 10797), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (10795, 10797), False, 'import uuid\n'), ((13159, 13171), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (13169, 13171), False, 'import uuid\n'), ((14455, 14467), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (14465, 14467), False, 'import uuid\n'), ((15187, 15199), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (15197, 15199), False, 'import uuid\n'), ((14718, 14742), 'numpy.array', 'np.array', (["data['matrix']"], {}), "(data['matrix'])\n", (14726, 14742), True, 'import numpy as np\n'), ((13545, 13569), 'numpy.array', 'np.array', (["data['matrix']"], {}), "(data['matrix'])\n", (13553, 13569), True, 'import numpy as np\n')] |
# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
import numpy as np
import popart
import test_util as tu
def test_basic():
builder = popart.Builder()
shape = popart.TensorInfo("FLOAT", [3])
i1 = builder.addInputTensor(shape)
i2 = builder.addInputTensor(shape)
a1 = builder.aiOnnx.add([i1, i2])
p1 = builder.aiGraphcore.nop([a1])
a2 = builder.aiOnnx.add([i1, p1])
p2 = builder.aiGraphcore.nop([a2])
o = p2
builder.addOutputTensor(o)
proto = builder.getModelProto()
dataFlow = popart.DataFlow(1, {o: popart.AnchorReturnType("All")})
opts = popart.SessionOptions()
opts.enableOutlining = False
opts.enableOutliningCopyCostPruning = False
session = popart.InferenceSession(fnModel=proto,
dataFlow=dataFlow,
userOptions=opts,
deviceInfo=tu.create_test_device())
session.prepareDevice()
anchors = session.initAnchorArrays()
inputs = {
i1: np.array([1., 2., 3.], dtype=np.float32),
i2: np.array([4., 5., 6.], dtype=np.float32)
}
stepio = popart.PyStepIO(inputs, anchors)
session.run(stepio)
assert np.array_equal(anchors[o], np.array([6., 9., 12.],
dtype=np.float32))
def test_builder_shape_inference():
builder = popart.Builder()
shape = popart.TensorInfo("FLOAT", [3])
i1 = builder.addInputTensor(shape)
n1 = builder.aiGraphcore.nop([i1])
m1 = builder.aiOnnx.mul([n1, i1])
o = m1
builder.addOutputTensor(o)
nopShape = builder.getTensorShape(n1)
print(f'nopShape: {nopShape}')
| [
"popart.Builder",
"popart.AnchorReturnType",
"test_util.create_test_device",
"numpy.array",
"popart.TensorInfo",
"popart.PyStepIO",
"popart.SessionOptions"
] | [((147, 163), 'popart.Builder', 'popart.Builder', ([], {}), '()\n', (161, 163), False, 'import popart\n'), ((177, 208), 'popart.TensorInfo', 'popart.TensorInfo', (['"""FLOAT"""', '[3]'], {}), "('FLOAT', [3])\n", (194, 208), False, 'import popart\n'), ((606, 629), 'popart.SessionOptions', 'popart.SessionOptions', ([], {}), '()\n', (627, 629), False, 'import popart\n'), ((1165, 1197), 'popart.PyStepIO', 'popart.PyStepIO', (['inputs', 'anchors'], {}), '(inputs, anchors)\n', (1180, 1197), False, 'import popart\n'), ((1404, 1420), 'popart.Builder', 'popart.Builder', ([], {}), '()\n', (1418, 1420), False, 'import popart\n'), ((1434, 1465), 'popart.TensorInfo', 'popart.TensorInfo', (['"""FLOAT"""', '[3]'], {}), "('FLOAT', [3])\n", (1451, 1465), False, 'import popart\n'), ((1051, 1094), 'numpy.array', 'np.array', (['[1.0, 2.0, 3.0]'], {'dtype': 'np.float32'}), '([1.0, 2.0, 3.0], dtype=np.float32)\n', (1059, 1094), True, 'import numpy as np\n'), ((1105, 1148), 'numpy.array', 'np.array', (['[4.0, 5.0, 6.0]'], {'dtype': 'np.float32'}), '([4.0, 5.0, 6.0], dtype=np.float32)\n', (1113, 1148), True, 'import numpy as np\n'), ((1262, 1306), 'numpy.array', 'np.array', (['[6.0, 9.0, 12.0]'], {'dtype': 'np.float32'}), '([6.0, 9.0, 12.0], dtype=np.float32)\n', (1270, 1306), True, 'import numpy as np\n'), ((561, 591), 'popart.AnchorReturnType', 'popart.AnchorReturnType', (['"""All"""'], {}), "('All')\n", (584, 591), False, 'import popart\n'), ((927, 950), 'test_util.create_test_device', 'tu.create_test_device', ([], {}), '()\n', (948, 950), True, 'import test_util as tu\n')] |
import numpy as np
import matplotlib.pyplot as plt
class Bandit():
def __init__(self, arms: int):
"""
Base bandit constructor
:param amrs: probability distribution of each arm
"""
# quantity of arms
self.narms = arms
# times each arm was used
self.narms_n = np.ones(self.narms)
# mean reward for each arm
self.narms_rmean = np.zeros(self.narms)
# total average reward on each step
self.reward = [0]
# n times that any arm was pulled
self.n = 1
def pull(self):
"""
Function that pulls one arm
"""
pass
def update(self, arm_selected: int, reward: float):
"""
Function that updates the total average reward of the bandit and arm average
"""
pass
def show_statistics(self):
"""
Function that plots statistics of the arms
:param name: subplot name
:param color: color of the bars of the plots
"""
print()
for a in range(self.narms):
print("ARM: " + str(a))
print("\t Pulled " + str(self.narms_n[a] - 1) + " times")
print("\t Average arm reward " + str(self.narms_rmean[a]))
print("Final system reward = " + str(self.reward[-1]))
plt.figure(figsize=(14, 8))
plt.title("Rewards")
plt.plot(self.reward, label="Rewards")
plt.legend(bbox_to_anchor=(1.2, 0.5))
plt.xlabel("Iterations")
plt.ylabel("Average Reward")
plt.show() | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"numpy.zeros",
"numpy.ones",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] | [((328, 347), 'numpy.ones', 'np.ones', (['self.narms'], {}), '(self.narms)\n', (335, 347), True, 'import numpy as np\n'), ((410, 430), 'numpy.zeros', 'np.zeros', (['self.narms'], {}), '(self.narms)\n', (418, 430), True, 'import numpy as np\n'), ((1331, 1358), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(14, 8)'}), '(figsize=(14, 8))\n', (1341, 1358), True, 'import matplotlib.pyplot as plt\n'), ((1367, 1387), 'matplotlib.pyplot.title', 'plt.title', (['"""Rewards"""'], {}), "('Rewards')\n", (1376, 1387), True, 'import matplotlib.pyplot as plt\n'), ((1396, 1434), 'matplotlib.pyplot.plot', 'plt.plot', (['self.reward'], {'label': '"""Rewards"""'}), "(self.reward, label='Rewards')\n", (1404, 1434), True, 'import matplotlib.pyplot as plt\n'), ((1443, 1480), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'bbox_to_anchor': '(1.2, 0.5)'}), '(bbox_to_anchor=(1.2, 0.5))\n', (1453, 1480), True, 'import matplotlib.pyplot as plt\n'), ((1489, 1513), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Iterations"""'], {}), "('Iterations')\n", (1499, 1513), True, 'import matplotlib.pyplot as plt\n'), ((1522, 1550), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Average Reward"""'], {}), "('Average Reward')\n", (1532, 1550), True, 'import matplotlib.pyplot as plt\n'), ((1559, 1569), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1567, 1569), True, 'import matplotlib.pyplot as plt\n')] |
import numpy as np
ub = 2 ** 31 - 1;
with open("data.txt","w") as f:
for i in range(128):
x = np.random.randint(0, ub)
x=hex(x)[2:].zfill(8)
print(x[0:2],x[2:4],x[4:6],x[6:8],file=f)
s= "00 00 00 3f\n" + \
"00 00 00 06\n" + \
"00 00 00 5b\n" + \
"00 00 00 4f\n" + \
"00 00 00 66\n" + \
"00 00 00 6d\n" + \
"00 00 00 7d\n" + \
"00 00 00 07\n" + \
"00 00 00 7f\n" + \
"00 00 00 6f\n" + \
"00 00 00 77\n" + \
"00 00 00 7c\n" + \
"00 00 00 39\n" + \
"00 00 00 5e\n" + \
"00 00 00 7b\n" + \
"00 00 00 71\n"
print(s,file=f) | [
"numpy.random.randint"
] | [((110, 134), 'numpy.random.randint', 'np.random.randint', (['(0)', 'ub'], {}), '(0, ub)\n', (127, 134), True, 'import numpy as np\n')] |
# Importing the Keras libraries and packages
from keras.models import load_model
model = load_model('Resources/CNNModel/fashionModel.h5')
import numpy as np
# import os
import urllib.request
# import gzip
# import shutil
# import matplotlib.pyplot as plt
from tkinter import filedialog
from tkinter import *
from PIL import Image
import os
def Test():
root = Tk()
# root.filename = filedialog.askopenfilename()
root.filename = filedialog.askopenfilename(initialdir=os.getcwd(), title="Select file",filetypes = (("png files","*.png"),("all files","*.*")))
url = root.filename
# for the while loop
choice = True
# this makes sure a file is selcted
while choice:
# check if the file is selected
if (url.endswith('.jpg')) or (url.endswith('.png')):
print (root.filename)
choice = None
else:
root.filename = filedialog.askopenfilename(initialdir=os.getcwd(), title="Select file",filetypes = (("png files","*.png"),("all files","*.*")))
# this is the path if the image
Imgpath = root.filename
# the label is the name of the image in this case
#print("\nThe label of the Image is", unserInput)
#here the image is converted to grayscale and then numpy array
img = Image.open(Imgpath).convert("L")
img = img.resize((28,28))
im2arr = np.array(img)
im2arr = im2arr.reshape(1,28,28,1)
# Predicting the Test set results
pred = model.predict(im2arr)
print(pred)
correct_indices = np.nonzero(pred > 0.1)
#print("The program predicts image number to be:", correct_indices[-1])
#print(pred.index(max(pred))
#print(correct_indices)
# from the prediction array print the result
if correct_indices[-1] == 0:
print("The program predicts image number to be T-shirt/top")
elif correct_indices[-1] == 1:
print("The program predicts image number to be Trouser")
elif correct_indices[-1] == 2:
print("The program predicts image number to be Pullover")
elif correct_indices[-1] == 3:
print("The program predicts image number to be Dress")
elif correct_indices[-1] == 4:
print("The program predicts image number to be Coat")
elif correct_indices[-1] == 5:
print("The program predicts image number to be Sandle")
elif correct_indices[-1] == 6:
print("The program predicts image number to be Shirt")
elif correct_indices[-1] == 7:
print("The program predicts image number to be Sneaker")
elif correct_indices[-1] == 8:
print("The program predicts image number to be Bag")
elif correct_indices[-1] == 9:
print("The program predicts image number to be Ankle boot")
#https://stackoverflow.com/questions/20443846/python-pil-nameerror-global-name-image-is-not-defined | [
"keras.models.load_model",
"os.getcwd",
"PIL.Image.open",
"numpy.nonzero",
"numpy.array"
] | [((89, 137), 'keras.models.load_model', 'load_model', (['"""Resources/CNNModel/fashionModel.h5"""'], {}), "('Resources/CNNModel/fashionModel.h5')\n", (99, 137), False, 'from keras.models import load_model\n'), ((1363, 1376), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (1371, 1376), True, 'import numpy as np\n'), ((1526, 1548), 'numpy.nonzero', 'np.nonzero', (['(pred > 0.1)'], {}), '(pred > 0.1)\n', (1536, 1548), True, 'import numpy as np\n'), ((480, 491), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (489, 491), False, 'import os\n'), ((1287, 1306), 'PIL.Image.open', 'Image.open', (['Imgpath'], {}), '(Imgpath)\n', (1297, 1306), False, 'from PIL import Image\n'), ((939, 950), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (948, 950), False, 'import os\n')] |
# Modifications copyright 2022 AI Singapore
#
# 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
#
# https://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.
#
# Original copyright (c) 2020 YifuZhang
#
# 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.
"""Model components such as backbone, neck, and head for FairMOT.
Modifications include:
- Remove fill_fc_weights() and other fc weights initialization
- Remove fill_up_weights()
- Remove code branch when head_conv <= 0
- Avoid using loading model zoo weights to create fc layer in DLA
- DLASeg:
- Remove base_name, pretrained, and out_channel arguments
- Add default value for final_kernel, last_level, and head_conv
- Hardcode final_kernel to 1
- Remove load_base_weights
- DLA:
- Use BasicBlock only
- Remove linear_root argument
- Omit creating num_classes member variable
- Remove _make_level()
- Remove dilation argument from _make_conv_level()
- IDAUp
- Remove output_padding in Conv2DTranspose function call
"""
from typing import Dict, List
import numpy as np
import torch
from torch import nn
from peekingduck.pipeline.nodes.model.fairmotv1.fairmot_files.network_blocks import (
BN_MOMENTUM,
BasicBlock,
DeformConv,
Tree,
)
class DLASeg(nn.Module):
"""The encoder-decoder network comprising of:
- ResNet-34 with an enhanced Deep Layer Aggregation (DLA) as backbone
- CenterNet as the detection branch
- FairMOT EmbeddingHead as the Re-ID branch
Args:
heads (Dict[str, int]): Configuration for the output channels for the
various heads of the model.
down_ratio (int): The downscale ratio from images to heatmap. In the
case of FairMOT, this is 4.
last_level (int): The last level of input feature fed into the
upsampling block. Default is 5.
head_conv (int): Number of channels in all heads. Default is 256.
"""
# pylint: disable=redefined-builtin
def __init__(
self,
heads: Dict[str, int],
down_ratio: int,
last_level: int = 5,
head_conv: int = 256,
) -> None:
super().__init__()
self.first_level = int(np.log2(down_ratio))
self.last_level = last_level
self.base = DLA([1, 1, 1, 2, 2, 1], [16, 32, 64, 128, 256, 512])
channels = self.base.channels
scales = [2 ** i for i in range(len(channels[self.first_level :]))]
self.dla_up = DLAUp(self.first_level, channels[self.first_level :], scales)
self.ida_up = IDAUp(
channels[self.first_level : self.last_level],
channels[self.first_level],
[2 ** i for i in range(self.last_level - self.first_level)],
)
self.heads = heads
for head in self.heads:
classes = self.heads[head]
head_network = nn.Sequential(
nn.Conv2d(
channels[self.first_level],
head_conv,
kernel_size=3,
padding=1,
bias=True,
),
nn.ReLU(inplace=True),
nn.Conv2d(
head_conv, classes, kernel_size=1, stride=1, padding=0, bias=True
),
)
# Sets the dict key as the member variable
self.__setattr__(head, head_network)
def forward( # pylint: disable=invalid-name
self, input: torch.Tensor
) -> Dict[str, torch.Tensor]:
"""Defines the computation performed at every call.
Args:
input (torch.Tensor): Input from the previous layer.
Returns:
(Dict[str, torch.Tensor]): A dictionary of tensors with keys
corresponding to `self.heads`.
"""
layers = self.base(input)
layers = self.dla_up(layers)
y = [layers[i].clone() for i in range(self.last_level - self.first_level)]
self.ida_up(y, 0, len(y))
outputs = {}
for head in self.heads:
outputs[head] = getattr(self, head)(y[-1])
return outputs
class DLA(nn.Module): # pylint: disable=too-many-instance-attributes
"""Deep Layer Aggregation to be used as the backbone of FairMOT's
encoder-decoder network.
Args:
levels (List[int]): List of aggregation depths at various stages.
channels (List[int]): List of number of channels at various stages.
num_classes (int): Number of classes for classification. NOTE: Not used
in FairMOT is needed to properly load the model weights.
residual_root (bool): Flag to indicate if a residual layer should be
used in the root block. Default is False.
"""
# pylint: disable=redefined-builtin
def __init__(
self,
levels: List[int],
channels: List[int],
num_classes: int = 1000,
) -> None:
super().__init__()
# DLA-34 (used by FairMOT) uses basic blocks as the residual block
block = BasicBlock
self.channels = channels
self.base_layer = nn.Sequential(
nn.Conv2d(3, channels[0], kernel_size=7, stride=1, padding=3, bias=False),
nn.BatchNorm2d(channels[0], momentum=BN_MOMENTUM),
nn.ReLU(inplace=True),
)
self.level0 = self._make_conv_level(channels[0], channels[0], levels[0])
self.level1 = self._make_conv_level(
channels[0], channels[1], levels[1], stride=2
)
self.level2 = Tree(
levels[2],
block,
channels[1],
channels[2],
2,
level_root=False,
)
self.level3 = Tree(
levels[3],
block,
channels[2],
channels[3],
2,
level_root=True,
)
self.level4 = Tree(
levels[4],
block,
channels[3],
channels[4],
2,
level_root=True,
)
self.level5 = Tree(
levels[5],
block,
channels[4],
channels[5],
2,
level_root=True,
)
# Apparently not needed
self.fc = nn.Conv2d( # pylint: disable=invalid-name
self.channels[-1],
num_classes,
kernel_size=1,
stride=1,
padding=0,
bias=True,
)
def forward(self, input: torch.Tensor) -> List[torch.Tensor]:
"""Defines the computation performed at every call.
Args:
input (torch.Tensor): Input from the previous layer.
Returns:
(List[torch.Tensor]): A list of tensors containing the output at
every stage.
"""
outputs = []
input = self.base_layer(input)
for i in range(6):
input = getattr(self, f"level{i}")(input)
outputs.append(input)
return outputs
@staticmethod
def _make_conv_level(
in_channels: int, out_channels: int, num_convs: int, stride: int = 1
) -> nn.Sequential:
"""Creates the networks for one of the earlier stages in DLA.
Args:
in_channels (int): Number of channels in the input image.
out_channels (int): Number of channels producted by the
convolution.
num_convs (int): Number of convolution layers in the stage.
stride (int): Stride of the convolution. Default is 1.
Returns:
(nn.Sequential): A sequential container of all the networks in the
stage.
"""
modules = []
for i in range(num_convs):
modules.extend(
[
nn.Conv2d(
in_channels,
out_channels,
kernel_size=3,
stride=stride if i == 0 else 1,
padding=1,
bias=False,
),
nn.BatchNorm2d(out_channels, momentum=BN_MOMENTUM),
nn.ReLU(inplace=True),
]
)
in_channels = out_channels
return nn.Sequential(*modules)
class DLAUp(nn.Module):
"""DLA upsample network.
Args:
start_level (int): The starting stage of this upsample network.
channels (List[int]): List of number of channels at various stages.
scales (List[int]): Scale factors at various stages.
in_channels (List[int]): Number of channels in the input image at
various stages.
"""
def __init__(
self,
start_level: int,
channels: List[int],
scales: List[int],
in_channels: List[int] = None,
) -> None:
super().__init__()
self.start_level = start_level
if in_channels is None:
in_channels = channels
self.channels = channels
scales_arr = np.array(scales, dtype=int)
for i in range(len(channels) - 1):
j = -i - 2
setattr(
self,
f"ida_{i}",
IDAUp(in_channels[j:], channels[j], scales_arr[j:] // scales_arr[j]),
)
scales_arr[j + 1 :] = scales_arr[j]
in_channels[j + 1 :] = [channels[j] for _ in channels[j + 1 :]]
def forward(self, layers: List[torch.Tensor]) -> List[torch.Tensor]:
"""Defines the computation performed at every call.
Args:
layers (List[torch.Tensor]): Inputs from the various stages.
Returns:
(List[torch.Tensor]): A list of tensors containing the output at
every stage.
"""
out = [layers[-1]] # start with 32
for i in range(len(layers) - self.start_level - 1):
ida = getattr(self, f"ida_{i}")
ida(layers, len(layers) - i - 2, len(layers))
out.insert(0, layers[-1])
return out
class IDAUp(nn.Module):
"""Iterative Deep Aggregation network.
Args:
in_channels_list (List[int]): List of Number of channels in the input
image at various stages.
out_channels (int): Number of channels producted by the convolution.
up_strides (List[int]): List of strides for upsampling at various
stages.
"""
def __init__(
self, in_channels_list: List[int], out_channels: int, up_strides: List[int]
) -> None:
super().__init__()
for i in range(1, len(in_channels_list)):
in_channels = in_channels_list[i]
stride = int(up_strides[i])
project = DeformConv(in_channels, out_channels)
node = DeformConv(out_channels, out_channels)
upsample = nn.ConvTranspose2d(
out_channels,
out_channels,
stride * 2,
stride=stride,
padding=stride // 2,
groups=out_channels,
bias=False,
)
setattr(self, f"proj_{i}", project)
setattr(self, f"up_{i}", upsample)
setattr(self, f"node_{i}", node)
def forward(
self, layers: List[torch.Tensor], start_level: int, end_level: int
) -> None:
"""Defines the computation performed at every call. NOTE: This modifies
``layers`` in-place.
Args:
layers (List[torch.Tensor]): Inputs from the various stages.
start_level (int): The starting stage number.
end_level (int): The ending stage number.
"""
for i in range(start_level + 1, end_level):
project = getattr(self, f"proj_{i - start_level}")
node = getattr(self, f"node_{i - start_level}")
upsample = getattr(self, f"up_{i - start_level}")
layers[i] = upsample(project(layers[i]))
layers[i] = node(layers[i] + layers[i - 1])
| [
"torch.nn.ReLU",
"torch.nn.ConvTranspose2d",
"torch.nn.Sequential",
"numpy.log2",
"torch.nn.Conv2d",
"torch.nn.BatchNorm2d",
"numpy.array",
"peekingduck.pipeline.nodes.model.fairmotv1.fairmot_files.network_blocks.Tree",
"peekingduck.pipeline.nodes.model.fairmotv1.fairmot_files.network_blocks.DeformC... | [((6939, 7008), 'peekingduck.pipeline.nodes.model.fairmotv1.fairmot_files.network_blocks.Tree', 'Tree', (['levels[2]', 'block', 'channels[1]', 'channels[2]', '(2)'], {'level_root': '(False)'}), '(levels[2], block, channels[1], channels[2], 2, level_root=False)\n', (6943, 7008), False, 'from peekingduck.pipeline.nodes.model.fairmotv1.fairmot_files.network_blocks import BN_MOMENTUM, BasicBlock, DeformConv, Tree\n'), ((7114, 7182), 'peekingduck.pipeline.nodes.model.fairmotv1.fairmot_files.network_blocks.Tree', 'Tree', (['levels[3]', 'block', 'channels[2]', 'channels[3]', '(2)'], {'level_root': '(True)'}), '(levels[3], block, channels[2], channels[3], 2, level_root=True)\n', (7118, 7182), False, 'from peekingduck.pipeline.nodes.model.fairmotv1.fairmot_files.network_blocks import BN_MOMENTUM, BasicBlock, DeformConv, Tree\n'), ((7288, 7356), 'peekingduck.pipeline.nodes.model.fairmotv1.fairmot_files.network_blocks.Tree', 'Tree', (['levels[4]', 'block', 'channels[3]', 'channels[4]', '(2)'], {'level_root': '(True)'}), '(levels[4], block, channels[3], channels[4], 2, level_root=True)\n', (7292, 7356), False, 'from peekingduck.pipeline.nodes.model.fairmotv1.fairmot_files.network_blocks import BN_MOMENTUM, BasicBlock, DeformConv, Tree\n'), ((7462, 7530), 'peekingduck.pipeline.nodes.model.fairmotv1.fairmot_files.network_blocks.Tree', 'Tree', (['levels[5]', 'block', 'channels[4]', 'channels[5]', '(2)'], {'level_root': '(True)'}), '(levels[5], block, channels[4], channels[5], 2, level_root=True)\n', (7466, 7530), False, 'from peekingduck.pipeline.nodes.model.fairmotv1.fairmot_files.network_blocks import BN_MOMENTUM, BasicBlock, DeformConv, Tree\n'), ((7664, 7757), 'torch.nn.Conv2d', 'nn.Conv2d', (['self.channels[-1]', 'num_classes'], {'kernel_size': '(1)', 'stride': '(1)', 'padding': '(0)', 'bias': '(True)'}), '(self.channels[-1], num_classes, kernel_size=1, stride=1, padding=\n 0, bias=True)\n', (7673, 7757), False, 'from torch import nn\n'), ((9668, 9691), 'torch.nn.Sequential', 'nn.Sequential', (['*modules'], {}), '(*modules)\n', (9681, 9691), False, 'from torch import nn\n'), ((10433, 10460), 'numpy.array', 'np.array', (['scales'], {'dtype': 'int'}), '(scales, dtype=int)\n', (10441, 10460), True, 'import numpy as np\n'), ((3610, 3629), 'numpy.log2', 'np.log2', (['down_ratio'], {}), '(down_ratio)\n', (3617, 3629), True, 'import numpy as np\n'), ((6540, 6613), 'torch.nn.Conv2d', 'nn.Conv2d', (['(3)', 'channels[0]'], {'kernel_size': '(7)', 'stride': '(1)', 'padding': '(3)', 'bias': '(False)'}), '(3, channels[0], kernel_size=7, stride=1, padding=3, bias=False)\n', (6549, 6613), False, 'from torch import nn\n'), ((6627, 6676), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['channels[0]'], {'momentum': 'BN_MOMENTUM'}), '(channels[0], momentum=BN_MOMENTUM)\n', (6641, 6676), False, 'from torch import nn\n'), ((6690, 6711), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (6697, 6711), False, 'from torch import nn\n'), ((12117, 12154), 'peekingduck.pipeline.nodes.model.fairmotv1.fairmot_files.network_blocks.DeformConv', 'DeformConv', (['in_channels', 'out_channels'], {}), '(in_channels, out_channels)\n', (12127, 12154), False, 'from peekingduck.pipeline.nodes.model.fairmotv1.fairmot_files.network_blocks import BN_MOMENTUM, BasicBlock, DeformConv, Tree\n'), ((12174, 12212), 'peekingduck.pipeline.nodes.model.fairmotv1.fairmot_files.network_blocks.DeformConv', 'DeformConv', (['out_channels', 'out_channels'], {}), '(out_channels, out_channels)\n', (12184, 12212), False, 'from peekingduck.pipeline.nodes.model.fairmotv1.fairmot_files.network_blocks import BN_MOMENTUM, BasicBlock, DeformConv, Tree\n'), ((12236, 12367), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['out_channels', 'out_channels', '(stride * 2)'], {'stride': 'stride', 'padding': '(stride // 2)', 'groups': 'out_channels', 'bias': '(False)'}), '(out_channels, out_channels, stride * 2, stride=stride,\n padding=stride // 2, groups=out_channels, bias=False)\n', (12254, 12367), False, 'from torch import nn\n'), ((4307, 4396), 'torch.nn.Conv2d', 'nn.Conv2d', (['channels[self.first_level]', 'head_conv'], {'kernel_size': '(3)', 'padding': '(1)', 'bias': '(True)'}), '(channels[self.first_level], head_conv, kernel_size=3, padding=1,\n bias=True)\n', (4316, 4396), False, 'from torch import nn\n'), ((4529, 4550), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (4536, 4550), False, 'from torch import nn\n'), ((4568, 4644), 'torch.nn.Conv2d', 'nn.Conv2d', (['head_conv', 'classes'], {'kernel_size': '(1)', 'stride': '(1)', 'padding': '(0)', 'bias': '(True)'}), '(head_conv, classes, kernel_size=1, stride=1, padding=0, bias=True)\n', (4577, 4644), False, 'from torch import nn\n'), ((9192, 9303), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_channels', 'out_channels'], {'kernel_size': '(3)', 'stride': '(stride if i == 0 else 1)', 'padding': '(1)', 'bias': '(False)'}), '(in_channels, out_channels, kernel_size=3, stride=stride if i == 0\n else 1, padding=1, bias=False)\n', (9201, 9303), False, 'from torch import nn\n'), ((9487, 9537), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['out_channels'], {'momentum': 'BN_MOMENTUM'}), '(out_channels, momentum=BN_MOMENTUM)\n', (9501, 9537), False, 'from torch import nn\n'), ((9559, 9580), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (9566, 9580), False, 'from torch import nn\n')] |
import numpy as np
import itertools
# compute exact distribution from weight matrices
def compute_probabilities(num_nodes, num_classes, A):
num_states = num_classes ** num_nodes
probs = np.zeros(num_states)
dim0 = num_nodes * num_classes
Atr = np.array(A).transpose(0, 2, 1, 3).reshape(dim0, dim0)
pre_eye = np.eye(num_classes, dtype = int)
for pi in range(num_states):
repr_str = np.base_repr(pi, base = num_classes, padding = num_nodes)[-num_nodes:]
y = np.array(list(repr_str), dtype = int)
x = pre_eye[y].reshape(dim0, 1)
probs[pi] = np.exp(x.T.dot(Atr).dot(x) / 2).item()
probs /= np.sum(probs)
return probs
# sampling from a distribution with exact probabilities computed
def sampling(num_nodes, num_classes, num_samples, probs):
num_states = probs.size
samples = np.zeros((num_samples, num_nodes), dtype = int)
index_samples = np.random.choice(np.arange(num_states), size = num_samples, p = probs)
for si in range(num_samples):
repr_str = np.base_repr(index_samples[si], base = num_classes, padding = num_nodes)[-num_nodes:]
samples[si] = np.array(list(repr_str), dtype = int)
return samples
# add noise to data
def add_noise(samples, num_classes, p_noise, noise_model):
assert 0 <= p_noise and p_noise <= 1
assert noise_model in ['noiseless', 'huber', 'independent']
num_samples, num_nodes = samples.shape
if noise_model == 'noiseless':
pass
elif noise_model == 'huber':
W = np.random.binomial(1, p_noise, num_samples).astype(bool)
samples[W] = np.random.randint(num_classes, size = (W.sum(), num_nodes))
elif noise_model == 'independent':
W = np.random.binomial(1, p_noise, samples.shape).astype(bool)
sel_entries = samples[W]
r = np.random.randint(num_classes - 1, size = sel_entries.shape)
r += (r >= sel_entries).astype(int)
samples[W] = r
return samples
# get a diamond-shaped graph, returning weight and adjacency matrix
def get_diamond_graph(num_nodes, num_classes, theta):
A = np.zeros((num_nodes, num_nodes, num_classes, num_classes))
G = np.zeros((num_nodes, num_nodes), dtype = bool)
cW = np.ones((num_classes, num_classes)) * theta
cW[0::2, 1::2] = -theta
cW[1::2, 0::2] = -theta
A[0, 1:-1] = A[-1, 1:-1] = A[1:-1, 0] = A[1:-1, -1] = cW
G[0, 1:-1] = G[-1, 1:-1] = G[1:-1, 0] = G[1:-1, -1] = True
fW = np.random.randint(2, size = (num_nodes - 2, 1, 1)) * 2 - 1
A[0, 1:-1] *= fW
A[1:-1, 0] *= fW
fW = np.random.randint(2, size = (num_nodes - 2, 1, 1)) * 2 - 1
A[-1, 1:-1] *= fW
A[1:-1, -1] *= fW
return A, G
# get a grid-shaped graph, returning weight and adjacency matrix
def get_grid_graph(num_nodes, num_classes, theta):
A = np.zeros((num_nodes, num_nodes, num_classes, num_classes))
G = np.zeros((num_nodes, num_nodes), dtype = bool)
cW = np.ones((num_classes, num_classes)) * theta
cW[0::2, 1::2] = -theta
cW[1::2, 0::2] = -theta
ne = np.sqrt(num_nodes).astype(int)
for i in range(ne):
for j in range(ne):
idx = i * ne + j
if j > 0:
G[idx, idx - 1] = G[idx - 1, idx] = True
if np.random.rand() < 0.5:
A[idx, idx - 1] = A[idx - 1, idx] = cW
else:
A[idx, idx - 1] = A[idx - 1, idx] = -cW
if i > 0:
G[idx, idx - ne] = G[idx - ne, idx] = True
if np.random.rand() < 0.5:
A[idx, idx - ne] = A[idx - ne, idx] = cW
else:
A[idx, idx - ne] = A[idx - ne, idx] = -cW
return A, G
# get a random graph, returning weight and adjacency matrix
def get_random_graph(num_nodes, num_classes, theta):
A = np.zeros((num_nodes, num_nodes, num_classes, num_classes))
G = np.zeros((num_nodes, num_nodes), dtype = bool)
cW = np.ones((num_classes, num_classes)) * theta
cW[0::2, 1::2] = -theta
cW[1::2, 0::2] = -theta
for i, j in itertools.combinations(range(num_nodes), 2):
G[i, j] = G[j, i] = (np.random.rand() > 0.5)
A[i, j] = A[j, i] = G[i, j] * (np.random.randint(2) * 2 - 1) * cW
return A, G
# generate samples from a type of graph and perturb the data
def generate_samples(num_nodes, num_classes, graph_type, theta, num_samples, p_noise, noise_model):
assert graph_type in ['diamond', 'grid', 'random']
if graph_type == 'diamond':
A, G = get_diamond_graph(num_nodes, num_classes, theta)
elif graph_type == 'grid':
A, G = get_grid_graph(num_nodes, num_classes, theta)
elif graph_type == 'random':
A, G = get_random_graph(num_nodes, num_classes, theta)
probs = compute_probabilities(num_nodes, num_classes, A)
samples = sampling(num_nodes, num_classes, num_samples, probs)
samples = add_noise(samples, num_classes, p_noise, noise_model)
return A, G, samples
| [
"numpy.sum",
"numpy.random.binomial",
"numpy.zeros",
"numpy.ones",
"numpy.base_repr",
"numpy.random.randint",
"numpy.arange",
"numpy.array",
"numpy.random.rand",
"numpy.eye",
"numpy.sqrt"
] | [((197, 217), 'numpy.zeros', 'np.zeros', (['num_states'], {}), '(num_states)\n', (205, 217), True, 'import numpy as np\n'), ((332, 362), 'numpy.eye', 'np.eye', (['num_classes'], {'dtype': 'int'}), '(num_classes, dtype=int)\n', (338, 362), True, 'import numpy as np\n'), ((660, 673), 'numpy.sum', 'np.sum', (['probs'], {}), '(probs)\n', (666, 673), True, 'import numpy as np\n'), ((860, 905), 'numpy.zeros', 'np.zeros', (['(num_samples, num_nodes)'], {'dtype': 'int'}), '((num_samples, num_nodes), dtype=int)\n', (868, 905), True, 'import numpy as np\n'), ((2125, 2183), 'numpy.zeros', 'np.zeros', (['(num_nodes, num_nodes, num_classes, num_classes)'], {}), '((num_nodes, num_nodes, num_classes, num_classes))\n', (2133, 2183), True, 'import numpy as np\n'), ((2192, 2236), 'numpy.zeros', 'np.zeros', (['(num_nodes, num_nodes)'], {'dtype': 'bool'}), '((num_nodes, num_nodes), dtype=bool)\n', (2200, 2236), True, 'import numpy as np\n'), ((2840, 2898), 'numpy.zeros', 'np.zeros', (['(num_nodes, num_nodes, num_classes, num_classes)'], {}), '((num_nodes, num_nodes, num_classes, num_classes))\n', (2848, 2898), True, 'import numpy as np\n'), ((2907, 2951), 'numpy.zeros', 'np.zeros', (['(num_nodes, num_nodes)'], {'dtype': 'bool'}), '((num_nodes, num_nodes), dtype=bool)\n', (2915, 2951), True, 'import numpy as np\n'), ((3859, 3917), 'numpy.zeros', 'np.zeros', (['(num_nodes, num_nodes, num_classes, num_classes)'], {}), '((num_nodes, num_nodes, num_classes, num_classes))\n', (3867, 3917), True, 'import numpy as np\n'), ((3926, 3970), 'numpy.zeros', 'np.zeros', (['(num_nodes, num_nodes)'], {'dtype': 'bool'}), '((num_nodes, num_nodes), dtype=bool)\n', (3934, 3970), True, 'import numpy as np\n'), ((945, 966), 'numpy.arange', 'np.arange', (['num_states'], {}), '(num_states)\n', (954, 966), True, 'import numpy as np\n'), ((2249, 2284), 'numpy.ones', 'np.ones', (['(num_classes, num_classes)'], {}), '((num_classes, num_classes))\n', (2256, 2284), True, 'import numpy as np\n'), ((2964, 2999), 'numpy.ones', 'np.ones', (['(num_classes, num_classes)'], {}), '((num_classes, num_classes))\n', (2971, 2999), True, 'import numpy as np\n'), ((3983, 4018), 'numpy.ones', 'np.ones', (['(num_classes, num_classes)'], {}), '((num_classes, num_classes))\n', (3990, 4018), True, 'import numpy as np\n'), ((422, 475), 'numpy.base_repr', 'np.base_repr', (['pi'], {'base': 'num_classes', 'padding': 'num_nodes'}), '(pi, base=num_classes, padding=num_nodes)\n', (434, 475), True, 'import numpy as np\n'), ((1052, 1120), 'numpy.base_repr', 'np.base_repr', (['index_samples[si]'], {'base': 'num_classes', 'padding': 'num_nodes'}), '(index_samples[si], base=num_classes, padding=num_nodes)\n', (1064, 1120), True, 'import numpy as np\n'), ((2483, 2531), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': '(num_nodes - 2, 1, 1)'}), '(2, size=(num_nodes - 2, 1, 1))\n', (2500, 2531), True, 'import numpy as np\n'), ((2593, 2641), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': '(num_nodes - 2, 1, 1)'}), '(2, size=(num_nodes - 2, 1, 1))\n', (2610, 2641), True, 'import numpy as np\n'), ((3074, 3092), 'numpy.sqrt', 'np.sqrt', (['num_nodes'], {}), '(num_nodes)\n', (3081, 3092), True, 'import numpy as np\n'), ((4175, 4191), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (4189, 4191), True, 'import numpy as np\n'), ((1844, 1902), 'numpy.random.randint', 'np.random.randint', (['(num_classes - 1)'], {'size': 'sel_entries.shape'}), '(num_classes - 1, size=sel_entries.shape)\n', (1861, 1902), True, 'import numpy as np\n'), ((264, 275), 'numpy.array', 'np.array', (['A'], {}), '(A)\n', (272, 275), True, 'import numpy as np\n'), ((1551, 1594), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'p_noise', 'num_samples'], {}), '(1, p_noise, num_samples)\n', (1569, 1594), True, 'import numpy as np\n'), ((3284, 3300), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (3298, 3300), True, 'import numpy as np\n'), ((3549, 3565), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (3563, 3565), True, 'import numpy as np\n'), ((1740, 1785), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'p_noise', 'samples.shape'], {}), '(1, p_noise, samples.shape)\n', (1758, 1785), True, 'import numpy as np\n'), ((4238, 4258), 'numpy.random.randint', 'np.random.randint', (['(2)'], {}), '(2)\n', (4255, 4258), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 31 20:44:36 2019
@author: Excalibur
"""
import numpy as np
def typeNode(lams):
lam1, lam2, lam3 = lams
if any(lam == 0 for lam in lams):
return "Non hyperbolic!"
elif all(np.isreal(lam) for lam in lams):
signs = list(map(np.sign,list(lams)))
if all(lam<0 for lam in lams):
return 'Attracting Node'
elif all(lam > 0 for lam in lams):
return 'Repelling Node'
elif sum(signs) == -1:
return 'Saddle'
elif sum(signs) == 1:
return 'Saddle'
elif any(np.isreal(lam) for lam in lams):
realLams = np.real(list(lams))
signs = list(map(np.sign,list(realLams)))
if sum(signs) == -3:
return "Stable Focus-Node"
elif sum(signs) == 3:
return "Unstable Focus-Node"
else:
return "Saddle-Focus Point"
| [
"numpy.isreal"
] | [((245, 259), 'numpy.isreal', 'np.isreal', (['lam'], {}), '(lam)\n', (254, 259), True, 'import numpy as np\n'), ((609, 623), 'numpy.isreal', 'np.isreal', (['lam'], {}), '(lam)\n', (618, 623), True, 'import numpy as np\n')] |
# <NAME>
# 2019 Edgise
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import tensorflow as tf
import keras
from keras.applications.mobilenetv2 import MobileNetV2, preprocess_input, decode_predictions
import os
#import cv2
import PIL
import time
execution_path = os.getcwd()
print("tf version : " + tf.__version__)
print("keras version : " + keras.__version__)
# In[2]:
# load in the neural network
net = MobileNetV2(weights = 'imagenet', include_top = True)
# In[3]:
input_image_path = os.path.join(execution_path, 'images/cat.jpg')
print("input image read from : " + str(input_image_path))
# In[4]:
# Installing OpenCV on raspberry pi can be a burden, so let's switch to PIL
# However, if OpenCV is installed, it does tend to be a little faster
#input_image = cv2.imread(input_image_path)
#input_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2RGB)
input_image = PIL.Image.open(input_image_path)
input_image = np.asarray(input_image)
# In[11]:
# Use the MobileNet preprocessing function,
# and expand dimensions to create a batch of 1 image
preprocessed = preprocess_input(input_image)
preprocessed = np.expand_dims(preprocessed, axis=0)
print('input tensor shape : ' + str(preprocessed.shape))
# In[12]:
# Do 1 warmup prediction, this way we make sure everything is loaded as it should
print("warmup prediction")
prediction = net.predict(preprocessed)
print(decode_predictions(prediction, top=1)[0])
time.sleep(1)
# In[13]:
print("starting now...")
s = time.time()
for i in range(0,250,1):
prediction = net.predict(preprocessed)
e = time.time()
print('Time[ms] : ' + str(e-s))
print('FPS : ' + str(1.0/((e-s)/250.0)))
# In[ ]:
# Save the model to an h5 file
net.save('MobileNetV2_ImageNet.h5')
print("Model saved.")
| [
"keras.applications.mobilenetv2.MobileNetV2",
"keras.applications.mobilenetv2.decode_predictions",
"os.getcwd",
"numpy.asarray",
"keras.applications.mobilenetv2.preprocess_input",
"numpy.expand_dims",
"PIL.Image.open",
"time.sleep",
"time.time",
"os.path.join"
] | [((284, 295), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (293, 295), False, 'import os\n'), ((429, 478), 'keras.applications.mobilenetv2.MobileNetV2', 'MobileNetV2', ([], {'weights': '"""imagenet"""', 'include_top': '(True)'}), "(weights='imagenet', include_top=True)\n", (440, 478), False, 'from keras.applications.mobilenetv2 import MobileNetV2, preprocess_input, decode_predictions\n'), ((515, 561), 'os.path.join', 'os.path.join', (['execution_path', '"""images/cat.jpg"""'], {}), "(execution_path, 'images/cat.jpg')\n", (527, 561), False, 'import os\n'), ((896, 928), 'PIL.Image.open', 'PIL.Image.open', (['input_image_path'], {}), '(input_image_path)\n', (910, 928), False, 'import PIL\n'), ((943, 966), 'numpy.asarray', 'np.asarray', (['input_image'], {}), '(input_image)\n', (953, 966), True, 'import numpy as np\n'), ((1092, 1121), 'keras.applications.mobilenetv2.preprocess_input', 'preprocess_input', (['input_image'], {}), '(input_image)\n', (1108, 1121), False, 'from keras.applications.mobilenetv2 import MobileNetV2, preprocess_input, decode_predictions\n'), ((1137, 1173), 'numpy.expand_dims', 'np.expand_dims', (['preprocessed'], {'axis': '(0)'}), '(preprocessed, axis=0)\n', (1151, 1173), True, 'import numpy as np\n'), ((1440, 1453), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (1450, 1453), False, 'import time\n'), ((1496, 1507), 'time.time', 'time.time', ([], {}), '()\n', (1505, 1507), False, 'import time\n'), ((1581, 1592), 'time.time', 'time.time', ([], {}), '()\n', (1590, 1592), False, 'import time\n'), ((1398, 1435), 'keras.applications.mobilenetv2.decode_predictions', 'decode_predictions', (['prediction'], {'top': '(1)'}), '(prediction, top=1)\n', (1416, 1435), False, 'from keras.applications.mobilenetv2 import MobileNetV2, preprocess_input, decode_predictions\n')] |
#!/usr/bin/python
#
# Simple class to emulate SoapySDR devices locally.
# This is an initial version and needs improvement.
# It can only really be used to quickly test SoapySDR code.
#
# It is lacking any sort of timestamp or streaming ability, or any notion of sample rate.
# It could probably be done much more effectively at a lower layer, e.g., a SoapyRemote
# device attached to a channel emulator.
#
#
#
# #usage: import SoapySDRVirt as SoapySDR
# call ChanEmu().reset() to clear the buffers.
#
# 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.
#
# (c) 2020 <EMAIL>
import numpy as np
#these are included just to avoid errors.
#Constants
SOAPY_SDR_TX = 0
SOAPY_SDR_RX = 1
SOAPY_SDR_END_BURST = (1 << 1)
SOAPY_SDR_HAS_TIME = (1 << 2)
SOAPY_SDR_END_ABRUPT = (1 << 3)
SOAPY_SDR_ONE_PACKET = (1 << 4)
SOAPY_SDR_MORE_FRAGMENTS = (1 << 5)
SOAPY_SDR_WAIT_TRIGGER = (1 << 6)
#data types
SOAPY_SDR_CF64 = "CF64"
SOAPY_SDR_CF32 = "CF32"
SOAPY_SDR_CS32 = "CS32"
SOAPY_SDR_CU32 = "CU32"
SOAPY_SDR_CS16 = "CS16"
SOAPY_SDR_CU16 = "CU16"
SOAPY_SDR_CS12 = "CS12"
SOAPY_SDR_CU12 = "CU12"
SOAPY_SDR_CS8 = "CS8"
SOAPY_SDR_CU8 = "CU8"
SOAPY_SDR_CS4 = "CS4"
SOAPY_SDR_CU4 = "CU4"
SOAPY_SDR_F64 = "F64"
SOAPY_SDR_F32 = "F32"
SOAPY_SDR_S32 = "S32"
SOAPY_SDR_U32 = "U32"
SOAPY_SDR_S16 = "S16"
SOAPY_SDR_U16 = "U16"
SOAPY_SDR_S8 = "S8"
SOAPY_SDR_U8 = "U8"
def ticksToTimeNs(ticks, rate):
return ticks*1e9/rate
def timeNsToTicks(timeNs, rate):
return timeNs*rate/1e9
def clip(a, m=1, nbits=12):
np.clip(a.real, -m, m, out=a.real)
np.clip(a.imag, -m, m, out=a.imag)
if nbits is not None:
#quick way to simulate limited bit precision (and make rx gain important)
a.real[np.argwhere(np.abs(a.real) < 1/2**(nbits-1))] = 0 #highest bit is sign
a.imag[np.argwhere(np.abs(a.imag) < 1/2**(nbits-1))] = 0
return a
class Channel:
'''
A very basic multipath channel model with some number of taps over a delay spread, each with their own phase and attenuation.
It implements various impairments including noise, CFO, delay, and DC offset.
Parameters are static once instantiated.
'''
def __init__(self, noise=-70, phase_shift=True, attn=-40, attn_var=5, delay=48, delay_var=5, dc=.1, iq_imbal=.1, cfo=.00005, delay_spread=5, num_taps=4, tap_attn=12):
#def __init__(self, noise=None, phase_shift=False, attn=-30, attn_var=0, delay=48, delay_var=0, dc=0, iq_imbal=0, cfo=0, delay_spread=1, num_taps=1, tap_attn=4):
#cfo in phase rotation per sample in radians
if num_taps < 1:
print("There must be at least one tap.")
num_taps = 1
if num_taps > delay_spread:
print("num_taps must be higher than delay_spread. adjusting delay_spread.")
delay_spread = num_taps + 1
self.delay = delay
self.delay_spread = delay_spread
self.num_taps = num_taps
if delay_var > 0: self.delay += np.random.randint(0,delay_var+1) #weird behavior, where delay_var=1 always returns 0
self.dc_rx = 0 if dc == 0 else np.random.normal(scale=dc) + np.random.normal(scale=dc)*1j #randomize dc offset
self.dc_tx = 0 if dc == 0 else np.random.normal(scale=dc) + np.random.normal(scale=dc)*1j #randomize dc offset
self.iq_imbal_tx = 1 if iq_imbal == 0 else 1 + np.random.normal(scale=iq_imbal) #randomize IQ imbalance
self.iq_imbal_rx = 1 if iq_imbal == 0 else 1 + np.random.normal(scale=iq_imbal) #randomize IQ imbalance
self.noise = noise
self.cfo = cfo
self.paths = []
self.path_delays = [0]
self.num_taps=num_taps
for i in range(num_taps):
new_path = 10**((attn + np.random.normal(scale=attn_var))/20)
if i > 0: new_path /= i*10**(tap_attn/20) #increasingly attenuate additional paths
if phase_shift: new_path *= np.exp(np.random.uniform(high=2*np.pi)*1j)
self.paths.append(new_path)
if i > 0: self.path_delays.append(np.random.randint(low=i,high=delay_spread+1)) #weird behavior, high never happens #could result in two of the same delays -- but that's ok
def channelize(self,samps):
'''Apply the channel to a buffer of samples.'''
out = np.zeros(samps.shape[0]+self.delay+self.delay_spread,dtype=np.complex64)
samps_c = np.copy(samps) #create copy so we don't alter original
for i in range(self.num_taps):
out[self.delay+self.path_delays[i]:self.delay+self.path_delays[i]+samps.shape[0]] += samps_c*self.paths[i] #apply path phase shift, attenuation, and delay
out *= self.genCFO(out.shape[0], self.cfo) #apply cfo #each device should have a different CFO!
out += self.dc_tx #apply dc #more physically accurate to do it for each path, but end result is just another constant dc offset
out.real *= self.iq_imbal_tx #apply iq imbalance -- we just do real, but it can be more or less than 1, so result is fine
if self.noise is not None:
out += np.random.normal(scale=10**(self.noise/20), size=out.shape[0]) + np.random.normal(scale=10**(self.noise/20), size=out.shape[0])*1.j #add noise
return out[:samps.shape[0]]
@staticmethod
def genCFO(nsamps, cfo):
return np.exp(np.array(np.arange(0,nsamps)).transpose()*1.j*cfo).astype(np.complex64) #*2j*np.pi #cfo is radians per sample
class Stream:
'''Simple abstraction layer to keep track of channel IDs for the channel emulator.'''
def __init__(self, chan_ids):
#print(chan_ids)
self.chan_ids = chan_ids
self.chan_em = ChanEmu()
def write(self, stream, buffs, numElems, flags=0, timeNs=0, timeoutUs=int(1e6)):
for i,buff in enumerate(buffs):
self.chan_em.write(buff[:numElems],self.chan_ids[i])
return StreamReturn(numElems)
def read(self, stream, buffs, numElems, flags=0, timeNs=0, timeoutUs=int(1e6)):
for i,buff in enumerate(buffs):
buff[:numElems] = self.chan_em.read(numElems,self.chan_ids[i])
return StreamReturn(numElems)
class ChanEmu:
'''
Implements shared buffers for every TX "stream", as well as an NxN set of channels for every SDR radio interface.
When an rx radio "reads" the channel, it channelizes every TX buffer, using its unique channel to that rx radio, then sums them.
This implementation is lacking any notion of rate or timestamps.
'''
_instance = None
def __new__(cls, bufsize=204800):
'''Singleton pattern.'''
if cls._instance is None:
cls._instance = super(ChanEmu, cls).__new__(cls)
cls._bufsize=bufsize
cls._bufs = []
cls._channels = [[Channel()]]
cls.tx_gains = []
cls.rx_gains = []
#cls._buf = np.zeros(bufsize, dtype=np.complex64)
return cls._instance
def add_chan(cls):
#right now we make every radio tx and rx, and add them on device creation
#we could be more efficient by only creating channels when the stream is created, and only for tx or rx
cls._bufs.append(np.zeros(cls._bufsize, dtype=np.complex64)) #one buffer per radio
if len(cls._bufs) > 1: #awkwardly grow square list of lists of channels
for c in cls._channels:
c.append(Channel())
cls._channels.append([Channel() for i in range(len(cls._channels)+1)])
cls.tx_gains.append(0)
cls.rx_gains.append(0)
def read(cls, num, chan_id):
out = np.zeros(num,dtype=np.complex64)
for i , (c,b) in enumerate(zip(cls._channels[chan_id],cls._bufs)): #channelize and sum all buffers
if i != chan_id: out += c.channelize(b[:num]) #assume you can't rx your own tx
out *= 10**(cls.rx_gains[chan_id]/20) #apply rx gain
out.real *= cls._channels[chan_id][chan_id].iq_imbal_rx #apply iq imbalance -- we just do real, but it can be more or less than 1, so result is fine #apply here so that gains don't affect it.
out += cls._channels[chan_id][chan_id].dc_rx #apply dc #typically happens after amplification
return clip(out) #clip after RX gain. The rx gain doesn't do much in this sim, since it scales everything. We may need to add another noise stage or quantization lower bound to be more realistic.
def write(cls, vals, chan_id):
cls._bufs[chan_id][:vals.shape[0]] = clip(vals)*10**(cls.tx_gains[chan_id]/20) #clip before TX gain
def reset(cls):
for buf in cls._bufs:
buf[:] = 0
class StreamReturn:
''' Simple class to mimic stream status return syntax. '''
def __init__(self, ret):
self.ret = ret
class Device:
'''
Oversimplified virtual SoapySDR device to simply read/write stream operations.
It has no notion of rate or timestamps, and doesn't mimic functionality, just syntax.
'''
_NEXT_CHAN = 0 #keep unique device identifiers for the channel emulation
_TX_GAIN_RANGE = [-50,50]
_RX_GAIN_RANGE = [-50,50]
def __init__(self, *argv, num_chan=2):
#to replicate this properly, we should be able to take a list of args in and return a list of devices.
self.rate = None
self.freq = None
self.bandwidth = None
self.chan_em = ChanEmu()
self.num_chan = num_chan
self.chan_ids = range(self._NEXT_CHAN,self._NEXT_CHAN+num_chan)
Device._NEXT_CHAN += num_chan #this will increment the chan_ids for the next instance
for i in range(num_chan): self.chan_em.add_chan() #add these channels to the channel emulator
self.serial = argv[0]['serial'] + '-SIM' if 'serial' in argv[0] else 'NoSerial-SIM'
self.hw_info = { 'driver' : '2020.11.0.1-f0f0f0',
'firmware' : '2020.11.0.1-f0f0f0',
'fpga' : '2020.11.0.1-f0f0f0',
'frontend' : 'SIM',
'revision' : 'Simulated-1.00-MIMO',
'serial' : self.serial,
}
def getSampleRate(self, direction, channel):
return self.rate
def setSampleRate(self, direction, channel, rate):
self.rate = rate
def getBandwidth(self, direction, channel):
return self.bandwidth
def setBandwidth(self, direction, channel, bw):
self.bandwidth = bw
def getGain(self, direction, channel, *argv, **kwargs):
if direction == SOAPY_SDR_TX:
return self.chan_em.tx_gains[self.chan_ids[channel]]
if direction == SOAPY_SDR_RX:
return self.chan_em.rx_gains[self.chan_ids[channel]]
def getGainRange(self, direction, channel, *argv, **kwargs):
if direction == SOAPY_SDR_TX:
return self._TX_GAIN_RANGE
if direction == SOAPY_SDR_RX:
return self._RX_GAIN_RANGE
def setGain(self, direction, channel, value, *argv, **kwargs):
#Note: we have the ChanEmu keep track of gains since there is a layer of indirection in the
#Stream -- when we write stream, we actually don't know which channel is being written to,
#so it is easier to consider the gain as part of the channel.
if direction == SOAPY_SDR_TX:
self.chan_em.tx_gains[self.chan_ids[channel]] = np.clip(value, self._TX_GAIN_RANGE[0], self._TX_GAIN_RANGE[1])
if direction == SOAPY_SDR_RX:
self.chan_em.rx_gains[self.chan_ids[channel]] = np.clip(value, self._RX_GAIN_RANGE[0], self._RX_GAIN_RANGE[1])
def getFrequency(self, direction, channel, name='RF'):
return self.freq
def setFrequency(self, direction, channel, name, frequency):
self.freq = frequency
def getAntenna(self, *argv, **kwargs):
return
def setAntenna(self, *argv, **kwargs):
return
def getDCOffsetMode(self, *argv, **kwargs):
return
def setDCOffsetMode(self, *argv, **kwargs):
return
def getHardwareInfo(self, *argv, **kwargs):
return self.hw_info
def setupStream(self, direction, packing_form, channels, kwargs):
return Stream([self.chan_ids[i] for i in channels])
def activateStream(self, *argv, **kwargs):
return
#these can be static...
def writeStream(self, stream, buffs, numElems, flags=0, timeNs=0, timeoutUs=int(1e6)):
return stream.write(stream, buffs, numElems, flags, timeNs, timeoutUs)
def readStream(self, stream, buffs, numElems, flags=0, timeNs=0, timeoutUs=int(1e6)):
return stream.read(stream, buffs, numElems, flags, timeNs, timeoutUs)
def deactivateStream(self, *argv, **kwargs):
return
def closeStream(self, *argv, **kwargs):
return
def readSetting(self, *argv, **kwargs):
return
def writeSetting(self, *argv, **kwargs):
return
def readRegister(self, *argv, **kwargs):
return
def writeRegister(self, *argv, **kwargs):
return
def getHardwareTime(self, *argv, **kwargs):
return 0
def setHardwareTime(self, *argv, **kwargs):
return
def listSensors(self, *argv, **kwargs):
return
def readSensor(self, *argv, **kwargs):
return
#generated using:
#method_list = [func for func in dir(SoapySDR.Device) if callable(getattr(SoapySDR.Device, func))]
#for m in method_list:
# print(' def ' + m + '(self, *argv, **kwargs):\n return')
#import inspect
#for m in method_list:
# inspect.getfullargspec(getattr(SoapySDR.Device,m)) #doesn't work because of the way SWIG bindings are set apparently
def acquireReadBuffer(self, *argv, **kwargs):
return
def acquireWriteBuffer(self, *argv, **kwargs):
return
def close(self, *argv, **kwargs):
return
def getBandwidthRange(self, *argv, **kwargs):
return
def getChannelInfo(self, *argv, **kwargs):
return
def getClockSource(self, *argv, **kwargs):
return
def getDCOffset(self, *argv, **kwargs):
return
def getDirectAccessBufferAddrs(self, *argv, **kwargs):
return
def getDriverKey(self, *argv, **kwargs):
return
def getFrequencyArgsInfo(self, *argv, **kwargs):
return
def getFrequencyCorrection(self, *argv, **kwargs):
return
def getFrequencyRange(self, *argv, **kwargs):
return
def getFrontendMapping(self, *argv, **kwargs):
return
def getFullDuplex(self, *argv, **kwargs):
return
def getGainMode(self, *argv, **kwargs):
return
def getHardwareKey(self, *argv, **kwargs):
return
def getIQBalance(self, *argv, **kwargs):
return
def getMasterClockRate(self, *argv, **kwargs):
return
def getMasterClockRates(self, *argv, **kwargs):
return
def getNativeStreamFormat(self, *argv, **kwargs):
return
def getNumChannels(self, *argv, **kwargs):
return
def getNumDirectAccessBuffers(self, *argv, **kwargs):
return
def getSampleRateRange(self, *argv, **kwargs):
return
def getSensorInfo(self, *argv, **kwargs):
return
def getSettingInfo(self, *argv, **kwargs):
return
def getStreamArgsInfo(self, *argv, **kwargs):
return
def getStreamFormats(self, *argv, **kwargs):
return
def getStreamMTU(self, *argv, **kwargs):
return
def getTimeSource(self, *argv, **kwargs):
return
def hasDCOffset(self, *argv, **kwargs):
return
def hasDCOffsetMode(self, *argv, **kwargs):
return
def hasFrequencyCorrection(self, *argv, **kwargs):
return
def hasGainMode(self, *argv, **kwargs):
return
def hasHardwareTime(self, *argv, **kwargs):
return
def hasIQBalance(self, *argv, **kwargs):
return
def listAntennas(self, *argv, **kwargs):
return
def listBandwidths(self, *argv, **kwargs):
return
def listClockSources(self, *argv, **kwargs):
return
def listFrequencies(self, *argv, **kwargs):
return
def listGPIOBanks(self, *argv, **kwargs):
return
def listGains(self, *argv, **kwargs):
return
def listRegisterInterfaces(self, *argv, **kwargs):
return
def listSampleRates(self, *argv, **kwargs):
return
def listTimeSources(self, *argv, **kwargs):
return
def listUARTs(self, *argv, **kwargs):
return
def make(self, *argv, **kwargs):
return
def readGPIO(self, *argv, **kwargs):
return
def readGPIODir(self, *argv, **kwargs):
return
def readI2C(self, *argv, **kwargs):
return
def readRegisters(self, *argv, **kwargs):
return
def readSensorBool(self, *argv, **kwargs):
return
def readSensorFloat(self, *argv, **kwargs):
return
def readSensorInt(self, *argv, **kwargs):
return
def readSettingBool(self, *argv, **kwargs):
return
def readSettingFloat(self, *argv, **kwargs):
return
def readSettingInt(self, *argv, **kwargs):
return
def readStreamStatus(self, *argv, **kwargs):
return
def readStreamStatus__(self, *argv, **kwargs):
return
def readStream__(self, *argv, **kwargs):
return
def readUART(self, *argv, **kwargs):
return
def releaseReadBuffer(self, *argv, **kwargs):
return
def releaseWriteBuffer(self, *argv, **kwargs):
return
def setClockSource(self, *argv, **kwargs):
return
def setCommandTime(self, *argv, **kwargs):
return
def setDCOffset(self, *argv, **kwargs):
return
def setFrequencyCorrection(self, *argv, **kwargs):
return
def setFrontendMapping(self, *argv, **kwargs):
return
def setGainMode(self, *argv, **kwargs):
return
def setIQBalance(self, *argv, **kwargs):
return
def setMasterClockRate(self, *argv, **kwargs):
return
def setTimeSource(self, *argv, **kwargs):
return
def transactSPI(self, *argv, **kwargs):
return
def unmake(self, *argv, **kwargs):
return
def writeGPIO(self, *argv, **kwargs):
return
def writeGPIODir(self, *argv, **kwargs):
return
def writeI2C(self, *argv, **kwargs):
return
def writeRegisters(self, *argv, **kwargs):
return
def writeUART(self, *argv, **kwargs):
return
| [
"numpy.random.uniform",
"numpy.abs",
"numpy.copy",
"numpy.zeros",
"numpy.clip",
"numpy.random.randint",
"numpy.arange",
"numpy.random.normal"
] | [((1954, 1988), 'numpy.clip', 'np.clip', (['a.real', '(-m)', 'm'], {'out': 'a.real'}), '(a.real, -m, m, out=a.real)\n', (1961, 1988), True, 'import numpy as np\n'), ((1993, 2027), 'numpy.clip', 'np.clip', (['a.imag', '(-m)', 'm'], {'out': 'a.imag'}), '(a.imag, -m, m, out=a.imag)\n', (2000, 2027), True, 'import numpy as np\n'), ((4715, 4792), 'numpy.zeros', 'np.zeros', (['(samps.shape[0] + self.delay + self.delay_spread)'], {'dtype': 'np.complex64'}), '(samps.shape[0] + self.delay + self.delay_spread, dtype=np.complex64)\n', (4723, 4792), True, 'import numpy as np\n'), ((4806, 4820), 'numpy.copy', 'np.copy', (['samps'], {}), '(samps)\n', (4813, 4820), True, 'import numpy as np\n'), ((8050, 8083), 'numpy.zeros', 'np.zeros', (['num'], {'dtype': 'np.complex64'}), '(num, dtype=np.complex64)\n', (8058, 8083), True, 'import numpy as np\n'), ((3398, 3433), 'numpy.random.randint', 'np.random.randint', (['(0)', '(delay_var + 1)'], {}), '(0, delay_var + 1)\n', (3415, 3433), True, 'import numpy as np\n'), ((7631, 7673), 'numpy.zeros', 'np.zeros', (['cls._bufsize'], {'dtype': 'np.complex64'}), '(cls._bufsize, dtype=np.complex64)\n', (7639, 7673), True, 'import numpy as np\n'), ((11839, 11901), 'numpy.clip', 'np.clip', (['value', 'self._TX_GAIN_RANGE[0]', 'self._TX_GAIN_RANGE[1]'], {}), '(value, self._TX_GAIN_RANGE[0], self._TX_GAIN_RANGE[1])\n', (11846, 11901), True, 'import numpy as np\n'), ((12000, 12062), 'numpy.clip', 'np.clip', (['value', 'self._RX_GAIN_RANGE[0]', 'self._RX_GAIN_RANGE[1]'], {}), '(value, self._RX_GAIN_RANGE[0], self._RX_GAIN_RANGE[1])\n', (12007, 12062), True, 'import numpy as np\n'), ((3522, 3548), 'numpy.random.normal', 'np.random.normal', ([], {'scale': 'dc'}), '(scale=dc)\n', (3538, 3548), True, 'import numpy as np\n'), ((3641, 3667), 'numpy.random.normal', 'np.random.normal', ([], {'scale': 'dc'}), '(scale=dc)\n', (3657, 3667), True, 'import numpy as np\n'), ((3776, 3808), 'numpy.random.normal', 'np.random.normal', ([], {'scale': 'iq_imbal'}), '(scale=iq_imbal)\n', (3792, 3808), True, 'import numpy as np\n'), ((3888, 3920), 'numpy.random.normal', 'np.random.normal', ([], {'scale': 'iq_imbal'}), '(scale=iq_imbal)\n', (3904, 3920), True, 'import numpy as np\n'), ((5501, 5567), 'numpy.random.normal', 'np.random.normal', ([], {'scale': '(10 ** (self.noise / 20))', 'size': 'out.shape[0]'}), '(scale=10 ** (self.noise / 20), size=out.shape[0])\n', (5517, 5567), True, 'import numpy as np\n'), ((2163, 2177), 'numpy.abs', 'np.abs', (['a.real'], {}), '(a.real)\n', (2169, 2177), True, 'import numpy as np\n'), ((2249, 2263), 'numpy.abs', 'np.abs', (['a.imag'], {}), '(a.imag)\n', (2255, 2263), True, 'import numpy as np\n'), ((3551, 3577), 'numpy.random.normal', 'np.random.normal', ([], {'scale': 'dc'}), '(scale=dc)\n', (3567, 3577), True, 'import numpy as np\n'), ((3670, 3696), 'numpy.random.normal', 'np.random.normal', ([], {'scale': 'dc'}), '(scale=dc)\n', (3686, 3696), True, 'import numpy as np\n'), ((4461, 4508), 'numpy.random.randint', 'np.random.randint', ([], {'low': 'i', 'high': '(delay_spread + 1)'}), '(low=i, high=delay_spread + 1)\n', (4478, 4508), True, 'import numpy as np\n'), ((5566, 5632), 'numpy.random.normal', 'np.random.normal', ([], {'scale': '(10 ** (self.noise / 20))', 'size': 'out.shape[0]'}), '(scale=10 ** (self.noise / 20), size=out.shape[0])\n', (5582, 5632), True, 'import numpy as np\n'), ((4158, 4190), 'numpy.random.normal', 'np.random.normal', ([], {'scale': 'attn_var'}), '(scale=attn_var)\n', (4174, 4190), True, 'import numpy as np\n'), ((4339, 4372), 'numpy.random.uniform', 'np.random.uniform', ([], {'high': '(2 * np.pi)'}), '(high=2 * np.pi)\n', (4356, 4372), True, 'import numpy as np\n'), ((5759, 5779), 'numpy.arange', 'np.arange', (['(0)', 'nsamps'], {}), '(0, nsamps)\n', (5768, 5779), True, 'import numpy as np\n')] |
import numpy as np
import tensorflow as tf
from ..utils import shape_list
def maximum_path(value, mask, max_neg_val=-np.inf):
""" Numpy-friendly version. It's about 4 times faster than torch version.
value: [b, t_x, t_y]
mask: [b, t_x, t_y]
"""
value = value * mask
dtype = value.dtype
mask = mask.astype(np.bool)
b, t_x, t_y = value.shape
direction = np.zeros(value.shape, dtype=np.int64)
v = np.zeros((b, t_x), dtype=np.float32)
x_range = np.arange(t_x, dtype=np.float32).reshape(1, -1)
for j in range(t_y):
v0 = np.pad(v, [[0, 0], [1, 0]], mode="constant", constant_values=max_neg_val)[:, :-1]
v1 = v
max_mask = (v1 >= v0)
v_max = np.where(max_mask, v1, v0)
direction[:, :, j] = max_mask
index_mask = (x_range <= j)
v = np.where(index_mask, v_max + value[:, :, j], max_neg_val)
direction = np.where(mask, direction, 1)
path = np.zeros(value.shape, dtype=np.float32)
index = mask[:, :, 0].sum(1).astype(np.int64) - 1
index_range = np.arange(b)
for j in reversed(range(t_y)):
path[index_range, index, j] = 1
index = index + direction[index_range, index, j] - 1
path = path * mask.astype(np.float32)
return path
def sequence_mask(length, max_length=None):
if max_length is None:
max_length = tf.reduce_max(length)
x = tf.range(max_length, dtype=length.dtype)
x = tf.expand_dims(x, 0)
x = tf.tile(x, (tf.shape(length)[0], 1))
ones = tf.ones_like(x)
zeros = tf.zeros_like(x)
return tf.where(x < tf.expand_dims(length, -1), ones, zeros)
def generate_path(duration, mask):
"""
duration: [b, t_x]
mask: [b, t_x, t_y]
"""
b, t_x, t_y = shape_list(mask)
cum_duration = tf.math.cumsum(duration, 1)
path = tf.zeros((b, t_x, t_y), dtype=mask.dtype)
cum_duration_flat = tf.reshape(cum_duration, (b * t_x,))
path = tf.sequence_mask(cum_duration_flat, t_y)
path = tf.cast(path, mask.dtype)
path = tf.reshape(path, (b, t_x, t_y))
path = path - tf.pad(path, [[0, 0], [1, 0], [0, 0]])[:, :-1]
path = path * mask
return path
def squeeze(x, x_mask=None, n_sqz=2):
b, t, c = shape_list(x)
t = (t // n_sqz) * n_sqz
x = x[:, :t]
x_sqz = tf.reshape(x, (b, t//n_sqz, n_sqz, c))
x_sqz = tf.reshape(x_sqz, (b, t//n_sqz, c * n_sqz))
if x_mask is not None:
x_mask = x_mask[:, n_sqz-1::n_sqz]
else:
x_mask = tf.ones((b, t // n_sqz, 1), dtype=x.dtype)
return x_sqz * x_mask, x_mask
def unsqueeze(x, x_mask=None, n_sqz=2):
b, t, c = shape_list(x)
x_unsqz = tf.reshape(x, (b, t, n_sqz, c//n_sqz))
x_unsqz = tf.reshape(x_unsqz, (b, t*n_sqz, c//n_sqz))
if x_mask is not None:
x_mask = tf.expand_dims(x_mask, 2)
x_mask = tf.tile(x_mask, (1, 1, n_sqz, 1))
x_mask = tf.reshape(x_mask, (b, t*n_sqz, 1))
else:
x_mask = tf.ones((b, t*n_sqz, 1), dtype=x.dtype)
return x_unsqz * x_mask, x_mask
| [
"numpy.pad",
"tensorflow.ones",
"tensorflow.range",
"tensorflow.reshape",
"numpy.zeros",
"tensorflow.zeros_like",
"tensorflow.reduce_max",
"tensorflow.ones_like",
"tensorflow.pad",
"tensorflow.cast",
"tensorflow.tile",
"numpy.where",
"numpy.arange",
"tensorflow.zeros",
"tensorflow.sequen... | [((392, 429), 'numpy.zeros', 'np.zeros', (['value.shape'], {'dtype': 'np.int64'}), '(value.shape, dtype=np.int64)\n', (400, 429), True, 'import numpy as np\n'), ((438, 474), 'numpy.zeros', 'np.zeros', (['(b, t_x)'], {'dtype': 'np.float32'}), '((b, t_x), dtype=np.float32)\n', (446, 474), True, 'import numpy as np\n'), ((906, 934), 'numpy.where', 'np.where', (['mask', 'direction', '(1)'], {}), '(mask, direction, 1)\n', (914, 934), True, 'import numpy as np\n'), ((947, 986), 'numpy.zeros', 'np.zeros', (['value.shape'], {'dtype': 'np.float32'}), '(value.shape, dtype=np.float32)\n', (955, 986), True, 'import numpy as np\n'), ((1059, 1071), 'numpy.arange', 'np.arange', (['b'], {}), '(b)\n', (1068, 1071), True, 'import numpy as np\n'), ((1390, 1430), 'tensorflow.range', 'tf.range', (['max_length'], {'dtype': 'length.dtype'}), '(max_length, dtype=length.dtype)\n', (1398, 1430), True, 'import tensorflow as tf\n'), ((1439, 1459), 'tensorflow.expand_dims', 'tf.expand_dims', (['x', '(0)'], {}), '(x, 0)\n', (1453, 1459), True, 'import tensorflow as tf\n'), ((1516, 1531), 'tensorflow.ones_like', 'tf.ones_like', (['x'], {}), '(x)\n', (1528, 1531), True, 'import tensorflow as tf\n'), ((1544, 1560), 'tensorflow.zeros_like', 'tf.zeros_like', (['x'], {}), '(x)\n', (1557, 1560), True, 'import tensorflow as tf\n'), ((1781, 1808), 'tensorflow.math.cumsum', 'tf.math.cumsum', (['duration', '(1)'], {}), '(duration, 1)\n', (1795, 1808), True, 'import tensorflow as tf\n'), ((1820, 1861), 'tensorflow.zeros', 'tf.zeros', (['(b, t_x, t_y)'], {'dtype': 'mask.dtype'}), '((b, t_x, t_y), dtype=mask.dtype)\n', (1828, 1861), True, 'import tensorflow as tf\n'), ((1886, 1922), 'tensorflow.reshape', 'tf.reshape', (['cum_duration', '(b * t_x,)'], {}), '(cum_duration, (b * t_x,))\n', (1896, 1922), True, 'import tensorflow as tf\n'), ((1934, 1974), 'tensorflow.sequence_mask', 'tf.sequence_mask', (['cum_duration_flat', 't_y'], {}), '(cum_duration_flat, t_y)\n', (1950, 1974), True, 'import tensorflow as tf\n'), ((1986, 2011), 'tensorflow.cast', 'tf.cast', (['path', 'mask.dtype'], {}), '(path, mask.dtype)\n', (1993, 2011), True, 'import tensorflow as tf\n'), ((2023, 2054), 'tensorflow.reshape', 'tf.reshape', (['path', '(b, t_x, t_y)'], {}), '(path, (b, t_x, t_y))\n', (2033, 2054), True, 'import tensorflow as tf\n'), ((2285, 2325), 'tensorflow.reshape', 'tf.reshape', (['x', '(b, t // n_sqz, n_sqz, c)'], {}), '(x, (b, t // n_sqz, n_sqz, c))\n', (2295, 2325), True, 'import tensorflow as tf\n'), ((2336, 2381), 'tensorflow.reshape', 'tf.reshape', (['x_sqz', '(b, t // n_sqz, c * n_sqz)'], {}), '(x_sqz, (b, t // n_sqz, c * n_sqz))\n', (2346, 2381), True, 'import tensorflow as tf\n'), ((2639, 2679), 'tensorflow.reshape', 'tf.reshape', (['x', '(b, t, n_sqz, c // n_sqz)'], {}), '(x, (b, t, n_sqz, c // n_sqz))\n', (2649, 2679), True, 'import tensorflow as tf\n'), ((2692, 2739), 'tensorflow.reshape', 'tf.reshape', (['x_unsqz', '(b, t * n_sqz, c // n_sqz)'], {}), '(x_unsqz, (b, t * n_sqz, c // n_sqz))\n', (2702, 2739), True, 'import tensorflow as tf\n'), ((718, 744), 'numpy.where', 'np.where', (['max_mask', 'v1', 'v0'], {}), '(max_mask, v1, v0)\n', (726, 744), True, 'import numpy as np\n'), ((832, 889), 'numpy.where', 'np.where', (['index_mask', '(v_max + value[:, :, j])', 'max_neg_val'], {}), '(index_mask, v_max + value[:, :, j], max_neg_val)\n', (840, 889), True, 'import numpy as np\n'), ((1360, 1381), 'tensorflow.reduce_max', 'tf.reduce_max', (['length'], {}), '(length)\n', (1373, 1381), True, 'import tensorflow as tf\n'), ((2477, 2519), 'tensorflow.ones', 'tf.ones', (['(b, t // n_sqz, 1)'], {'dtype': 'x.dtype'}), '((b, t // n_sqz, 1), dtype=x.dtype)\n', (2484, 2519), True, 'import tensorflow as tf\n'), ((2781, 2806), 'tensorflow.expand_dims', 'tf.expand_dims', (['x_mask', '(2)'], {}), '(x_mask, 2)\n', (2795, 2806), True, 'import tensorflow as tf\n'), ((2824, 2857), 'tensorflow.tile', 'tf.tile', (['x_mask', '(1, 1, n_sqz, 1)'], {}), '(x_mask, (1, 1, n_sqz, 1))\n', (2831, 2857), True, 'import tensorflow as tf\n'), ((2875, 2912), 'tensorflow.reshape', 'tf.reshape', (['x_mask', '(b, t * n_sqz, 1)'], {}), '(x_mask, (b, t * n_sqz, 1))\n', (2885, 2912), True, 'import tensorflow as tf\n'), ((2938, 2979), 'tensorflow.ones', 'tf.ones', (['(b, t * n_sqz, 1)'], {'dtype': 'x.dtype'}), '((b, t * n_sqz, 1), dtype=x.dtype)\n', (2945, 2979), True, 'import tensorflow as tf\n'), ((489, 521), 'numpy.arange', 'np.arange', (['t_x'], {'dtype': 'np.float32'}), '(t_x, dtype=np.float32)\n', (498, 521), True, 'import numpy as np\n'), ((575, 648), 'numpy.pad', 'np.pad', (['v', '[[0, 0], [1, 0]]'], {'mode': '"""constant"""', 'constant_values': 'max_neg_val'}), "(v, [[0, 0], [1, 0]], mode='constant', constant_values=max_neg_val)\n", (581, 648), True, 'import numpy as np\n'), ((1585, 1611), 'tensorflow.expand_dims', 'tf.expand_dims', (['length', '(-1)'], {}), '(length, -1)\n', (1599, 1611), True, 'import tensorflow as tf\n'), ((2073, 2111), 'tensorflow.pad', 'tf.pad', (['path', '[[0, 0], [1, 0], [0, 0]]'], {}), '(path, [[0, 0], [1, 0], [0, 0]])\n', (2079, 2111), True, 'import tensorflow as tf\n'), ((1480, 1496), 'tensorflow.shape', 'tf.shape', (['length'], {}), '(length)\n', (1488, 1496), True, 'import tensorflow as tf\n')] |
# Copyright (c) xiaoxuan : https://github.com/shawnau/kaggle-HPA
# modified by sailfish009
import sys
sys.path.append('../')
import os
import math
import operator
from functools import reduce
from collections import Counter
import numpy as np
import pandas as pd
from .ml_stratifiers import MultilabelStratifiedShuffleSplit
def combine_dataset(root, a_csv, b_csv):
df_train = pd.read_csv(os.path.join(root, a_csv))
df_external = pd.read_csv(os.path.join(root, b_csv))
df_combined = pd.concat([df_train, df_external])
df_combined.reset_index(drop=True, inplace=True)
print("train: %d, external: %d, combined: %d" % (len(df_train), len(df_external), len(df_combined)))
df_combined['target_vec'] = df_combined['Target'].apply(str2vec)
return df_combined
def str2vec(s):
tags = list(map(int, s.split(' ')))
vec = np.zeros(28)
vec[tags] = 1
return vec.tolist()
def train_valid_split(df, n_splits=4) -> ([pd.DataFrame], [pd.DataFrame]):
df_backup = df.copy()
X = df['Id'].tolist()
y = df['target_vec'].tolist()
msss = MultilabelStratifiedShuffleSplit(n_splits=n_splits, test_size=0.1, random_state=42)
train_dfs, valid_dfs = [], []
for train_index, valid_index in msss.split(X,y):
train_df = df_backup.iloc[train_index]
train_dfs.append(train_df[['Id', 'Target']])
valid_df = df_backup.iloc[valid_index]
valid_dfs.append(valid_df[['Id', 'Target']])
return train_dfs, valid_dfs
def count_distrib(df):
tag_list = df['Target'].tolist()
tag_list = reduce(operator.add, map(lambda x: list(map(int, x.split(' '))), tag_list))
return Counter(tag_list)
def create_class_weight(root, labels_dict, mu=0.5):
"""
this is for calculating weighted BCE loss only
:param labels_dict:
:param mu:
:return:
"""
total = sum(labels_dict.values())
keys = labels_dict.keys()
class_weight = dict()
class_weight_log = dict()
for key in keys:
score = total / float(labels_dict[key])
score_log = math.log(mu * total / float(labels_dict[key]))
class_weight[key] = round(score, 2) if score > 1.0 else round(1.0, 2)
class_weight_log[key] = round(score_log, 2) if score_log > 1.0 else round(1.0, 2)
class_weight_vec = np.zeros(len(class_weight))
class_weight_log_vec = np.zeros(len(class_weight))
for k in class_weight:
class_weight_vec[k] = class_weight[k]
for k in class_weight_log:
class_weight_log_vec[k] = class_weight_log[k]
return class_weight_vec, class_weight_log_vec
def create_sample_weight(root, df, save_name, mu=1.0):
"""
assign sample weights for each sample. rare sample have higher weights(linearly)
refer to
:param df:
:param save_name:
:param mu:
:return:
"""
label_list = df['Target'].tolist()
import pickle
import operator
from functools import reduce
from collections import Counter
freq_count = dict(Counter(
reduce(operator.add,
map(lambda x: list(map(int, x.split(' '))),
label_list
)
)
))
total = sum(freq_count.values())
keys = freq_count.keys()
assert sorted(list(keys)) == list(range(len(keys)))
class_weight = dict()
class_weight_log = dict()
for key in range(len(keys)):
score = total / float(freq_count[key])
score_log = math.log(mu * total / float(freq_count[key]))
class_weight[key] = round(score, 2) if score > 1.0 else round(1.0, 2)
class_weight_log[key] = round(score_log, 2) if score_log > 1.0 else round(1.0, 2)
rareness = [x[0] for x in sorted(freq_count.items(), key=operator.itemgetter(1))]
weights = []
sample_labels = list(map(lambda x: list(map(int, x.split(' '))), label_list))
for labels in sample_labels:
for rare_label in rareness:
if rare_label in labels:
weights.append(class_weight[rare_label])
break
assert len(weights) == len(label_list)
save_path = os.path.join(root, save_name)
with open(save_path, 'wb') as f:
pickle.dump(weights, f)
print("%d weights saved into %s" % (len(label_list), save_path))
def calc_statistics(cfg, loader='train'):
"""
calculate mean and std for data sets
please close normalize in dataset's transform manually
:return:
"""
from .data import make_data_loader
if loader == 'train':
data_loader = make_data_loader(cfg, cfg.DATASETS.TRAIN, is_train=True)
elif loader == 'valid':
data_loader = make_data_loader(cfg, cfg.DATASETS.VALID, is_train=False)
elif loader == 'test':
data_loader = make_data_loader(cfg, cfg.DATASETS.TEST, is_train=False)
else:
raise KeyError('loader must be specified')
mean = 0.
std = 0.
nb_samples = 0.
for iteration, (images, targets, indices) in enumerate(data_loader):
batch_size = images.size(0)
images = images.view(batch_size, images.size(1), -1)
mean += images.mean(2).sum(0)
std += images.std(2).sum(0)
nb_samples += batch_size
running_mean = mean / nb_samples
running_std = std / nb_samples
print("iter %d running mean: " % iteration, running_mean)
print("iter %d running std : " % iteration, running_std)
# if __name__ == "__main__":
# df_combined = combine_dataset("kaggle/")
# train_dfs, valid_dfs = train_test_split(df_combined, 4)
# for i in range(4):
# train_df = train_dfs[i]
# train_df.to_csv("train_split_%d.csv"%i, index=False)
# valid_df = valid_dfs[i]
# valid_df.to_csv("valid_split_%d.csv"%i, index=False)
#
# create_sample_weight(train_df, "train_split_%d_weights.pickle"%i)
# class_weight_vec, class_weight_log_vec = create_class_weight(dict(count_distrib(df_combined)), mu=0.5)
| [
"sys.path.append",
"pickle.dump",
"numpy.zeros",
"collections.Counter",
"operator.itemgetter",
"os.path.join",
"pandas.concat"
] | [((103, 125), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (118, 125), False, 'import sys\n'), ((498, 532), 'pandas.concat', 'pd.concat', (['[df_train, df_external]'], {}), '([df_train, df_external])\n', (507, 532), True, 'import pandas as pd\n'), ((851, 863), 'numpy.zeros', 'np.zeros', (['(28)'], {}), '(28)\n', (859, 863), True, 'import numpy as np\n'), ((1647, 1664), 'collections.Counter', 'Counter', (['tag_list'], {}), '(tag_list)\n', (1654, 1664), False, 'from collections import Counter\n'), ((4087, 4116), 'os.path.join', 'os.path.join', (['root', 'save_name'], {}), '(root, save_name)\n', (4099, 4116), False, 'import os\n'), ((396, 421), 'os.path.join', 'os.path.join', (['root', 'a_csv'], {}), '(root, a_csv)\n', (408, 421), False, 'import os\n'), ((453, 478), 'os.path.join', 'os.path.join', (['root', 'b_csv'], {}), '(root, b_csv)\n', (465, 478), False, 'import os\n'), ((4163, 4186), 'pickle.dump', 'pickle.dump', (['weights', 'f'], {}), '(weights, f)\n', (4174, 4186), False, 'import pickle\n'), ((3717, 3739), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (3736, 3739), False, 'import operator\n')] |
import numpy as np
from timer import Timer
def sparsify(M, n):
# sparsify
for i in range(n):
print('sparsify ({})'.format(i))
S = np.random.randint(0, high=2, size=M.shape, dtype=np.uint8)
M = np.multiply(M, S)
return M
def make_matrix(C, G, spars=0):
"""
TODO: IMPLEMENT: import the data matrix
M[C,G] = 0 or 1
"""
# C = n_candid = 15
# G = n_item = 9
# M = np.zeros((C, G), dtype=np.uint8)
# OR, faster and not so safe:
# M = np.empty((C, G), dtype=np.uint8)
# TODO: read the values of M ...
# DEBUG: random init (zero or one)
M = np.random.randint(0, high=2, size=(C, G), dtype=np.uint8)
M = sparsify(M, spars)
# save M for inspection, debug
# N = np.copy(M)
# ~ DEBUG
return M
def test(sc, M, n_thread=8, col_sum_dtype=np.float32):
with Timer() as t:
x = sc.run(M, n_thread, col_sum_dtype)
print('time: {}'.format(t.interval))
return x
| [
"numpy.random.randint",
"numpy.multiply",
"timer.Timer"
] | [((623, 680), 'numpy.random.randint', 'np.random.randint', (['(0)'], {'high': '(2)', 'size': '(C, G)', 'dtype': 'np.uint8'}), '(0, high=2, size=(C, G), dtype=np.uint8)\n', (640, 680), True, 'import numpy as np\n'), ((157, 215), 'numpy.random.randint', 'np.random.randint', (['(0)'], {'high': '(2)', 'size': 'M.shape', 'dtype': 'np.uint8'}), '(0, high=2, size=M.shape, dtype=np.uint8)\n', (174, 215), True, 'import numpy as np\n'), ((228, 245), 'numpy.multiply', 'np.multiply', (['M', 'S'], {}), '(M, S)\n', (239, 245), True, 'import numpy as np\n'), ((858, 865), 'timer.Timer', 'Timer', ([], {}), '()\n', (863, 865), False, 'from timer import Timer\n')] |
"""Train Glow on CIFAR-10.
Train script adapted from: https://github.com/kuangliu/pytorch-cifar/
"""
import argparse
import numpy as np
import os
import random
import torch
import torch.optim as optim
import torch.optim.lr_scheduler as sched
import torch.backends.cudnn as cudnn
import torch.utils.data as data
import torchvision
import torchvision.transforms as transforms
import util
from data_loader import get_loader
from models import Glow
from tqdm import tqdm
import pdb
parser = argparse.ArgumentParser(description='Glow on CIFAR-10')
def str2bool(s):
return s.lower().startswith('t')
parser.add_argument('--mode', type=str, choices=['train', 'test'])
# Model
parser.add_argument('--model', type=str, default='glow', choices=['glow'])
parser.add_argument('--in-channels', type=int, required=True, help='Number of channels in input layer')
parser.add_argument('--mid-channels', default=512, type=int, help='Number of channels in hidden layers')
parser.add_argument('--num-levels', '-L', default=3, type=int, help='Number of levels in the Glow model')
parser.add_argument('--num-steps', '-K', default=32, type=int, help='Number of steps of flow in each level')
parser.add_argument('--layer-type', type=str, choices=['conv', 'fc'])
# Training
parser.add_argument('--batch-size', default=64, type=int, help='Batch size per GPU')
parser.add_argument('--benchmark', type=str2bool, default=True, help='Turn on CUDNN benchmarking')
parser.add_argument('--optim', type=str, default='SGD')
parser.add_argument('--lr', default=1e-3, type=float, help='Learning rate.')
parser.add_argument('--wd', default=1e-5, type=float, help="Weight decay.")
parser.add_argument('--use-val', type=int, help="Whether to use a val set during training.")
parser.add_argument('--max_grad_norm', type=float, default=-1., help='Max gradient norm for clipping')
parser.add_argument('--num_epochs', default=100, type=int, help='Number of epochs to train')
parser.add_argument('--num_samples', default=64, type=int, help='Number of samples at test time')
# Data
parser.add_argument('--dataset', type=str, choices=['cifar10', '2Dline', '16Dline'])
parser.add_argument('--fdata', type=str, help="Path to data file.")
# Misc
parser.add_argument('--gpu_ids', default=[0], type=eval, help='IDs of GPUs to use')
parser.add_argument('--num_workers', default=8, type=int, help='Number of data loader threads')
parser.add_argument('--resume', type=str2bool, default=False, help='Resume from checkpoint')
parser.add_argument('--seed', type=int, default=0, help='Random seed for reproducibility')
parser.add_argument('--warm_up', default=500000, type=int, help='Number of steps for lr warm-up')
# wandb
parser.add_argument('--project', type=str)
parser.add_argument('--wb-name', type=str)
args = parser.parse_args()
import wandb
wandb.init(project=args.project, name=args.wb_name, config=args)
def main():
# Set up main device and scale batch size
device = 'cuda' if torch.cuda.is_available() and args.gpu_ids else 'cpu'
args.batch_size *= max(1, len(args.gpu_ids))
# Set random seeds
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
torch.cuda.manual_seed_all(args.seed)
# Model
print('Building model..')
net = Glow(in_channels=args.in_channels,
mid_channels=args.mid_channels,
num_levels=args.num_levels,
num_steps=args.num_steps,
layer_type=args.layer_type)
net = net.to(device)
print('Model built.')
if device == 'cuda':
net = torch.nn.DataParallel(net, args.gpu_ids)
cudnn.benchmark = args.benchmark
# Train / Test loop
if args.mode == 'train':
trainloader, testloader = get_loader(args, is_train=True)
start_epoch = 0
if args.resume:
# Load checkpoint.
print('Resuming from checkpoint at ckpts/best.pth.tar...')
assert os.path.isdir('ckpts'), 'Error: no checkpoint directory found!'
checkpoint = torch.load('ckpts/best.pth.tar')
net.load_state_dict(checkpoint['net'])
global best_loss
global global_step
best_loss = checkpoint['test_loss']
start_epoch = checkpoint['epoch']
global_step = start_epoch * len(trainset)
loss_fn = util.NLLLoss().to(device)
if args.optim == 'Adam':
optimizer = optim.Adam(net.parameters(), lr=args.lr)
elif args.optim == 'SGD':
optimizer = optim.SGD(net.parameters(), lr=args.lr, weight_decay=args.wd)
scheduler = sched.LambdaLR(optimizer, lambda s: min(1., s / args.warm_up))
for epoch in range(start_epoch, start_epoch + args.num_epochs):
train(epoch, net, trainloader, device, optimizer, scheduler,
loss_fn, args.max_grad_norm)
test(epoch, net, testloader, device, loss_fn, args.num_samples, args.layer_type, args.in_channels)
elif args.mode == 'test':
testloader = get_loader(args, is_train=False)
@torch.enable_grad()
def train(epoch, net, trainloader, device, optimizer, scheduler, loss_fn, max_grad_norm):
global global_step
print('\nEpoch: %d' % epoch)
net.train()
loss_meter = util.AverageMeter()
with tqdm(total=len(trainloader.dataset)) as progress_bar:
for bi, x in enumerate(trainloader):
if type(x) is tuple or type(x) is list:
x = x[0]
x = x.type(torch.FloatTensor).to(device)
optimizer.zero_grad()
# pdb.set_trace()
z, sldj = net(x, reverse=False)
loss = loss_fn(z, sldj)
loss_meter.update(loss.item(), x.size(0))
loss.backward()
if max_grad_norm > 0:
util.clip_grad_norm(optimizer, max_grad_norm)
optimizer.step()
scheduler.step(global_step)
progress_bar.set_postfix(nll=loss_meter.avg,
bpd=util.bits_per_dim(x, loss_meter.avg),
lr=optimizer.param_groups[0]['lr'])
progress_bar.update(x.size(0))
global_step += x.size(0)
if bi % 500 == 0:
wandb.log({
'loss': loss,
})
@torch.no_grad()
def sample(net, layer_type, batch_size, device, in_channels=16):
"""Sample from RealNVP model.
Args:
net (torch.nn.DataParallel): The RealNVP model wrapped in DataParallel.
batch_size (int): Number of samples to generate.
device (torch.device): Device to use.
"""
if layer_type == 'conv':
z = torch.randn((batch_size, 3, 32, 32), dtype=torch.float32, device=device)
elif layer_type == 'fc':
z = torch.randn((batch_size, in_channels), dtype=torch.float32, device=device)
x, _ = net(z, reverse=True)
x = torch.sigmoid(x)
return x
@torch.no_grad()
def test(epoch, net, testloader, device, loss_fn, num_samples, layer_type, in_channels=16):
global best_loss
net.eval()
loss_meter = util.AverageMeter()
with tqdm(total=len(testloader.dataset)) as progress_bar:
for x in testloader:
if type(x) is tuple or type(x) is list:
x = x[0]
x = x.type(torch.FloatTensor).to(device)
z, sldj = net(x, reverse=False)
loss = loss_fn(z, sldj)
loss_meter.update(loss.item(), x.size(0))
progress_bar.set_postfix(nll=loss_meter.avg,
bpd=util.bits_per_dim(x, loss_meter.avg))
progress_bar.update(x.size(0))
# Save checkpoint
if loss_meter.avg < best_loss:
print('Saving...')
state = {
'net': net.state_dict(),
'test_loss': loss_meter.avg,
'epoch': epoch,
}
os.makedirs('ckpts', exist_ok=True)
torch.save(state, 'ckpts/best.pth.tar')
best_loss = loss_meter.avg
# Save samples and data
images = sample(net, layer_type, num_samples, device, in_channels)
os.makedirs(os.path.join('samples', args.dataset), exist_ok=True)
images_concat = torchvision.utils.make_grid(images, nrow=int(num_samples ** 0.5), padding=2, pad_value=255)
torchvision.utils.save_image(images_concat, 'samples/epoch_{}.png'.format(epoch))
if __name__ == '__main__':
best_loss = 0
global_step = 0
main()
| [
"wandb.log",
"numpy.random.seed",
"argparse.ArgumentParser",
"torch.randn",
"util.clip_grad_norm",
"util.AverageMeter",
"torch.no_grad",
"os.path.join",
"torch.load",
"util.NLLLoss",
"random.seed",
"util.bits_per_dim",
"torch.manual_seed",
"torch.cuda.is_available",
"torch.enable_grad",
... | [((491, 546), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Glow on CIFAR-10"""'}), "(description='Glow on CIFAR-10')\n", (514, 546), False, 'import argparse\n'), ((2803, 2867), 'wandb.init', 'wandb.init', ([], {'project': 'args.project', 'name': 'args.wb_name', 'config': 'args'}), '(project=args.project, name=args.wb_name, config=args)\n', (2813, 2867), False, 'import wandb\n'), ((5007, 5026), 'torch.enable_grad', 'torch.enable_grad', ([], {}), '()\n', (5024, 5026), False, 'import torch\n'), ((6104, 6119), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6117, 6119), False, 'import torch\n'), ((6695, 6710), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6708, 6710), False, 'import torch\n'), ((3081, 3103), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (3092, 3103), False, 'import random\n'), ((3108, 3133), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (3122, 3133), True, 'import numpy as np\n'), ((3138, 3166), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (3155, 3166), False, 'import torch\n'), ((3171, 3208), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['args.seed'], {}), '(args.seed)\n', (3197, 3208), False, 'import torch\n'), ((3266, 3423), 'models.Glow', 'Glow', ([], {'in_channels': 'args.in_channels', 'mid_channels': 'args.mid_channels', 'num_levels': 'args.num_levels', 'num_steps': 'args.num_steps', 'layer_type': 'args.layer_type'}), '(in_channels=args.in_channels, mid_channels=args.mid_channels,\n num_levels=args.num_levels, num_steps=args.num_steps, layer_type=args.\n layer_type)\n', (3270, 3423), False, 'from models import Glow\n'), ((5198, 5217), 'util.AverageMeter', 'util.AverageMeter', ([], {}), '()\n', (5215, 5217), False, 'import util\n'), ((6663, 6679), 'torch.sigmoid', 'torch.sigmoid', (['x'], {}), '(x)\n', (6676, 6679), False, 'import torch\n'), ((6850, 6869), 'util.AverageMeter', 'util.AverageMeter', ([], {}), '()\n', (6867, 6869), False, 'import util\n'), ((3565, 3605), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['net', 'args.gpu_ids'], {}), '(net, args.gpu_ids)\n', (3586, 3605), False, 'import torch\n'), ((3733, 3764), 'data_loader.get_loader', 'get_loader', (['args'], {'is_train': '(True)'}), '(args, is_train=True)\n', (3743, 3764), False, 'from data_loader import get_loader\n'), ((6444, 6516), 'torch.randn', 'torch.randn', (['(batch_size, 3, 32, 32)'], {'dtype': 'torch.float32', 'device': 'device'}), '((batch_size, 3, 32, 32), dtype=torch.float32, device=device)\n', (6455, 6516), False, 'import torch\n'), ((7551, 7586), 'os.makedirs', 'os.makedirs', (['"""ckpts"""'], {'exist_ok': '(True)'}), "('ckpts', exist_ok=True)\n", (7562, 7586), False, 'import os\n'), ((7593, 7632), 'torch.save', 'torch.save', (['state', '"""ckpts/best.pth.tar"""'], {}), "(state, 'ckpts/best.pth.tar')\n", (7603, 7632), False, 'import torch\n'), ((7776, 7813), 'os.path.join', 'os.path.join', (['"""samples"""', 'args.dataset'], {}), "('samples', args.dataset)\n", (7788, 7813), False, 'import os\n'), ((2950, 2975), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2973, 2975), False, 'import torch\n'), ((3924, 3946), 'os.path.isdir', 'os.path.isdir', (['"""ckpts"""'], {}), "('ckpts')\n", (3937, 3946), False, 'import os\n'), ((4011, 4043), 'torch.load', 'torch.load', (['"""ckpts/best.pth.tar"""'], {}), "('ckpts/best.pth.tar')\n", (4021, 4043), False, 'import torch\n'), ((4971, 5003), 'data_loader.get_loader', 'get_loader', (['args'], {'is_train': '(False)'}), '(args, is_train=False)\n', (4981, 5003), False, 'from data_loader import get_loader\n'), ((6552, 6626), 'torch.randn', 'torch.randn', (['(batch_size, in_channels)'], {'dtype': 'torch.float32', 'device': 'device'}), '((batch_size, in_channels), dtype=torch.float32, device=device)\n', (6563, 6626), False, 'import torch\n'), ((4310, 4324), 'util.NLLLoss', 'util.NLLLoss', ([], {}), '()\n', (4322, 4324), False, 'import util\n'), ((5658, 5703), 'util.clip_grad_norm', 'util.clip_grad_norm', (['optimizer', 'max_grad_norm'], {}), '(optimizer, max_grad_norm)\n', (5677, 5703), False, 'import util\n'), ((6054, 6079), 'wandb.log', 'wandb.log', (["{'loss': loss}"], {}), "({'loss': loss})\n", (6063, 6079), False, 'import wandb\n'), ((5848, 5884), 'util.bits_per_dim', 'util.bits_per_dim', (['x', 'loss_meter.avg'], {}), '(x, loss_meter.avg)\n', (5865, 5884), False, 'import util\n'), ((7267, 7303), 'util.bits_per_dim', 'util.bits_per_dim', (['x', 'loss_meter.avg'], {}), '(x, loss_meter.avg)\n', (7284, 7303), False, 'import util\n')] |
import numpy as np
import circlehough.hough_transformation as ht
import math
def test_apply_triangular_evaluation():
ring_radius = 5
r_point = 4.5
amplitude = 1
hough_epsilon = 1
result_value = ht.py_apply_triangular_evaluation(
r_point, hough_epsilon, ring_radius, amplitude)
assert result_value == 0.5
def test_calculate_point_distance():
ring_cx = 0
ring_cy = 0
point_x = 0
point_y = 1
r_point = ht.py_calculate_point_distance(
ring_cx, ring_cy, point_x, point_y)
assert r_point == 1
def test_sum_point_contributions():
point_positions = np.array([
[1, 0], [0, 1], [0.5, 0], [0, 0.5],
[1.5, 0], [0, 1.5], [2, 0], [0, 2],
[2.5, 0], [0, 2.5], [3, 0], [0, 3]
], dtype=np.float32)
cx = np.float32(0)
cy = np.float32(0)
r = np.float32(2)
hough_epsilon = 1.
total_amplitude = ht.py_sum_point_contributions(
point_positions, cx, cy, r, hough_epsilon)
assert total_amplitude == 4
def test_hough_transform_ring():
point_positions = np.array([
[2, 0], [0, 2], [-2, 0], [0, -2],
[math.sqrt(2), math.sqrt(2)], [math.sqrt(2), -math.sqrt(2)],
[-math.sqrt(2), math.sqrt(2)], [-math.sqrt(2), -math.sqrt(2)]
], dtype=np.float32)
cx_bin_centers = np.array(list(range(-3, 4)), dtype=np.float32)
cy_bin_centers = np.array(list(range(-3, 4)), dtype=np.float32)
r_bin_centers = np.array(list(range(5)), dtype=np.float32)
hough_epsilon = 1
houghSpace = ht.hough_transform_ring(
point_positions,
cx_bin_centers,
cy_bin_centers,
r_bin_centers,
hough_epsilon
)
indices_of_maximum_value = np.unravel_index(
np.argmax(houghSpace), dims=houghSpace.shape)
assert indices_of_maximum_value == (3, 3, 2) | [
"math.sqrt",
"numpy.argmax",
"numpy.float32",
"circlehough.hough_transformation.hough_transform_ring",
"circlehough.hough_transformation.py_calculate_point_distance",
"circlehough.hough_transformation.py_sum_point_contributions",
"numpy.array",
"circlehough.hough_transformation.py_apply_triangular_eva... | [((215, 300), 'circlehough.hough_transformation.py_apply_triangular_evaluation', 'ht.py_apply_triangular_evaluation', (['r_point', 'hough_epsilon', 'ring_radius', 'amplitude'], {}), '(r_point, hough_epsilon, ring_radius,\n amplitude)\n', (248, 300), True, 'import circlehough.hough_transformation as ht\n'), ((454, 520), 'circlehough.hough_transformation.py_calculate_point_distance', 'ht.py_calculate_point_distance', (['ring_cx', 'ring_cy', 'point_x', 'point_y'], {}), '(ring_cx, ring_cy, point_x, point_y)\n', (484, 520), True, 'import circlehough.hough_transformation as ht\n'), ((614, 755), 'numpy.array', 'np.array', (['[[1, 0], [0, 1], [0.5, 0], [0, 0.5], [1.5, 0], [0, 1.5], [2, 0], [0, 2], [\n 2.5, 0], [0, 2.5], [3, 0], [0, 3]]'], {'dtype': 'np.float32'}), '([[1, 0], [0, 1], [0.5, 0], [0, 0.5], [1.5, 0], [0, 1.5], [2, 0], [\n 0, 2], [2.5, 0], [0, 2.5], [3, 0], [0, 3]], dtype=np.float32)\n', (622, 755), True, 'import numpy as np\n'), ((790, 803), 'numpy.float32', 'np.float32', (['(0)'], {}), '(0)\n', (800, 803), True, 'import numpy as np\n'), ((813, 826), 'numpy.float32', 'np.float32', (['(0)'], {}), '(0)\n', (823, 826), True, 'import numpy as np\n'), ((835, 848), 'numpy.float32', 'np.float32', (['(2)'], {}), '(2)\n', (845, 848), True, 'import numpy as np\n'), ((894, 966), 'circlehough.hough_transformation.py_sum_point_contributions', 'ht.py_sum_point_contributions', (['point_positions', 'cx', 'cy', 'r', 'hough_epsilon'], {}), '(point_positions, cx, cy, r, hough_epsilon)\n', (923, 966), True, 'import circlehough.hough_transformation as ht\n'), ((1520, 1626), 'circlehough.hough_transformation.hough_transform_ring', 'ht.hough_transform_ring', (['point_positions', 'cx_bin_centers', 'cy_bin_centers', 'r_bin_centers', 'hough_epsilon'], {}), '(point_positions, cx_bin_centers, cy_bin_centers,\n r_bin_centers, hough_epsilon)\n', (1543, 1626), True, 'import circlehough.hough_transformation as ht\n'), ((1726, 1747), 'numpy.argmax', 'np.argmax', (['houghSpace'], {}), '(houghSpace)\n', (1735, 1747), True, 'import numpy as np\n'), ((1127, 1139), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (1136, 1139), False, 'import math\n'), ((1141, 1153), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (1150, 1153), False, 'import math\n'), ((1157, 1169), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (1166, 1169), False, 'import math\n'), ((1211, 1223), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (1220, 1223), False, 'import math\n'), ((1172, 1184), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (1181, 1184), False, 'import math\n'), ((1197, 1209), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (1206, 1209), False, 'import math\n'), ((1228, 1240), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (1237, 1240), False, 'import math\n'), ((1243, 1255), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (1252, 1255), False, 'import math\n')] |
#!/usr/bin/env python
from __future__ import division
import numpy as np
import pytest
from chanjo._compat import text_type
from chanjo.utils import (
average,
_RawInterval,
bed_to_interval,
completeness,
id_generator,
BaseInterval,
serialize_interval,
validate_bed_format
)
def test_RawInterval():
"""Test generating a base :class:`_RawInterval`."""
interval = (
'chr1', 10, 20, 'int1', 0, '-', ['block1'], ['superblock1'], 12.3, .93
)
bed_interval = _RawInterval(*interval)
assert bed_interval == interval
assert bed_interval.start == 10
assert bed_interval.contig == 'chr1'
assert bed_interval.block_ids == ['block1']
assert bed_interval.completeness == .93
def test_BaseInterval():
"""Test generating an interval without all fields filled in."""
interval = ('chr1', 10, 20, 'int1')
bed_interval = BaseInterval(*interval)
assert bed_interval != interval
assert bed_interval.start == 10
assert bed_interval.contig == 'chr1'
assert bed_interval.score == ''
assert bed_interval.name == 'int1'
assert bed_interval.block_ids == []
def test_bed_to_interval():
"""Test converting between BED interval and Chanjo interval."""
bed_interval = ('22', '101', '220', 'int32', 0, '+', 'block11')
chanjo_interval = bed_to_interval(*bed_interval)
assert chanjo_interval.contig == '22'
# BED specifies 0:1 intervals, Chanjo works with 1:1 mapping
assert chanjo_interval.start == 102
assert chanjo_interval.end == 220
assert chanjo_interval.block_ids == ['block11']
assert chanjo_interval.superblock_ids == []
with pytest.raises(ValueError):
# interval with invalid coordinates/arguments
bed_to_interval(20, 'X', 24, 'int2', 0, '-')
def test_average():
"""Test calculating average of a list of values."""
values = [0, 5, 5, 6]
# 'without' numpy
assert average(values) == 4.
# with numpy array
assert average(np.array(values)) == 4.
def test_completeness():
"""Test calculating completeness of a list of read depths."""
# test simple case
assert completeness(np.array([0, 10, 10, 20, 10, 0])) == 4/6
# test edge case with 0 positions, should *not* raise
# ``ZeroDivisionError``.
assert completeness(np.array([])) == 0.
# test with a different ``threshold``
assert completeness(np.array([20, 40, 10, 0, 10]), threshold=30) == 1/5
def test_serialize_interval():
"""Test serializing an BaseInterval instance."""
# simple case, should remove empty fields to the right
interval = BaseInterval('chr1', 10, 20)
assert serialize_interval(interval) == 'chr1\t10\t20'
# test convertion to BED format
interval = BaseInterval('chr1', 123, 123, 'int1')
assert serialize_interval(interval, bed=True) == 'chr1\t122\t123\tint1'
# with block ids, should maintain empty intermediate fields!
interval = BaseInterval('chr22', 101, 200, block_ids=['block11', 'block12'])
serialized_interval = 'chr22\t101\t200\t\t\t\tblock11,block12'
assert serialize_interval(interval) == serialized_interval
# test curried function composition
serialize_interval_alt = serialize_interval(delimiter='|', subdelimiter=';')
serialized_interval_alt = 'chr22|101|200||||block11;block12'
assert serialize_interval_alt(interval) == serialized_interval_alt
def test_id_generator():
"""Test generating a random id."""
# difficult to test randomly generated strings...
assert len(id_generator()) == 8
assert isinstance(id_generator(), text_type)
# test with custom sized id
assert len(id_generator(3)) == 3
# test edge case with 0 lenght
assert id_generator(0) == ''
def test_validate_bed_format():
"""Test validating BED format"""
# test proper formatting
assert validate_bed_format('1\t23\t45\tinterval1'.split('\t')) == True
# test bad formatting
with pytest.raises(AssertionError):
assert validate_bed_format('1 23 45 interval1'.split('\t'))
# test missing fields
with pytest.raises(AssertionError):
validate_bed_format('1\t23'.split('\t'))
| [
"chanjo.utils.BaseInterval",
"chanjo.utils._RawInterval",
"pytest.raises",
"chanjo.utils.average",
"numpy.array",
"chanjo.utils.id_generator",
"chanjo.utils.serialize_interval",
"chanjo.utils.bed_to_interval"
] | [((484, 507), 'chanjo.utils._RawInterval', '_RawInterval', (['*interval'], {}), '(*interval)\n', (496, 507), False, 'from chanjo.utils import average, _RawInterval, bed_to_interval, completeness, id_generator, BaseInterval, serialize_interval, validate_bed_format\n'), ((852, 875), 'chanjo.utils.BaseInterval', 'BaseInterval', (['*interval'], {}), '(*interval)\n', (864, 875), False, 'from chanjo.utils import average, _RawInterval, bed_to_interval, completeness, id_generator, BaseInterval, serialize_interval, validate_bed_format\n'), ((1275, 1305), 'chanjo.utils.bed_to_interval', 'bed_to_interval', (['*bed_interval'], {}), '(*bed_interval)\n', (1290, 1305), False, 'from chanjo.utils import average, _RawInterval, bed_to_interval, completeness, id_generator, BaseInterval, serialize_interval, validate_bed_format\n'), ((2498, 2526), 'chanjo.utils.BaseInterval', 'BaseInterval', (['"""chr1"""', '(10)', '(20)'], {}), "('chr1', 10, 20)\n", (2510, 2526), False, 'from chanjo.utils import average, _RawInterval, bed_to_interval, completeness, id_generator, BaseInterval, serialize_interval, validate_bed_format\n'), ((2631, 2669), 'chanjo.utils.BaseInterval', 'BaseInterval', (['"""chr1"""', '(123)', '(123)', '"""int1"""'], {}), "('chr1', 123, 123, 'int1')\n", (2643, 2669), False, 'from chanjo.utils import average, _RawInterval, bed_to_interval, completeness, id_generator, BaseInterval, serialize_interval, validate_bed_format\n'), ((2821, 2886), 'chanjo.utils.BaseInterval', 'BaseInterval', (['"""chr22"""', '(101)', '(200)'], {'block_ids': "['block11', 'block12']"}), "('chr22', 101, 200, block_ids=['block11', 'block12'])\n", (2833, 2886), False, 'from chanjo.utils import average, _RawInterval, bed_to_interval, completeness, id_generator, BaseInterval, serialize_interval, validate_bed_format\n'), ((3079, 3130), 'chanjo.utils.serialize_interval', 'serialize_interval', ([], {'delimiter': '"""|"""', 'subdelimiter': '""";"""'}), "(delimiter='|', subdelimiter=';')\n", (3097, 3130), False, 'from chanjo.utils import average, _RawInterval, bed_to_interval, completeness, id_generator, BaseInterval, serialize_interval, validate_bed_format\n'), ((1588, 1613), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1601, 1613), False, 'import pytest\n'), ((1669, 1713), 'chanjo.utils.bed_to_interval', 'bed_to_interval', (['(20)', '"""X"""', '(24)', '"""int2"""', '(0)', '"""-"""'], {}), "(20, 'X', 24, 'int2', 0, '-')\n", (1684, 1713), False, 'from chanjo.utils import average, _RawInterval, bed_to_interval, completeness, id_generator, BaseInterval, serialize_interval, validate_bed_format\n'), ((1843, 1858), 'chanjo.utils.average', 'average', (['values'], {}), '(values)\n', (1850, 1858), False, 'from chanjo.utils import average, _RawInterval, bed_to_interval, completeness, id_generator, BaseInterval, serialize_interval, validate_bed_format\n'), ((2536, 2564), 'chanjo.utils.serialize_interval', 'serialize_interval', (['interval'], {}), '(interval)\n', (2554, 2564), False, 'from chanjo.utils import average, _RawInterval, bed_to_interval, completeness, id_generator, BaseInterval, serialize_interval, validate_bed_format\n'), ((2679, 2717), 'chanjo.utils.serialize_interval', 'serialize_interval', (['interval'], {'bed': '(True)'}), '(interval, bed=True)\n', (2697, 2717), False, 'from chanjo.utils import average, _RawInterval, bed_to_interval, completeness, id_generator, BaseInterval, serialize_interval, validate_bed_format\n'), ((2961, 2989), 'chanjo.utils.serialize_interval', 'serialize_interval', (['interval'], {}), '(interval)\n', (2979, 2989), False, 'from chanjo.utils import average, _RawInterval, bed_to_interval, completeness, id_generator, BaseInterval, serialize_interval, validate_bed_format\n'), ((3433, 3447), 'chanjo.utils.id_generator', 'id_generator', ([], {}), '()\n', (3445, 3447), False, 'from chanjo.utils import average, _RawInterval, bed_to_interval, completeness, id_generator, BaseInterval, serialize_interval, validate_bed_format\n'), ((3569, 3584), 'chanjo.utils.id_generator', 'id_generator', (['(0)'], {}), '(0)\n', (3581, 3584), False, 'from chanjo.utils import average, _RawInterval, bed_to_interval, completeness, id_generator, BaseInterval, serialize_interval, validate_bed_format\n'), ((1904, 1920), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (1912, 1920), True, 'import numpy as np\n'), ((2062, 2094), 'numpy.array', 'np.array', (['[0, 10, 10, 20, 10, 0]'], {}), '([0, 10, 10, 20, 10, 0])\n', (2070, 2094), True, 'import numpy as np\n'), ((2209, 2221), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2217, 2221), True, 'import numpy as np\n'), ((2292, 2321), 'numpy.array', 'np.array', (['[20, 40, 10, 0, 10]'], {}), '([20, 40, 10, 0, 10])\n', (2300, 2321), True, 'import numpy as np\n'), ((3392, 3406), 'chanjo.utils.id_generator', 'id_generator', ([], {}), '()\n', (3404, 3406), False, 'from chanjo.utils import average, _RawInterval, bed_to_interval, completeness, id_generator, BaseInterval, serialize_interval, validate_bed_format\n'), ((3504, 3519), 'chanjo.utils.id_generator', 'id_generator', (['(3)'], {}), '(3)\n', (3516, 3519), False, 'from chanjo.utils import average, _RawInterval, bed_to_interval, completeness, id_generator, BaseInterval, serialize_interval, validate_bed_format\n'), ((3804, 3833), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (3817, 3833), False, 'import pytest\n'), ((3937, 3966), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (3950, 3966), False, 'import pytest\n')] |
import numpy as np
from bab.mcmc import get_mcmc, get_stan_model
from bab.make_data import make_data
from bab.power import get_power
from bab.model import BayesAB
y1, y2 = make_data(0, 1, 1, 2, 10, percent_outliers=0, sd_outlier_factor=2.0, rand_seed=1)
stan_model = get_stan_model()
mcmc = get_mcmc(stan_model, y1, y2)
get_power(stan_model, y1, y2, (-1., 1.), (0., 1.), 1., 1., n_sim=10)
model = BayesAB()
model.fit(2 * np.random.randn(10) + 3, np.random.randn(10))
| [
"numpy.random.randn",
"bab.model.BayesAB",
"bab.mcmc.get_stan_model",
"bab.mcmc.get_mcmc",
"bab.power.get_power",
"bab.make_data.make_data"
] | [((175, 260), 'bab.make_data.make_data', 'make_data', (['(0)', '(1)', '(1)', '(2)', '(10)'], {'percent_outliers': '(0)', 'sd_outlier_factor': '(2.0)', 'rand_seed': '(1)'}), '(0, 1, 1, 2, 10, percent_outliers=0, sd_outlier_factor=2.0,\n rand_seed=1)\n', (184, 260), False, 'from bab.make_data import make_data\n'), ((270, 286), 'bab.mcmc.get_stan_model', 'get_stan_model', ([], {}), '()\n', (284, 286), False, 'from bab.mcmc import get_mcmc, get_stan_model\n'), ((294, 322), 'bab.mcmc.get_mcmc', 'get_mcmc', (['stan_model', 'y1', 'y2'], {}), '(stan_model, y1, y2)\n', (302, 322), False, 'from bab.mcmc import get_mcmc, get_stan_model\n'), ((324, 398), 'bab.power.get_power', 'get_power', (['stan_model', 'y1', 'y2', '(-1.0, 1.0)', '(0.0, 1.0)', '(1.0)', '(1.0)'], {'n_sim': '(10)'}), '(stan_model, y1, y2, (-1.0, 1.0), (0.0, 1.0), 1.0, 1.0, n_sim=10)\n', (333, 398), False, 'from bab.power import get_power\n'), ((402, 411), 'bab.model.BayesAB', 'BayesAB', ([], {}), '()\n', (409, 411), False, 'from bab.model import BayesAB\n'), ((451, 470), 'numpy.random.randn', 'np.random.randn', (['(10)'], {}), '(10)\n', (466, 470), True, 'import numpy as np\n'), ((426, 445), 'numpy.random.randn', 'np.random.randn', (['(10)'], {}), '(10)\n', (441, 445), True, 'import numpy as np\n')] |
import numpy as np
import pickle
from sklearn import datasets
import lightgbm as lgb
from sklearn.model_selection import train_test_split
data = datasets.load_iris()
X = data['data']
y = data['target']
y[y > 0] = 1
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
n_estimators = 30
d_train = lgb.Dataset(X_train, label=y_train)
params = {
'boosting_type': 'rf',
'objective': 'binary',
'bagging_fraction': 0.8,
'feature_fraction': 0.8,
'bagging_freq': 1,
}
clf = lgb.train(params, d_train, n_estimators)
y_pred = clf.predict(X_test)
model_filename = 'lg_rf_iris.model'
pred_filename = 'lg_rf_iris_true_predictions.txt'
# test_filename = 'iris_test.libsvm'
clf.save_model(model_filename)
np.savetxt(pred_filename, y_pred)
# datasets.dump_svmlight_file(X_test, y_test, test_filename) | [
"sklearn.datasets.load_iris",
"lightgbm.train",
"lightgbm.Dataset",
"sklearn.model_selection.train_test_split",
"numpy.savetxt"
] | [((147, 167), 'sklearn.datasets.load_iris', 'datasets.load_iris', ([], {}), '()\n', (165, 167), False, 'from sklearn import datasets\n'), ((252, 305), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)', 'random_state': '(0)'}), '(X, y, test_size=0.2, random_state=0)\n', (268, 305), False, 'from sklearn.model_selection import train_test_split\n'), ((335, 370), 'lightgbm.Dataset', 'lgb.Dataset', (['X_train'], {'label': 'y_train'}), '(X_train, label=y_train)\n', (346, 370), True, 'import lightgbm as lgb\n'), ((526, 566), 'lightgbm.train', 'lgb.train', (['params', 'd_train', 'n_estimators'], {}), '(params, d_train, n_estimators)\n', (535, 566), True, 'import lightgbm as lgb\n'), ((753, 786), 'numpy.savetxt', 'np.savetxt', (['pred_filename', 'y_pred'], {}), '(pred_filename, y_pred)\n', (763, 786), True, 'import numpy as np\n')] |
import sys
import numpy as np
def make_predictions(model, X, fname, verbose=2):
"""
Makes predictions on data array X using model and saves it to fname
"""
print('Making predictions.')
sys.stdout.flush()
scores = model.predict(X, batch_size = 128, verbose=verbose)
np.save(fname, scores)
return scores | [
"numpy.save",
"sys.stdout.flush"
] | [((196, 214), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (212, 214), False, 'import sys\n'), ((281, 303), 'numpy.save', 'np.save', (['fname', 'scores'], {}), '(fname, scores)\n', (288, 303), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
import sys
import numpy
N = int(input())
arr = []
for _ in range(0, N):
temp = list(map(int, input().split()))
arr.append(temp)
n = numpy.array(arr)
arr = []
for _ in range(0, N):
temp = list(map(int, input().split()))
arr.append(temp)
m = numpy.array(arr)
print(numpy.dot(n, m))
| [
"numpy.dot",
"numpy.array"
] | [((164, 180), 'numpy.array', 'numpy.array', (['arr'], {}), '(arr)\n', (175, 180), False, 'import numpy\n'), ((281, 297), 'numpy.array', 'numpy.array', (['arr'], {}), '(arr)\n', (292, 297), False, 'import numpy\n'), ((304, 319), 'numpy.dot', 'numpy.dot', (['n', 'm'], {}), '(n, m)\n', (313, 319), False, 'import numpy\n')] |
import argparse
import os
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
methods = ["vpg", "rrpg", "qmcpg"]
def main():
parser = argparse.ArgumentParser(description="Run a classic control benchmark.")
parser.add_argument("--log_dir", type=str, default="./runs")
parser.add_argument("--out_dir", type=str, default="./out")
parser.add_argument("--max_frame", type=int, default=200000)
parser.add_argument("--n_mesh", type=int, default=200)
args = parser.parse_args()
log_dir = args.log_dir
out_dir = args.out_dir
max_frame = args.max_frame
n_mesh = args.n_mesh
buckets = np.linspace(0, max_frame, n_mesh + 1)
returns = {m:[] for m in methods}
discounted_returns = {m:[] for m in methods}
grad_var = {m:[] for m in methods}
grad_norm2 = {m:[] for m in methods}
grad_cost = {m:[] for m in methods}
grad_var_times_cost = {m:[] for m in methods}
grad_expection_norm2 = {m:[] for m in methods}
for d in os.listdir(log_dir):
# find the method for the path (log) by the first 3 chars of the path
method = {
"vpg": "vpg",
"rrp": "rrpg",
"qmc": "qmcpg",
}[d[:3]]
# extend `d` to a path
d = os.path.join(log_dir, d, "CartPole-v1")
# read csv files as numpy arrays
returns[method].append(bucket_average(os.path.join(d, "returns.csv"), buckets))
discounted_returns[method].append(bucket_average(os.path.join(d, "discounted_returns.csv"), buckets))
grad_norm2[method].append(bucket_average(os.path.join(d, "grad_norm.csv"), buckets))
# this makes it hard to use for loop different types of plots
norm2 = bucket_average(os.path.join(d, "grad_norm.csv"), buckets)
var = bucket_average(os.path.join(d, "grad_var.csv"), buckets)
cost = bucket_average(os.path.join(d, "grad_cost.csv"), buckets)
grad_var[method].append(var)
grad_cost[method].append(cost)
grad_norm2[method].append(norm2)
grad_var_times_cost[method].append([v * c for v, c in zip(var, cost)])
grad_expection_norm2[method].append([np.sqrt(n - v) ** 2 for n, v in zip(norm2, var)])
plot_with_confint(buckets, returns, "(Undiscounted) Cumulative Reward", out_dir)
plot_with_confint(buckets, discounted_returns, "Discounted Cumulative Reward", out_dir)
plot_with_confint(buckets, grad_norm2, "Squared Norm of Batch Gradient", out_dir, log=True)
plot_with_confint(buckets, grad_var, "Variance of Batch Gradient", out_dir, log=True)
plot_with_confint(buckets, grad_cost, "Cost of a Batch", out_dir, log=True)
plot_with_confint(buckets, grad_var_times_cost, "Variance for Unit Cost", out_dir, log=True)
plot_with_confint(buckets, grad_expection_norm2, "Squared Norm of Expected Gradient", out_dir, log=True)
def bucket_average(csv_path, buckets):
data = pd.read_csv(csv_path, header=None)
frames = data.iloc[:, 0].to_numpy()
values = data.iloc[:, 1].to_numpy()
if csv_path[-8:-4] == "norm":
values = values ** 2
sep_indices = np.searchsorted(frames, buckets)
means = []
for start, end in zip(sep_indices[:-1], sep_indices[1:]):
means.append(values[start:end].mean() if start < end else np.nan)
return means
def plot_with_confint(buckets, data, y_label, out_dir, log=False):
bucket_centers = 0.5 * buckets[1] + buckets[:-1]
plt.style.use("seaborn-whitegrid")
plt.set_cmap("tab10")
legend_args = [[], []]
for method in methods:
values = np.array(data[method])
if log:
log_values = np.log(values)
means = np.nanmean(log_values, axis=0)
std = np.nanstd(log_values, axis=0) / np.sqrt(np.sum(~np.isnan(values), axis=0)) * 2.5
lower, upper = means - std, means + std
means, lower, upper = map(np.exp, [means, lower, upper])
else:
means = np.nanmean(values, axis=0)
std = np.nanstd(values, axis=0) / np.sqrt(np.sum(~np.isnan(values), axis=0)) * 2.5
lower, upper = means - std, means + std
line = plt.plot(bucket_centers, means)[0]
band = plt.fill_between(bucket_centers, lower, upper, alpha=0.1)
legend_args[0].append((line, band))
legend_args[1].append(method.upper())
plt.legend(*legend_args) # ignore fill_between
plt.xlabel("Total frames")
plt.ylabel(y_label)
plt.xlim([0, buckets[-1]])
if log:
plt.yscale("log")
plt.savefig(os.path.join(out_dir, y_label + ".pdf"))
plt.clf()
if __name__ == "__main__":
main()
| [
"matplotlib.pyplot.yscale",
"argparse.ArgumentParser",
"matplotlib.pyplot.clf",
"pandas.read_csv",
"numpy.isnan",
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.fill_between",
"os.path.join",
"numpy.nanmean",
"matplotlib.pyplot.set_cmap",
"numpy.linspace",
"matplotlib.pyplot.legend",
"mat... | [((165, 236), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Run a classic control benchmark."""'}), "(description='Run a classic control benchmark.')\n", (188, 236), False, 'import argparse\n'), ((646, 683), 'numpy.linspace', 'np.linspace', (['(0)', 'max_frame', '(n_mesh + 1)'], {}), '(0, max_frame, n_mesh + 1)\n', (657, 683), True, 'import numpy as np\n'), ((1007, 1026), 'os.listdir', 'os.listdir', (['log_dir'], {}), '(log_dir)\n', (1017, 1026), False, 'import os\n'), ((2927, 2961), 'pandas.read_csv', 'pd.read_csv', (['csv_path'], {'header': 'None'}), '(csv_path, header=None)\n', (2938, 2961), True, 'import pandas as pd\n'), ((3123, 3155), 'numpy.searchsorted', 'np.searchsorted', (['frames', 'buckets'], {}), '(frames, buckets)\n', (3138, 3155), True, 'import numpy as np\n'), ((3450, 3484), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""seaborn-whitegrid"""'], {}), "('seaborn-whitegrid')\n", (3463, 3484), True, 'from matplotlib import pyplot as plt\n'), ((3489, 3510), 'matplotlib.pyplot.set_cmap', 'plt.set_cmap', (['"""tab10"""'], {}), "('tab10')\n", (3501, 3510), True, 'from matplotlib import pyplot as plt\n'), ((4361, 4385), 'matplotlib.pyplot.legend', 'plt.legend', (['*legend_args'], {}), '(*legend_args)\n', (4371, 4385), True, 'from matplotlib import pyplot as plt\n'), ((4413, 4439), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Total frames"""'], {}), "('Total frames')\n", (4423, 4439), True, 'from matplotlib import pyplot as plt\n'), ((4444, 4463), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['y_label'], {}), '(y_label)\n', (4454, 4463), True, 'from matplotlib import pyplot as plt\n'), ((4468, 4494), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0, buckets[-1]]'], {}), '([0, buckets[-1]])\n', (4476, 4494), True, 'from matplotlib import pyplot as plt\n'), ((4594, 4603), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (4601, 4603), True, 'from matplotlib import pyplot as plt\n'), ((1267, 1306), 'os.path.join', 'os.path.join', (['log_dir', 'd', '"""CartPole-v1"""'], {}), "(log_dir, d, 'CartPole-v1')\n", (1279, 1306), False, 'import os\n'), ((3583, 3605), 'numpy.array', 'np.array', (['data[method]'], {}), '(data[method])\n', (3591, 3605), True, 'import numpy as np\n'), ((4208, 4265), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (['bucket_centers', 'lower', 'upper'], {'alpha': '(0.1)'}), '(bucket_centers, lower, upper, alpha=0.1)\n', (4224, 4265), True, 'from matplotlib import pyplot as plt\n'), ((4515, 4532), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (4525, 4532), True, 'from matplotlib import pyplot as plt\n'), ((4549, 4588), 'os.path.join', 'os.path.join', (['out_dir', "(y_label + '.pdf')"], {}), "(out_dir, y_label + '.pdf')\n", (4561, 4588), False, 'import os\n'), ((1741, 1773), 'os.path.join', 'os.path.join', (['d', '"""grad_norm.csv"""'], {}), "(d, 'grad_norm.csv')\n", (1753, 1773), False, 'import os\n'), ((1813, 1844), 'os.path.join', 'os.path.join', (['d', '"""grad_var.csv"""'], {}), "(d, 'grad_var.csv')\n", (1825, 1844), False, 'import os\n'), ((1885, 1917), 'os.path.join', 'os.path.join', (['d', '"""grad_cost.csv"""'], {}), "(d, 'grad_cost.csv')\n", (1897, 1917), False, 'import os\n'), ((3647, 3661), 'numpy.log', 'np.log', (['values'], {}), '(values)\n', (3653, 3661), True, 'import numpy as np\n'), ((3682, 3712), 'numpy.nanmean', 'np.nanmean', (['log_values'], {'axis': '(0)'}), '(log_values, axis=0)\n', (3692, 3712), True, 'import numpy as np\n'), ((3968, 3994), 'numpy.nanmean', 'np.nanmean', (['values'], {'axis': '(0)'}), '(values, axis=0)\n', (3978, 3994), True, 'import numpy as np\n'), ((4158, 4189), 'matplotlib.pyplot.plot', 'plt.plot', (['bucket_centers', 'means'], {}), '(bucket_centers, means)\n', (4166, 4189), True, 'from matplotlib import pyplot as plt\n'), ((1395, 1425), 'os.path.join', 'os.path.join', (['d', '"""returns.csv"""'], {}), "(d, 'returns.csv')\n", (1407, 1425), False, 'import os\n'), ((1494, 1535), 'os.path.join', 'os.path.join', (['d', '"""discounted_returns.csv"""'], {}), "(d, 'discounted_returns.csv')\n", (1506, 1535), False, 'import os\n'), ((1596, 1628), 'os.path.join', 'os.path.join', (['d', '"""grad_norm.csv"""'], {}), "(d, 'grad_norm.csv')\n", (1608, 1628), False, 'import os\n'), ((2169, 2183), 'numpy.sqrt', 'np.sqrt', (['(n - v)'], {}), '(n - v)\n', (2176, 2183), True, 'import numpy as np\n'), ((3731, 3760), 'numpy.nanstd', 'np.nanstd', (['log_values'], {'axis': '(0)'}), '(log_values, axis=0)\n', (3740, 3760), True, 'import numpy as np\n'), ((4013, 4038), 'numpy.nanstd', 'np.nanstd', (['values'], {'axis': '(0)'}), '(values, axis=0)\n', (4022, 4038), True, 'import numpy as np\n'), ((3780, 3796), 'numpy.isnan', 'np.isnan', (['values'], {}), '(values)\n', (3788, 3796), True, 'import numpy as np\n'), ((4058, 4074), 'numpy.isnan', 'np.isnan', (['values'], {}), '(values)\n', (4066, 4074), True, 'import numpy as np\n')] |
# Treat all division as float division even in python2
from __future__ import division
from collections import Counter
import numpy as np
from annotypes import TYPE_CHECKING
from malcolm.core import Info
if TYPE_CHECKING:
from typing import Tuple, Dict, Sequence, Optional, Set
# All possible PMAC CS axis assignment
cs_axis_names = list("ABCUVWXYZ")
class ControllerInfo(Info):
def __init__(self, i10):
# type: (int) -> None
self.i10 = i10
def servo_freq(self):
# type: () -> float
freq = 8388608000. / self.i10
return freq
class CSInfo(Info):
def __init__(self, mri, port):
# type: (str, str) -> None
self.mri = mri
self.port = port
@classmethod
def get_cs_mri(cls, part_info, cs_port):
# type: (Dict[str, Optional[Sequence]], str) -> str
for info in cls.filter_values(part_info):
if info.port == cs_port:
return info.mri
raise ValueError(
"CS port %s not found in %s" % (cs_port, list(part_info)))
class MotorInfo(Info):
def __init__(self,
cs_axis, # type: str
cs_port, # type: str
acceleration, # type: float
resolution, # type: float
offset, # type: float
max_velocity, # type: float
current_position, # type: float
scannable, # type: str
velocity_settle, # type: float
units # type: str
):
# type: (...) -> None
self.cs_axis = cs_axis
self.cs_port = cs_port
self.acceleration = acceleration
self.resolution = resolution
self.offset = offset
self.max_velocity = max_velocity
self.current_position = current_position
self.scannable = scannable
self.velocity_settle = velocity_settle
self.units = units
def acceleration_time(self, v1, v2):
# The time taken to ramp from v1 to pad_velocity
ramp_time = abs(v2 - v1) / self.acceleration
return ramp_time
def ramp_distance(self, v1, v2, ramp_time=None):
# The distance moved in the first part of the ramp
if ramp_time is None:
ramp_time = self.acceleration_time(v1, v2)
ramp_distance = (v1 + v2) * ramp_time / 2
return ramp_distance
def _make_padded_ramp(self, v1, v2, pad_velocity, total_time):
"""Makes a ramp that looks like this:
v1 \______ pad_velocity
| |\
| | \v2
t1 tp t2
Such that whole section takes total_time
"""
# The time taken to ramp from v1 to pad_velocity
t1 = self.acceleration_time(v1, pad_velocity)
# Then on to v2
t2 = self.acceleration_time(pad_velocity, v2)
# The distance during the pad
tp = total_time - t1 - t2
# Yield the points
yield t1, pad_velocity
yield tp, pad_velocity
yield t2, v2
def _calculate_hat_params(self, v1, v2, acceleration, distance):
# Calculate how long to spend at max velocity
if acceleration > 0:
vm = self.max_velocity
else:
vm = -self.max_velocity
t1 = self.acceleration_time(v1, vm)
d1 = self.ramp_distance(v1, vm, t1)
t2 = self.acceleration_time(vm, v2)
d2 = self.ramp_distance(v1, vm, t1)
dm = distance - d1 - d2
tm = dm / vm
return t1, tm, t2, vm
def _make_hat(self, v1, v2, acceleration, distance, min_time):
"""Make a hat that looks like this:
______ vm
v1 /| | \
d1| dm|d2\ v2
| |
t1 tm t2
Such that the area under the graph (d1+d2+d3) is distance and
t1+t2+t3 >= min_time
"""
if min_time > 0:
# We are trying to meet time constraints
# Solve quadratic to give vm
b = v1 + v2 + min_time * acceleration
c = distance * acceleration + (v1*v1 + v2*v2) / 2
op = b*b - 4 * c
if np.isclose(op, 0):
# Might have a negative number as rounding error...
op = 0
elif op < 0:
# Can't do this, set something massive to fail vm check...
op = 10000000000
def get_times(vm):
t1 = (vm - v1) / acceleration
t2 = (vm - v2) / acceleration
tm = min_time - t1 - t2
assert -self.max_velocity <= vm <= self.max_velocity
assert t1 >= 0 and t2 >= 0 and tm >= 0
return t1, tm, t2
try:
# Try negative root
vm = (b - np.sqrt(op)) / 2
t1, tm, t2 = get_times(vm)
except AssertionError:
try:
# Try positive root
vm = (b + np.sqrt(op)) / 2
t1, tm, t2 = get_times(vm)
except AssertionError:
# If vm is out of range or any segment takes negative time,
# we can't do it in min_time, so act as if unconstrained
t1, tm, t2, vm = self._calculate_hat_params(
v1, v2, acceleration, distance)
else:
t1, tm, t2, vm = self._calculate_hat_params(
v1, v2, acceleration, distance)
# If middle segment needs to be negative time then we need to cap
# vm and spend no time at vm
if tm < 0:
# Solve the quadratic to work out how long to spend accelerating
vm = np.sqrt(
(2 * acceleration * distance + v1 * v1 + v2 * v2) / 2)
if acceleration < 0:
vm = -vm
t1 = self.acceleration_time(v1, vm)
t2 = self.acceleration_time(vm, v2)
tm = 0
# Yield the result
yield t1, vm
yield tm, vm
yield t2, v2
def make_velocity_profile(self, v1, v2, distance, min_time):
"""Calculate PVT points that will perform the move within motor params
Args:
v1 (float): Starting velocity in EGUs/s
v2 (float): Ending velocity in EGUs/s
distance (float): Relative distance to travel in EGUs
min_time (float): The minimum time the move should take
Returns:
tuple: (time_list, position_list) where time_list is a list of
relative time points in seconds, and position_list is the
position in EGUs that the motor should be
"""
# Take off the settle time and distance
if min_time > 0:
min_time -= self.velocity_settle
distance -= self.velocity_settle * v2
# The ramp time and distance of a continuous ramp from v1 to v2
ramp_time = self.acceleration_time(v1, v2)
ramp_distance = self.ramp_distance(v1, v2, ramp_time)
remaining_distance = distance - ramp_distance
# Check if we need to stretch in time
if min_time > ramp_time:
# Check how fast we would need to be going so that the total move
# completes in min_time
pad_velocity = remaining_distance / (min_time - ramp_time)
if pad_velocity > max(v1, v2):
# Can't just pad the ramp, make a hat pointing up
it = self._make_hat(
v1, v2, self.acceleration, distance, min_time)
elif pad_velocity < min(v1, v2):
# Can't just pad the ramp, make a hat pointing down
it = self._make_hat(
v1, v2, -self.acceleration, distance, min_time)
else:
# Make a padded ramp
it = self._make_padded_ramp(v1, v2, pad_velocity, min_time)
elif remaining_distance < 0:
# Make a hat pointing down
it = self._make_hat(v1, v2, -self.acceleration, distance, min_time)
else:
# Make a hat pointing up
it = self._make_hat(v1, v2, self.acceleration, distance, min_time)
# Create the time and velocity arrays
time_array = [0.0]
velocity_array = [v1]
for t, v in it:
assert t >= 0, "Got negative t %s" % t
if t == 0:
assert v == velocity_array[-1], \
"Can't move velocity in zero time"
continue
if v * velocity_array[-1] < 0:
# Crossed zero, put in an explicit zero velocity
fraction = velocity_array[-1] / (velocity_array[-1] - v)
time_array.append(time_array[-1] + fraction * t)
velocity_array.append(0)
t -= fraction * t
time_array.append(time_array[-1] + t)
velocity_array.append(v)
# Add on the settle time
if self.velocity_settle > 0:
time_array.append(time_array[-1] + self.velocity_settle)
velocity_array.append(v2)
return time_array, velocity_array
@classmethod
def cs_axis_mapping(cls,
part_info, # type: Dict[str, Optional[Sequence]]
axes_to_move # type: Sequence[str]
):
# type: (...) -> Tuple[str, Dict[str, MotorInfo]]
"""Given the motor infos for the parts, filter those with scannable
names in axes_to_move, check they are all in the same CS, and return
the cs_port and mapping of cs_axis to MotorInfo"""
cs_ports = set() # type: Set[str]
axis_mapping = {} # type: Dict[str, MotorInfo]
for motor_info in cls.filter_values(part_info):
if motor_info.scannable in axes_to_move:
assert motor_info.cs_axis in cs_axis_names, \
"Can only scan 1-1 mappings, %r is %r" % \
(motor_info.scannable, motor_info.cs_axis)
cs_ports.add(motor_info.cs_port)
axis_mapping[motor_info.scannable] = motor_info
missing = list(set(axes_to_move) - set(axis_mapping))
assert not missing, \
"Some scannables %s are not in the CS mapping %s" % (
missing, axis_mapping)
assert len(cs_ports) == 1, \
"Requested axes %s are in multiple CS numbers %s" % (
axes_to_move, list(cs_ports))
cs_axis_counts = Counter([x.cs_axis for x in axis_mapping.values()])
# Any cs_axis defs that are used for more that one raw motor
overlap = [k for k, v in cs_axis_counts.items() if v > 1]
assert not overlap, \
"CS axis defs %s have more that one raw motor attached" % overlap
return cs_ports.pop(), axis_mapping
| [
"numpy.isclose",
"numpy.sqrt"
] | [((4163, 4180), 'numpy.isclose', 'np.isclose', (['op', '(0)'], {}), '(op, 0)\n', (4173, 4180), True, 'import numpy as np\n'), ((5719, 5781), 'numpy.sqrt', 'np.sqrt', (['((2 * acceleration * distance + v1 * v1 + v2 * v2) / 2)'], {}), '((2 * acceleration * distance + v1 * v1 + v2 * v2) / 2)\n', (5726, 5781), True, 'import numpy as np\n'), ((4808, 4819), 'numpy.sqrt', 'np.sqrt', (['op'], {}), '(op)\n', (4815, 4819), True, 'import numpy as np\n'), ((4994, 5005), 'numpy.sqrt', 'np.sqrt', (['op'], {}), '(op)\n', (5001, 5005), True, 'import numpy as np\n')] |
#!/usr/bin/env python
#Copyright (c) 2011, 2012 <NAME>
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
from gettext import gettext as _
try:
from numpy import append
from numpy.fft import rfft
PITCH_AVAILABLE = True
except:
PITCH_AVAILABLE = False
from plugins.plugin import Plugin
from plugins.audio_sensors.audiograb import (AudioGrab,
SENSOR_DC_NO_BIAS, SENSOR_DC_BIAS, SENSOR_AC_BIAS)
from plugins.audio_sensors.ringbuffer import RingBuffer1d
from TurtleArt.tapalette import make_palette
from TurtleArt.taconstants import XO1, XO15, XO175, XO30, XO4
from TurtleArt.talogo import primitive_dictionary
from TurtleArt.tautils import debug_output
import logging
_logger = logging.getLogger('turtleart-activity audio sensors plugin')
def _avg(array, abs_value=False):
''' Calc. the average value of an array '''
if len(array) == 0:
return 0
array_sum = 0
if abs_value:
for a in array:
array_sum += abs(a)
else:
for a in array:
array_sum += a
return float(array_sum) / len(array)
class Audio_sensors(Plugin):
def __init__(self, parent):
self._parent = parent
self._status = True # TODO: test for audio device
# These flags are referenced by audiograb
self.hw = self._parent.hw
self.running_sugar = self._parent.running_sugar
def setup(self):
''' set up audio-sensor-specific blocks '''
self.max_samples = 1500
self.input_step = 1
self.ringbuffer = []
palette = make_palette('sensor',
colors=["#FF6060", "#A06060"],
help_string=_('Palette of sensor blocks'),
position=6)
primitive_dictionary['sound'] = self.prim_sound
primitive_dictionary['volume'] = self.prim_volume
if self._status:
palette.add_block('sound',
style='box-style',
label=_('sound'),
help_string=_('raw microphone input signal'),
value_block=True,
prim_name='sound')
palette.add_block('volume',
style='box-style',
label=_('loudness'),
help_string=_('microphone input volume'),
value_block=True,
prim_name='volume')
else:
palette.add_block('sound',
hidden=True,
style='box-style',
label=_('sound'),
help_string=_('raw microphone input signal'),
value_block=True,
prim_name='sound')
palette.add_block('volume',
hidden=True,
style='box-style',
label=_('loudness'),
help_string=_('microphone input volume'),
value_block=True,
prim_name='volume')
self._parent.lc.def_prim(
'sound', 0, lambda self: primitive_dictionary['sound'](0))
self._parent.lc.def_prim(
'volume', 0, lambda self: primitive_dictionary['volume'](0))
primitive_dictionary['pitch'] = self.prim_pitch
if PITCH_AVAILABLE and self._status:
palette.add_block('pitch',
style='box-style',
label=_('pitch'),
help_string=_('microphone input pitch'),
value_block=True,
prim_name='pitch')
else:
palette.add_block('pitch',
hidden=True,
style='box-style',
label=_('pitch'),
help_string=_('microphone input pitch'),
value_block=True,
prim_name='pitch')
self._parent.lc.def_prim('pitch', 0,
lambda self: primitive_dictionary['pitch'](0))
primitive_dictionary['resistance'] = self.prim_resistance
primitive_dictionary['voltage'] = self.prim_voltage
if self.hw in [XO1, XO15, XO175, XO4, XO30] and self._status:
if self.hw == XO1:
self.voltage_gain = 0.000022
self.voltage_bias = 1.14
elif self.hw == XO15:
self.voltage_gain = -0.00015
self.voltage_bias = 1.70
elif self.hw in [XO175, XO4]: # recalibrate in light of #3675?
self.voltage_gain = 0.000071
self.voltage_bias = 0.55
else: # XO 3.0
self.voltage_gain = 0.000077
self.voltage_bias = 0.72
palette.add_block('resistance',
style='box-style',
label=_('resistance'),
help_string=_('microphone input resistance'),
value_block=True,
prim_name='resistance')
palette.add_block('voltage',
style='box-style',
label=_('voltage'),
help_string=_('microphone input voltage'),
value_block=True,
prim_name='voltage')
else:
palette.add_block('resistance',
hidden=True,
style='box-style',
label=_('resistance'),
help_string=_('microphone input resistance'),
prim_name='resistance')
palette.add_block('voltage',
hidden=True,
style='box-style',
label=_('voltage'),
help_string=_('microphone input voltage'),
prim_name='voltage')
# FIXME: Only add stereo capture for XO15 (broken on ARM #3675)
if self.hw in [XO15] and self._status:
palette.add_block('resistance2',
style='box-style',
label=_('resistance') + '2',
help_string=_('microphone input resistance'),
value_block=True,
prim_name='resistance2')
palette.add_block('voltage2',
style='box-style',
label=_('voltage') + '2',
help_string=_('microphone input voltage'),
value_block=True,
prim_name='voltage2')
else:
palette.add_block('resistance2',
hidden=True,
style='box-style',
label=_('resistance') + '2',
help_string=_('microphone input resistance'),
prim_name='resistance2')
palette.add_block('voltage2',
hidden=True,
style='box-style',
label=_('voltage') + '2',
help_string=_('microphone input voltage'),
prim_name='voltage2')
self._parent.lc.def_prim(
'resistance', 0,
lambda self: primitive_dictionary['resistance'](0))
self._parent.lc.def_prim(
'voltage', 0, lambda self: primitive_dictionary['voltage'](0))
self._parent.lc.def_prim(
'resistance2', 0,
lambda self: primitive_dictionary['resistance'](1))
self._parent.lc.def_prim(
'voltage2', 0, lambda self: primitive_dictionary['voltage'](1))
self.audio_started = False
if self.hw in [XO175, XO30, XO4]:
self.PARAMETERS = {
SENSOR_AC_BIAS: (False, True, 80, True),
SENSOR_DC_NO_BIAS: (True, False, 80, False),
SENSOR_DC_BIAS: (True, True, 90, False)
}
elif self.hw == XO15:
self.PARAMETERS = {
SENSOR_AC_BIAS: (False, True, 80, True),
SENSOR_DC_NO_BIAS: (True, False, 80, False),
SENSOR_DC_BIAS: (True, True, 90, False)
}
elif self.hw == XO1:
self.PARAMETERS = {
SENSOR_AC_BIAS: (False, True, 40, True),
SENSOR_DC_NO_BIAS: (True, False, 0, False),
SENSOR_DC_BIAS: (True, True, 0, False)
}
else:
self.PARAMETERS = {
SENSOR_AC_BIAS: (None, True, 40, True),
SENSOR_DC_NO_BIAS: (True, False, 80, False),
SENSOR_DC_BIAS: (True, True, 90, False)
}
def start(self):
''' Start grabbing audio if there is an audio block in use '''
if not self._status:
return
if self.audio_started:
self.audiograb.stop_grabbing()
if len(self._parent.block_list.get_similar_blocks(
'block', ['volume', 'sound', 'pitch'])) > 0:
mode, bias, gain, boost = self.PARAMETERS[SENSOR_AC_BIAS]
elif len(self._parent.block_list.get_similar_blocks(
'block', ['resistance', 'resistance2'])) > 0:
mode, bias, gain, boost = self.PARAMETERS[SENSOR_DC_BIAS]
elif len(self._parent.block_list.get_similar_blocks(
'block', ['voltage', 'voltage2'])) > 0:
mode, bias, gain, boost = self.PARAMETERS[SENSOR_DC_NO_BIAS]
else:
return # No audio blocks in use.
self.audiograb = AudioGrab(self.new_buffer, self,
mode, bias, gain, boost)
self._channels = self.audiograb.channels
for i in range(self._channels):
self.ringbuffer.append(RingBuffer1d(self.max_samples,
dtype='int16'))
self.audiograb.start_grabbing()
self.audio_started = True
def new_buffer(self, buf, channel=0):
''' Append a new buffer to the ringbuffer '''
self.ringbuffer[channel].append(buf)
return True
def stop(self):
''' This gets called by the stop button '''
if self._status and self.audio_started:
self.audiograb.on_activity_quit() # reset all setting
self.audio_started = False
def goto_background(self):
''' This gets called when your process is sent to the background '''
pass
def return_to_foreground(self):
''' This gets called when your process returns from the background '''
pass
def quit(self):
''' This gets called by the quit button '''
if self._status and self.audio_started:
self.audiograb.on_activity_quit()
def _status_report(self):
debug_output(
'Reporting audio sensor status: %s' % (str(self._status)),
self._parent.running_sugar)
return self._status
# Block primitives used in talogo
def prim_volume(self, channel):
if not self._status:
return 0
# Return average of both channels if sampling in stereo
if self._channels == 2:
chan0 = self._prim_volume(0)
chan1 = self._prim_volume(1)
return (chan0 + chan1) / 2
else:
return self._prim_volume(0)
def _prim_volume(self, channel):
''' return mic in value '''
buf = self.ringbuffer[channel].read(None, self.input_step)
if len(buf) > 0:
volume = float(_avg(buf, abs_value=True))
self._parent.lc.update_label_value('volume', volume)
return volume
else:
return 0
def prim_sound(self, channel):
if not self._status:
return 0
# Return average of both channels if sampling in stereo
if self._channels == 2:
chan0 = self._prim_sound(0)
chan1 = self._prim_sound(1)
return (chan0 + chan1) / 2
else:
return self._prim_sound(0)
def _prim_sound(self, channel):
''' return raw mic in value '''
buf = self.ringbuffer[channel].read(None, self.input_step)
if len(buf) > 0:
sound = float(buf[0])
if self._parent.lc.update_values:
self._parent.lc.update_label_value('sound', sound)
return sound
else:
return 0
def prim_pitch(self, channel):
if not PITCH_AVAILABLE or not self._status:
return 0
# Return average of both channels if sampling in stereo
if self._channels == 2:
chan0 = self._prim_pitch(0)
chan1 = self._prim_pitch(1)
return (chan0 + chan1) / 2
else:
return self._prim_pitch(0)
def _prim_pitch(self, channel):
''' return index of max value in fft of mic in values '''
buf = self.ringbuffer[channel].read(None, self.input_step)
if len(buf) > 0:
buf = rfft(buf)
buf = abs(buf)
maxi = buf.argmax()
if maxi == 0:
pitch = 0
else: # Simple interpolation
a, b, c = buf[maxi - 1], buf[maxi], buf[maxi + 1]
maxi -= a / float(a + b + c)
maxi += c / float(a + b + c)
pitch = maxi * 48000 / (len(buf) * 2)
if self._parent.lc.update_values:
self._parent.lc.update_label_value('pitch', pitch)
return pitch
else:
return 0
def prim_resistance(self, channel):
if not self.hw in [XO1, XO15, XO175, XO30, XO4] or not self._status:
return 0
if self.hw in [XO1, XO4]:
resistance = self._prim_resistance(0)
if self._parent.lc.update_values:
self._update_resistance_labels(0, resistance)
return resistance
elif self.hw == XO15:
resistance = self._prim_resistance(channel)
if self._parent.lc.update_values:
self._update_resistance_labels(channel, resistance)
return resistance
# FIXME: For XO175: channel assignment is seemingly random
# (#3675), so sum both channels (one of them will be 0)
else:
chan0 = self._prim_resistance(0)
chan1 = self._prim_resistance(1)
resistance = chan0 + chan1
if self._parent.lc.update_values:
self._update_resistance_labels(0, resistance)
return resistance
def _prim_resistance(self, channel):
''' return resistance sensor value '''
buf = self.ringbuffer[channel].read(None, self.input_step)
if len(buf) > 0:
# See <http://bugs.sugarlabs.org/ticket/552#comment:7>
# TODO: test this calibration on XO 1.5, XO 1.75
avg_buf = float(_avg(buf))
if self.hw == XO1:
resistance = 2.718 ** ((avg_buf * 0.000045788) + 8.0531)
elif self.hw == XO15:
if avg_buf > 0:
resistance = (420000000 / avg_buf) - 13500
else:
resistance = 420000000
elif self.hw in [XO175, XO4]:
if avg_buf < 30700:
resistance = .12 * ((180000000 / (30700 - avg_buf)) - 3150)
else:
resistance = 999999999
else: # XO 3.0
if avg_buf < 30514:
resistance = (46000000 / (30514 - avg_buf)) - 1150
else:
resistance = 999999999
if resistance < 0:
resistance = 0
return resistance
else:
return 0
def _update_resistance_labels(self, channel, resistance):
if channel == 0:
self._parent.lc.update_label_value('resistance', resistance)
else:
self._parent.lc.update_label_value('resistance2', resistance)
def prim_voltage(self, channel):
if not self.hw in [XO1, XO15, XO175, XO30, XO4] or not self._status:
return 0
if self.hw in [XO1, XO4]:
voltage = self._prim_voltage(0)
if self._parent.lc.update_values:
self._update_voltage_labels(0, voltage)
return voltage
elif self.hw == XO15:
voltage = self._prim_voltage(channel)
if self._parent.lc.update_values:
self._update_voltage_labels(channel, voltage)
return voltage
# FIXME: For XO175: channel assignment is seemingly random
# (#3675), so sum both channels (one of them will be 0)
else:
chan0 = self._prim_voltage(0)
chan1 = self._prim_voltage(1)
voltage = chan0 + chan1
if self._parent.lc.update_values:
self._update_voltage_labels(0, voltage)
return voltage
def _prim_voltage(self, channel):
''' return voltage sensor value '''
buf = self.ringbuffer[channel].read(None, self.input_step)
if len(buf) > 0:
# See <http://bugs.sugarlabs.org/ticket/552#comment:7>
voltage = float(_avg(buf)) * self.voltage_gain + self.voltage_bias
return voltage
else:
return 0
def _update_voltage_labels(self, channel, voltage):
if channel == 0:
self._parent.lc.update_label_value('voltage', voltage)
else:
self._parent.lc.update_label_value('voltage2', voltage)
| [
"numpy.fft.rfft",
"plugins.audio_sensors.audiograb.AudioGrab",
"plugins.audio_sensors.ringbuffer.RingBuffer1d",
"logging.getLogger",
"gettext.gettext"
] | [((1354, 1414), 'logging.getLogger', 'logging.getLogger', (['"""turtleart-activity audio sensors plugin"""'], {}), "('turtleart-activity audio sensors plugin')\n", (1371, 1414), False, 'import logging\n'), ((10801, 10858), 'plugins.audio_sensors.audiograb.AudioGrab', 'AudioGrab', (['self.new_buffer', 'self', 'mode', 'bias', 'gain', 'boost'], {}), '(self.new_buffer, self, mode, bias, gain, boost)\n', (10810, 10858), False, 'from plugins.audio_sensors.audiograb import AudioGrab, SENSOR_DC_NO_BIAS, SENSOR_DC_BIAS, SENSOR_AC_BIAS\n'), ((14245, 14254), 'numpy.fft.rfft', 'rfft', (['buf'], {}), '(buf)\n', (14249, 14254), False, 'from numpy.fft import rfft\n'), ((2338, 2367), 'gettext.gettext', '_', (['"""Palette of sensor blocks"""'], {}), "('Palette of sensor blocks')\n", (2339, 2367), True, 'from gettext import gettext as _\n'), ((11018, 11063), 'plugins.audio_sensors.ringbuffer.RingBuffer1d', 'RingBuffer1d', (['self.max_samples'], {'dtype': '"""int16"""'}), "(self.max_samples, dtype='int16')\n", (11030, 11063), False, 'from plugins.audio_sensors.ringbuffer import RingBuffer1d\n'), ((2676, 2686), 'gettext.gettext', '_', (['"""sound"""'], {}), "('sound')\n", (2677, 2686), True, 'from gettext import gettext as _\n'), ((2730, 2762), 'gettext.gettext', '_', (['"""raw microphone input signal"""'], {}), "('raw microphone input signal')\n", (2731, 2762), True, 'from gettext import gettext as _\n'), ((2987, 3000), 'gettext.gettext', '_', (['"""loudness"""'], {}), "('loudness')\n", (2988, 3000), True, 'from gettext import gettext as _\n'), ((3044, 3072), 'gettext.gettext', '_', (['"""microphone input volume"""'], {}), "('microphone input volume')\n", (3045, 3072), True, 'from gettext import gettext as _\n'), ((3353, 3363), 'gettext.gettext', '_', (['"""sound"""'], {}), "('sound')\n", (3354, 3363), True, 'from gettext import gettext as _\n'), ((3407, 3439), 'gettext.gettext', '_', (['"""raw microphone input signal"""'], {}), "('raw microphone input signal')\n", (3408, 3439), True, 'from gettext import gettext as _\n'), ((3706, 3719), 'gettext.gettext', '_', (['"""loudness"""'], {}), "('loudness')\n", (3707, 3719), True, 'from gettext import gettext as _\n'), ((3763, 3791), 'gettext.gettext', '_', (['"""microphone input volume"""'], {}), "('microphone input volume')\n", (3764, 3791), True, 'from gettext import gettext as _\n'), ((4330, 4340), 'gettext.gettext', '_', (['"""pitch"""'], {}), "('pitch')\n", (4331, 4340), True, 'from gettext import gettext as _\n'), ((4384, 4411), 'gettext.gettext', '_', (['"""microphone input pitch"""'], {}), "('microphone input pitch')\n", (4385, 4411), True, 'from gettext import gettext as _\n'), ((4691, 4701), 'gettext.gettext', '_', (['"""pitch"""'], {}), "('pitch')\n", (4692, 4701), True, 'from gettext import gettext as _\n'), ((4745, 4772), 'gettext.gettext', '_', (['"""microphone input pitch"""'], {}), "('microphone input pitch')\n", (4746, 4772), True, 'from gettext import gettext as _\n'), ((5835, 5850), 'gettext.gettext', '_', (['"""resistance"""'], {}), "('resistance')\n", (5836, 5850), True, 'from gettext import gettext as _\n'), ((5894, 5926), 'gettext.gettext', '_', (['"""microphone input resistance"""'], {}), "('microphone input resistance')\n", (5895, 5926), True, 'from gettext import gettext as _\n'), ((6156, 6168), 'gettext.gettext', '_', (['"""voltage"""'], {}), "('voltage')\n", (6157, 6168), True, 'from gettext import gettext as _\n'), ((6212, 6241), 'gettext.gettext', '_', (['"""microphone input voltage"""'], {}), "('microphone input voltage')\n", (6213, 6241), True, 'from gettext import gettext as _\n'), ((6528, 6543), 'gettext.gettext', '_', (['"""resistance"""'], {}), "('resistance')\n", (6529, 6543), True, 'from gettext import gettext as _\n'), ((6587, 6619), 'gettext.gettext', '_', (['"""microphone input resistance"""'], {}), "('microphone input resistance')\n", (6588, 6619), True, 'from gettext import gettext as _\n'), ((6844, 6856), 'gettext.gettext', '_', (['"""voltage"""'], {}), "('voltage')\n", (6845, 6856), True, 'from gettext import gettext as _\n'), ((6900, 6929), 'gettext.gettext', '_', (['"""microphone input voltage"""'], {}), "('microphone input voltage')\n", (6901, 6929), True, 'from gettext import gettext as _\n'), ((7297, 7329), 'gettext.gettext', '_', (['"""microphone input resistance"""'], {}), "('microphone input resistance')\n", (7298, 7329), True, 'from gettext import gettext as _\n'), ((7623, 7652), 'gettext.gettext', '_', (['"""microphone input voltage"""'], {}), "('microphone input voltage')\n", (7624, 7652), True, 'from gettext import gettext as _\n'), ((8006, 8038), 'gettext.gettext', '_', (['"""microphone input resistance"""'], {}), "('microphone input resistance')\n", (8007, 8038), True, 'from gettext import gettext as _\n'), ((8327, 8356), 'gettext.gettext', '_', (['"""microphone input voltage"""'], {}), "('microphone input voltage')\n", (8328, 8356), True, 'from gettext import gettext as _\n'), ((7232, 7247), 'gettext.gettext', '_', (['"""resistance"""'], {}), "('resistance')\n", (7233, 7247), True, 'from gettext import gettext as _\n'), ((7561, 7573), 'gettext.gettext', '_', (['"""voltage"""'], {}), "('voltage')\n", (7562, 7573), True, 'from gettext import gettext as _\n'), ((7941, 7956), 'gettext.gettext', '_', (['"""resistance"""'], {}), "('resistance')\n", (7942, 7956), True, 'from gettext import gettext as _\n'), ((8265, 8277), 'gettext.gettext', '_', (['"""voltage"""'], {}), "('voltage')\n", (8266, 8277), True, 'from gettext import gettext as _\n')] |
# ------------------------------------------------------------------
# Compute residual VLM from alt-tg
# This program has 2 modes:
# First mode:
# Compute alt-tg for provisional region list for during TG QC
# Compute alt-tg for final region list
# ------------------------------------------------------------------
import numpy as np
from netCDF4 import Dataset
import os
import mod_gentools as gentools
import shutil
import multiprocessing as mp
import ctypes as ct
import glob
def main():
set_settings()
read_altimetry()
set_alttg_list()
compute_correlating_points()
compute_ts()
compute_trend()
save_data()
return
def set_settings():
print('Define settings...')
global settings
settings = {}
settings['region_selection'] = False # True: read from region_selection list. # False: read from final list
settings['select_latest_statlist'] = False
settings['test_run_ICE6G_D'] = True
settings['years'] = np.arange(1900,2019)
settings['min_alt_years'] = 15 # Minimum number of years of overlap between alt/tg required to compute VLM trend
settings['min_corr'] = 0.5 # Minimum correlation between altimetry and tide gauge
settings['max_dist'] = 300000 # Maximum distance (m) between altimetry grid cell and tide gauge location
settings['num_ens'] = 100 # Number of ensembles
settings['dir_data'] = os.getenv('HOME') + '/Data/'
settings['dir_scratch'] = os.getenv('HOME') + '/Scratch/'
if os.uname().nodename == 'MT-110180':
settings['nproc'] = 4
settings['fn_hector'] = os.getenv('HOME') + '/Scripts/Hector/Python/MacOS/est_trend/estimatetrend'
else:
settings['nproc'] = 40
settings['fn_hector'] = os.getenv('HOME') + '/Code/Hector/estimatetrend'
settings['dir_budget'] = settings['dir_data'] + 'Budget_20c/'
if settings['test_run_ICE6G_D']:
settings['dir_grd'] = settings['dir_budget'] + 'grd_ICE6G/'
settings['fn_gia_rad'] = settings['dir_data']+'GIA/ICE6G_D/ICE6G_D_05.nc'
settings['fn_gia_rsl'] = settings['dir_data']+'GIA/ICE6G_D/ICE6G_D_05.nc'
settings['probability'] = np.ones(settings['num_ens'])/settings['num_ens']
else:
settings['dir_grd'] = settings['dir_budget'] + 'grd/'
settings['fn_gia_rad'] = settings['dir_data'] + 'GIA/Caron/Ensemble/rad_ens_05.nc'
settings['fn_gia_rsl'] = settings['dir_data'] + 'GIA/Caron/Ensemble/rsl_ens_05.nc'
settings['probability'] = Dataset(settings['fn_gia_rad'], 'r').variables['probability'][:settings['num_ens']]._get_data()
settings['probability'] = settings['probability'] / settings['probability'].sum()
settings['fn_altimetry'] = settings['dir_budget']+'vlm/Altimetry_annual.nc'
settings['fn_station_data'] = settings['dir_budget']+'tg/station_data.npy'
settings['fn_regions_for_selection'] = settings['dir_budget']+'tg/regions_for_selection.npy'
if settings['region_selection']:
print(' MODE: REGION SELECTION')
settings['fn_alttg_data'] = settings['dir_budget'] + 'vlm/alttg_for_region_selection.npy'
else:
print(' MODE: VIRTUAL STATION')
if settings['test_run_ICE6G_D']:
settings['fn_alttg_data'] = settings['dir_budget'] + 'vlm/alttg_for_virstat_ice6g.npy'
else:
settings['fn_alttg_data'] = settings['dir_budget'] + 'vlm/alttg_for_virstat.npy'
# REGION LIST
if settings['select_latest_statlist']:
flist = glob.glob(settings['dir_budget']+'region_data/region_list*')
cdate = np.zeros(len(flist))
for idx, file in enumerate(flist): cdate[idx] = os.path.getmtime(file)
settings['fn_region_list'] = flist[np.argmax(cdate)]
print(flist[np.argmax(cdate)])
else:
settings['fn_region_list'] = settings['dir_budget']+'region_data/region_list_beta_march_9.npy'
return
def set_alttg_list():
print('Filling alt-tg-information...')
global alttg_list, settings
alttg_list = {}
time_alt_idx = np.in1d(settings['years'],altimetry['time'])
if settings['region_selection']: # Read from region_selection
regions_for_selection = np.load(settings['fn_regions_for_selection'], allow_pickle=True).all()
alttg_list['id'] = regions_for_selection['id'].copy()
alttg_list['coords'] = mp_filled_float(regions_for_selection['coords'])
alttg_list['height'] = mp_filled_float(regions_for_selection['height_corr'][:,time_alt_idx])
else: # Compute merged stations from definitive list
station_data = np.load(settings['fn_station_data'], allow_pickle=True).all()
region_list = np.load(settings['fn_region_list'], allow_pickle=True)
alttg_id = []
alttg_coords = []
alttg_height = []
for basin in range(len(region_list)):
for region in range(len(region_list[basin]['list'])):
if 'ALTTG' in region_list[basin]['list'][region]['vlm_id']:
rsl_in_region = np.zeros([len(settings['years']), len(region_list[basin]['list'][region]['id'])])
for station in range(len(region_list[basin]['list'][region]['id'])):
idx = station_data['id'] == region_list[basin]['list'][region]['id'][station]
rsl_in_region[:,station] = station_data['height_corr'][idx,:]
height_lcl = merge_stations_to_region(rsl_in_region)
# Store
alttg_id.append(region_list[basin]['list'][region]['id'])
alttg_coords.append(station_data['coords'][idx])
alttg_height.append(height_lcl)
alttg_list['id'] = np.array(alttg_id)
alttg_list['coords'] = mp_filled_float(np.array(alttg_coords).squeeze())
alttg_list['height'] = mp_filled_float(np.array(alttg_height)[:,time_alt_idx])
return
def compute_correlating_points():
global altimetry, alttg_list, settings
# ------------------------------------------------------
# Determine points in altimetry that correlate with tide
# gauge sea level and store for ensemble computation
# ------------------------------------------------------
print('Computing correlation points...')
alttg_list['tg_coords'] = np.zeros([len(alttg_list['id']),2],dtype=int)
alttg_list['weight'] = np.zeros(len(alttg_list['id']),dtype=object)
alttg_list['has_corr'] = np.zeros(len(alttg_list['id']),dtype=bool)
alttg_list['time_acc'] = np.zeros(len(alttg_list['id']),dtype=object)
alttg_list['tg_tseries'] = np.zeros(len(alttg_list['id']),dtype=object)
alttg_list['alt_coords'] = np.zeros(len(alttg_list['id']),dtype=object)
for region in range(len(alttg_list['id'])):
time_acc = np.isfinite(alttg_list['height'][region,:])
if time_acc.sum()>settings['min_alt_years']:
alttg_list['tg_coords'][region,0] = np.argmin(np.abs(altimetry['lat'] - alttg_list['coords'][region,0]))
alttg_list['tg_coords'][region,1] = np.argmin(np.abs(altimetry['lon'] - alttg_list['coords'][region,1]))
# Detrend TG and altimetry data set for correlation
amat = np.ones([time_acc.sum(),2])
amat[:,1] = altimetry['time'][time_acc] - altimetry['time'][time_acc].mean()
tg_detrend = alttg_list['height'][region,:][time_acc] - np.matmul(amat,np.linalg.lstsq(amat, alttg_list['height'][region,:][time_acc],rcond=None)[0])
# Accepted points
distance = gentools.point_grid_distance(alttg_list['coords'][region,0],alttg_list['coords'][region,1],altimetry['lat'],altimetry['lon'])
distance[~altimetry['slm']] = 1e9
alt_acc = np.array(np.where(distance < settings['max_dist'])).T
corr_array = np.zeros(len(alt_acc))
for alt in range(len(alt_acc)):
alt_detrend = altimetry['ssh'][:,alt_acc[alt,0],alt_acc[alt,1]][time_acc] - np.matmul(amat, np.linalg.lstsq(amat, altimetry['ssh'][:,alt_acc[alt,0],alt_acc[alt,1]][time_acc], rcond=None)[0])
corr_array[alt] = np.corrcoef(alt_detrend,tg_detrend)[0,1]
corr_array[np.isnan(corr_array)]=-1
if (corr_array>settings['min_corr']).sum()>0:
# Compute weight
corr_array_flt = corr_array[corr_array>settings['min_corr']]
weight = corr_array_flt/corr_array_flt.sum()
# Store data
alttg_list['has_corr'][region] = True
alttg_list['weight'][region] = weight
alttg_list['time_acc'][region] = time_acc
alttg_list['alt_coords'][region] = alt_acc[corr_array>settings['min_corr'],:]
return
def compute_ts():
global altimetry, alttg_list, alttg_data, settings
print('Sampling GIA and GRD at altimetry points...')
# --------------------------------------------------------
# Compute time series of VLM and residual VLM
# vlm_res = Alt - GSL_gia - GSL_pd - TG + RSL_gia + RSL_pd
# --------------------------------------------------------
alttg_data = {}
alttg_data['vlm_ts'] = mp_filled_float(np.zeros([len(alttg_list['id']),len(altimetry['time'])])*np.nan)
alttg_data['resvlm_ts'] = mp_filled_float(np.zeros([settings['num_ens'],len(alttg_list['id']),len(altimetry['time'])])*np.nan)
# Full VLM time series
for region in range(len(alttg_list['has_corr'])):
if alttg_list['has_corr'][region]:
# vlm_ts_lcl = altimetry - tg: Weighted average of all grid points
vlm_ts_lcl = (alttg_list['weight'][region] * (altimetry['ssh'][:,alttg_list['alt_coords'][region][:,0], alttg_list['alt_coords'][region][:,1]] - alttg_list['height'][region,:][:, np.newaxis])).sum(axis=1)
alttg_data['vlm_ts'][region] = vlm_ts_lcl - np.nanmean(vlm_ts_lcl)
pool = mp.Pool(settings['nproc'])
out = pool.map(resvlm_ts_ens, range(settings['num_ens']))
return
def resvlm_ts_ens(ens):
print(ens)
global altimetry, alttg_list, alttg_data, settings
time_alt_idx = np.in1d(settings['years'],altimetry['time'])
GRD = read_GRD_ens(ens, time_alt_idx, settings)
GIA = read_GIA_ens(ens,settings)
# Dynamic altimetry: altimetry - GSL_GRD - GSL_GIA
# Dynamic tide gauge = tide gauge - RSL_GIA - RSL_GRD
altimetry_dynamic = altimetry['ssh'] - GIA['gsl'][np.newaxis, :, :] * (altimetry['time'] - altimetry['time'].mean())[:, np.newaxis, np.newaxis] - GRD['gsl']
for region in range(len(alttg_list['has_corr'])):
if alttg_list['has_corr'][region]:
tidegauge_dynamic = alttg_list['height'][region] - GIA['rsl'][alttg_list['tg_coords'][region,0],alttg_list['tg_coords'][region,1]]*(altimetry['time']-altimetry['time'].mean())-GRD['rsl'][:,alttg_list['tg_coords'][region, 0],alttg_list['tg_coords'][region, 1]]
residual_vlm_lcl = (alttg_list['weight'][region]*(altimetry_dynamic[:,alttg_list['alt_coords'][region][:,0], alttg_list['alt_coords'][region][:, 1]]-tidegauge_dynamic[:, np.newaxis])).sum(axis=1)
alttg_data['resvlm_ts'][ens,region,:] = residual_vlm_lcl
return
def compute_trend():
global alttg_list, alttg_data, settings
print('Computing ALTTG trends...')
alttg_data['vlm_trend'] = mp_filled_float(np.zeros([len(alttg_list['id']),2])*np.nan)
alttg_data['resvlm_trend_mean'] = mp_filled_float(np.zeros([len(alttg_list['id']),2])*np.nan)
alttg_data['resvlm_trend_ens'] = mp_filled_float(np.zeros([settings['num_ens'],len(alttg_list['id'])])*np.nan)
alttg_data['resvlm_sterr_AR1'] = mp_filled_float(np.zeros(len(alttg_list['id']))*np.nan)
pool = mp.Pool(settings['nproc'])
out = pool.map(compute_trend_indiv, range(len(alttg_list['id'])))
return
def compute_trend_indiv(region):
global altimetry, alttg_list, alttg_data, settings
if alttg_list['has_corr'][region]:
print(' Region ' + str(region))
# Trend in VLM
alttg_data['vlm_trend'][region,:] = np.array(trend_ar1(region, altimetry['time'][alttg_list['time_acc'][region]], alttg_data['vlm_ts'][region][alttg_list['time_acc'][region]]))
# Trend in residual VLM
# AR1 trend uncertainty
alttg_data['resvlm_trend_mean'][region,:] = np.array(trend_ar1(region, altimetry['time'][alttg_list['time_acc'][region]], (settings['probability'][:,np.newaxis] * alttg_data['resvlm_ts'][:,region, :]).sum(axis=0)[alttg_list['time_acc'][region]]))
alttg_data['resvlm_sterr_AR1'][region] = alttg_data['resvlm_trend_mean'][region,1].copy()
amat = np.ones([alttg_list['time_acc'][region].sum(), 2])
amat[:, 1] = altimetry['time'][alttg_list['time_acc'][region]] - altimetry['time'][alttg_list['time_acc'][region]].mean()
resvlm_ens_mean = np.zeros(settings['num_ens'])
for ens in range(settings['num_ens']):
resvlm_ens_mean[ens] = np.linalg.lstsq(amat, alttg_data['resvlm_ts'][ens,region, alttg_list['time_acc'][region]], rcond=None)[0][1]
alttg_data['resvlm_trend_ens'][:,region] = resvlm_ens_mean
resvlm_mn = (settings['probability'] * resvlm_ens_mean).sum()
resvlm_se = np.sqrt((settings['probability'] * (resvlm_ens_mean-resvlm_mn)**2).sum())
alttg_data['resvlm_trend_mean'][region,1] = np.sqrt(alttg_data['resvlm_sterr_AR1'][region]**2+resvlm_se**2)
return
def save_data():
print('Saving data...')
global alttg_list, alttg_data, settings
acc_idx = np.isfinite(alttg_data['vlm_trend'][:,0])
alttg = {}
alttg['id'] = alttg_list['id'][acc_idx]
alttg['coords'] = alttg_list['coords'][acc_idx,:]
alttg['vlm_trend'] = alttg_data['vlm_trend'][acc_idx,:]
alttg['resvlm_trend_mean'] = alttg_data['resvlm_trend_mean'][acc_idx,:]
alttg['resvlm_trend_ens'] = alttg_data['resvlm_trend_ens'][:,acc_idx]
alttg['resvlm_sterr_AR1'] = alttg_data['resvlm_sterr_AR1'][acc_idx]
alttg['code'] = np.zeros(acc_idx.sum(),dtype=object)
alttg['code'][:] = 'ALTTG'
np.save(settings['fn_alttg_data'],alttg)
return
### HELPER FUNCTIONS
# def read_GIA(settings):
# print('Reading GIA...')
# global GIA
# GIA = {}
# file_handle = Dataset(settings['fn_gia_rad'], 'r')
# file_handle.set_auto_mask(False)
# GIA['lat'] = mp_filled_float(file_handle.variables['y'][:])
# GIA['lon'] = mp_filled_float(file_handle.variables['x'][:])
# GIA['probability'] = mp_filled_float(file_handle.variables['probability'][:settings['num_ens']])
# GIA['probability'] = GIA['probability']/GIA['probability'].sum()
# GIA['rad'] = mp_filled_float(file_handle.variables['rad'][:settings['num_ens'],:,:])
# file_handle.close()
#
# file_handle = Dataset(settings['fn_gia_rsl'], 'r')
# file_handle.set_auto_mask(False)
# GIA['rsl'] = mp_filled_float(file_handle.variables['rsl'][:settings['num_ens'],:,:])
# file_handle.close()
# GIA['gsl'] = mp_filled_float(GIA['rad'] + GIA['rsl'])
# return
def read_GIA_ens(ens,settings):
GIA = {}
# radial deformation
file_handle = Dataset(settings['fn_gia_rad'], 'r')
file_handle.set_auto_mask(False)
if settings['test_run_ICE6G_D']:
GIA['rad'] = file_handle.variables['rad'][:]
else:
GIA['rad'] = file_handle.variables['rad'][ens,:,:]
# rsl
file_handle = Dataset(settings['fn_gia_rsl'], 'r')
file_handle.set_auto_mask(False)
if settings['test_run_ICE6G_D']:
GIA['rsl'] = file_handle.variables['RSL'][:]
else:
GIA['rsl'] = file_handle.variables['rsl'][ens,:,:]
file_handle.close()
#gsl
GIA['gsl'] = mp_filled_float(GIA['rad'] + GIA['rsl'])
return(GIA)
def read_GRD_ens(ens,time_alt_idx,settings):
file_handle = Dataset(settings['dir_grd']+'grd_'+str(ens)+'.nc', 'r')
file_handle.set_auto_mask(False)
PD = {}
PD['rad'] = file_handle.variables['rad'][time_alt_idx,:,:]
PD['rsl'] = file_handle.variables['rsl'][time_alt_idx,:,:]
PD['gsl'] = PD['rad'] + PD['rsl']
file_handle.close()
return(PD)
def read_altimetry():
print('Reading altimetry...')
global altimetry, settings
altimetry = {}
file_handle = Dataset(settings['fn_altimetry'], 'r')
file_handle.set_auto_mask(False)
altimetry['lat'] = mp_filled_float(file_handle.variables['y'][:])
altimetry['lon'] = mp_filled_float(file_handle.variables['x'][:])
altimetry['time'] = mp_filled_float(file_handle.variables['t'][:])
altimetry['ssh'] = mp_filled_float(file_handle.variables['z'][:])
file_handle.close()
altimetry['slm'] = mp_filled_bool(np.isfinite(altimetry['ssh'][-1,:,:]))
return
def trend_ar1(region,time,tseries):
global settings
# Determine trend and associated uncertainty (AR1) using Hector
# 1. Save settings
dir_lcl = settings['dir_scratch']+str(region)+'/'
if not os.path.isdir(dir_lcl):
os.mkdir(dir_lcl)
config_list = []
config_list.append('DataFile input.mom\n')
config_list.append('DataDirectory ./\n')
config_list.append('OutputFile trend.out\n')
config_list.append('interpolate no\n')
config_list.append('firstdifference no\n')
config_list.append('PhysicalUnit m\n')
config_list.append('DegreePolynomial 1\n')
config_list.append('seasonalsignal no\n')
config_list.append('halfseasonalsignal no\n')
config_list.append('estimateoffsets no\n')
config_list.append('NoiseModels ARMA White\n')
config_list.append('AR_p 1\n')
config_list.append('MA_q 0\n')
config_list.append('RandomiseFirstGuess yes\n')
open(dir_lcl+'estimatetrend.ctl','w+').writelines(config_list)
out = shutil.copy2(settings['fn_hector'],dir_lcl) # Copy Hector executable to scratch
tseries = tseries - tseries.mean()
mjd = 365.25 * (time-time[0])
sample_period = np.min(np.diff(mjd))
headerline = 'sampling period '+str(sample_period)
np.savetxt(dir_lcl+'input.mom', np.transpose([mjd, tseries]), fmt=['%.4f', '%.4f'], header=headerline)
os.chdir(dir_lcl)
os.system(dir_lcl + 'estimatetrend >' + dir_lcl + 'output_orig.txt')
output_data = [line.rstrip('\n') for line in open(dir_lcl + 'output_orig.txt')]
trend_str = next((s for s in output_data if 'trend: ' in s), None)
trend_mean = float(trend_str.split()[1])
trend_sterr = float(trend_str.split()[3])
os.chdir(os.getenv('HOME')+'/Scripts/Python/')
return(trend_mean,trend_sterr)
def merge_stations_to_region(rsl_in_region):
while rsl_in_region.shape[1]>1:
# Find max number of overlaps
n_ovl = np.zeros([rsl_in_region.shape[1],rsl_in_region.shape[1]],dtype=int)
for i in range(rsl_in_region.shape[1]):
for j in range(rsl_in_region.shape[1]):
if i>j: n_ovl[i,j] = np.isfinite(rsl_in_region[:,i]*rsl_in_region[:,j]).sum()
merge_idx = np.unravel_index(np.argmax(n_ovl),n_ovl.shape)
merge_array_lcl = rsl_in_region[:,merge_idx]
merge_array_lcl = gentools.merge_common_mean(merge_array_lcl)
rsl_in_region = np.hstack([rsl_in_region,merge_array_lcl[:,np.newaxis]])
rsl_in_region = np.delete(rsl_in_region,merge_idx,axis=1)
rsl_in_region = rsl_in_region.flatten()
return(rsl_in_region)
# Parallel processing routines
def mp_empty_float(shape):
shared_array_base = mp.RawArray(ct.c_float, int(np.prod(shape)))
shared_array = np.ctypeslib.as_array(shared_array_base).reshape(*shape)
return shared_array
def mp_empty_int(shape):
shared_array_base = mp.RawArray(ct.c_int, int(np.prod(shape)))
shared_array = np.ctypeslib.as_array(shared_array_base).reshape(*shape)
return shared_array
def mp_filled_float(input_array):
shape = input_array.shape
shared_array_base = mp.RawArray(ct.c_float, input_array.flatten())
shared_array = np.ctypeslib.as_array(shared_array_base).reshape(*shape)
return shared_array
def mp_filled_bool(input_array):
shape = input_array.shape
shared_array_base = mp.RawArray(ct.c_bool, input_array.flatten())
shared_array = np.ctypeslib.as_array(shared_array_base).reshape(*shape)
return shared_array
if __name__ == '__main__':
main() | [
"os.mkdir",
"numpy.load",
"numpy.abs",
"numpy.argmax",
"numpy.ones",
"numpy.isnan",
"numpy.arange",
"glob.glob",
"os.chdir",
"numpy.prod",
"numpy.nanmean",
"netCDF4.Dataset",
"os.uname",
"numpy.transpose",
"numpy.isfinite",
"numpy.save",
"numpy.in1d",
"numpy.corrcoef",
"shutil.co... | [((965, 986), 'numpy.arange', 'np.arange', (['(1900)', '(2019)'], {}), '(1900, 2019)\n', (974, 986), True, 'import numpy as np\n'), ((4063, 4108), 'numpy.in1d', 'np.in1d', (["settings['years']", "altimetry['time']"], {}), "(settings['years'], altimetry['time'])\n", (4070, 4108), True, 'import numpy as np\n'), ((9928, 9954), 'multiprocessing.Pool', 'mp.Pool', (["settings['nproc']"], {}), "(settings['nproc'])\n", (9935, 9954), True, 'import multiprocessing as mp\n'), ((10143, 10188), 'numpy.in1d', 'np.in1d', (["settings['years']", "altimetry['time']"], {}), "(settings['years'], altimetry['time'])\n", (10150, 10188), True, 'import numpy as np\n'), ((11730, 11756), 'multiprocessing.Pool', 'mp.Pool', (["settings['nproc']"], {}), "(settings['nproc'])\n", (11737, 11756), True, 'import multiprocessing as mp\n'), ((13540, 13582), 'numpy.isfinite', 'np.isfinite', (["alttg_data['vlm_trend'][:, 0]"], {}), "(alttg_data['vlm_trend'][:, 0])\n", (13551, 13582), True, 'import numpy as np\n'), ((14071, 14112), 'numpy.save', 'np.save', (["settings['fn_alttg_data']", 'alttg'], {}), "(settings['fn_alttg_data'], alttg)\n", (14078, 14112), True, 'import numpy as np\n'), ((15131, 15167), 'netCDF4.Dataset', 'Dataset', (["settings['fn_gia_rad']", '"""r"""'], {}), "(settings['fn_gia_rad'], 'r')\n", (15138, 15167), False, 'from netCDF4 import Dataset\n'), ((15392, 15428), 'netCDF4.Dataset', 'Dataset', (["settings['fn_gia_rsl']", '"""r"""'], {}), "(settings['fn_gia_rsl'], 'r')\n", (15399, 15428), False, 'from netCDF4 import Dataset\n'), ((16229, 16267), 'netCDF4.Dataset', 'Dataset', (["settings['fn_altimetry']", '"""r"""'], {}), "(settings['fn_altimetry'], 'r')\n", (16236, 16267), False, 'from netCDF4 import Dataset\n'), ((17701, 17745), 'shutil.copy2', 'shutil.copy2', (["settings['fn_hector']", 'dir_lcl'], {}), "(settings['fn_hector'], dir_lcl)\n", (17713, 17745), False, 'import shutil\n'), ((18061, 18078), 'os.chdir', 'os.chdir', (['dir_lcl'], {}), '(dir_lcl)\n', (18069, 18078), False, 'import os\n'), ((18083, 18151), 'os.system', 'os.system', (["(dir_lcl + 'estimatetrend >' + dir_lcl + 'output_orig.txt')"], {}), "(dir_lcl + 'estimatetrend >' + dir_lcl + 'output_orig.txt')\n", (18092, 18151), False, 'import os\n'), ((1391, 1408), 'os.getenv', 'os.getenv', (['"""HOME"""'], {}), "('HOME')\n", (1400, 1408), False, 'import os\n'), ((1450, 1467), 'os.getenv', 'os.getenv', (['"""HOME"""'], {}), "('HOME')\n", (1459, 1467), False, 'import os\n'), ((4689, 4743), 'numpy.load', 'np.load', (["settings['fn_region_list']"], {'allow_pickle': '(True)'}), "(settings['fn_region_list'], allow_pickle=True)\n", (4696, 4743), True, 'import numpy as np\n'), ((5732, 5750), 'numpy.array', 'np.array', (['alttg_id'], {}), '(alttg_id)\n', (5740, 5750), True, 'import numpy as np\n'), ((6838, 6882), 'numpy.isfinite', 'np.isfinite', (["alttg_list['height'][region, :]"], {}), "(alttg_list['height'][region, :])\n", (6849, 6882), True, 'import numpy as np\n'), ((12857, 12886), 'numpy.zeros', 'np.zeros', (["settings['num_ens']"], {}), "(settings['num_ens'])\n", (12865, 12886), True, 'import numpy as np\n'), ((13361, 13430), 'numpy.sqrt', 'np.sqrt', (["(alttg_data['resvlm_sterr_AR1'][region] ** 2 + resvlm_se ** 2)"], {}), "(alttg_data['resvlm_sterr_AR1'][region] ** 2 + resvlm_se ** 2)\n", (13368, 13430), True, 'import numpy as np\n'), ((16653, 16692), 'numpy.isfinite', 'np.isfinite', (["altimetry['ssh'][-1, :, :]"], {}), "(altimetry['ssh'][-1, :, :])\n", (16664, 16692), True, 'import numpy as np\n'), ((16916, 16938), 'os.path.isdir', 'os.path.isdir', (['dir_lcl'], {}), '(dir_lcl)\n', (16929, 16938), False, 'import os\n'), ((16948, 16965), 'os.mkdir', 'os.mkdir', (['dir_lcl'], {}), '(dir_lcl)\n', (16956, 16965), False, 'import os\n'), ((17881, 17893), 'numpy.diff', 'np.diff', (['mjd'], {}), '(mjd)\n', (17888, 17893), True, 'import numpy as np\n'), ((17986, 18014), 'numpy.transpose', 'np.transpose', (['[mjd, tseries]'], {}), '([mjd, tseries])\n', (17998, 18014), True, 'import numpy as np\n'), ((18620, 18689), 'numpy.zeros', 'np.zeros', (['[rsl_in_region.shape[1], rsl_in_region.shape[1]]'], {'dtype': 'int'}), '([rsl_in_region.shape[1], rsl_in_region.shape[1]], dtype=int)\n', (18628, 18689), True, 'import numpy as np\n'), ((19028, 19071), 'mod_gentools.merge_common_mean', 'gentools.merge_common_mean', (['merge_array_lcl'], {}), '(merge_array_lcl)\n', (19054, 19071), True, 'import mod_gentools as gentools\n'), ((19096, 19154), 'numpy.hstack', 'np.hstack', (['[rsl_in_region, merge_array_lcl[:, np.newaxis]]'], {}), '([rsl_in_region, merge_array_lcl[:, np.newaxis]])\n', (19105, 19154), True, 'import numpy as np\n'), ((19177, 19220), 'numpy.delete', 'np.delete', (['rsl_in_region', 'merge_idx'], {'axis': '(1)'}), '(rsl_in_region, merge_idx, axis=1)\n', (19186, 19220), True, 'import numpy as np\n'), ((1489, 1499), 'os.uname', 'os.uname', ([], {}), '()\n', (1497, 1499), False, 'import os\n'), ((1587, 1604), 'os.getenv', 'os.getenv', (['"""HOME"""'], {}), "('HOME')\n", (1596, 1604), False, 'import os\n'), ((1735, 1752), 'os.getenv', 'os.getenv', (['"""HOME"""'], {}), "('HOME')\n", (1744, 1752), False, 'import os\n'), ((2155, 2183), 'numpy.ones', 'np.ones', (["settings['num_ens']"], {}), "(settings['num_ens'])\n", (2162, 2183), True, 'import numpy as np\n'), ((3501, 3563), 'glob.glob', 'glob.glob', (["(settings['dir_budget'] + 'region_data/region_list*')"], {}), "(settings['dir_budget'] + 'region_data/region_list*')\n", (3510, 3563), False, 'import glob\n'), ((7585, 7720), 'mod_gentools.point_grid_distance', 'gentools.point_grid_distance', (["alttg_list['coords'][region, 0]", "alttg_list['coords'][region, 1]", "altimetry['lat']", "altimetry['lon']"], {}), "(alttg_list['coords'][region, 0], alttg_list[\n 'coords'][region, 1], altimetry['lat'], altimetry['lon'])\n", (7613, 7720), True, 'import mod_gentools as gentools\n'), ((18411, 18428), 'os.getenv', 'os.getenv', (['"""HOME"""'], {}), "('HOME')\n", (18420, 18428), False, 'import os\n'), ((18919, 18935), 'numpy.argmax', 'np.argmax', (['n_ovl'], {}), '(n_ovl)\n', (18928, 18935), True, 'import numpy as np\n'), ((19400, 19414), 'numpy.prod', 'np.prod', (['shape'], {}), '(shape)\n', (19407, 19414), True, 'import numpy as np\n'), ((19436, 19476), 'numpy.ctypeslib.as_array', 'np.ctypeslib.as_array', (['shared_array_base'], {}), '(shared_array_base)\n', (19457, 19476), True, 'import numpy as np\n'), ((19593, 19607), 'numpy.prod', 'np.prod', (['shape'], {}), '(shape)\n', (19600, 19607), True, 'import numpy as np\n'), ((19629, 19669), 'numpy.ctypeslib.as_array', 'np.ctypeslib.as_array', (['shared_array_base'], {}), '(shared_array_base)\n', (19650, 19669), True, 'import numpy as np\n'), ((19865, 19905), 'numpy.ctypeslib.as_array', 'np.ctypeslib.as_array', (['shared_array_base'], {}), '(shared_array_base)\n', (19886, 19905), True, 'import numpy as np\n'), ((20099, 20139), 'numpy.ctypeslib.as_array', 'np.ctypeslib.as_array', (['shared_array_base'], {}), '(shared_array_base)\n', (20120, 20139), True, 'import numpy as np\n'), ((3663, 3685), 'os.path.getmtime', 'os.path.getmtime', (['file'], {}), '(file)\n', (3679, 3685), False, 'import os\n'), ((3733, 3749), 'numpy.argmax', 'np.argmax', (['cdate'], {}), '(cdate)\n', (3742, 3749), True, 'import numpy as np\n'), ((4206, 4270), 'numpy.load', 'np.load', (["settings['fn_regions_for_selection']"], {'allow_pickle': '(True)'}), "(settings['fn_regions_for_selection'], allow_pickle=True)\n", (4213, 4270), True, 'import numpy as np\n'), ((4604, 4659), 'numpy.load', 'np.load', (["settings['fn_station_data']"], {'allow_pickle': '(True)'}), "(settings['fn_station_data'], allow_pickle=True)\n", (4611, 4659), True, 'import numpy as np\n'), ((5879, 5901), 'numpy.array', 'np.array', (['alttg_height'], {}), '(alttg_height)\n', (5887, 5901), True, 'import numpy as np\n'), ((6993, 7051), 'numpy.abs', 'np.abs', (["(altimetry['lat'] - alttg_list['coords'][region, 0])"], {}), "(altimetry['lat'] - alttg_list['coords'][region, 0])\n", (6999, 7051), True, 'import numpy as np\n'), ((7110, 7168), 'numpy.abs', 'np.abs', (["(altimetry['lon'] - alttg_list['coords'][region, 1])"], {}), "(altimetry['lon'] - alttg_list['coords'][region, 1])\n", (7116, 7168), True, 'import numpy as np\n'), ((8230, 8250), 'numpy.isnan', 'np.isnan', (['corr_array'], {}), '(corr_array)\n', (8238, 8250), True, 'import numpy as np\n'), ((9894, 9916), 'numpy.nanmean', 'np.nanmean', (['vlm_ts_lcl'], {}), '(vlm_ts_lcl)\n', (9904, 9916), True, 'import numpy as np\n'), ((3775, 3791), 'numpy.argmax', 'np.argmax', (['cdate'], {}), '(cdate)\n', (3784, 3791), True, 'import numpy as np\n'), ((5798, 5820), 'numpy.array', 'np.array', (['alttg_coords'], {}), '(alttg_coords)\n', (5806, 5820), True, 'import numpy as np\n'), ((7788, 7829), 'numpy.where', 'np.where', (["(distance < settings['max_dist'])"], {}), "(distance < settings['max_dist'])\n", (7796, 7829), True, 'import numpy as np\n'), ((8166, 8202), 'numpy.corrcoef', 'np.corrcoef', (['alt_detrend', 'tg_detrend'], {}), '(alt_detrend, tg_detrend)\n', (8177, 8202), True, 'import numpy as np\n'), ((12969, 13077), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['amat', "alttg_data['resvlm_ts'][ens, region, alttg_list['time_acc'][region]]"], {'rcond': 'None'}), "(amat, alttg_data['resvlm_ts'][ens, region, alttg_list[\n 'time_acc'][region]], rcond=None)\n", (12984, 13077), True, 'import numpy as np\n'), ((7452, 7528), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['amat', "alttg_list['height'][region, :][time_acc]"], {'rcond': 'None'}), "(amat, alttg_list['height'][region, :][time_acc], rcond=None)\n", (7467, 7528), True, 'import numpy as np\n'), ((2492, 2528), 'netCDF4.Dataset', 'Dataset', (["settings['fn_gia_rad']", '"""r"""'], {}), "(settings['fn_gia_rad'], 'r')\n", (2499, 2528), False, 'from netCDF4 import Dataset\n'), ((8033, 8136), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['amat', "altimetry['ssh'][:, alt_acc[alt, 0], alt_acc[alt, 1]][time_acc]"], {'rcond': 'None'}), "(amat, altimetry['ssh'][:, alt_acc[alt, 0], alt_acc[alt, 1]]\n [time_acc], rcond=None)\n", (8048, 8136), True, 'import numpy as np\n'), ((18825, 18879), 'numpy.isfinite', 'np.isfinite', (['(rsl_in_region[:, i] * rsl_in_region[:, j])'], {}), '(rsl_in_region[:, i] * rsl_in_region[:, j])\n', (18836, 18879), True, 'import numpy as np\n')] |
import numpy as np
def StandardMap(t_initial, u_initial, PARAMETERS=[0.3, 1]):
"""
Chirikov standard map for initial conditions in a unit square, centred at the origin (as used in [1]_).
The map is defined in a perioidic manner, but maps points outside the unit square (periodic domain).
The Lagrangian descriptor calculations use a correction, so that points are mapped into the unit square.
Number of model parameters: 1 . PARAMETERS = [K]
Functional form:
x_next = x_initial + y_initial - (K/(2*np.pi))*np.sin(2*np.pi*x_initial
y_next = y_initial - (K/(2*np.pi))*np.sin(2*np.pi*x_initial))
where u_initial = (x_initial, y_initial)
Parameters
----------
t_initial : float,
Time corresponding to u_initial.
u_initial : ndarray, shape(n,),
Points to be mapped.
PARAMETERS : list of floats,
Map parameters.
Returns
-------
u_next : ndarray, shape(n,)
Array of forward images of u under Chirikov standard map (not in the unit square necessarily).
References
----------
.. [1] J.D. Meiss Visual explorations of dynamics: The standard map. Pramana - J Phys 70, 965–988 (2008). https://doi.org/10.1007/s12043-008-0103-3
"""
x_initial, y_initial = u_initial.T
# Map parameters
K, time_step = PARAMETERS
# Map components
t_next = t_initial + time_step
x_next = x_initial + y_initial - (K/(2*np.pi))*np.sin(2*np.pi*x_initial)
y_next = y_initial - (K/(2*np.pi))*np.sin(2*np.pi*x_initial)
# Map next iteration
u_next = np.column_stack([ x_next, y_next])
return t_next, u_next
def StandardMap_inverse(t_initial, u_initial, PARAMETERS=[0.3, 1]):
"""
Inverse of Chirikov standard map for initial conditions in a unit square, centred at the origin (as used in [1]_).
The map is defined in a perioidic manner, but maps points outside the unit square (periodic domain).
The Lagrangian descriptor calculations use a correction, so that points are mapped into the unit square.
Number of model parameters: 1 . PARAMETERS = [K, time_step]
Functional form:
t_next = t_initial - time_step
x_next = x_initial - y_initial
y_next = y_initial + (K/(2*np.pi))*np.sin(2*np.pi*(x_initial - y_initial))
where u_initial = (x_initial, y_initial)
Parameters
----------
t_initial : float,
Time corresponding to u_initial.
u_initial : ndarray, shape(n,),
Points to be mapped.
PARAMETERS : list of floats,
Map parameters.
Returns
-------
t_next : float,
Time corresponding to u_next.
u_next : ndarray, shape(n,)
Array of backward images of u under Chirikov standard map (not in the unit square necessarily).
References
----------
.. [1] J.D. Meiss Visual explorations of dynamics: The standard map. Pramana - J Phys 70, 965–988 (2008). https://doi.org/10.1007/s12043-008-0103-3
"""
x_initial, y_initial = u_initial.T
# Map parameters
K, time_step = PARAMETERS
# Map components
t_next = t_initial - time_step
x_next = x_initial - y_initial
y_next = y_initial + (K/(2*np.pi))*np.sin(2*np.pi*(x_initial - y_initial))
# Map next iteration
u_next = np.column_stack([ x_next, y_next])
return t_next, u_next
def HenonMap(t_initial, u_initial, PARAMETERS=[0.298, 1, 1]):
"""
Henon map.
Number of model parameters: 2 . PARAMETERS = [a, b, time_step]
Functional form:
t_next = t_initial + time_step
x_next = a - x_initial^2 + b*y_initial
y_next = x_initial
where u_initial = (x_initial, y_initial)
Parameters
----------
t_initial : float,
Time corresponding to u_initial.
u_initial : ndarray, shape(n,),
Points to be mapped.
PARAMETERS : list of floats,
Map parameters.
Returns
-------
t_next : float,
Time corresponding to u_next.
u_next : ndarray, shape(n,)
Array of forward images of u under Henon map.
"""
x_initial, y_initial = u_initial.T
# Map parameters
a, b, time_step = PARAMETERS
# Map components
t_next = t_initial + time_step
x_next = a - x_initial**2 + b*y_initial
y_next = x_initial
# Map next iteration
u_next = np.column_stack([ x_next, y_next])
return t_next, u_next
def HenonMap_inverse(t_initial, u_initial, PARAMETERS=[0.298, 1, 1]):
"""
Inverse of Henon map.
Number of model parameters: 2 . PARAMETERS = [a, b, time_step]
Functional form:
t_next = t_initial - time_step
x_next = y_initial
y_next = (x_initial - a + y_initial^2)/b
where u_initial = (x_initial, y_initial)
Parameters
----------
t_initial : float,
Time corresponding to u_initial.
u_initial : ndarray, shape(n,),
Points to be mapped.
PARAMETERS : list of floats,
Map parameters.
Returns
-------
t_next : float,
Time corresponding to u_next.
u_next : ndarray, shape(n,)
Array of backward images of u under Henon map.
"""
x_initial, y_initial = u_initial.T
# Map parameters
a, b, time_step = PARAMETERS
# Map components
t_next = t_initial - time_step
x_next = y_initial
y_next = (x_initial - a + y_initial**2)/b
# Map next iteration
u_next = np.column_stack([ x_next, y_next])
return t_next, u_next
| [
"numpy.sin",
"numpy.column_stack"
] | [((1616, 1649), 'numpy.column_stack', 'np.column_stack', (['[x_next, y_next]'], {}), '([x_next, y_next])\n', (1631, 1649), True, 'import numpy as np\n'), ((3354, 3387), 'numpy.column_stack', 'np.column_stack', (['[x_next, y_next]'], {}), '([x_next, y_next])\n', (3369, 3387), True, 'import numpy as np\n'), ((4439, 4472), 'numpy.column_stack', 'np.column_stack', (['[x_next, y_next]'], {}), '([x_next, y_next])\n', (4454, 4472), True, 'import numpy as np\n'), ((5551, 5584), 'numpy.column_stack', 'np.column_stack', (['[x_next, y_next]'], {}), '([x_next, y_next])\n', (5566, 5584), True, 'import numpy as np\n'), ((1482, 1511), 'numpy.sin', 'np.sin', (['(2 * np.pi * x_initial)'], {}), '(2 * np.pi * x_initial)\n', (1488, 1511), True, 'import numpy as np\n'), ((1547, 1576), 'numpy.sin', 'np.sin', (['(2 * np.pi * x_initial)'], {}), '(2 * np.pi * x_initial)\n', (1553, 1576), True, 'import numpy as np\n'), ((3271, 3314), 'numpy.sin', 'np.sin', (['(2 * np.pi * (x_initial - y_initial))'], {}), '(2 * np.pi * (x_initial - y_initial))\n', (3277, 3314), True, 'import numpy as np\n')] |
import networkx as nx
import numpy as np
from scipy import sparse
def barabasi(n, mean_degree):
""" Adjacency matrix for a Barabasi-Albert preferential attachment network.
Each node is added with `mean_degree` edges.
Parameters
mean_degree (int): average edges per node. Must be an even integer
n (int): Number of nodes in the network
Returns
A (csc sparse matrix): Adjacency matrix of the network
"""
A = nx.adj_matrix(nx.barabasi_albert_graph(n,m)).T
return A
def erdos(n, mean_degree):
""" Erdos-Renyi random graph.
Parameters
mean_degree (int): average edges per node. Must be an even integer
n (int): Number of nodes in the network
Returns
A (csc sparse matrix): Adjacency matrix of the network
"""
p = mean_degree/n
A = nx.adj_matrix(nx.erdos_renyi_graph(n,p)).T
return A
def random_digraph(n, mean_degree):
""" Adjacency matrix for a random digraph. Each directed edge is present with probability p = mean_degree/n.
Since this is a directed graph model, `mean_degree = mean(indegree) = mean(outdegree)`
Parameters
mean_degree (int): average edges per node. Must be an even integer
n (int): Number of nodes in the network
Returns
A (csc sparse matrix): Adjacency matrix of the network
"""
p = mean_degree/n
return sparse.random(n,n, density=p, data_rvs=np.ones, format='csc')
def watts(mean_degree, n, p=0.1):
""" Adjacency matrix for a Watts-Strogatz small world network
Parameters
mean_degree (int): Average edges per node. Must be an even integer
n (int): Number of nodes in the network
param (float): Rewiring probability. p=0 produces a lattice,
p=1 produces a random graph
Returns
A (csc sparse matrix): Adjacency matrix of the network
"""
if mean_degree % 2 != 0:
warn("Watts-Strogatz requires a even integer mean degree. Rounding up.")
mean_degree = 2 * np.ceil(mean_degree / 2)
A = nx.adj_matrix(nx.watts_strogatz_graph(n, mean_degree, p)).T
return A
def geometric(mean_degree, n):
""" Random geometric graph
Parameters
mean_degree (int): average edges per node. Must be an even integer
n (int): Number of nodes in the network
Returns
A (csc sparse matrix): Adjacency matrix of the network
"""
r = (mean_degree/(np.pi*n))**.5
A = nx.adj_matrix(nx.random_geometric_graph(n, r)).T
return sparse.dok_matrix(A)
| [
"scipy.sparse.random",
"numpy.ceil",
"networkx.erdos_renyi_graph",
"networkx.watts_strogatz_graph",
"networkx.random_geometric_graph",
"networkx.barabasi_albert_graph",
"scipy.sparse.dok_matrix"
] | [((1448, 1510), 'scipy.sparse.random', 'sparse.random', (['n', 'n'], {'density': 'p', 'data_rvs': 'np.ones', 'format': '"""csc"""'}), "(n, n, density=p, data_rvs=np.ones, format='csc')\n", (1461, 1510), False, 'from scipy import sparse\n'), ((2619, 2639), 'scipy.sparse.dok_matrix', 'sparse.dok_matrix', (['A'], {}), '(A)\n', (2636, 2639), False, 'from scipy import sparse\n'), ((493, 523), 'networkx.barabasi_albert_graph', 'nx.barabasi_albert_graph', (['n', 'm'], {}), '(n, m)\n', (517, 523), True, 'import networkx as nx\n'), ((887, 913), 'networkx.erdos_renyi_graph', 'nx.erdos_renyi_graph', (['n', 'p'], {}), '(n, p)\n', (907, 913), True, 'import networkx as nx\n'), ((2105, 2129), 'numpy.ceil', 'np.ceil', (['(mean_degree / 2)'], {}), '(mean_degree / 2)\n', (2112, 2129), True, 'import numpy as np\n'), ((2152, 2194), 'networkx.watts_strogatz_graph', 'nx.watts_strogatz_graph', (['n', 'mean_degree', 'p'], {}), '(n, mean_degree, p)\n', (2175, 2194), True, 'import networkx as nx\n'), ((2573, 2604), 'networkx.random_geometric_graph', 'nx.random_geometric_graph', (['n', 'r'], {}), '(n, r)\n', (2598, 2604), True, 'import networkx as nx\n')] |
import magic
import numpy as np
import scanpy as sc
import torch
from datasets.np import NpDataset
from models.ae import AE
from models.api import *
from utils.plot import plot_gene_expression, generate_plot_embeddings
from utils.preprocess import preprocess_recipe, run_pca
from utils.trainer import AETrainer, AEMixupTrainer
from utils.config import *
random_seed = 0
np.random.seed(random_seed)
torch.manual_seed(random_seed)
# Load data
data_path = "/home/lexent/ensemble-ti/ensemble-ti/data/marrow_sample_scseq_counts.csv"
adata = sc.read(data_path, first_column_names=True)
# Preprocessing
min_expr_level = 50
min_cells = 10
use_hvg = False
n_top_genes = 1500
preprocessed_data = preprocess_recipe(
adata,
min_expr_level=min_expr_level,
min_cells=min_cells,
use_hvg=use_hvg,
n_top_genes=n_top_genes,
)
# Apply MAGIC on the data
magic_op = magic.MAGIC(random_state=random_seed, solver="exact")
X_magic = magic_op.fit_transform(preprocessed_data.X, genes="all_genes")
preprocessed_data.obsm["X_magic"] = X_magic
# Apply PCA
print("Computing PCA...")
_, _, n_comps = run_pca(preprocessed_data, use_hvg=use_hvg)
print(f"Components computed: {n_comps}")
# Train scvi on the data
train_scvi(adata, save_path="/home/lexent/ensemble_data/", n_epochs=400)
X_scvi = adata.obsm["X_scVI"]
preprocessed_data["X_scVI"] = X_scvi
# Apply different Non-Linear manifold learning embeddings
# Can also apply isomap, lle etc. here
embedding = Embedding(n_comps=10)
embedding.fit_transform(preprocessed_data, method="diffmap", metric="euclidean")
X_diffusion = preprocessed_data.obsm["diffusion_eigenvectors"]
embedding.fit_transform(preprocessed_data, method="lle")
X_lle = preprocessed_data.obsm["X_lle"]
embedding.fit_transform(preprocessed_data, method="isomap")
X_isomap = preprocessed_data.obsm["X_isomap"]
# Train the AutoEncoder to get the shared latent space
X_train = np.concatenate([X_diffusion, X_scvi], 1)
infeatures = X_scvi.shape[-1] + X_diffusion.shape[-1]
code_size = 10
dataset = NpDataset(X_train)
model = AE(infeatures, code_size=code_size)
train_loss = get_loss("mse")
trainer = AEMixupTrainer(dataset, model, train_loss, num_epochs=150)
trainer.train("/home/lexent/ensemble_data/ae/")
# FIXME: Refactor code to move this part in the code for AE
embedding = []
model = model.cpu()
model.eval()
with torch.no_grad():
for data in dataset:
embedding.append(model.encode(data.unsqueeze(0)).squeeze().numpy())
X_embedding = np.array(embedding)
# Compute the 2d embedding and plot
X_embedded = generate_plot_embeddings(X_diffusion, method="tsne", perplexity=150)
preprocessed_data.obsm["X_embedded"] = X_embedded
plot_gene_expression(
preprocessed_data,
genes=["CD34", "MPO", "GATA1", "IRF8"],
figsize=(16, 4),
cmap="plasma",
)
# Save this anndata object
preprocessed_data.write_h5ad(filename="./analysis.h5ad")
| [
"utils.plot.plot_gene_expression",
"numpy.random.seed",
"magic.MAGIC",
"torch.manual_seed",
"scanpy.read",
"utils.preprocess.preprocess_recipe",
"models.ae.AE",
"utils.preprocess.run_pca",
"utils.trainer.AEMixupTrainer",
"numpy.array",
"utils.plot.generate_plot_embeddings",
"datasets.np.NpData... | [((373, 400), 'numpy.random.seed', 'np.random.seed', (['random_seed'], {}), '(random_seed)\n', (387, 400), True, 'import numpy as np\n'), ((401, 431), 'torch.manual_seed', 'torch.manual_seed', (['random_seed'], {}), '(random_seed)\n', (418, 431), False, 'import torch\n'), ((541, 584), 'scanpy.read', 'sc.read', (['data_path'], {'first_column_names': '(True)'}), '(data_path, first_column_names=True)\n', (548, 584), True, 'import scanpy as sc\n'), ((692, 814), 'utils.preprocess.preprocess_recipe', 'preprocess_recipe', (['adata'], {'min_expr_level': 'min_expr_level', 'min_cells': 'min_cells', 'use_hvg': 'use_hvg', 'n_top_genes': 'n_top_genes'}), '(adata, min_expr_level=min_expr_level, min_cells=min_cells,\n use_hvg=use_hvg, n_top_genes=n_top_genes)\n', (709, 814), False, 'from utils.preprocess import preprocess_recipe, run_pca\n'), ((872, 925), 'magic.MAGIC', 'magic.MAGIC', ([], {'random_state': 'random_seed', 'solver': '"""exact"""'}), "(random_state=random_seed, solver='exact')\n", (883, 925), False, 'import magic\n'), ((1098, 1141), 'utils.preprocess.run_pca', 'run_pca', (['preprocessed_data'], {'use_hvg': 'use_hvg'}), '(preprocessed_data, use_hvg=use_hvg)\n', (1105, 1141), False, 'from utils.preprocess import preprocess_recipe, run_pca\n'), ((1896, 1936), 'numpy.concatenate', 'np.concatenate', (['[X_diffusion, X_scvi]', '(1)'], {}), '([X_diffusion, X_scvi], 1)\n', (1910, 1936), True, 'import numpy as np\n'), ((2016, 2034), 'datasets.np.NpDataset', 'NpDataset', (['X_train'], {}), '(X_train)\n', (2025, 2034), False, 'from datasets.np import NpDataset\n'), ((2043, 2078), 'models.ae.AE', 'AE', (['infeatures'], {'code_size': 'code_size'}), '(infeatures, code_size=code_size)\n', (2045, 2078), False, 'from models.ae import AE\n'), ((2118, 2176), 'utils.trainer.AEMixupTrainer', 'AEMixupTrainer', (['dataset', 'model', 'train_loss'], {'num_epochs': '(150)'}), '(dataset, model, train_loss, num_epochs=150)\n', (2132, 2176), False, 'from utils.trainer import AETrainer, AEMixupTrainer\n'), ((2471, 2490), 'numpy.array', 'np.array', (['embedding'], {}), '(embedding)\n', (2479, 2490), True, 'import numpy as np\n'), ((2541, 2609), 'utils.plot.generate_plot_embeddings', 'generate_plot_embeddings', (['X_diffusion'], {'method': '"""tsne"""', 'perplexity': '(150)'}), "(X_diffusion, method='tsne', perplexity=150)\n", (2565, 2609), False, 'from utils.plot import plot_gene_expression, generate_plot_embeddings\n'), ((2660, 2775), 'utils.plot.plot_gene_expression', 'plot_gene_expression', (['preprocessed_data'], {'genes': "['CD34', 'MPO', 'GATA1', 'IRF8']", 'figsize': '(16, 4)', 'cmap': '"""plasma"""'}), "(preprocessed_data, genes=['CD34', 'MPO', 'GATA1',\n 'IRF8'], figsize=(16, 4), cmap='plasma')\n", (2680, 2775), False, 'from utils.plot import plot_gene_expression, generate_plot_embeddings\n'), ((2339, 2354), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2352, 2354), False, 'import torch\n')] |
#!/usr/bin/env python3
import numpy as np
from scipy import misc, ndimage, signal
# def cool_effect(img, k):
# img_c = np.zeros_like(img)
# for c in range(img.shape[2]):
# img_c[:, :, c] = signal.convolve2d(img[:, :, c], k[:, :, c], mode='same')
# return np.sum(img_c, axis=2)
def translate(img, dx):
img_t = np.zeros_like(img)
if dx == 0:
img_t[:, :] = img[:, :]
elif dx > 0:
img_t[:, dx:] = img[:, :-dx]
else:
img_t[:, :dx] = img[:, -dx:]
return img_t
def convolution(img, k):
return np.sum(
[
signal.convolve2d(img[:, :, c], k[:, :, c])
for c in range(img.shape[2])
],
axis=0,
)
img = ndimage.imread("house.jpg")
k = np.array(
[
[[0, 1, -1], [1, -1, 0], [0, 0, 0]],
[[-1, 0, -1], [1, -1, 0], [1, 0, 0]],
[[1, -1, 0], [1, 0, 1], [-1, 0, 1]],
]
)
ct = translate(convolution(img, k), 100)
tc = convolution(translate(img, 100), k)
misc.imsave("conv_then_trans.png", ct)
misc.imsave("trans_then_conv.png", tc)
if np.all(ct[2:-2, 2:-2] == tc[2:-2, 2:-2]):
print("Equal!")
| [
"numpy.zeros_like",
"scipy.signal.convolve2d",
"numpy.array",
"scipy.misc.imsave",
"scipy.ndimage.imread",
"numpy.all"
] | [((716, 743), 'scipy.ndimage.imread', 'ndimage.imread', (['"""house.jpg"""'], {}), "('house.jpg')\n", (730, 743), False, 'from scipy import misc, ndimage, signal\n'), ((749, 875), 'numpy.array', 'np.array', (['[[[0, 1, -1], [1, -1, 0], [0, 0, 0]], [[-1, 0, -1], [1, -1, 0], [1, 0, 0]],\n [[1, -1, 0], [1, 0, 1], [-1, 0, 1]]]'], {}), '([[[0, 1, -1], [1, -1, 0], [0, 0, 0]], [[-1, 0, -1], [1, -1, 0], [1,\n 0, 0]], [[1, -1, 0], [1, 0, 1], [-1, 0, 1]]])\n', (757, 875), True, 'import numpy as np\n'), ((993, 1031), 'scipy.misc.imsave', 'misc.imsave', (['"""conv_then_trans.png"""', 'ct'], {}), "('conv_then_trans.png', ct)\n", (1004, 1031), False, 'from scipy import misc, ndimage, signal\n'), ((1032, 1070), 'scipy.misc.imsave', 'misc.imsave', (['"""trans_then_conv.png"""', 'tc'], {}), "('trans_then_conv.png', tc)\n", (1043, 1070), False, 'from scipy import misc, ndimage, signal\n'), ((1075, 1115), 'numpy.all', 'np.all', (['(ct[2:-2, 2:-2] == tc[2:-2, 2:-2])'], {}), '(ct[2:-2, 2:-2] == tc[2:-2, 2:-2])\n', (1081, 1115), True, 'import numpy as np\n'), ((337, 355), 'numpy.zeros_like', 'np.zeros_like', (['img'], {}), '(img)\n', (350, 355), True, 'import numpy as np\n'), ((590, 633), 'scipy.signal.convolve2d', 'signal.convolve2d', (['img[:, :, c]', 'k[:, :, c]'], {}), '(img[:, :, c], k[:, :, c])\n', (607, 633), False, 'from scipy import misc, ndimage, signal\n')] |
"""
Runner for system_simulator.py
Written by <NAME>
Adapted from the India5G repository.
January 2022
"""
import os
import sys
import configparser
import csv
import math
import fiona
from shapely.geometry import shape, Point, LineString, mapping
import numpy as np
from random import choice
from rtree import index
from collections import OrderedDict
from dice.generate_hex import produce_sites_and_site_areas
from dice.system_simulator import SimulationManager
np.random.seed(42)
CONFIG = configparser.ConfigParser()
CONFIG.read(os.path.join(os.path.dirname(__file__), 'script_config.ini'))
BASE_PATH = CONFIG['file_locations']['base_path']
DATA_INTERMEDIATE = os.path.join(BASE_PATH, 'intermediate')
def generate_receivers(site_area, parameters, grid):
"""
Generate receiver locations as points within the site area.
Sampling points can either be generated on a grid (grid=1)
or more efficiently between the transmitter and the edge
of the site (grid=0) area.
Parameters
----------
site_area : polygon
Shape of the site area we want to generate receivers within.
parameters : dict
Contains all necessary simulation parameters.
grid : int
Binary indicator to dictate receiver generation type.
Output
------
receivers : List of dicts
Contains the quantity of desired receivers within the area boundary.
"""
receivers = []
if grid == 1:
geom = shape(site_area[0]['geometry'])
geom_box = geom.bounds
minx = geom_box[0]
miny = geom_box[1]
maxx = geom_box[2]
maxy = geom_box[3]
id_number = 0
x_axis = np.linspace(
minx, maxx, num=(
int(math.sqrt(geom.area) / (math.sqrt(geom.area)/50))
)
)
y_axis = np.linspace(
miny, maxy, num=(
int(math.sqrt(geom.area) / (math.sqrt(geom.area)/50))
)
)
xv, yv = np.meshgrid(x_axis, y_axis, sparse=False, indexing='ij')
for i in range(len(x_axis)):
for j in range(len(y_axis)):
receiver = Point((xv[i,j], yv[i,j]))
indoor_outdoor_probability = np.random.rand(1,1)[0][0]
if geom.contains(receiver):
receivers.append({
'type': "Feature",
'geometry': {
"type": "Point",
"coordinates": [xv[i,j], yv[i,j]],
},
'properties': {
'ue_id': "id_{}".format(id_number),
"misc_losses": parameters['rx_misc_losses'],
"gain": parameters['rx_gain'],
"losses": parameters['rx_losses'],
"ue_height": float(parameters['rx_height']),
"indoor": (True if float(indoor_outdoor_probability) < \
float(0.5) else False),
}
})
id_number += 1
else:
pass
else:
centroid = shape(site_area[0]['geometry']).centroid
coord = site_area[0]['geometry']['coordinates'][0][0]
path = LineString([(coord), (centroid)])
length = int(path.length)
increment = int(length / 20)
indoor = parameters['indoor_users_percentage'] / 100
id_number = 0
for increment_value in range(1, 11):
point = path.interpolate(increment * increment_value)
indoor_outdoor_probability = np.random.rand(1,1)[0][0]
receivers.append({
'type': "Feature",
'geometry': mapping(point),
'properties': {
'ue_id': "id_{}".format(id_number),
"misc_losses": parameters['rx_misc_losses'],
"gain": parameters['rx_gain'],
"losses": parameters['rx_losses'],
"ue_height": float(parameters['rx_height']),
"indoor": (True if float(indoor_outdoor_probability) < \
float(indoor) else False),
}
})
id_number += 1
return receivers
def obtain_percentile_values(results, transmission_type, parameters, confidence_intervals):
"""
Get the threshold value for a metric based on a given percentiles.
Parameters
----------
results : list of dicts
All data returned from the system simulation.
parameters : dict
Contains all necessary simulation parameters.
Output
------
percentile_site_results : dict
Contains the percentile value for each site metric.
"""
output = []
path_loss_values = []
received_power_values = []
interference_values = []
noise_values = []
sinr_values = []
spectral_efficiency_values = []
estimated_capacity_values = []
estimated_capacity_values_km2 = []
for result in results:
path_loss_values.append(result['path_loss'])
received_power_values.append(result['received_power'])
interference_values.append(result['interference'])
noise_values.append(result['noise'])
sinr = result['sinr']
if sinr == None:
sinr = 0
else:
sinr_values.append(sinr)
spectral_efficiency = result['spectral_efficiency']
if spectral_efficiency == None:
spectral_efficiency = 0
else:
spectral_efficiency_values.append(spectral_efficiency)
estimated_capacity = result['capacity_mbps']
if estimated_capacity == None:
estimated_capacity = 0
else:
estimated_capacity_values.append(estimated_capacity)
estimated_capacity_km2 = result['capacity_mbps_km2']
if estimated_capacity_km2 == None:
estimated_capacity_km2 = 0
else:
estimated_capacity_values_km2.append(estimated_capacity_km2)
for confidence_interval in confidence_intervals:
output.append({
'confidence_interval': confidence_interval,
'tranmission_type': transmission_type,
'path_loss': np.percentile(
path_loss_values, confidence_interval #<- low path loss is better
),
'received_power': np.percentile(
received_power_values, 100 - confidence_interval
),
'interference': np.percentile(
interference_values, confidence_interval #<- low interference is better
),
'noise': np.percentile(
noise_values, confidence_interval #<- low interference is better
),
'sinr': np.percentile(
sinr_values, 100 - confidence_interval
),
'spectral_efficiency': np.percentile(
spectral_efficiency_values, 100 - confidence_interval
),
'capacity_mbps': np.percentile(
estimated_capacity_values, 100 - confidence_interval
),
'capacity_mbps_km2': np.percentile(
estimated_capacity_values_km2, 100 - confidence_interval
)
})
return output
def obtain_threshold_values_choice(results, parameters):
"""
Get the threshold capacity based on a given percentile.
Parameters
----------
results : list of dicts
All data returned from the system simulation.
parameters : dict
Contains all necessary simulation parameters.
Output
------
matching_result : float
Contains the chosen percentile value based on the input data.
"""
sinr_values = []
percentile = parameters['percentile']
for result in results:
sinr = result['sinr']
if sinr == None:
pass
else:
sinr_values.append(sinr)
sinr = np.percentile(sinr_values, percentile, interpolation='nearest')
matching_result = []
for result in results:
if float(result['sinr']) == float(sinr):
matching_result.append(result)
return float(choice(matching_result))
def convert_results_geojson(data):
"""
Convert results to geojson format, for writing to shapefile.
Parameters
----------
data : list of dicts
Contains all results ready to be written.
Outputs
-------
output : list of dicts
A list of geojson dictionaries ready for writing.
"""
output = []
for datum in data:
output.append({
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [
datum['receiver_x'], datum['receiver_y']]
},
'properties': {
'path_loss': float(datum['path_loss']),
'received_power': float(datum['received_power']),
'interference': float(datum['interference']),
'noise': float(datum['noise']),
'sinr': float(datum['sinr']),
'spectral_efficiency': float(
datum['spectral_efficiency']
),
'capacity_mbps': float(
datum['capacity_mbps']
),
'capacity_mbps_km2': float(
datum['capacity_mbps_km2']
),
},
}
)
return output
def write_full_results(data, environment, site_radius, frequency,
bandwidth, generation, ant_type, transmittion_type, directory,
filename, parameters):
"""
Write full results data to .csv.
Parameters
----------
data : list of dicts
Contains all results ready to be written.
environment : string
Either urban, suburban or rural clutter type.
site_radius : int
Radius of site area in meters.
frequency : float
Spectral frequency of carrier band in GHz.
bandwidth : int
Channel bandwidth of carrier band in MHz.
generation : string
Either 4G or 5G depending on technology generation.
ant_type : string
The type of transmitter modelled (macro, micro etc.).
tranmission_type : string
The type of tranmission (SISO, MIMO 4x4, MIMO 8x8 etc.).
directory : string
Folder the data will be written to.
filename : string
Name of the .csv file.
parameters : dict
Contains all necessary simulation parameters.
"""
sectors = parameters['sectorization']
inter_site_distance = site_radius * 2
site_area_km2 = (
math.sqrt(3) / 2 * inter_site_distance ** 2 / 1e6
)
sites_per_km2 = 1 / site_area_km2
if not os.path.exists(directory):
os.makedirs(directory)
full_path = os.path.join(directory, filename)
results_file = open(full_path, 'w', newline='')
results_writer = csv.writer(results_file)
results_writer.writerow(
(
'environment',
'inter_site_distance_m',
'sites_per_km2',
'frequency_GHz',
'bandwidth_MHz',
'number_of_sectors',
'generation',
'ant_type',
'transmittion_type',
'receiver_x',
'receiver_y',
'r_distance',
'path_loss_dB',
'r_model',
'received_power_dB',
'interference_dB',
'i_model',
'noise_dB',
'sinr_dB',
'spectral_efficiency_bps_hz',
'capacity_mbps',
'capacity_mbps_km2'
)
)
for row in data:
results_writer.writerow((
environment,
inter_site_distance,
sites_per_km2,
frequency,
bandwidth,
sectors,
generation,
ant_type,
transmittion_type,
row['receiver_x'],
row['receiver_y'],
row['distance'],
row['path_loss'],
row['r_model'],
row['received_power'],
row['interference'],
row['i_model'],
row['noise'],
row['sinr'],
row['spectral_efficiency'],
row['capacity_mbps'],
row['capacity_mbps_km2'],
))
def write_frequency_lookup_table(results, environment, site_radius,
frequency, bandwidth, generation, ant_type, tranmission_type,
directory, filename, parameters):
"""
Write the main, comprehensive lookup table for all environments,
site radii, frequencies etc.
Parameters
----------
results : list of dicts
Contains all results ready to be written.
environment : string
Either urban, suburban or rural clutter type.
site_radius : int
Radius of site area in meters.
frequency : float
Spectral frequency of carrier band in GHz.
bandwidth : int
Channel bandwidth of carrier band in MHz.
generation : string
Either 4G or 5G depending on technology generation.
ant_type : string
Type of transmitters modelled.
tranmission_type : string
The transmission type (SISO, MIMO etc.).
directory : string
Folder the data will be written to.
filename : string
Name of the .csv file.
parameters : dict
Contains all necessary simulation parameters.
"""
inter_site_distance = site_radius * 2
site_area_km2 = math.sqrt(3) / 2 * inter_site_distance ** 2 / 1e6
sites_per_km2 = 1 / site_area_km2
sectors = parameters['sectorization']
if not os.path.exists(directory):
os.makedirs(directory)
directory = os.path.join(directory, filename)
if not os.path.exists(directory):
lut_file = open(directory, 'w', newline='')
lut_writer = csv.writer(lut_file)
lut_writer.writerow(
(
'confidence_interval',
'environment',
'inter_site_distance_m',
'site_area_km2',
'sites_per_km2',
'frequency_GHz',
'bandwidth_MHz',
'number_of_sectors',
'generation',
'ant_type',
'transmission_type',
'path_loss_dB',
'received_power_dBm',
'interference_dBm',
'noise_dB',
'sinr_dB',
'spectral_efficiency_bps_hz',
'capacity_mbps',
'capacity_mbps_km2',
)
)
else:
lut_file = open(directory, 'a', newline='')
lut_writer = csv.writer(lut_file)
for result in results:
lut_writer.writerow(
(
result['confidence_interval'],
environment,
inter_site_distance,
site_area_km2,
sites_per_km2,
frequency,
bandwidth,
sectors,
generation,
ant_type,
tranmission_type,
result['path_loss'],
result['received_power'],
result['interference'],
result['noise'],
result['sinr'],
result['spectral_efficiency'],
result['capacity_mbps'],
result['capacity_mbps_km2'] * sectors,
)
)
lut_file.close()
if __name__ == '__main__':
PARAMETERS = {
'iterations': 1,
'seed_value1_3G': 1,
'seed_value2_3G': 2,
'seed_value1_4G': 3,
'seed_value2_4G': 4,
'seed_value1_5G': 5,
'seed_value2_5G': 6,
'seed_value1_urban': 7,
'seed_value2_urban': 8,
'seed_value1_suburban': 9,
'seed_value2_suburban': 10,
'seed_value1_rural': 11,
'seed_value2_rural': 12,
'seed_value1_free-space': 13,
'seed_value2_free-space': 14,
'indoor_users_percentage': 50,
'los_breakpoint_m': 500,
'tx_macro_baseline_height': 30,
'tx_macro_power': 40,
'tx_macro_gain': 16,
'tx_macro_losses': 1,
'tx_micro_baseline_height': 10,
'tx_micro_power': 24,
'tx_micro_gain': 5,
'tx_micro_losses': 1,
'rx_gain': 0,
'rx_losses': 4,
'rx_misc_losses': 4,
'rx_height': 1.5,
'building_height': 5,
'street_width': 20,
'above_roof': 0,
'network_load': 100,
'percentile': 50,
'sectorization': 3,
'mnos': 2,
'asset_lifetime': 10,
'discount_rate': 3.5,
'opex_percentage_of_capex': 10,
}
SPECTRUM_PORTFOLIO = [
(0.8, 10, '4G', '2x2'),
# (1.7, 10, '4G', '2x2'),
# (1.8, 1, '4G', '2x2'),
# (1.9, 1, '4G', '2x2'),
# (2.3, 1, '4G', '2x2'),
# (2.5, 1, '4G', '2x2'),
# (2.6, 10, '4G', '2x2'),
]
ANT_TYPES = [
('macro'),
]
MODULATION_AND_CODING_LUT = {
# ETSI. 2018. ‘5G; NR; Physical Layer Procedures for Data
# (3GPP TS 38.214 Version 15.3.0 Release 15)’. Valbonne, France: ETSI.
# Generation MIMO CQI Index Modulation Coding rate
# Spectral efficiency (bps/Hz) SINR estimate (dB)
'4G': [
('4G', '2x2', 1, 'QPSK', 78, 0.3, -6.7),
('4G', '2x2', 2, 'QPSK', 120, 0.46, -4.7),
('4G', '2x2', 3, 'QPSK', 193, 0.74, -2.3),
('4G', '2x2', 4, 'QPSK', 308, 1.2, 0.2),
('4G', '2x2', 5, 'QPSK', 449, 1.6, 2.4),
('4G', '2x2', 6, 'QPSK', 602, 2.2, 4.3),
('4G', '2x2', 7, '16QAM', 378, 2.8, 5.9),
('4G', '2x2', 8, '16QAM', 490, 3.8, 8.1),
('4G', '2x2', 9, '16QAM', 616, 4.8, 10.3),
('4G', '2x2', 10, '64QAM', 466, 5.4, 11.7),
('4G', '2x2', 11, '64QAM', 567, 6.6, 14.1),
('4G', '2x2', 12, '64QAM', 666, 7.8, 16.3),
('4G', '2x2', 13, '64QAM', 772, 9, 18.7),
('4G', '2x2', 14, '64QAM', 973, 10.2, 21),
('4G', '2x2', 15, '64QAM', 948, 11.4, 22.7),
],
'5G': [
('5G', '4x4', 1, 'QPSK', 78, 0.15, -6.7),
('5G', '4x4', 2, 'QPSK', 193, 1.02, -4.7),
('5G', '4x4', 3, 'QPSK', 449, 2.21, -2.3),
('5G', '4x4', 4, '16QAM', 378, 3.20, 0.2),
('5G', '4x4', 5, '16QAM', 490, 4.00, 2.4),
('5G', '4x4', 6, '16QAM', 616, 5.41, 4.3),
('5G', '4x4', 7, '64QAM', 466, 6.20, 5.9),
('5G', '4x4', 8, '64QAM', 567, 8.00, 8.1),
('5G', '4x4', 9, '64QAM', 666, 9.50, 10.3),
('5G', '4x4', 10, '64QAM', 772, 11.00, 11.7),
('5G', '4x4', 11, '64QAM', 873, 14.00, 14.1),
('5G', '4x4', 12, '256QAM', 711, 16.00, 16.3),
('5G', '4x4', 13, '256QAM', 797, 19.00, 18.7),
('5G', '4x4', 14, '256QAM', 885, 22.00, 21),
('5G', '4x4', 15, '256QAM', 948, 25.00, 22.7),
]
}
CONFIDENCE_INTERVALS = [
# 5,
# 50,
95,
]
def generate_site_radii(min, max, increment):
for n in range(min, max, increment):
yield n
INCREMENT_MA = (125,40000,125) #(400, 40400, 1000)
SITE_RADII = {
'macro': {
# 'urban':
# generate_site_radii(INCREMENT_MA[0],INCREMENT_MA[1],INCREMENT_MA[2]),
# 'suburban':
# generate_site_radii(INCREMENT_MA[0],INCREMENT_MA[1],INCREMENT_MA[2]),
# 'rural':
# generate_site_radii(INCREMENT_MA[0],INCREMENT_MA[1],INCREMENT_MA[2]),
'free-space':
generate_site_radii(INCREMENT_MA[0],INCREMENT_MA[1],INCREMENT_MA[2])
},
}
unprojected_point = {
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': (0, 0),
},
'properties': {
'site_id': 'Radio Tower'
}
}
unprojected_crs = 'epsg:4326'
projected_crs = 'epsg:3857'
environments =[
# 'urban',
# 'suburban',
# 'rural'
'free-space'
]
for environment in environments:
for ant_type in ANT_TYPES:
site_radii_generator = SITE_RADII[ant_type]
for site_radius in site_radii_generator[environment]:
# if not site_radius == 4400:
# continue
if environment == 'urban' and site_radius > 5000:
continue
if environment == 'suburban' and site_radius > 15000:
continue
print('--working on {}: {}'.format(environment, site_radius))
transmitter, interfering_transmitters, site_area, int_site_areas = \
produce_sites_and_site_areas(
unprojected_point['geometry']['coordinates'],
site_radius,
unprojected_crs,
projected_crs
)
receivers = generate_receivers(site_area, PARAMETERS, 1)
for frequency, bandwidth, generation, transmission_type in SPECTRUM_PORTFOLIO:
print('{}, {}, {}, {}'.format(frequency, bandwidth, generation, transmission_type))
MANAGER = SimulationManager(
transmitter, interfering_transmitters, ant_type,
receivers, site_area, PARAMETERS
)
results = MANAGER.estimate_link_budget(
frequency,
bandwidth,
generation,
ant_type,
transmission_type,
environment,
MODULATION_AND_CODING_LUT,
PARAMETERS
)
folder = os.path.join(DATA_INTERMEDIATE, 'luts', 'full_tables')
filename = 'full_capacity_lut_{}_{}_{}_{}_{}_{}.csv'.format(
environment, site_radius, generation, frequency, ant_type, transmission_type)
write_full_results(results, environment, site_radius,
frequency, bandwidth, generation, ant_type, transmission_type,
folder, filename, PARAMETERS)
percentile_site_results = obtain_percentile_values(
results, transmission_type, PARAMETERS, CONFIDENCE_INTERVALS
)
results_directory = os.path.join(DATA_INTERMEDIATE, 'luts')
write_frequency_lookup_table(percentile_site_results, environment,
site_radius, frequency, bandwidth, generation,
ant_type, transmission_type, results_directory,
'capacity_lut_by_frequency.csv', PARAMETERS
)
| [
"shapely.geometry.Point",
"numpy.meshgrid",
"numpy.random.seed",
"csv.writer",
"os.makedirs",
"math.sqrt",
"os.path.dirname",
"shapely.geometry.mapping",
"os.path.exists",
"random.choice",
"dice.generate_hex.produce_sites_and_site_areas",
"numpy.percentile",
"shapely.geometry.LineString",
... | [((471, 489), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (485, 489), True, 'import numpy as np\n'), ((500, 527), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (525, 527), False, 'import configparser\n'), ((672, 711), 'os.path.join', 'os.path.join', (['BASE_PATH', '"""intermediate"""'], {}), "(BASE_PATH, 'intermediate')\n", (684, 711), False, 'import os\n'), ((8086, 8149), 'numpy.percentile', 'np.percentile', (['sinr_values', 'percentile'], {'interpolation': '"""nearest"""'}), "(sinr_values, percentile, interpolation='nearest')\n", (8099, 8149), True, 'import numpy as np\n'), ((10997, 11030), 'os.path.join', 'os.path.join', (['directory', 'filename'], {}), '(directory, filename)\n', (11009, 11030), False, 'import os\n'), ((11105, 11129), 'csv.writer', 'csv.writer', (['results_file'], {}), '(results_file)\n', (11115, 11129), False, 'import csv\n'), ((13912, 13945), 'os.path.join', 'os.path.join', (['directory', 'filename'], {}), '(directory, filename)\n', (13924, 13945), False, 'import os\n'), ((553, 578), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (568, 578), False, 'import os\n'), ((1465, 1496), 'shapely.geometry.shape', 'shape', (["site_area[0]['geometry']"], {}), "(site_area[0]['geometry'])\n", (1470, 1496), False, 'from shapely.geometry import shape, Point, LineString, mapping\n'), ((2003, 2059), 'numpy.meshgrid', 'np.meshgrid', (['x_axis', 'y_axis'], {'sparse': '(False)', 'indexing': '"""ij"""'}), "(x_axis, y_axis, sparse=False, indexing='ij')\n", (2014, 2059), True, 'import numpy as np\n'), ((3356, 3385), 'shapely.geometry.LineString', 'LineString', (['[coord, centroid]'], {}), '([coord, centroid])\n', (3366, 3385), False, 'from shapely.geometry import shape, Point, LineString, mapping\n'), ((8314, 8337), 'random.choice', 'choice', (['matching_result'], {}), '(matching_result)\n', (8320, 8337), False, 'from random import choice\n'), ((10922, 10947), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (10936, 10947), False, 'import os\n'), ((10957, 10979), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (10968, 10979), False, 'import os\n'), ((13837, 13862), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (13851, 13862), False, 'import os\n'), ((13872, 13894), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (13883, 13894), False, 'import os\n'), ((13958, 13983), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (13972, 13983), False, 'import os\n'), ((14058, 14078), 'csv.writer', 'csv.writer', (['lut_file'], {}), '(lut_file)\n', (14068, 14078), False, 'import csv\n'), ((14881, 14901), 'csv.writer', 'csv.writer', (['lut_file'], {}), '(lut_file)\n', (14891, 14901), False, 'import csv\n'), ((3237, 3268), 'shapely.geometry.shape', 'shape', (["site_area[0]['geometry']"], {}), "(site_area[0]['geometry'])\n", (3242, 3268), False, 'from shapely.geometry import shape, Point, LineString, mapping\n'), ((2165, 2192), 'shapely.geometry.Point', 'Point', (['(xv[i, j], yv[i, j])'], {}), '((xv[i, j], yv[i, j]))\n', (2170, 2192), False, 'from shapely.geometry import shape, Point, LineString, mapping\n'), ((6362, 6414), 'numpy.percentile', 'np.percentile', (['path_loss_values', 'confidence_interval'], {}), '(path_loss_values, confidence_interval)\n', (6375, 6414), True, 'import numpy as np\n'), ((6504, 6567), 'numpy.percentile', 'np.percentile', (['received_power_values', '(100 - confidence_interval)'], {}), '(received_power_values, 100 - confidence_interval)\n', (6517, 6567), True, 'import numpy as np\n'), ((6627, 6682), 'numpy.percentile', 'np.percentile', (['interference_values', 'confidence_interval'], {}), '(interference_values, confidence_interval)\n', (6640, 6682), True, 'import numpy as np\n'), ((6766, 6814), 'numpy.percentile', 'np.percentile', (['noise_values', 'confidence_interval'], {}), '(noise_values, confidence_interval)\n', (6779, 6814), True, 'import numpy as np\n'), ((6897, 6950), 'numpy.percentile', 'np.percentile', (['sinr_values', '(100 - confidence_interval)'], {}), '(sinr_values, 100 - confidence_interval)\n', (6910, 6950), True, 'import numpy as np\n'), ((7017, 7085), 'numpy.percentile', 'np.percentile', (['spectral_efficiency_values', '(100 - confidence_interval)'], {}), '(spectral_efficiency_values, 100 - confidence_interval)\n', (7030, 7085), True, 'import numpy as np\n'), ((7146, 7213), 'numpy.percentile', 'np.percentile', (['estimated_capacity_values', '(100 - confidence_interval)'], {}), '(estimated_capacity_values, 100 - confidence_interval)\n', (7159, 7213), True, 'import numpy as np\n'), ((7278, 7349), 'numpy.percentile', 'np.percentile', (['estimated_capacity_values_km2', '(100 - confidence_interval)'], {}), '(estimated_capacity_values_km2, 100 - confidence_interval)\n', (7291, 7349), True, 'import numpy as np\n'), ((10816, 10828), 'math.sqrt', 'math.sqrt', (['(3)'], {}), '(3)\n', (10825, 10828), False, 'import math\n'), ((13694, 13706), 'math.sqrt', 'math.sqrt', (['(3)'], {}), '(3)\n', (13703, 13706), False, 'import math\n'), ((21089, 21212), 'dice.generate_hex.produce_sites_and_site_areas', 'produce_sites_and_site_areas', (["unprojected_point['geometry']['coordinates']", 'site_radius', 'unprojected_crs', 'projected_crs'], {}), "(unprojected_point['geometry']['coordinates'],\n site_radius, unprojected_crs, projected_crs)\n", (21117, 21212), False, 'from dice.generate_hex import produce_sites_and_site_areas\n'), ((3698, 3718), 'numpy.random.rand', 'np.random.rand', (['(1)', '(1)'], {}), '(1, 1)\n', (3712, 3718), True, 'import numpy as np\n'), ((3818, 3832), 'shapely.geometry.mapping', 'mapping', (['point'], {}), '(point)\n', (3825, 3832), False, 'from shapely.geometry import shape, Point, LineString, mapping\n'), ((21637, 21741), 'dice.system_simulator.SimulationManager', 'SimulationManager', (['transmitter', 'interfering_transmitters', 'ant_type', 'receivers', 'site_area', 'PARAMETERS'], {}), '(transmitter, interfering_transmitters, ant_type,\n receivers, site_area, PARAMETERS)\n', (21654, 21741), False, 'from dice.system_simulator import SimulationManager\n'), ((22235, 22289), 'os.path.join', 'os.path.join', (['DATA_INTERMEDIATE', '"""luts"""', '"""full_tables"""'], {}), "(DATA_INTERMEDIATE, 'luts', 'full_tables')\n", (22247, 22289), False, 'import os\n'), ((22910, 22949), 'os.path.join', 'os.path.join', (['DATA_INTERMEDIATE', '"""luts"""'], {}), "(DATA_INTERMEDIATE, 'luts')\n", (22922, 22949), False, 'import os\n'), ((1741, 1761), 'math.sqrt', 'math.sqrt', (['geom.area'], {}), '(geom.area)\n', (1750, 1761), False, 'import math\n'), ((1903, 1923), 'math.sqrt', 'math.sqrt', (['geom.area'], {}), '(geom.area)\n', (1912, 1923), False, 'import math\n'), ((2236, 2256), 'numpy.random.rand', 'np.random.rand', (['(1)', '(1)'], {}), '(1, 1)\n', (2250, 2256), True, 'import numpy as np\n'), ((1765, 1785), 'math.sqrt', 'math.sqrt', (['geom.area'], {}), '(geom.area)\n', (1774, 1785), False, 'import math\n'), ((1927, 1947), 'math.sqrt', 'math.sqrt', (['geom.area'], {}), '(geom.area)\n', (1936, 1947), False, 'import math\n')] |
"""
Match two sets of on-sky coordinates to each other.
I.e., find nearest neighbor of one that's in the other.
Similar in purpose to IDL's spherematch, but totally different implementation.
Requires numpy and scipy.
<NAME>
https://gist.github.com/eteq/4599814
"""
from __future__ import division
import numpy as np
try:
from scipy.spatial import cKDTree as KDT
except ImportError:
from scipy.spatial import KDTree as KDT
def spherematch(ra1, dec1, ra2, dec2, tol=None, nnearest=1):
"""
Finds matches in one catalog to another.
Parameters
ra1 : array-like
Right Ascension in degrees of the first catalog
dec1 : array-like
Declination in degrees of the first catalog (shape of array must match `ra1`)
ra2 : array-like
Right Ascension in degrees of the second catalog
dec2 : array-like
Declination in degrees of the second catalog (shape of array must match `ra2`)
tol : float or None, optional
How close (in degrees) a match has to be to count as a match. If None,
all nearest neighbors for the first catalog will be returned.
nnearest : int, optional
The nth neighbor to find. E.g., 1 for the nearest nearby, 2 for the
second nearest neighbor, etc. Particularly useful if you want to get
the nearest *non-self* neighbor of a catalog. To do this, use:
``spherematch(ra, dec, ra, dec, nnearest=2)``
Returns
-------
idx1 : int array
Indecies into the first catalog of the matches. Will never be
larger than `ra1`/`dec1`.
idx2 : int array
Indecies into the second catalog of the matches. Will never be
larger than `ra1`/`dec1`.
ds : float array
Distance (in degrees) between the matches
"""
ra1 = np.array(ra1, copy=False)
dec1 = np.array(dec1, copy=False)
ra2 = np.array(ra2, copy=False)
dec2 = np.array(dec2, copy=False)
if ra1.shape != dec1.shape:
raise ValueError('ra1 and dec1 do not match!')
if ra2.shape != dec2.shape:
raise ValueError('ra2 and dec2 do not match!')
x1, y1, z1 = _spherical_to_cartesian(ra1.ravel(), dec1.ravel())
# this is equivalent to, but faster than just doing np.array([x1, y1, z1])
coords1 = np.empty((x1.size, 3))
coords1[:, 0] = x1
coords1[:, 1] = y1
coords1[:, 2] = z1
x2, y2, z2 = _spherical_to_cartesian(ra2.ravel(), dec2.ravel())
# this is equivalent to, but faster than just doing np.array([x1, y1, z1])
coords2 = np.empty((x2.size, 3))
coords2[:, 0] = x2
coords2[:, 1] = y2
coords2[:, 2] = z2
kdt = KDT(coords2)
if nnearest == 1:
idxs2 = kdt.query(coords1)[1]
elif nnearest > 1:
idxs2 = kdt.query(coords1, nnearest)[1][:, -1]
else:
raise ValueError('invalid nnearest ' + str(nnearest))
ds = _great_circle_distance(ra1, dec1, ra2[idxs2], dec2[idxs2])
idxs1 = np.arange(ra1.size)
if tol is not None:
msk = ds < tol
idxs1 = idxs1[msk]
idxs2 = idxs2[msk]
ds = ds[msk]
return idxs1, idxs2, ds
def _spherical_to_cartesian(ra, dec):
"""
(Private internal function)
Inputs in degrees. Outputs x,y,z
"""
rar = np.radians(ra)
decr = np.radians(dec)
x = np.cos(rar) * np.cos(decr)
y = np.sin(rar) * np.cos(decr)
z = np.sin(decr)
return x, y, z
def _great_circle_distance(ra1, dec1, ra2, dec2):
"""
(Private internal function)
Returns great circle distance. Inputs in degrees.
Uses vincenty distance formula - a bit slower than others, but
numerically stable.
"""
from numpy import radians, degrees, sin, cos, arctan2, hypot
# terminology from the Vincenty formula - lambda and phi and
# "standpoint" and "forepoint"
lambs = radians(ra1)
phis = radians(dec1)
lambf = radians(ra2)
phif = radians(dec2)
dlamb = lambf - lambs
numera = cos(phif) * sin(dlamb)
numerb = cos(phis) * sin(phif) - sin(phis) * cos(phif) * cos(dlamb)
numer = hypot(numera, numerb)
denom = sin(phis) * sin(phif) + cos(phis) * cos(phif) * cos(dlamb)
return degrees(arctan2(numer, denom))
| [
"numpy.radians",
"numpy.arctan2",
"numpy.empty",
"numpy.hypot",
"numpy.sin",
"numpy.array",
"numpy.arange",
"scipy.spatial.KDTree",
"numpy.cos"
] | [((1800, 1825), 'numpy.array', 'np.array', (['ra1'], {'copy': '(False)'}), '(ra1, copy=False)\n', (1808, 1825), True, 'import numpy as np\n'), ((1837, 1863), 'numpy.array', 'np.array', (['dec1'], {'copy': '(False)'}), '(dec1, copy=False)\n', (1845, 1863), True, 'import numpy as np\n'), ((1874, 1899), 'numpy.array', 'np.array', (['ra2'], {'copy': '(False)'}), '(ra2, copy=False)\n', (1882, 1899), True, 'import numpy as np\n'), ((1911, 1937), 'numpy.array', 'np.array', (['dec2'], {'copy': '(False)'}), '(dec2, copy=False)\n', (1919, 1937), True, 'import numpy as np\n'), ((2276, 2298), 'numpy.empty', 'np.empty', (['(x1.size, 3)'], {}), '((x1.size, 3))\n', (2284, 2298), True, 'import numpy as np\n'), ((2531, 2553), 'numpy.empty', 'np.empty', (['(x2.size, 3)'], {}), '((x2.size, 3))\n', (2539, 2553), True, 'import numpy as np\n'), ((2634, 2646), 'scipy.spatial.KDTree', 'KDT', (['coords2'], {}), '(coords2)\n', (2637, 2646), True, 'from scipy.spatial import KDTree as KDT\n'), ((2939, 2958), 'numpy.arange', 'np.arange', (['ra1.size'], {}), '(ra1.size)\n', (2948, 2958), True, 'import numpy as np\n'), ((3247, 3261), 'numpy.radians', 'np.radians', (['ra'], {}), '(ra)\n', (3257, 3261), True, 'import numpy as np\n'), ((3273, 3288), 'numpy.radians', 'np.radians', (['dec'], {}), '(dec)\n', (3283, 3288), True, 'import numpy as np\n'), ((3368, 3380), 'numpy.sin', 'np.sin', (['decr'], {}), '(decr)\n', (3374, 3380), True, 'import numpy as np\n'), ((3826, 3838), 'numpy.radians', 'radians', (['ra1'], {}), '(ra1)\n', (3833, 3838), False, 'from numpy import radians, degrees, sin, cos, arctan2, hypot\n'), ((3850, 3863), 'numpy.radians', 'radians', (['dec1'], {}), '(dec1)\n', (3857, 3863), False, 'from numpy import radians, degrees, sin, cos, arctan2, hypot\n'), ((3876, 3888), 'numpy.radians', 'radians', (['ra2'], {}), '(ra2)\n', (3883, 3888), False, 'from numpy import radians, degrees, sin, cos, arctan2, hypot\n'), ((3900, 3913), 'numpy.radians', 'radians', (['dec2'], {}), '(dec2)\n', (3907, 3913), False, 'from numpy import radians, degrees, sin, cos, arctan2, hypot\n'), ((4062, 4083), 'numpy.hypot', 'hypot', (['numera', 'numerb'], {}), '(numera, numerb)\n', (4067, 4083), False, 'from numpy import radians, degrees, sin, cos, arctan2, hypot\n'), ((3298, 3309), 'numpy.cos', 'np.cos', (['rar'], {}), '(rar)\n', (3304, 3309), True, 'import numpy as np\n'), ((3312, 3324), 'numpy.cos', 'np.cos', (['decr'], {}), '(decr)\n', (3318, 3324), True, 'import numpy as np\n'), ((3333, 3344), 'numpy.sin', 'np.sin', (['rar'], {}), '(rar)\n', (3339, 3344), True, 'import numpy as np\n'), ((3347, 3359), 'numpy.cos', 'np.cos', (['decr'], {}), '(decr)\n', (3353, 3359), True, 'import numpy as np\n'), ((3955, 3964), 'numpy.cos', 'cos', (['phif'], {}), '(phif)\n', (3958, 3964), False, 'from numpy import radians, degrees, sin, cos, arctan2, hypot\n'), ((3967, 3977), 'numpy.sin', 'sin', (['dlamb'], {}), '(dlamb)\n', (3970, 3977), False, 'from numpy import radians, degrees, sin, cos, arctan2, hypot\n'), ((4174, 4195), 'numpy.arctan2', 'arctan2', (['numer', 'denom'], {}), '(numer, denom)\n', (4181, 4195), False, 'from numpy import radians, degrees, sin, cos, arctan2, hypot\n'), ((3991, 4000), 'numpy.cos', 'cos', (['phis'], {}), '(phis)\n', (3994, 4000), False, 'from numpy import radians, degrees, sin, cos, arctan2, hypot\n'), ((4003, 4012), 'numpy.sin', 'sin', (['phif'], {}), '(phif)\n', (4006, 4012), False, 'from numpy import radians, degrees, sin, cos, arctan2, hypot\n'), ((4039, 4049), 'numpy.cos', 'cos', (['dlamb'], {}), '(dlamb)\n', (4042, 4049), False, 'from numpy import radians, degrees, sin, cos, arctan2, hypot\n'), ((4096, 4105), 'numpy.sin', 'sin', (['phis'], {}), '(phis)\n', (4099, 4105), False, 'from numpy import radians, degrees, sin, cos, arctan2, hypot\n'), ((4108, 4117), 'numpy.sin', 'sin', (['phif'], {}), '(phif)\n', (4111, 4117), False, 'from numpy import radians, degrees, sin, cos, arctan2, hypot\n'), ((4144, 4154), 'numpy.cos', 'cos', (['dlamb'], {}), '(dlamb)\n', (4147, 4154), False, 'from numpy import radians, degrees, sin, cos, arctan2, hypot\n'), ((4015, 4024), 'numpy.sin', 'sin', (['phis'], {}), '(phis)\n', (4018, 4024), False, 'from numpy import radians, degrees, sin, cos, arctan2, hypot\n'), ((4027, 4036), 'numpy.cos', 'cos', (['phif'], {}), '(phif)\n', (4030, 4036), False, 'from numpy import radians, degrees, sin, cos, arctan2, hypot\n'), ((4120, 4129), 'numpy.cos', 'cos', (['phis'], {}), '(phis)\n', (4123, 4129), False, 'from numpy import radians, degrees, sin, cos, arctan2, hypot\n'), ((4132, 4141), 'numpy.cos', 'cos', (['phif'], {}), '(phif)\n', (4135, 4141), False, 'from numpy import radians, degrees, sin, cos, arctan2, hypot\n')] |
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table
from app import app
import numpy as np
import pandas as pd
import plotly.graph_objs as go
import json, codecs
import csv
from functions import keel_solve, sac_solve, section_solve, wl_solve
@app.callback(Output('output-optimization', 'figure'), [Input('resultshullaxisy', 'value'), Input('resultshullaxisx', 'value')])
def update_output(resultshullaxisy, resultshullaxisx):
# calculate pareto frontier
def pareto_frontier(Xs, Ys, maxX = True, maxY = True):
myList = sorted([[Xs[i], Ys[i]] for i in range(len(Xs))], reverse=maxX)
p_front = [myList[0]]
for pair in myList[1:]:
if maxY:
if pair[1] >= p_front[-1][1]:
p_front.append(pair)
else:
if pair[1] <= p_front[-1][1]:
p_front.append(pair)
p_frontX = [pair[0] for pair in p_front]
p_frontY = [pair[1] for pair in p_front]
return p_frontX, p_frontY
df = pd.read_csv("assets/data/optimizationresistance.csv")
dfvalid = df.loc[df['valid']==True]
dfvalid = dfvalid.reset_index()
dfnotvalid = df.loc[df["valid"]==False]
p_front = pareto_frontier(dfvalid["Comfort"], dfvalid["Resistance"], maxX = True, maxY = False)
paretox, paretoy, paretoname = [], [], []
if (resultshullaxisx == "Comfort" and resultshullaxisy == "Resistance"):
paretox=p_front[0]
paretoy=p_front[1]
paretoname='Pareto'
elif (resultshullaxisx == "Resistance" and resultshullaxisy == "Comfort"):
paretoy=p_front[0]
paretox=p_front[1]
paretoname='Pareto'
else:
paretoy=[]
paretox=[]
paretoname='No Pareto'
ymin = min(df[resultshullaxisy])*0.9
ymax = max(df[resultshullaxisy])
if ymax > 7000:
ymax = 7000
gaconfig_obj = codecs.open('assets/data/parametersga.json', 'r', encoding='utf-8').read()
gaconfig = json.loads(gaconfig_obj)
gamethod = gaconfig["gamethod"]
return {
'data': [
go.Scatter(
x=dfvalid[resultshullaxisx],
y=dfvalid[resultshullaxisy],
text = dfvalid["id"],
textposition='top center',
mode='markers',
name='Valid individuals',
marker=dict(
cmax=max(df["id"]),
cmin=1,
color=df["id"],
colorbar=dict(
title='#Offspring'
),
colorscale='Viridis',
opacity = 0.5+0.5*df["id"]/max(df["id"]),
),
),
go.Scatter(
x=dfnotvalid[resultshullaxisx],
y=dfnotvalid[resultshullaxisy],
text=dfnotvalid["id"],
textposition='top center',
mode='markers',
name='Invalid',
marker=dict(
color='rgba(255,0,0,0.2)',
symbol='cross',
),
),
go.Scatter(
x = [df.iloc[0][resultshullaxisx]],
y = [df.iloc[0][resultshullaxisy]],
text=df["id"],
textposition='top center',
mode='markers',
name='Initial hull',
marker=dict(
symbol='star',
size = 10,
color = "black",
),
),
go.Scatter(
x=paretox,
y=paretoy,
mode='lines',
name=paretoname,
line = dict(dash = 'dash'),
),
],
'layout': go.Layout(
title="{} Optimization".format(gamethod),
height=500,
hovermode="closest",
margin={
"r": 20,
"t": 30,
"b": 50,
"l": 80
},
xaxis={
"autorange": True,
"linewidth": 1,
"showgrid": True,
"showline": True,
"mirror": True,
"title": resultshullaxisx,
},
yaxis={
"autorange": False,
"linewidth": 1,
"showgrid": True,
"showline": True,
"mirror": True,
"title": resultshullaxisy,
"range": [ymin, ymax],
},
legend=dict(x=0.75, y=1),
font=dict(size=12),
)
}
@app.callback(Output('plot-resistance-individual', 'figure'), [Input('output-optimization', 'hoverData')])
def update_resistance(hoverData):
df = pd.read_csv("assets/data/optimizationresistance.csv")
if hoverData is None:
hover = np.int(1)
else:
hover = np.int(hoverData["points"][0]['text'])
row = df.loc[df['id']==hover]
Rv = [row.iloc[0]['Rv']]
Ri = [row.iloc[0]['Ri']]
Rr = [row.iloc[0]['Rr']]
Rincli = [row.iloc[0]['Rincli']]
return {
'data': [
go.Bar(
x=['R'],
y=Rv,
name = "Viscous",
marker=dict(
color='rgb(43,140,190)'
),
),
go.Bar(
x=['R'],
y=Ri,
name = "Induced",
marker=dict(
color='rgb(123,204,196)'
)
),
go.Bar(
x=['R'],
y=Rr,
name = "Residual",
marker=dict(
color='rgb(186,228,188)'
),
),
go.Bar(
x=['R'],
y=Rincli,
name = "Inclination",
marker=dict(
color='rgb(240,249,232)'
),
),
],
'layout': go.Layout(
barmode="stack",
title="Resistance #{}".format(hover),
hovermode="closest",
height=600,
margin={
"r": 20,
"t": 30,
"b": 50,
"l": 50
},
yaxis={
"title": "Resistance Components",
},
legend=dict(x=-.1, y=-0.3),
font=dict(size=10),
)
}
@app.callback(Output('plot-limits-lwl-bwl', 'figure'), [Input('output-optimization', 'hoverData')])
def update_y_timeseries(hoverData):
df = pd.read_csv("assets/data/optimizationresistance.csv")
xmin = min(df["BWL"])
xmax = max(df["BWL"])
hover = np.int(hoverData["points"][0]['text'])
row = df.loc[df['id']==hover]
init = df.loc[df['id']==1]
lwlinit = [init.iloc[0]['LWL']]
bwlinit = [init.iloc[0]['BWL']]
return {
'data': [
go.Scatter(
x=df["BWL"],
y=df["LWL"],
text=df["id"],
textposition='top center',
mode='markers',
),
go.Scatter(
x=[xmin, xmax],
y=[xmin*2.73, xmax*2.73],
mode='lines',
line = dict(color = 'red', dash = 'dash'),
fill='tozeroy',
fillcolor='rgba(255,0,0,0.2)',
),
go.Scatter(
x=[xmin, xmax],
y=[xmin*5, xmax*5],
mode='lines',
line = dict(color = 'red', dash = 'dash'),
),
go.Scatter(
x=[xmin, xmax],
y=[xmax*7, xmax*7],
mode='lines',
fill='tonexty',
fillcolor='rgba(255,0,0,0.2)',
line=dict(
color='red',
dash='dash'
),
),
go.Scatter(
x=bwlinit,
y=lwlinit,
mode='markers',
marker = dict(color = 'green', symbol = 'star'),
),
go.Scatter(
x=[row.iloc[0]['BWL']],
y=[row.iloc[0]['LWL']],
marker=dict(
color='orange',
symbol='cross'
),
),
],
'layout': go.Layout(
height=200,
hovermode="closest",
showlegend=False,
margin={
"r": 10,
"t": 20,
"b": 30,
"l": 30
},
xaxis={
"autorange": False,
"linewidth": 1,
"showgrid": True,
"showline": True,
"mirror": True,
"title": "Waterline beam",
"range": [xmin, xmax],
},
yaxis={
"autorange": False,
"linewidth": 1,
"showgrid": True,
"showline": True,
"mirror": True,
"title": "Waterline length",
"range": [xmin*2.5, xmax*5.5],
},
font=dict(size=10),
)
}
@app.callback(
dash.dependencies.Output('plot-limits-bwl-tc', 'figure'),
[Input('output-optimization', 'hoverData')])
def plot_limits_bwltc(hoverData):
df = pd.read_csv("assets/data/optimizationresistance.csv")
xmin = min(df["BWL"])
xmax = max(df["BWL"])
hover = np.int(hoverData["points"][0]['text'])
row = df.loc[df['id']==hover]
init = df.loc[df['id']==1]
bwlinit = [init.iloc[0]['BWL']]
tcinit = [init.iloc[0]['Draft']]
return {
'data': [
go.Scatter(
x=df["BWL"],
y=df["Draft"],
text=df["id"],
textposition='top center',
mode='markers',
),
go.Scatter(
x=[xmin, xmax],
y=[xmin/2.46, xmax/2.46],
mode='lines',
line = dict(color = 'red', dash = 'dash'),
),
go.Scatter(
x=[xmin, xmax],
y=[xmax/2, xmax/2],
mode='lines',
fill='tonexty',
fillcolor='rgba(255,0,0,0.2)',
line=dict(
color='red',
dash='dash'
),
),
go.Scatter(
x=[xmin, xmax],
y=[xmin/19.38, xmax/9.38],
mode='lines',
line = dict(color = 'red', dash = 'dash'),
fill='tozeroy',
fillcolor='rgba(255,0,0,0.2)',
),
go.Scatter(
x=bwlinit,
y=tcinit,
mode='markers',
marker = dict(color = 'green', symbol = 'star'),
),
go.Scatter(
x=[row.iloc[0]['BWL']],
y=[row.iloc[0]['Draft']],
marker=dict(
color='orange',
symbol='cross'
),
),
],
'layout': go.Layout(
height=200,
hovermode="closest",
showlegend=False,
margin={
"r": 10,
"t": 20,
"b": 30,
"l": 30
},
xaxis={
"autorange": False,
"linewidth": 1,
"showgrid": True,
"showline": True,
"mirror": True,
"title": "Waterline beam",
"range": [xmin, xmax],
},
yaxis={
"autorange": False,
"linewidth": 1,
"showgrid": True,
"showline": True,
"mirror": True,
"title": "Draft",
"range": [0, xmax/2.4]
},
font=dict(size=10),
)
}
@app.callback(
dash.dependencies.Output('plot-limits-lwl-disp', 'figure'),
[Input('output-optimization', 'hoverData')])
def plot_limits_lwldisp(hoverData):
df = pd.read_csv("assets/data/optimizationresistance.csv")
xmin = min(df["LWL"])
xmax = max(df["LWL"])
hover = np.int(hoverData["points"][0]['text'])
row = df.loc[df['id']==hover]
init = df.loc[df['id']==1]
lwlinit = [init.iloc[0]['LWL']]
dispinit = [init.iloc[0]['Displacement']]
return {
'data': [
go.Scatter(
x=df["LWL"],
y=df["Displacement"],
text=df["id"],
textposition='top center',
mode='markers',
),
go.Scatter(
x=[xmin, xmax],
y=[(xmin/4.34)**3, (xmax/4.34)**3],
mode='lines',
line = dict(color = 'red', dash = 'dash'),
),
go.Scatter(
x=[xmin, xmax],
y=[(xmax/4)**3, (xmax/4)**3],
mode='lines',
fill='tonexty',
fillcolor='rgba(255,0,0,0.2)',
line=dict(
color='red',
dash='dash'
),
),
go.Scatter(
x=[xmin, xmax],
y=[(xmin/8.5)**3, (xmax/8.5)**3],
fill='tozeroy',
fillcolor='rgba(255,0,0,0.2)',
mode='lines',
line = dict(color = 'red', dash = 'dash'),
),
go.Scatter(
x=lwlinit,
y=dispinit,
mode='markers',
marker = dict(color = 'green', symbol = 'star'),
),
go.Scatter(
x=[row.iloc[0]['LWL']],
y=[row.iloc[0]['Displacement']],
marker=dict(
color='orange',
symbol='cross'
),
),
],
'layout': go.Layout(
height=200,
hovermode="closest",
showlegend=False,
margin={
"r": 10,
"t": 20,
"b": 30,
"l": 30
},
xaxis={
"autorange": False,
"linewidth": 1,
"showgrid": True,
"showline": True,
"mirror": True,
"title": "Waterline length",
"range": [xmin, xmax]
},
yaxis={
"autorange": False,
"linewidth": 1,
"showgrid": True,
"showline": True,
"mirror": True,
"title": "Displacement",
"range": [0, (xmax/4.3)**3],
},
font=dict(size=10),
)
}
@app.callback(
dash.dependencies.Output('plot-limits-awp-disp', 'figure'),
[Input('output-optimization', 'hoverData')])
def plot_limits_awpdisp(hoverData):
df = pd.read_csv("assets/data/optimizationresistance.csv")
xmin = min(df["AWP"])
xmax = max(df["AWP"])
hover = np.int(hoverData["points"][0]['text'])
row = df.loc[df['id']==hover]
init = df.loc[df['id']==1]
awpinit = [init.iloc[0]['AWP']]
dispinit = [init.iloc[0]['Displacement']]
return {
'data': [
go.Scatter(
x=df["AWP"],
y=df["Displacement"],
text=df["id"],
textposition='top center',
mode='markers',
),
go.Scatter(
x=[xmin, xmax],
y=[(xmin/3.78)**(3/2), (xmax/3.78)**(3/2)],
mode='lines',
line = dict(color = 'red', dash = 'dash'),
),
go.Scatter(
x=[xmin, xmax],
y=[(xmax/3)**(3/2), (xmax/3)**(3/2)],
mode='lines',
fill='tonexty',
fillcolor='rgba(255,0,0,0.2)',
line=dict(
color='red',
dash='dash'
),
),
go.Scatter(
x=[xmin, xmax],
y=[(xmin/12.67)**(3/2), (xmax/12.67)**(3/2)],
mode='lines',
line = dict(color = 'red', dash = 'dash'),
fill='tozeroy',
fillcolor='rgba(255,0,0,0.2)',
),
go.Scatter(
x=awpinit,
y=dispinit,
mode='markers',
marker = dict(color = 'green', symbol = 'star'),
),
go.Scatter(
x=[row.iloc[0]['AWP']],
y=[row.iloc[0]['Displacement']],
marker=dict(
color='orange',
symbol='cross'
),
),
],
'layout': go.Layout(
height=200,
hovermode="closest",
showlegend=False,
margin={
"r": 10,
"t": 20,
"b": 30,
"l": 30
},
xaxis={
"autorange": False,
"linewidth": 1,
"showgrid": True,
"showline": True,
"mirror": True,
"title": "Waterplane area",
"range": [xmin, xmax],
},
yaxis={
"autorange": False,
"linewidth": 1,
"showgrid": True,
"showline": True,
"mirror": True,
"title": "Displacement",
"range":[0, (xmax/3.7)**(3/2)],
},
font=dict(size=10),
)
}
@app.callback(Output("plot-constraints-count", "children"), [Input('resultshullaxisy', 'value')])
def update_graph(resultshullaxisy):
df = pd.read_csv("assets/data/optimizationresistance.csv")
constraint1 = df.constraint1.value_counts().loc[True]
constraint2 = df.constraint2.value_counts().loc[True]
#constraint3 = df.constraint3.value_counts().loc[True]
constraint4 = df.constraint4.value_counts().loc[True]
constraint5 = df.constraint5.value_counts().loc[True]
return html.Div([
dcc.Graph(
figure={
'data': [
go.Bar(
x=[1, 2, 3, 4],
y=[constraint1, constraint2, constraint4, constraint5],
name='Valid',
),
],
'layout': go.Layout(
height=250,
margin={
"r": 10,
"t": 20,
"b": 30,
"l": 30
},
xaxis=go.layout.XAxis(
autorange= True,
linewidth= 1,
showgrid= True,
showline= True,
mirror= True,
ticktext= ['lwl/bwl', 'bwl/tcan', 'disp', 'cs'],
tickvals=[1, 2, 3, 4],
tickmode='array',
),
yaxis=go.layout.YAxis(
autorange= True,
linewidth= 1,
showgrid= True,
showline= True,
mirror= True,
title= "Number of times",
),
font=dict(size=10),
)
},
)
]
)
@app.callback(
Output('plot-parallel-dimensions', 'figure'),
[Input('parallel-datatype', 'value')])
def plot_parallel_dimensions(type):
if np.int(type) == 1:
df = pd.read_csv("assets/data/optimizationresistance.csv")
elif np.int(type) == 2:
df = pd.read_csv("assets/data/optimizationresistance.csv")
df = df.loc[df['valid']==True]
elif np.int(type) == 3:
df = pd.read_csv("assets/data/optimizationresistance.csv")
df = df.loc[df['valid']==False]
return {
'data': [
go.Parcoords(
line = dict(
color=df["id"],
colorscale = 'Viridis',
showscale = True,
cmin=1,
cmax=max(df["id"]),
colorbar=dict(
title='#Offspring'
),
),
dimensions = list([
dict(label = 'Waterline Length [m]', values = df['LWL']),
dict(label = 'Waterline Beam [m]', values = df['BWL']),
dict(label = 'Draft [m]', values = df['Draft']),
dict(label = 'Displacement [m3]', values = df['Displacement']),
dict(label = 'LCB [m]', values = df['LCB']),
dict(label = 'LCF [m]', values = df['LCF']),
]),
),
],
'layout': go.Layout(
title="Dimension set per hull",
hovermode="closest",
margin={
"r": 20,
"t": 100,
"b": 50,
"l": 50
},
font=dict(size=12),
)
}
@app.callback(Output("table-all-individuals", "children"), [Input("resultshullaxisx", "value")])
def table_all_individuals(resultshullaxisx):
datatable = pd.read_csv("assets/data/optimizationresistance.csv")
datatable = datatable.loc[datatable['valid']==True]
datatable = datatable.loc[:,"id":"LCF"]
return html.Div(
dash_table.DataTable(
id='datatable-interactivity',
columns=[{"name": i, "id": i, "deletable": True} for i in datatable.columns],
data=datatable.to_dict("rows"),
editable=True,
#filtering=True,
#sorting=True,
#sorting_type="multi",
row_selectable="multi",
row_deletable=True,
selected_rows=[],
#n_fixed_rows=1,
style_cell={'font-size': '8pt', 'font_family': 'Source Sans Pro'},
style_as_list_view=True,
style_header={'fontWeight': 'bold'},
#pagination_mode="fe",
#pagination_settings={
# "displayed_pages": 1,
# "current_page": 0,
# "page_size": 10,
#},
#navigation="page",
),
)
@app.callback(Output("plot-dimensions", "children"), [Input('datatable-interactivity', 'selected_rows')])
def plot_dimensions(selected_row_indices):
datatable_all = pd.read_csv("assets/data/optimizationresistance.csv")
datatable_valid = datatable_all.loc[datatable_all['valid']==True]
datatable_unvalid = datatable_all.loc[datatable_all['valid']==False]
if selected_row_indices is None:
selected_row_indices = []
file = open("assets/data/optimizationresistance.csv")
xmax = len(file.readlines())-1
xmin = 0
return html.Div([
dcc.Graph(
id=column,
figure={
'data': [
go.Bar(
x=datatable_valid["id"],
y=datatable_valid[column] if column in datatable_valid else [],
name='Valid',
),
go.Bar(
x=datatable_unvalid["id"],
y=datatable_unvalid[column] if column in datatable_unvalid else [],
marker=dict(color='red'),
name='Not valid',
),
go.Bar(
x=datatable_all["id"].iloc[selected_row_indices],
y=datatable_all[column].iloc[selected_row_indices] if column in datatable_unvalid else [],
marker=dict(color='green'),
name='Selected',
),
],
"layout": {
"xaxis": {"automargin": False, "range": [xmin, xmax]},
"yaxis": {"automargin": True},
"height": 100,
"width": "100%",
"margin": {"t": 30, "l": 10, "r": 10, "b": 20},
"title": column,
'font': dict(size=9),
'barmode': 'overlay',
},
},
)
for column in ["LWL", "BWL", "Draft", "Resistance", "Comfort"]
]
)
@app.callback(Output("export-hull-dimensions", "children"), [Input('output-optimization', 'hoverData')])
def export_hull_dimensions(hoverData):
df = pd.read_csv("assets/data/optimizationresistance.csv")
if hoverData is None:
index = np.int(1)
else:
index = np.int(hoverData["points"][0]['text'])
row = df.loc[df['id']==index]
bwl = np.float(row.iloc[0]['BWL'])
lwl = np.float(row.iloc[0]['LWL'])
tc = np.float(row.iloc[0]['Draft'])
lcb = np.float(row.iloc[0]['LCB'])
lcf = np.float(row.iloc[0]['LCF'])
disp = np.float(row.iloc[0]['Displacement'])
cs = np.float(row.iloc[0]['CS'])
json.dump({'lwl': lwl, 'bwl': bwl, 'tc': tc, 'disp': disp, 'lcb': lcb, 'lcf': lcf}, codecs.open('assets/data/dimensions-hull.json', 'w', encoding='utf-8'), separators=(', ',': '), sort_keys=True)
return html.Div([
html.P("Capsize Screening Factor: {}".format(round(np.float(cs),2)), style={'padding-left': '20px', 'display': 'inline-block'}),
html.P("Waterline Length: {}m -- Waterline Beam: {}m -- Draft: {}m".format(round(np.float(lwl),2), round(np.float(bwl),2), round(np.float(tc),2)), style={'padding-left': '20px', 'display': 'inline-block'})
])
@app.callback(Output('insert-section-choosen', 'figure'), [Input('output-optimization', 'hoverData'), Input("alpha_f_sac2", "value"), Input("alpha_i_sac2", "value"), Input("beta_n2", "value")])
def insert_section_choosen(hoverData, alpha_f_sac2, alpha_i_sac2, beta_n2):
df = pd.read_csv("assets/data/optimizationresistance.csv")
if hoverData is None:
index = np.int(1)
else:
index = np.int(hoverData["points"][0]['text'])
row = df.loc[df['id']==index]
bwl = np.float(row.iloc[0]['BWL'])
lwl = np.float(row.iloc[0]['LWL'])
tc = np.float(row.iloc[0]['Draft'])
lcb = np.float(row.iloc[0]['LCB'])
lcf = np.float(row.iloc[0]['LCF'])
disp = np.float(row.iloc[0]['Displacement'])
awp = np.float(row.iloc[0]['AWP'])
cb = disp/(lwl*bwl*tc)
cwp = awp/(lwl*bwl)
cm = 0.55
alpha_f_sac = np.float(alpha_f_sac2)
alpha_i_sac = np.float(alpha_i_sac2)
beamtransom = 0
beta_n = np.float(beta_n2)
sn_sections_sol = sac_solve(np.float(lwl), np.float(cb), np.float(lcb), np.float(alpha_f_sac), np.float(alpha_i_sac), np.float(beamtransom), np.float(bwl), np.float(tc), np.float(cm)),
sn_sections = sn_sections_sol[0][6]
bn_sections_sol = wl_solve(np.float(lcf), np.float(cwp), np.float(lwl), np.float(beamtransom), np.float(bwl))
bn_sections = bn_sections_sol[6]
tn_sections_sol = keel_solve(np.float(lwl), np.float(tc), np.float(20), np.float(35))
tn_sections = tn_sections_sol[5]
section_solution = section_solve(tn_sections, bn_sections, sn_sections, np.float(lwl), np.float(beta_n), np.float(2)),
return {
'data': [
go.Scatter(
x = -section_solution[0][1][4],
y = section_solution[0][2][4],
mode = 'lines',
marker = dict(color = 'rgb(254,224,139)'),
cliponaxis = False,
),
go.Scatter(
x = -section_solution[0][1][3],
y = section_solution[0][2][3],
mode = 'lines',
marker = dict(color = 'rgb(253,174,97)'),
cliponaxis = False,
),
go.Scatter(
x = -section_solution[0][1][2],
y = section_solution[0][2][2],
mode = 'lines',
marker = dict(color = 'rgb(244,109,67)'),
cliponaxis = False,
),
go.Scatter(
x = -section_solution[0][1][1],
y = section_solution[0][2][1],
mode = 'lines',
marker = dict(color = 'rgb(213,62,79)'),
cliponaxis = False,
),
go.Scatter(
x = -section_solution[0][1][0],
y = section_solution[0][2][0],
mode = 'lines',
marker = dict(color = 'rgb(158,1,66)'),
cliponaxis = False,
),
go.Scatter(
x = section_solution[0][1][5],
y = section_solution[0][2][5],
mode = 'lines',
marker = dict(color = 'rgb(230,245,152)'),
cliponaxis = False,
),
go.Scatter(
x = section_solution[0][1][6],
y = section_solution[0][2][6],
mode = 'lines',
marker = dict(color = 'rgb(171,221,164)'),
cliponaxis = False,
),
go.Scatter(
x = section_solution[0][1][7],
y = section_solution[0][2][7],
mode = 'lines',
marker = dict(color = 'rgb(102,194,165)'),
cliponaxis = False,
),
go.Scatter(
x = section_solution[0][1][8],
y = section_solution[0][2][8],
mode = 'lines',
marker = dict(color = 'rgb(50,136,189)'),
cliponaxis = False,
),
go.Scatter(
x = section_solution[0][1][9],
y = section_solution[0][2][9],
mode = 'lines',
marker = dict(color = 'rgb(94,79,162)'),
cliponaxis = False,
),
],
'layout': go.Layout(
title = "Body Plan: Hull #{}".format(index),
showlegend = False,
height = 230,
margin = {
"r": 20,
"t": 30,
"b": 50,
"l": 50
},
xaxis = {
"autorange": True,
"linewidth": 1,
"showgrid": True,
"showline": True,
"mirror": True,
"title": 'Half Beam [m]',
"zeroline": False,
},
yaxis = {
"autorange": False,
"linewidth": 1,
"showgrid": True,
"showline": True,
"mirror": True,
"title": "Draft [m]",
"zeroline": False,
"scaleanchor": "x",
"scaleratio": 1,
"range": [-1.2*tc, 0.2]
},
annotations=[
dict(
x=0.5,
y=0.1,
showarrow=False,
text='Bow'),
dict(
x=-0.5,
y=0.1,
showarrow=False,
text='Stern'),
],
font=dict(size=10),
)
}
#weight1 = np.float(gaconfig["weight1"])*(-1)/10
#weight2 = np.float(gaconfig["weight2"])*(-1)/10
#resist_mean = dfvalid["Resistance"].mean()
#comfort_mean = dfvalid["Comfort"].mean()
#values = weight1*dfvalid.Resistance/resist_mean+weight2*dfvalid.Comfort/comfort_mean
#dfvalid['Values'] = values
#best = dfvalid['Values'].idxmax() | [
"plotly.graph_objs.layout.YAxis",
"json.loads",
"codecs.open",
"pandas.read_csv",
"plotly.graph_objs.Scatter",
"plotly.graph_objs.layout.XAxis",
"numpy.float",
"dash.dependencies.Input",
"numpy.int",
"dash.dependencies.Output",
"plotly.graph_objs.Bar"
] | [((1126, 1179), 'pandas.read_csv', 'pd.read_csv', (['"""assets/data/optimizationresistance.csv"""'], {}), "('assets/data/optimizationresistance.csv')\n", (1137, 1179), True, 'import pandas as pd\n'), ((2087, 2111), 'json.loads', 'json.loads', (['gaconfig_obj'], {}), '(gaconfig_obj)\n', (2097, 2111), False, 'import json, codecs\n'), ((358, 397), 'dash.dependencies.Output', 'Output', (['"""output-optimization"""', '"""figure"""'], {}), "('output-optimization', 'figure')\n", (364, 397), False, 'from dash.dependencies import Input, Output, State\n'), ((4923, 4976), 'pandas.read_csv', 'pd.read_csv', (['"""assets/data/optimizationresistance.csv"""'], {}), "('assets/data/optimizationresistance.csv')\n", (4934, 4976), True, 'import pandas as pd\n'), ((4787, 4833), 'dash.dependencies.Output', 'Output', (['"""plot-resistance-individual"""', '"""figure"""'], {}), "('plot-resistance-individual', 'figure')\n", (4793, 4833), False, 'from dash.dependencies import Input, Output, State\n'), ((6752, 6805), 'pandas.read_csv', 'pd.read_csv', (['"""assets/data/optimizationresistance.csv"""'], {}), "('assets/data/optimizationresistance.csv')\n", (6763, 6805), True, 'import pandas as pd\n'), ((6875, 6913), 'numpy.int', 'np.int', (["hoverData['points'][0]['text']"], {}), "(hoverData['points'][0]['text'])\n", (6881, 6913), True, 'import numpy as np\n'), ((6621, 6660), 'dash.dependencies.Output', 'Output', (['"""plot-limits-lwl-bwl"""', '"""figure"""'], {}), "('plot-limits-lwl-bwl', 'figure')\n", (6627, 6660), False, 'from dash.dependencies import Input, Output, State\n'), ((9584, 9637), 'pandas.read_csv', 'pd.read_csv', (['"""assets/data/optimizationresistance.csv"""'], {}), "('assets/data/optimizationresistance.csv')\n", (9595, 9637), True, 'import pandas as pd\n'), ((9702, 9740), 'numpy.int', 'np.int', (["hoverData['points'][0]['text']"], {}), "(hoverData['points'][0]['text'])\n", (9708, 9740), True, 'import numpy as np\n'), ((9434, 9490), 'dash.dependencies.Output', 'dash.dependencies.Output', (['"""plot-limits-bwl-tc"""', '"""figure"""'], {}), "('plot-limits-bwl-tc', 'figure')\n", (9458, 9490), False, 'import dash\n'), ((12401, 12454), 'pandas.read_csv', 'pd.read_csv', (['"""assets/data/optimizationresistance.csv"""'], {}), "('assets/data/optimizationresistance.csv')\n", (12412, 12454), True, 'import pandas as pd\n'), ((12519, 12557), 'numpy.int', 'np.int', (["hoverData['points'][0]['text']"], {}), "(hoverData['points'][0]['text'])\n", (12525, 12557), True, 'import numpy as np\n'), ((12247, 12305), 'dash.dependencies.Output', 'dash.dependencies.Output', (['"""plot-limits-lwl-disp"""', '"""figure"""'], {}), "('plot-limits-lwl-disp', 'figure')\n", (12271, 12305), False, 'import dash\n'), ((15284, 15337), 'pandas.read_csv', 'pd.read_csv', (['"""assets/data/optimizationresistance.csv"""'], {}), "('assets/data/optimizationresistance.csv')\n", (15295, 15337), True, 'import pandas as pd\n'), ((15402, 15440), 'numpy.int', 'np.int', (["hoverData['points'][0]['text']"], {}), "(hoverData['points'][0]['text'])\n", (15408, 15440), True, 'import numpy as np\n'), ((15130, 15188), 'dash.dependencies.Output', 'dash.dependencies.Output', (['"""plot-limits-awp-disp"""', '"""figure"""'], {}), "('plot-limits-awp-disp', 'figure')\n", (15154, 15188), False, 'import dash\n'), ((18168, 18221), 'pandas.read_csv', 'pd.read_csv', (['"""assets/data/optimizationresistance.csv"""'], {}), "('assets/data/optimizationresistance.csv')\n", (18179, 18221), True, 'import pandas as pd\n'), ((18039, 18083), 'dash.dependencies.Output', 'Output', (['"""plot-constraints-count"""', '"""children"""'], {}), "('plot-constraints-count', 'children')\n", (18045, 18083), False, 'from dash.dependencies import Input, Output, State\n'), ((20091, 20135), 'dash.dependencies.Output', 'Output', (['"""plot-parallel-dimensions"""', '"""figure"""'], {}), "('plot-parallel-dimensions', 'figure')\n", (20097, 20135), False, 'from dash.dependencies import Input, Output, State\n'), ((21938, 21991), 'pandas.read_csv', 'pd.read_csv', (['"""assets/data/optimizationresistance.csv"""'], {}), "('assets/data/optimizationresistance.csv')\n", (21949, 21991), True, 'import pandas as pd\n'), ((21794, 21837), 'dash.dependencies.Output', 'Output', (['"""table-all-individuals"""', '"""children"""'], {}), "('table-all-individuals', 'children')\n", (21800, 21837), False, 'from dash.dependencies import Input, Output, State\n'), ((23134, 23187), 'pandas.read_csv', 'pd.read_csv', (['"""assets/data/optimizationresistance.csv"""'], {}), "('assets/data/optimizationresistance.csv')\n", (23145, 23187), True, 'import pandas as pd\n'), ((22979, 23016), 'dash.dependencies.Output', 'Output', (['"""plot-dimensions"""', '"""children"""'], {}), "('plot-dimensions', 'children')\n", (22985, 23016), False, 'from dash.dependencies import Input, Output, State\n'), ((25325, 25378), 'pandas.read_csv', 'pd.read_csv', (['"""assets/data/optimizationresistance.csv"""'], {}), "('assets/data/optimizationresistance.csv')\n", (25336, 25378), True, 'import pandas as pd\n'), ((25540, 25568), 'numpy.float', 'np.float', (["row.iloc[0]['BWL']"], {}), "(row.iloc[0]['BWL'])\n", (25548, 25568), True, 'import numpy as np\n'), ((25579, 25607), 'numpy.float', 'np.float', (["row.iloc[0]['LWL']"], {}), "(row.iloc[0]['LWL'])\n", (25587, 25607), True, 'import numpy as np\n'), ((25617, 25647), 'numpy.float', 'np.float', (["row.iloc[0]['Draft']"], {}), "(row.iloc[0]['Draft'])\n", (25625, 25647), True, 'import numpy as np\n'), ((25658, 25686), 'numpy.float', 'np.float', (["row.iloc[0]['LCB']"], {}), "(row.iloc[0]['LCB'])\n", (25666, 25686), True, 'import numpy as np\n'), ((25697, 25725), 'numpy.float', 'np.float', (["row.iloc[0]['LCF']"], {}), "(row.iloc[0]['LCF'])\n", (25705, 25725), True, 'import numpy as np\n'), ((25737, 25774), 'numpy.float', 'np.float', (["row.iloc[0]['Displacement']"], {}), "(row.iloc[0]['Displacement'])\n", (25745, 25774), True, 'import numpy as np\n'), ((25784, 25811), 'numpy.float', 'np.float', (["row.iloc[0]['CS']"], {}), "(row.iloc[0]['CS'])\n", (25792, 25811), True, 'import numpy as np\n'), ((25186, 25230), 'dash.dependencies.Output', 'Output', (['"""export-hull-dimensions"""', '"""children"""'], {}), "('export-hull-dimensions', 'children')\n", (25192, 25230), False, 'from dash.dependencies import Input, Output, State\n'), ((26684, 26737), 'pandas.read_csv', 'pd.read_csv', (['"""assets/data/optimizationresistance.csv"""'], {}), "('assets/data/optimizationresistance.csv')\n", (26695, 26737), True, 'import pandas as pd\n'), ((26899, 26927), 'numpy.float', 'np.float', (["row.iloc[0]['BWL']"], {}), "(row.iloc[0]['BWL'])\n", (26907, 26927), True, 'import numpy as np\n'), ((26938, 26966), 'numpy.float', 'np.float', (["row.iloc[0]['LWL']"], {}), "(row.iloc[0]['LWL'])\n", (26946, 26966), True, 'import numpy as np\n'), ((26976, 27006), 'numpy.float', 'np.float', (["row.iloc[0]['Draft']"], {}), "(row.iloc[0]['Draft'])\n", (26984, 27006), True, 'import numpy as np\n'), ((27017, 27045), 'numpy.float', 'np.float', (["row.iloc[0]['LCB']"], {}), "(row.iloc[0]['LCB'])\n", (27025, 27045), True, 'import numpy as np\n'), ((27056, 27084), 'numpy.float', 'np.float', (["row.iloc[0]['LCF']"], {}), "(row.iloc[0]['LCF'])\n", (27064, 27084), True, 'import numpy as np\n'), ((27096, 27133), 'numpy.float', 'np.float', (["row.iloc[0]['Displacement']"], {}), "(row.iloc[0]['Displacement'])\n", (27104, 27133), True, 'import numpy as np\n'), ((27144, 27172), 'numpy.float', 'np.float', (["row.iloc[0]['AWP']"], {}), "(row.iloc[0]['AWP'])\n", (27152, 27172), True, 'import numpy as np\n'), ((27256, 27278), 'numpy.float', 'np.float', (['alpha_f_sac2'], {}), '(alpha_f_sac2)\n', (27264, 27278), True, 'import numpy as np\n'), ((27297, 27319), 'numpy.float', 'np.float', (['alpha_i_sac2'], {}), '(alpha_i_sac2)\n', (27305, 27319), True, 'import numpy as np\n'), ((27353, 27370), 'numpy.float', 'np.float', (['beta_n2'], {}), '(beta_n2)\n', (27361, 27370), True, 'import numpy as np\n'), ((26419, 26461), 'dash.dependencies.Output', 'Output', (['"""insert-section-choosen"""', '"""figure"""'], {}), "('insert-section-choosen', 'figure')\n", (26425, 26461), False, 'from dash.dependencies import Input, Output, State\n'), ((400, 434), 'dash.dependencies.Input', 'Input', (['"""resultshullaxisy"""', '"""value"""'], {}), "('resultshullaxisy', 'value')\n", (405, 434), False, 'from dash.dependencies import Input, Output, State\n'), ((436, 470), 'dash.dependencies.Input', 'Input', (['"""resultshullaxisx"""', '"""value"""'], {}), "('resultshullaxisx', 'value')\n", (441, 470), False, 'from dash.dependencies import Input, Output, State\n'), ((5019, 5028), 'numpy.int', 'np.int', (['(1)'], {}), '(1)\n', (5025, 5028), True, 'import numpy as np\n'), ((5055, 5093), 'numpy.int', 'np.int', (["hoverData['points'][0]['text']"], {}), "(hoverData['points'][0]['text'])\n", (5061, 5093), True, 'import numpy as np\n'), ((4836, 4877), 'dash.dependencies.Input', 'Input', (['"""output-optimization"""', '"""hoverData"""'], {}), "('output-optimization', 'hoverData')\n", (4841, 4877), False, 'from dash.dependencies import Input, Output, State\n'), ((6663, 6704), 'dash.dependencies.Input', 'Input', (['"""output-optimization"""', '"""hoverData"""'], {}), "('output-optimization', 'hoverData')\n", (6668, 6704), False, 'from dash.dependencies import Input, Output, State\n'), ((9497, 9538), 'dash.dependencies.Input', 'Input', (['"""output-optimization"""', '"""hoverData"""'], {}), "('output-optimization', 'hoverData')\n", (9502, 9538), False, 'from dash.dependencies import Input, Output, State\n'), ((12312, 12353), 'dash.dependencies.Input', 'Input', (['"""output-optimization"""', '"""hoverData"""'], {}), "('output-optimization', 'hoverData')\n", (12317, 12353), False, 'from dash.dependencies import Input, Output, State\n'), ((15195, 15236), 'dash.dependencies.Input', 'Input', (['"""output-optimization"""', '"""hoverData"""'], {}), "('output-optimization', 'hoverData')\n", (15200, 15236), False, 'from dash.dependencies import Input, Output, State\n'), ((18086, 18120), 'dash.dependencies.Input', 'Input', (['"""resultshullaxisy"""', '"""value"""'], {}), "('resultshullaxisy', 'value')\n", (18091, 18120), False, 'from dash.dependencies import Input, Output, State\n'), ((20223, 20235), 'numpy.int', 'np.int', (['type'], {}), '(type)\n', (20229, 20235), True, 'import numpy as np\n'), ((20255, 20308), 'pandas.read_csv', 'pd.read_csv', (['"""assets/data/optimizationresistance.csv"""'], {}), "('assets/data/optimizationresistance.csv')\n", (20266, 20308), True, 'import pandas as pd\n'), ((20142, 20177), 'dash.dependencies.Input', 'Input', (['"""parallel-datatype"""', '"""value"""'], {}), "('parallel-datatype', 'value')\n", (20147, 20177), False, 'from dash.dependencies import Input, Output, State\n'), ((21840, 21874), 'dash.dependencies.Input', 'Input', (['"""resultshullaxisx"""', '"""value"""'], {}), "('resultshullaxisx', 'value')\n", (21845, 21874), False, 'from dash.dependencies import Input, Output, State\n'), ((23019, 23068), 'dash.dependencies.Input', 'Input', (['"""datatable-interactivity"""', '"""selected_rows"""'], {}), "('datatable-interactivity', 'selected_rows')\n", (23024, 23068), False, 'from dash.dependencies import Input, Output, State\n'), ((25421, 25430), 'numpy.int', 'np.int', (['(1)'], {}), '(1)\n', (25427, 25430), True, 'import numpy as np\n'), ((25457, 25495), 'numpy.int', 'np.int', (["hoverData['points'][0]['text']"], {}), "(hoverData['points'][0]['text'])\n", (25463, 25495), True, 'import numpy as np\n'), ((25900, 25970), 'codecs.open', 'codecs.open', (['"""assets/data/dimensions-hull.json"""', '"""w"""'], {'encoding': '"""utf-8"""'}), "('assets/data/dimensions-hull.json', 'w', encoding='utf-8')\n", (25911, 25970), False, 'import json, codecs\n'), ((25233, 25274), 'dash.dependencies.Input', 'Input', (['"""output-optimization"""', '"""hoverData"""'], {}), "('output-optimization', 'hoverData')\n", (25238, 25274), False, 'from dash.dependencies import Input, Output, State\n'), ((26780, 26789), 'numpy.int', 'np.int', (['(1)'], {}), '(1)\n', (26786, 26789), True, 'import numpy as np\n'), ((26816, 26854), 'numpy.int', 'np.int', (["hoverData['points'][0]['text']"], {}), "(hoverData['points'][0]['text'])\n", (26822, 26854), True, 'import numpy as np\n'), ((27631, 27644), 'numpy.float', 'np.float', (['lcf'], {}), '(lcf)\n', (27639, 27644), True, 'import numpy as np\n'), ((27646, 27659), 'numpy.float', 'np.float', (['cwp'], {}), '(cwp)\n', (27654, 27659), True, 'import numpy as np\n'), ((27661, 27674), 'numpy.float', 'np.float', (['lwl'], {}), '(lwl)\n', (27669, 27674), True, 'import numpy as np\n'), ((27676, 27697), 'numpy.float', 'np.float', (['beamtransom'], {}), '(beamtransom)\n', (27684, 27697), True, 'import numpy as np\n'), ((27699, 27712), 'numpy.float', 'np.float', (['bwl'], {}), '(bwl)\n', (27707, 27712), True, 'import numpy as np\n'), ((27784, 27797), 'numpy.float', 'np.float', (['lwl'], {}), '(lwl)\n', (27792, 27797), True, 'import numpy as np\n'), ((27799, 27811), 'numpy.float', 'np.float', (['tc'], {}), '(tc)\n', (27807, 27811), True, 'import numpy as np\n'), ((27813, 27825), 'numpy.float', 'np.float', (['(20)'], {}), '(20)\n', (27821, 27825), True, 'import numpy as np\n'), ((27827, 27839), 'numpy.float', 'np.float', (['(35)'], {}), '(35)\n', (27835, 27839), True, 'import numpy as np\n'), ((26464, 26505), 'dash.dependencies.Input', 'Input', (['"""output-optimization"""', '"""hoverData"""'], {}), "('output-optimization', 'hoverData')\n", (26469, 26505), False, 'from dash.dependencies import Input, Output, State\n'), ((26507, 26537), 'dash.dependencies.Input', 'Input', (['"""alpha_f_sac2"""', '"""value"""'], {}), "('alpha_f_sac2', 'value')\n", (26512, 26537), False, 'from dash.dependencies import Input, Output, State\n'), ((26539, 26569), 'dash.dependencies.Input', 'Input', (['"""alpha_i_sac2"""', '"""value"""'], {}), "('alpha_i_sac2', 'value')\n", (26544, 26569), False, 'from dash.dependencies import Input, Output, State\n'), ((26571, 26596), 'dash.dependencies.Input', 'Input', (['"""beta_n2"""', '"""value"""'], {}), "('beta_n2', 'value')\n", (26576, 26596), False, 'from dash.dependencies import Input, Output, State\n'), ((1997, 2064), 'codecs.open', 'codecs.open', (['"""assets/data/parametersga.json"""', '"""r"""'], {'encoding': '"""utf-8"""'}), "('assets/data/parametersga.json', 'r', encoding='utf-8')\n", (2008, 2064), False, 'import json, codecs\n'), ((7099, 7198), 'plotly.graph_objs.Scatter', 'go.Scatter', ([], {'x': "df['BWL']", 'y': "df['LWL']", 'text': "df['id']", 'textposition': '"""top center"""', 'mode': '"""markers"""'}), "(x=df['BWL'], y=df['LWL'], text=df['id'], textposition=\n 'top center', mode='markers')\n", (7109, 7198), True, 'import plotly.graph_objs as go\n'), ((9922, 10023), 'plotly.graph_objs.Scatter', 'go.Scatter', ([], {'x': "df['BWL']", 'y': "df['Draft']", 'text': "df['id']", 'textposition': '"""top center"""', 'mode': '"""markers"""'}), "(x=df['BWL'], y=df['Draft'], text=df['id'], textposition=\n 'top center', mode='markers')\n", (9932, 10023), True, 'import plotly.graph_objs as go\n'), ((12748, 12856), 'plotly.graph_objs.Scatter', 'go.Scatter', ([], {'x': "df['LWL']", 'y': "df['Displacement']", 'text': "df['id']", 'textposition': '"""top center"""', 'mode': '"""markers"""'}), "(x=df['LWL'], y=df['Displacement'], text=df['id'], textposition=\n 'top center', mode='markers')\n", (12758, 12856), True, 'import plotly.graph_objs as go\n'), ((15631, 15739), 'plotly.graph_objs.Scatter', 'go.Scatter', ([], {'x': "df['AWP']", 'y': "df['Displacement']", 'text': "df['id']", 'textposition': '"""top center"""', 'mode': '"""markers"""'}), "(x=df['AWP'], y=df['Displacement'], text=df['id'], textposition=\n 'top center', mode='markers')\n", (15641, 15739), True, 'import plotly.graph_objs as go\n'), ((20318, 20330), 'numpy.int', 'np.int', (['type'], {}), '(type)\n', (20324, 20330), True, 'import numpy as np\n'), ((20350, 20403), 'pandas.read_csv', 'pd.read_csv', (['"""assets/data/optimizationresistance.csv"""'], {}), "('assets/data/optimizationresistance.csv')\n", (20361, 20403), True, 'import pandas as pd\n'), ((27403, 27416), 'numpy.float', 'np.float', (['lwl'], {}), '(lwl)\n', (27411, 27416), True, 'import numpy as np\n'), ((27418, 27430), 'numpy.float', 'np.float', (['cb'], {}), '(cb)\n', (27426, 27430), True, 'import numpy as np\n'), ((27432, 27445), 'numpy.float', 'np.float', (['lcb'], {}), '(lcb)\n', (27440, 27445), True, 'import numpy as np\n'), ((27447, 27468), 'numpy.float', 'np.float', (['alpha_f_sac'], {}), '(alpha_f_sac)\n', (27455, 27468), True, 'import numpy as np\n'), ((27470, 27491), 'numpy.float', 'np.float', (['alpha_i_sac'], {}), '(alpha_i_sac)\n', (27478, 27491), True, 'import numpy as np\n'), ((27493, 27514), 'numpy.float', 'np.float', (['beamtransom'], {}), '(beamtransom)\n', (27501, 27514), True, 'import numpy as np\n'), ((27516, 27529), 'numpy.float', 'np.float', (['bwl'], {}), '(bwl)\n', (27524, 27529), True, 'import numpy as np\n'), ((27531, 27543), 'numpy.float', 'np.float', (['tc'], {}), '(tc)\n', (27539, 27543), True, 'import numpy as np\n'), ((27545, 27557), 'numpy.float', 'np.float', (['cm'], {}), '(cm)\n', (27553, 27557), True, 'import numpy as np\n'), ((27954, 27967), 'numpy.float', 'np.float', (['lwl'], {}), '(lwl)\n', (27962, 27967), True, 'import numpy as np\n'), ((27969, 27985), 'numpy.float', 'np.float', (['beta_n'], {}), '(beta_n)\n', (27977, 27985), True, 'import numpy as np\n'), ((27987, 27998), 'numpy.float', 'np.float', (['(2)'], {}), '(2)\n', (27995, 27998), True, 'import numpy as np\n'), ((20452, 20464), 'numpy.int', 'np.int', (['type'], {}), '(type)\n', (20458, 20464), True, 'import numpy as np\n'), ((20484, 20537), 'pandas.read_csv', 'pd.read_csv', (['"""assets/data/optimizationresistance.csv"""'], {}), "('assets/data/optimizationresistance.csv')\n", (20495, 20537), True, 'import pandas as pd\n'), ((26097, 26109), 'numpy.float', 'np.float', (['cs'], {}), '(cs)\n', (26105, 26109), True, 'import numpy as np\n'), ((26268, 26281), 'numpy.float', 'np.float', (['lwl'], {}), '(lwl)\n', (26276, 26281), True, 'import numpy as np\n'), ((26292, 26305), 'numpy.float', 'np.float', (['bwl'], {}), '(bwl)\n', (26300, 26305), True, 'import numpy as np\n'), ((26316, 26328), 'numpy.float', 'np.float', (['tc'], {}), '(tc)\n', (26324, 26328), True, 'import numpy as np\n'), ((18637, 18733), 'plotly.graph_objs.Bar', 'go.Bar', ([], {'x': '[1, 2, 3, 4]', 'y': '[constraint1, constraint2, constraint4, constraint5]', 'name': '"""Valid"""'}), "(x=[1, 2, 3, 4], y=[constraint1, constraint2, constraint4,\n constraint5], name='Valid')\n", (18643, 18733), True, 'import plotly.graph_objs as go\n'), ((23659, 23772), 'plotly.graph_objs.Bar', 'go.Bar', ([], {'x': "datatable_valid['id']", 'y': '(datatable_valid[column] if column in datatable_valid else [])', 'name': '"""Valid"""'}), "(x=datatable_valid['id'], y=datatable_valid[column] if column in\n datatable_valid else [], name='Valid')\n", (23665, 23772), True, 'import plotly.graph_objs as go\n'), ((19179, 19364), 'plotly.graph_objs.layout.XAxis', 'go.layout.XAxis', ([], {'autorange': '(True)', 'linewidth': '(1)', 'showgrid': '(True)', 'showline': '(True)', 'mirror': '(True)', 'ticktext': "['lwl/bwl', 'bwl/tcan', 'disp', 'cs']", 'tickvals': '[1, 2, 3, 4]', 'tickmode': '"""array"""'}), "(autorange=True, linewidth=1, showgrid=True, showline=True,\n mirror=True, ticktext=['lwl/bwl', 'bwl/tcan', 'disp', 'cs'], tickvals=[\n 1, 2, 3, 4], tickmode='array')\n", (19194, 19364), True, 'import plotly.graph_objs as go\n'), ((19644, 19760), 'plotly.graph_objs.layout.YAxis', 'go.layout.YAxis', ([], {'autorange': '(True)', 'linewidth': '(1)', 'showgrid': '(True)', 'showline': '(True)', 'mirror': '(True)', 'title': '"""Number of times"""'}), "(autorange=True, linewidth=1, showgrid=True, showline=True,\n mirror=True, title='Number of times')\n", (19659, 19760), True, 'import plotly.graph_objs as go\n')] |
#%%
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import seaborn as sns
import pandas as pd
import scipy.stats
import phd.viz
import phd.stats
colors, palette = phd.viz.phd_style()
# Load in the MCMC data.
data = pd.read_csv('../../data/ch9_mscl_si/complete_mcmc_traces.csv')
fig = plt.figure(figsize=(6, 3))
gs = gridspec.GridSpec(10, 10)
ax0 = fig.add_subplot(gs[:, 0:5])
ax1 = fig.add_subplot(gs[:4, 6:])
ax2 = fig.add_subplot(gs[6:, 6:])
ax0.set_ylim([2500, 4100])
ax0.set_xlim([4.75, 6])
fig.text(0.01, 0.9, '(A)', fontsize=8)
fig.text(0.55, 0.9, '(B)', fontsize=8)
fig.text(0.55, 0.4, '(C)', fontsize=8)
# Format the axes
phd.viz.despine([ax0, ax1, ax2])
# Plot the KDE if the samples.
_ = sns.kdeplot(data['hyper_A_mu'], data['hyper_alpha_mu'], ax=ax0, shade=True,
cmap=plt.cm.Purples)
ax0.set_ylabel('calibration factor [a.u. / MscL channel]', fontsize=8)
ax0.set_xlabel('average cell area [µm$^2$]', fontsize=8)
# Add a fake legend
ax1.plot([], [], color=colors['purple'], lw=1, label='replicate\n parameter')
ax1.plot([], [], color=colors['orange'], lw=1, label='hyper-\nparameter')
ax1.legend(fontsize=6, handlelength=1, loc='upper right')
# Evaluate the KDE for the low-level parameters
alpha_range = np.linspace(2000, 8000, 500)
area_range = np.linspace(4, 6.5, 500)
for i in range(6):
# Evaluate the KDE and normalize.
alpha_kernel = scipy.stats.gaussian_kde(data['alpha__{}'.format(i)])
area_kernel = scipy.stats.gaussian_kde(data['avg_A__{}'.format(i)])
alpha_fit = alpha_kernel(alpha_range)
area_fit = area_kernel(area_range)
alpha_fit *= np.sum(alpha_fit)**-1
area_fit *= np.sum(area_fit)**-1
# Plot the distributions.
_ = ax1.plot(alpha_range, alpha_fit, color=colors['purple'])
_ = ax2.plot(area_range, area_fit, color=colors['purple'])
_ = ax1.fill_between(alpha_range, alpha_fit, alpha=0.2, color=colors['light_purple'])
_ = ax2.fill_between(area_range, area_fit, alpha=0.2, color=colors['light_purple'])
# Plot the hyper parameters
hyper_alpha_kernel = scipy.stats.gaussian_kde(data['hyper_alpha_mu'])
hyper_area_kernel = scipy.stats.gaussian_kde(data['hyper_A_mu'])
hyper_alpha_fit = hyper_alpha_kernel(alpha_range)
hyper_area_fit = hyper_area_kernel(area_range)
hyper_alpha_fit *= np.sum(hyper_alpha_fit)**-1
hyper_area_fit *= np.sum(hyper_area_fit)**-1
_ = ax1.plot(alpha_range, hyper_alpha_fit, color=colors['orange'], lw=0.75)
_ = ax1.fill_between(alpha_range, hyper_alpha_fit, color=colors['orange'], alpha=0.4, zorder=100)
_ = ax2.plot(area_range, hyper_area_fit, color=colors['orange'], lw=0.75)
_ = ax2.fill_between(area_range, hyper_area_fit, color=colors['orange'], alpha=0.4, zorder=100)
ax1.set_xlabel('calibration factor [a.u./channel]')
ax2.set_xlabel('average cell area [µm$^2$]')
ax1.set_ylabel('$\propto$ probability')
ax2.set_ylabel('$\propto$ probability')
for a in (ax1, ax2):
a.set_yticks([])
plt.tight_layout()
plt.savefig('../figs/ch9_figS4.png', bbox_inches='tight')
plt.savefig('../figs/ch9_figS4.pdf', bbox_inches='tight')
# %%
| [
"seaborn.kdeplot",
"numpy.sum",
"pandas.read_csv",
"matplotlib.pyplot.figure",
"numpy.linspace",
"matplotlib.gridspec.GridSpec",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.savefig"
] | [((257, 319), 'pandas.read_csv', 'pd.read_csv', (['"""../../data/ch9_mscl_si/complete_mcmc_traces.csv"""'], {}), "('../../data/ch9_mscl_si/complete_mcmc_traces.csv')\n", (268, 319), True, 'import pandas as pd\n'), ((327, 353), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 3)'}), '(figsize=(6, 3))\n', (337, 353), True, 'import matplotlib.pyplot as plt\n'), ((359, 384), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['(10)', '(10)'], {}), '(10, 10)\n', (376, 384), True, 'import matplotlib.gridspec as gridspec\n'), ((743, 843), 'seaborn.kdeplot', 'sns.kdeplot', (["data['hyper_A_mu']", "data['hyper_alpha_mu']"], {'ax': 'ax0', 'shade': '(True)', 'cmap': 'plt.cm.Purples'}), "(data['hyper_A_mu'], data['hyper_alpha_mu'], ax=ax0, shade=True,\n cmap=plt.cm.Purples)\n", (754, 843), True, 'import seaborn as sns\n'), ((1262, 1290), 'numpy.linspace', 'np.linspace', (['(2000)', '(8000)', '(500)'], {}), '(2000, 8000, 500)\n', (1273, 1290), True, 'import numpy as np\n'), ((1304, 1328), 'numpy.linspace', 'np.linspace', (['(4)', '(6.5)', '(500)'], {}), '(4, 6.5, 500)\n', (1315, 1328), True, 'import numpy as np\n'), ((2946, 2964), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2962, 2964), True, 'import matplotlib.pyplot as plt\n'), ((2965, 3022), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""../figs/ch9_figS4.png"""'], {'bbox_inches': '"""tight"""'}), "('../figs/ch9_figS4.png', bbox_inches='tight')\n", (2976, 3022), True, 'import matplotlib.pyplot as plt\n'), ((3023, 3080), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""../figs/ch9_figS4.pdf"""'], {'bbox_inches': '"""tight"""'}), "('../figs/ch9_figS4.pdf', bbox_inches='tight')\n", (3034, 3080), True, 'import matplotlib.pyplot as plt\n'), ((2306, 2329), 'numpy.sum', 'np.sum', (['hyper_alpha_fit'], {}), '(hyper_alpha_fit)\n', (2312, 2329), True, 'import numpy as np\n'), ((2352, 2374), 'numpy.sum', 'np.sum', (['hyper_area_fit'], {}), '(hyper_area_fit)\n', (2358, 2374), True, 'import numpy as np\n'), ((1629, 1646), 'numpy.sum', 'np.sum', (['alpha_fit'], {}), '(alpha_fit)\n', (1635, 1646), True, 'import numpy as np\n'), ((1667, 1683), 'numpy.sum', 'np.sum', (['area_fit'], {}), '(area_fit)\n', (1673, 1683), True, 'import numpy as np\n')] |
import glob
import os
import random
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from torch.utils.data import Dataset
import matplotlib.pyplot as plt
import cv2
import scipy.ndimage as ndimage
import torch.optim as optim
import time
import shutil
from sklearn.metrics import roc_curve, auc
from argparse import ArgumentParser, Namespace
import torch.nn.functional as F
from torch.autograd import Variable
from torch.utils.data import DataLoader
import math
from functools import partial
from torch.utils.tensorboard import SummaryWriter
import torchio as tio
from tqdm.auto import tqdm
from seg_model_utils.torchio_transforms import *
from seg_model_utils.brats2021_dataset import BraTS2021
from seg_model_utils.augmentations3d import *
from seg_model_utils.visualization import *
from seg_model_utils.seg_model import UNet3D_v2
import json
import wandb
LOG_WANDB = False
def datestr():
now = time.gmtime()
return '{:02}_{:02}___{:02}_{:02}'.format(now.tm_mday, now.tm_mon, now.tm_hour, now.tm_min)
def make_dirs(path):
if os.path.exists(path):
shutil.rmtree(path)
os.mkdir(path)
else:
os.makedirs(path)
class TensorboardWriter():
def __init__(self, args):
name_model = args['log_dir'] + args['model'] + "_" + args['dataset_name'] + "_" + datestr()
self.writer = SummaryWriter(log_dir=args['log_dir'] + name_model, comment=name_model)
make_dirs(args['save'])
self.csv_train, self.csv_val = self.create_stats_files(args['save'])
self.dataset_name = args['dataset_name']
self.classes = args['classes']
self.label_names = args['class_names']
self.data = self.create_data_structure()
def create_data_structure(self, ):
data = {"train": dict((label, 0.0) for label in self.label_names),
"val": dict((label, 0.0) for label in self.label_names)}
data['train']['loss'] = 0.0
data['val']['loss'] = 0.0
data['train']['count'] = 1.0
data['val']['count'] = 1.0
data['train']['dsc'] = 0.0
data['val']['dsc'] = 0.0
data['train']['acc'] = 0.0
data['val']['acc'] = 0.0
data['train']['mse'] = 0.0
data['val']['mse'] = 0.0
return data
def display_terminal(self, iter, epoch, mode='train', summary=False):
"""
:param iter: iteration or partial epoch
:param epoch: epoch of training
:param loss: any loss numpy
:param mode: train or val ( for training and validation)
:param summary: to print total statistics at the end of epoch
"""
if summary:
info_print = "\nSummary {} Epoch {:2d}: Loss:{:.4f} \t DSC:{:.4f}\n Acc:{:.4f} MSE:{:.4f}".format(mode, epoch,
self.data[mode]['loss'] /
self.data[mode]['count'],
self.data[mode]['dsc'] /
self.data[mode]['count'],
self.data[mode]['acc'] / self.data[mode]['count'],
self.data[mode]['mse'] / self.data[mode]['count'])
for i in range(len(self.label_names)):
info_print += "\t{} : {:.4f}".format(self.label_names[i],
self.data[mode][self.label_names[i]] / self.data[mode]['count'])
print(info_print)
else:
info_print = "\nEpoch: {:.2f} Loss:{:.4f} \t DSC:{:.4f}\n Acc:{:.4f} MSE:{:.4f}".format(iter, self.data[mode]['loss'] /
self.data[mode]['count'],
self.data[mode]['dsc'] /
self.data[mode]['count'],
self.data[mode]['acc'] / self.data[mode]['count'],
self.data[mode]['mse'] / self.data[mode]['count'])
for i in range(len(self.label_names)):
info_print += "\t{}:{:.4f}".format(self.label_names[i],
self.data[mode][self.label_names[i]] / self.data[mode]['count'])
print(info_print)
def create_stats_files(self, path):
train_f = open(os.path.join(path, 'train.csv'), 'w')
val_f = open(os.path.join(path, 'val.csv'), 'w')
return train_f, val_f
def reset(self, mode):
self.data[mode]['dsc'] = 0.0
self.data[mode]['loss'] = 0.0
self.data[mode]['acc'] = 0.0
self.data[mode]['mse'] = 0.0
self.data[mode]['count'] = 1
for i in range(len(self.label_names)):
self.data[mode][self.label_names[i]] = 0.0
def update_scores(self, iter, loss, mse, channel_score, acc, mode, writer_step):
"""
:param iter: iteration or partial epoch
:param loss: any loss torch.tensor.item()
:param mse: mse loss torch.tensor.item()
:param channel_score: per channel score or dice coef
:param acc: classification accuracy
:param mode: train or val ( for training and validation)
:param writer_step: tensorboard writer step
"""
# WARNING ASSUMING THAT CHANNELS IN SAME ORDER AS DICTIONARY
dice_coeff = np.mean(channel_score) * 100
num_channels = len(channel_score)
self.data[mode]['dsc'] += dice_coeff
self.data[mode]['loss'] += loss
self.data[mode]['acc'] += acc
self.data[mode]['mse'] += mse
self.data[mode]['count'] = iter + 1
for i in range(num_channels):
chan_i = i
self.data[mode][self.label_names[i]] += channel_score[chan_i]
if self.writer is not None:
self.writer.add_scalar(mode + '/' + self.label_names[i], channel_score[chan_i], global_step=writer_step)
def write_end_of_epoch(self, epoch):
self.writer.add_scalars('DSC/', {'train': self.data['train']['dsc'] / self.data['train']['count'],
'val': self.data['val']['dsc'] / self.data['val']['count'],
}, epoch)
self.writer.add_scalars('Loss/', {'train': self.data['train']['loss'] / self.data['train']['count'],
'val': self.data['val']['loss'] / self.data['val']['count'],
}, epoch)
self.writer.add_scalars('Acc/', {'train': self.data['train']['acc'] / self.data['train']['count'],
'val': self.data['val']['acc'] / self.data['val']['count'],
}, epoch)
self.writer.add_scalars('MSE/', {'train': self.data['train']['mse'] / self.data['train']['count'],
'val': self.data['val']['mse'] / self.data['val']['count'],
}, epoch)
for i in range(len(self.label_names)):
self.writer.add_scalars(self.label_names[i],
{'train': self.data['train'][self.label_names[i]] / self.data['train']['count'],
'val': self.data['val'][self.label_names[i]] / self.data['train']['count'],
}, epoch)
train_csv_line = 'Epoch:{:2d} Loss:{:.4f} DSC:{:.4f} Acc:{:.4f} MSE:{:.4f}'.format(epoch,
self.data['train']['loss'] / self.data['train'][
'count'],
self.data['train']['dsc'] / self.data['train'][
'count'],
self.data['train']['acc'] / self.data['train'][
'count'],
self.data['train']['mse'] / self.data['train'][
'count'])
val_csv_line = 'Epoch:{:2d} Loss:{:.4f} DSC:{:.4f} Acc:{:.4f} MSE:{:.4f}'.format(epoch,
self.data['val']['loss'] / self.data['val'][
'count'],
self.data['val']['dsc'] / self.data['val'][
'count'],
self.data['val']['acc'] / self.data['val'][
'count'],
self.data['val']['mse'] / self.data['val'][
'count'])
self.csv_train.write(train_csv_line + '\n')
self.csv_val.write(val_csv_line + '\n')
class _AbstractDiceLoss(nn.Module):
"""
Base class for different implementations of Dice loss.
"""
def __init__(self, weight=None, sigmoid_normalization=True):
super(_AbstractDiceLoss, self).__init__()
self.register_buffer('weight', weight)
self.classes = None
self.skip_index_after = None
# The output from the network during training is assumed to be un-normalized probabilities and we would
# like to normalize the logits. Since Dice (or soft Dice in this case) is usually used for binary data,
# normalizing the channels with Sigmoid is the default choice even for multi-class segmentation problems.
# However if one would like to apply Softmax in order to get the proper probability distribution from the
# output, just specify sigmoid_normalization=False.
if sigmoid_normalization:
self.normalization = nn.Sigmoid()
else:
self.normalization = nn.Softmax(dim=1)
def dice(self, input, target, weight):
# actual Dice score computation; to be implemented by the subclass
raise NotImplementedError
def skip_target_channels(self, target, index):
"""
Assuming dim 1 is the classes dim , it skips all the indexes after the desired class
"""
assert index >= 2
return target[:, 0:index, ...]
def forward(self, input, target):
"""
Expand to one hot added extra for consistency reasons
"""
target = expand_as_one_hot(target.long(), self.classes)
assert input.dim() == target.dim() == 5, "'input' and 'target' have different number of dims"
if self.skip_index_after is not None:
before_size = target.size()
target = self.skip_target_channels(target, self.skip_index_after)
print("Target {} after skip index {}".format(before_size, target.size()))
assert input.size() == target.size(), "'input' and 'target' must have the same shape"
# get probabilities from logits
#input = self.normalization(input)
# compute per channel Dice coefficient
per_channel_dice = self.dice(input, target, weight=self.weight)
loss = (1. - torch.mean(per_channel_dice))
per_channel_dice = per_channel_dice.detach().cpu().numpy()
# average Dice score across all channels/classes
return loss, per_channel_dice
def expand_as_one_hot(input, C, ignore_index=None):
"""
Converts NxDxHxW label image to NxCxDxHxW, where each label gets converted to its corresponding one-hot vector
:param input: 4D input image (NxDxHxW)
:param C: number of channels/labels
:param ignore_index: ignore index to be kept during the expansion
:return: 5D output image (NxCxDxHxW)
"""
if input.dim() == 5:
return input
assert input.dim() == 4
# expand the input tensor to Nx1xDxHxW before scattering
input = input.unsqueeze(1)
# create result tensor shape (NxCxDxHxW)
shape = list(input.size())
shape[1] = C
if ignore_index is not None:
# create ignore_index mask for the result
mask = input.expand(shape) == ignore_index
# clone the lib tensor and zero out ignore_index in the input
input = input.clone()
input[input == ignore_index] = 0
# scatter to get the one-hot tensor
result = torch.zeros(shape).to(input.device).scatter_(1, input, 1)
# bring back the ignore_index in the result
result[mask] = ignore_index
return result
else:
# scatter to get the one-hot tensor
return torch.zeros(shape).to(input.device).scatter_(1, input, 1)
def flatten(tensor):
"""Flattens a given tensor such that the channel axis is first.
The shapes are transformed as follows:
(N, C, D, H, W) -> (C, N * D * H * W)
"""
# number of channels
C = tensor.size(1)
# new axis order
axis_order = (1, 0) + tuple(range(2, tensor.dim()))
# Transpose: (N, C, D, H, W) -> (C, N, D, H, W)
transposed = tensor.permute(axis_order)
# Flatten: (C, N, D, H, W) -> (C, N * D * H * W)
return transposed.contiguous().view(C, -1)
def compute_per_channel_dice(input, target, epsilon=1e-6, weight=None):
"""
Computes DiceCoefficient as defined in https://arxiv.org/abs/1606.04797 given a multi channel input and target.
Assumes the input is a normalized probability, e.g. a result of Sigmoid or Softmax function.
Args:
input (torch.Tensor): NxCxSpatial input tensor
target (torch.Tensor): NxCxSpatial target tensor
epsilon (float): prevents division by zero
weight (torch.Tensor): Cx1 tensor of weight per channel/class
"""
# input and target shapes must match
assert input.size() == target.size(), "'input' and 'target' must have the same shape"
input = flatten(input)
target = flatten(target)
target = target.float()
# compute per channel Dice Coefficient
intersect = (input * target).sum(-1)
if weight is not None:
intersect = weight * intersect
# here we can use standard dice (input + target).sum(-1) or extension (see V-Net) (input^2 + target^2).sum(-1)
denominator = (input * input).sum(-1) + (target * target).sum(-1)
return 2 * (intersect / denominator.clamp(min=epsilon))
def compute_channel_fusion_dice(input, target, epsilon=1e-6, weight=None):
"""
Computes DiceCoefficient as defined in https://arxiv.org/abs/1606.04797 given a multi channel input and target.
Assumes the input is a normalized probability, e.g. a result of Sigmoid or Softmax function.
Args:
input (torch.Tensor): NxCxSpatial input tensor
target (torch.Tensor): NxCxSpatial target tensor
epsilon (float): prevents division by zero
weight (torch.Tensor): Cx1 tensor of weight per channel/class
"""
# input and target shapes must match
assert input.size() == target.size(), "'input' and 'target' must have the same shape"
# reduce channel dimension to one
inp,_ = torch.max(input, dim=1, keepdim=True)
tgt,_ = torch.max(target, dim=1, keepdim=True)
#print(f'compute_channel_fusion_dice inp.shape {inp.shape}, tgt.shape {tgt.shape}')
inp = flatten(inp)
tgt = flatten(tgt)
tgt = tgt.float()
# compute per channel Dice Coefficient
intersect = (inp * tgt).sum(-1)
if weight is not None:
intersect = weight * intersect
# here we can use standard dice (input + target).sum(-1) or extension (see V-Net) (input^2 + target^2).sum(-1)
denominator = (inp * inp).sum(-1) + (tgt * tgt).sum(-1)
return 2 * (intersect / denominator.clamp(min=epsilon))
class DiceLoss(_AbstractDiceLoss):
"""Computes Dice Loss according to https://arxiv.org/abs/1606.04797.
For multi-class segmentation `weight` parameter can be used to assign different weights per class.
"""
def __init__(self, classes=1, skip_index_after=None, weight=None, sigmoid_normalization=True ):
super().__init__(weight, sigmoid_normalization)
self.classes = classes
if skip_index_after is not None:
self.skip_index_after = skip_index_after
def dice(self, input, target, weight):
return compute_per_channel_dice(input, target, weight=self.weight)
class Segmentation_class_accuracy():
def __init__(self, classes=2, class_axis=1):
self.classes = classes
self.class_axis = class_axis
def __call__(self, input, target):
#assert input.size() == target.size(), "'input' and 'target' must have the same shape"
input_classes = (input>0.0).flatten().type(torch.cuda.LongTensor)
target_classes = (target>0.0).flatten().type(torch.cuda.LongTensor)
return torch.sum(input_classes == target_classes) / input_classes.size()[0]
class BraTS2021_Trainer:
"""
Trainer class
"""
def __init__(self, args, model, criterion, optimizer, train_data_loader,
valid_data_loader=None, lr_scheduler=None):
self.args = args
use_cuda = torch.cuda.is_available()
self.device = torch.device("cuda:0" if use_cuda else "cpu")
self.model = model
self.optimizer = optimizer
self.criterion = criterion
self.train_data_loader = train_data_loader
# epoch-based training
self.len_epoch = len(self.train_data_loader)
self.valid_data_loader = valid_data_loader
self.do_validation = self.valid_data_loader is not None
self.lr_scheduler = lr_scheduler
self.log_step = int(np.sqrt(train_data_loader.batch_size))
self.writer = TensorboardWriter(args)
self.save_frequency = 10
self.terminal_show_freq = 50
self.start_epoch = 1
self.acc = Segmentation_class_accuracy()
self.mse_loss = torch.nn.BCEWithLogitsLoss()
self.mse_loss_weight = 2.0
self.save_dir = self.args['save']
def training(self):
for epoch in range(self.start_epoch, self.args['nEpochs']):
self.train_epoch(epoch)
if self.do_validation:
self.validate_epoch(epoch)
val_loss = self.writer.data['val']['loss'] / self.writer.data['val']['count']
if self.args['save'] is not None and ((epoch + 1) % self.save_frequency):
self.model.save_checkpoint(self.args['save'],
epoch, val_loss,
optimizer=self.optimizer)
self.writer.write_end_of_epoch(epoch)
self.writer.reset('train')
self.writer.reset('val')
def train_epoch(self, epoch):
self.model.train()
for batch_idx, input_samples in enumerate(self.train_data_loader):
self.optimizer.zero_grad()
input_tensor, target_seg, target_clf = input_samples['image'], input_samples['segmentation'], input_samples['label']
input_tensor, target_seg = input_tensor.to(self.device), target_seg.to(self.device)
target_clf = target_clf.to(self.device)
input_tensor.requires_grad = True
output_seg, output_clf = self.model(input_tensor)
loss_dice, per_ch_score = self.criterion(output_seg, target_seg)
loss_mse = self.mse_loss(output_clf, target_clf.unsqueeze(1).type(torch.cuda.FloatTensor))
loss_combined = loss_dice + loss_mse * self.mse_loss_weight
loss_combined.backward()
self.optimizer.step()
self.lr_scheduler.step()
with torch.no_grad():
acc = self.acc(output_clf, target_clf)
try:
self.writer.update_scores(batch_idx, loss_dice.item(), loss_mse.item(), per_ch_score, acc.item(), 'train',
epoch * self.len_epoch + batch_idx)
except Exception as e:
print(e)
if (batch_idx + 1) % self.terminal_show_freq == 0:
partial_epoch = epoch + batch_idx / self.len_epoch - 1
self.writer.display_terminal(partial_epoch, epoch, 'train')
self.writer.display_terminal(self.len_epoch, epoch, mode='train', summary=True)
def validate_epoch(self, epoch):
self.model.eval()
for batch_idx, input_samples in enumerate(self.valid_data_loader):
with torch.no_grad():
input_tensor, target_seg, target_clf = input_samples['image'], input_samples['segmentation'], input_samples['label']
input_tensor, target_seg = input_tensor.to(self.device), target_seg.to(self.device)
target_clf = target_clf.to(self.device)
input_tensor.requires_grad = False
output_seg, output_clf = self.model(input_tensor)
loss, per_ch_score = self.criterion(output_seg, target_seg)
loss_mse = self.mse_loss(output_clf, target_clf.unsqueeze(1).type(torch.cuda.FloatTensor))
acc = self.acc(output_clf, target_clf)
try:
self.writer.update_scores(batch_idx, loss.item(), loss_mse.item(), per_ch_score, acc.item(), 'val',
epoch * self.len_epoch + batch_idx)
except Exception as e:
print(e)
# preview one batch
if batch_idx == 0:
show_mri_sample(input_samples, pred_mask=output_seg,
pred_lbl=torch.sigmoid(output_clf.detach().cpu()).numpy(),
save_fn=os.path.join(self.save_dir, f'vis_epoch_{epoch}.png'))
if LOG_WANDB:
wandb.log({'validation': wandb.Image(os.path.join(self.save_dir, f'vis_epoch_{epoch}.png'))})
self.writer.display_terminal(len(self.valid_data_loader), epoch, mode='val', summary=True)
def inference_sample_tta(model, image, batch_size=1):
"""Inference 3d image with tta and average predictions. Image shape: 3xWxHxD"""
model.eval()
def _flip(im, index=0):
if index == 0:
return im
elif index == 1:
return torch.flip(im, [1])
elif index == 2:
return torch.flip(im, [2])
elif index == 3:
return torch.flip(im, [3])
elif index == 4:
return torch.flip(im, [1,2])
elif index == 5:
return torch.flip(im, [1,3])
elif index == 6:
return torch.flip(im, [1,2,3])
elif index == 7:
return torch.flip(im, [2,3])
def _predict(batch):
batch.requires_grad=False
seg_batch_flipped, clf_batch = model(batch.cuda())
seg_batch_flipped, clf_batch = seg_batch_flipped.detach().cpu(), clf_batch.detach().cpu()
# logits to preds
clf_batch = torch.sigmoid(clf_batch)
return seg_batch_flipped, clf_batch
batch = torch.stack([_flip(image.clone(), index) for index in range(4)], dim=0)
seg_batch_flipped_list, clf_batch_list = [],[]
with torch.no_grad():
for start in range(0, 4, batch_size):
seg_batch_flipped, clf_batch = _predict(batch[start:start + batch_size])
seg_batch_flipped_list = seg_batch_flipped_list + [seg for seg in seg_batch_flipped]
clf_batch_list = clf_batch_list + [clf for clf in clf_batch]
# flip masks back
seg_batch = torch.stack([_flip(seg, index) for index, seg in enumerate(seg_batch_flipped_list)], dim=0)
# average results
seg = torch.mean(seg_batch, dim=0)
clf = torch.mean(torch.stack(clf_batch_list, dim=0), dim=0)
return seg, clf
def eval_val_fold(out_dir, val_ds, model):
# create dirs
if not os.path.exists(out_dir): os.mkdir(out_dir)
pred_dir = os.path.join(out_dir, 'oof_preds')
if not os.path.exists(pred_dir): os.mkdir(pred_dir)
vis_dir = os.path.join(out_dir, 'vis')
if not os.path.exists(vis_dir): os.mkdir(vis_dir)
preds = []
gts = []
for val_index in tqdm(range(len(val_ds))):
sample = val_ds.__getitem__(val_index)
bratsid = f'{int(sample["BraTSID"]):05d}'
gts.append(float(sample['label']))
seg, clf = inference_sample_tta(model, sample['image'])
preds.append(float(clf.cpu().numpy()))
# save oof preds
seg_fn = os.path.join(pred_dir, f'{bratsid}_seg.npy')
np.save(seg_fn, seg.cpu().numpy())
pred_fn = os.path.join(pred_dir, f'{bratsid}_pred.npy')
np.save(pred_fn, clf.cpu().numpy())
vis_fn = os.path.join(vis_dir, f'{bratsid}.png')
show_mri_sample(
sample,
pred_mask=seg.unsqueeze(0),
pred_lbl=[clf.numpy()],
save_fn=vis_fn
)
plt.close('all')
auc_fn = os.path.join(out_dir, 'auc.png')
fpr, tpr, _ = roc_curve(np.array(gts), np.array(preds))
roc_auc = auc(fpr, tpr)
acc = np.sum((np.array(gts) > 0.5) == (np.array(preds) > 0.5)) / len(gts)
plt.figure()
lw = 2
plt.plot(fpr, tpr, color='darkorange',
lw=lw, label=f'ROC curve (area = {roc_auc:.2f}), Acc. = {acc*100:.2f}')
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic')
plt.legend(loc="lower right")
plt.savefig(auc_fn, transparent=False)
def main(fold:int, train_df:str, npy_dir:str, bs:int, epochs:int):
# start logging
global LOG_WANDB
wandb_config_fn = None
if os.path.exists('../wandb_params.json'):
wandb_config_fn = '../wandb_params.json'
if os.path.exists('./wandb_params.json'):
wandb_config_fn = './wandb_params.json'
if wandb_config_fn is not None:
with open(wandb_config_fn) as f:
config = json.load(f)
wandb.init(**config,
tags=['brain-segmentation', f'fold-{fold}'],
config={'bs':bs, 'epochs':epochs, 'fold':fold},
sync_tensorboard=True)
LOG_WANDB = True
df = pd.read_csv(train_df)
df_train = df[df.fold != fold]
df_val = df[df.fold == fold]
if len(df_val) == 0:
df_val = df[df.fold == 0]
sample_fns_train = [os.path.join(npy_dir, str(_id).zfill(5) + '.npy') for _id in df_train.BraTS21ID.values]
lbls_train = list(df_train.MGMT_value.values)
sample_fns_val = [os.path.join(npy_dir, str(_id).zfill(5) + '.npy') for _id in df_val.BraTS21ID.values]
lbls_val = list(df_val.MGMT_value.values)
crop_sz = (128,128,64)
max_out_size=crop_sz
tio_augmentations = tio.Compose([
tio.RandomAffine(p=0.5),
tio.RandomBiasField(p=0.3),
tio.RandomGhosting(p=0.05),
tio.RandomElasticDeformation(p=0.2),
tio.RandomSpike(p=0.05),
tio.RandomNoise(p=0.1),
tio.RandomAnisotropy(p=0.05),
tio.RandomFlip(p=0.5),
#tio.RandomSwap(p=0.05),
tio.RandomBlur(p=0.1),
tio.RandomGamma(p=0.15),
])
augmentations = ComposeTransforms([
RandomCropToSize(crop_sz=crop_sz),
], p=1.0)
train_ds = BraTS2021(
mode='train',
npy_fns_list=sample_fns_train,
label_list=lbls_train,
augmentations=augmentations,
tio_augmentations=tio_augmentations,
volume_normalize=True,
max_out_size=max_out_size
)
val_augmentations = ComposeTransforms([
RandomCropToSize(crop_sz=crop_sz),
], p=1.0)
val_ds = BraTS2021(
mode='val',
npy_fns_list=sample_fns_val,
label_list=lbls_val,
augmentations=val_augmentations,
volume_normalize=True,
max_out_size=max_out_size
)
dl_args = {
'batch_size': bs,
'shuffle': True,
'num_workers': 8,
}
train_generator = DataLoader(train_ds, **dl_args)
val_generator = DataLoader(val_ds, **dl_args)
# Load model
model_unet3d_v2 = UNet3D_v2(out_channels=1)
empty_state = model_unet3d_v2.state_dict()
model2d = torch.hub.load('mateuszbuda/brain-segmentation-pytorch', 'unet',
in_channels=3, out_channels=1, init_features=32, pretrained=True)
trained_2d_state = model2d.state_dict()
for key_3d in empty_state.keys():
if key_3d not in trained_2d_state.keys():
print(f'skip {key_3d}')
continue
weight_3d, weight_2d = empty_state[key_3d], trained_2d_state[key_3d]
# if shapes are same, regular copy
if weight_3d.shape == weight_2d.shape:
empty_state[key_3d] = trained_2d_state[key_3d].clone()
# don't copy final layer
elif key_3d != 'conv.weight' and key_3d != 'conv.bias':
weight = trained_2d_state[key_3d].clone()
empty_state[key_3d] = weight.unsqueeze(2).repeat(1, 1, weight.size(2), 1, 1)
model_unet3d_v2.load_state_dict(empty_state)
model = model_unet3d_v2.cuda()
if LOG_WANDB:
wandb.watch(model, log_freq=100)
optimizer_name = "adam" #'sgd'
lr= 3e-3
weight_decay = 0.0000000001
if optimizer_name == 'sgd':
optimizer = optim.SGD(model.parameters(), lr=lr, momentum=0.5, weight_decay=weight_decay)
elif optimizer_name == 'adam':
optimizer = optim.Adam(model.parameters(), lr=lr)
elif optimizer_name == 'rmsprop':
optimizer = optim.RMSprop(model.parameters(), lr=lr, weight_decay=weight_decay)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=6500, eta_min=1e-6, verbose=False)
loss = DiceLoss(classes=1)
train_args = {
'nEpochs' : epochs, # 100
'classes' : 1,
'class_names' : ['tumor'],
'inChannels' : 3,
'log_dir' : './runs/',
'save': f'./output/seg_model_256-{fold}',
'model':'3DUnet1chan',
'dataset_name':'registeredv1'
}
if 1:
trainer = BraTS2021_Trainer(train_args, model, loss, optimizer, train_data_loader=train_generator,
valid_data_loader=val_generator, lr_scheduler=scheduler)
trainer.training()
if fold == -1: return
# eval
# reload model
model = UNet3D_v2(out_channels=1).cuda()
model.load_state_dict(torch.load(f'./output/seg_model_256-{fold}/seg_model_256-{fold}_last_epoch.pth')['model_state_dict'])
_ = model.eval()
# load validation set
val_ds = BraTS2021(
mode='val',
npy_fns_list=sample_fns_val,
label_list=lbls_val,
augmentations=None,
volume_normalize=True,
max_out_size=(256,256,96)
)
out_dir = os.path.join(f'./output/seg_model_256-{fold}', 'eval')
eval_val_fold(out_dir, val_ds, model)
if __name__ == '__main__':
parser = ArgumentParser(parents=[])
parser.add_argument('--fold', type=int)
parser.add_argument('--bs', type=int, default=2)
parser.add_argument('--epochs', type=int, default=30)
parser.add_argument('--train_df', type=str, default='./input/train_labels_folds-v1.csv')
parser.add_argument('--npy_dir', type=str, default='./input/registered_cases/train/')
params = parser.parse_args()
fold = params.fold
train_df = params.train_df
npy_dir = params.npy_dir
bs = params.bs
epochs = params.epochs
main(fold, train_df, npy_dir, bs, epochs) | [
"matplotlib.pyplot.title",
"os.mkdir",
"argparse.ArgumentParser",
"torchio.RandomNoise",
"pandas.read_csv",
"wandb.watch",
"matplotlib.pyplot.figure",
"numpy.mean",
"torch.nn.Softmax",
"torchio.RandomAffine",
"torch.device",
"shutil.rmtree",
"torch.no_grad",
"os.path.join",
"torch.utils.... | [((931, 944), 'time.gmtime', 'time.gmtime', ([], {}), '()\n', (942, 944), False, 'import time\n'), ((1070, 1090), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (1084, 1090), False, 'import os\n'), ((15894, 15931), 'torch.max', 'torch.max', (['input'], {'dim': '(1)', 'keepdim': '(True)'}), '(input, dim=1, keepdim=True)\n', (15903, 15931), False, 'import torch\n'), ((15944, 15982), 'torch.max', 'torch.max', (['target'], {'dim': '(1)', 'keepdim': '(True)'}), '(target, dim=1, keepdim=True)\n', (15953, 15982), False, 'import torch\n'), ((24615, 24643), 'torch.mean', 'torch.mean', (['seg_batch'], {'dim': '(0)'}), '(seg_batch, dim=0)\n', (24625, 24643), False, 'import torch\n'), ((24859, 24893), 'os.path.join', 'os.path.join', (['out_dir', '"""oof_preds"""'], {}), "(out_dir, 'oof_preds')\n", (24871, 24893), False, 'import os\n'), ((24964, 24992), 'os.path.join', 'os.path.join', (['out_dir', '"""vis"""'], {}), "(out_dir, 'vis')\n", (24976, 24992), False, 'import os\n'), ((25917, 25949), 'os.path.join', 'os.path.join', (['out_dir', '"""auc.png"""'], {}), "(out_dir, 'auc.png')\n", (25929, 25949), False, 'import os\n'), ((26024, 26037), 'sklearn.metrics.auc', 'auc', (['fpr', 'tpr'], {}), '(fpr, tpr)\n', (26027, 26037), False, 'from sklearn.metrics import roc_curve, auc\n'), ((26130, 26142), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (26140, 26142), True, 'import matplotlib.pyplot as plt\n'), ((26158, 26275), 'matplotlib.pyplot.plot', 'plt.plot', (['fpr', 'tpr'], {'color': '"""darkorange"""', 'lw': 'lw', 'label': 'f"""ROC curve (area = {roc_auc:.2f}), Acc. = {acc * 100:.2f}"""'}), "(fpr, tpr, color='darkorange', lw=lw, label=\n f'ROC curve (area = {roc_auc:.2f}), Acc. = {acc * 100:.2f}')\n", (26166, 26275), True, 'import matplotlib.pyplot as plt\n'), ((26286, 26347), 'matplotlib.pyplot.plot', 'plt.plot', (['[0, 1]', '[0, 1]'], {'color': '"""navy"""', 'lw': 'lw', 'linestyle': '"""--"""'}), "([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\n", (26294, 26347), True, 'import matplotlib.pyplot as plt\n'), ((26352, 26372), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (26360, 26372), True, 'import matplotlib.pyplot as plt\n'), ((26377, 26398), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0.0, 1.05]'], {}), '([0.0, 1.05])\n', (26385, 26398), True, 'import matplotlib.pyplot as plt\n'), ((26403, 26436), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""False Positive Rate"""'], {}), "('False Positive Rate')\n", (26413, 26436), True, 'import matplotlib.pyplot as plt\n'), ((26441, 26473), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""True Positive Rate"""'], {}), "('True Positive Rate')\n", (26451, 26473), True, 'import matplotlib.pyplot as plt\n'), ((26478, 26524), 'matplotlib.pyplot.title', 'plt.title', (['"""Receiver operating characteristic"""'], {}), "('Receiver operating characteristic')\n", (26487, 26524), True, 'import matplotlib.pyplot as plt\n'), ((26529, 26558), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower right"""'}), "(loc='lower right')\n", (26539, 26558), True, 'import matplotlib.pyplot as plt\n'), ((26563, 26601), 'matplotlib.pyplot.savefig', 'plt.savefig', (['auc_fn'], {'transparent': '(False)'}), '(auc_fn, transparent=False)\n', (26574, 26601), True, 'import matplotlib.pyplot as plt\n'), ((26746, 26784), 'os.path.exists', 'os.path.exists', (['"""../wandb_params.json"""'], {}), "('../wandb_params.json')\n", (26760, 26784), False, 'import os\n'), ((26843, 26880), 'os.path.exists', 'os.path.exists', (['"""./wandb_params.json"""'], {}), "('./wandb_params.json')\n", (26857, 26880), False, 'import os\n'), ((27260, 27281), 'pandas.read_csv', 'pd.read_csv', (['train_df'], {}), '(train_df)\n', (27271, 27281), True, 'import pandas as pd\n'), ((28322, 28525), 'seg_model_utils.brats2021_dataset.BraTS2021', 'BraTS2021', ([], {'mode': '"""train"""', 'npy_fns_list': 'sample_fns_train', 'label_list': 'lbls_train', 'augmentations': 'augmentations', 'tio_augmentations': 'tio_augmentations', 'volume_normalize': '(True)', 'max_out_size': 'max_out_size'}), "(mode='train', npy_fns_list=sample_fns_train, label_list=\n lbls_train, augmentations=augmentations, tio_augmentations=\n tio_augmentations, volume_normalize=True, max_out_size=max_out_size)\n", (28331, 28525), False, 'from seg_model_utils.brats2021_dataset import BraTS2021\n'), ((28696, 28859), 'seg_model_utils.brats2021_dataset.BraTS2021', 'BraTS2021', ([], {'mode': '"""val"""', 'npy_fns_list': 'sample_fns_val', 'label_list': 'lbls_val', 'augmentations': 'val_augmentations', 'volume_normalize': '(True)', 'max_out_size': 'max_out_size'}), "(mode='val', npy_fns_list=sample_fns_val, label_list=lbls_val,\n augmentations=val_augmentations, volume_normalize=True, max_out_size=\n max_out_size)\n", (28705, 28859), False, 'from seg_model_utils.brats2021_dataset import BraTS2021\n'), ((29030, 29061), 'torch.utils.data.DataLoader', 'DataLoader', (['train_ds'], {}), '(train_ds, **dl_args)\n', (29040, 29061), False, 'from torch.utils.data import DataLoader\n'), ((29082, 29111), 'torch.utils.data.DataLoader', 'DataLoader', (['val_ds'], {}), '(val_ds, **dl_args)\n', (29092, 29111), False, 'from torch.utils.data import DataLoader\n'), ((29152, 29177), 'seg_model_utils.seg_model.UNet3D_v2', 'UNet3D_v2', ([], {'out_channels': '(1)'}), '(out_channels=1)\n', (29161, 29177), False, 'from seg_model_utils.seg_model import UNet3D_v2\n'), ((29240, 29374), 'torch.hub.load', 'torch.hub.load', (['"""mateuszbuda/brain-segmentation-pytorch"""', '"""unet"""'], {'in_channels': '(3)', 'out_channels': '(1)', 'init_features': '(32)', 'pretrained': '(True)'}), "('mateuszbuda/brain-segmentation-pytorch', 'unet',\n in_channels=3, out_channels=1, init_features=32, pretrained=True)\n", (29254, 29374), False, 'import torch\n'), ((30655, 30755), 'torch.optim.lr_scheduler.CosineAnnealingLR', 'torch.optim.lr_scheduler.CosineAnnealingLR', (['optimizer'], {'T_max': '(6500)', 'eta_min': '(1e-06)', 'verbose': '(False)'}), '(optimizer, T_max=6500, eta_min=\n 1e-06, verbose=False)\n', (30697, 30755), False, 'import torch\n'), ((31620, 31767), 'seg_model_utils.brats2021_dataset.BraTS2021', 'BraTS2021', ([], {'mode': '"""val"""', 'npy_fns_list': 'sample_fns_val', 'label_list': 'lbls_val', 'augmentations': 'None', 'volume_normalize': '(True)', 'max_out_size': '(256, 256, 96)'}), "(mode='val', npy_fns_list=sample_fns_val, label_list=lbls_val,\n augmentations=None, volume_normalize=True, max_out_size=(256, 256, 96))\n", (31629, 31767), False, 'from seg_model_utils.brats2021_dataset import BraTS2021\n'), ((31833, 31887), 'os.path.join', 'os.path.join', (['f"""./output/seg_model_256-{fold}"""', '"""eval"""'], {}), "(f'./output/seg_model_256-{fold}', 'eval')\n", (31845, 31887), False, 'import os\n'), ((31971, 31997), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'parents': '[]'}), '(parents=[])\n', (31985, 31997), False, 'from argparse import ArgumentParser, Namespace\n'), ((1100, 1119), 'shutil.rmtree', 'shutil.rmtree', (['path'], {}), '(path)\n', (1113, 1119), False, 'import shutil\n'), ((1128, 1142), 'os.mkdir', 'os.mkdir', (['path'], {}), '(path)\n', (1136, 1142), False, 'import os\n'), ((1161, 1178), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (1172, 1178), False, 'import os\n'), ((1361, 1432), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', ([], {'log_dir': "(args['log_dir'] + name_model)", 'comment': 'name_model'}), "(log_dir=args['log_dir'] + name_model, comment=name_model)\n", (1374, 1432), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((17941, 17966), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (17964, 17966), False, 'import torch\n'), ((17989, 18034), 'torch.device', 'torch.device', (["('cuda:0' if use_cuda else 'cpu')"], {}), "('cuda:0' if use_cuda else 'cpu')\n", (18001, 18034), False, 'import torch\n'), ((18709, 18737), 'torch.nn.BCEWithLogitsLoss', 'torch.nn.BCEWithLogitsLoss', ([], {}), '()\n', (18735, 18737), False, 'import torch\n'), ((23885, 23909), 'torch.sigmoid', 'torch.sigmoid', (['clf_batch'], {}), '(clf_batch)\n', (23898, 23909), False, 'import torch\n'), ((24108, 24123), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (24121, 24123), False, 'import torch\n'), ((24665, 24699), 'torch.stack', 'torch.stack', (['clf_batch_list'], {'dim': '(0)'}), '(clf_batch_list, dim=0)\n', (24676, 24699), False, 'import torch\n'), ((24801, 24824), 'os.path.exists', 'os.path.exists', (['out_dir'], {}), '(out_dir)\n', (24815, 24824), False, 'import os\n'), ((24826, 24843), 'os.mkdir', 'os.mkdir', (['out_dir'], {}), '(out_dir)\n', (24834, 24843), False, 'import os\n'), ((24905, 24929), 'os.path.exists', 'os.path.exists', (['pred_dir'], {}), '(pred_dir)\n', (24919, 24929), False, 'import os\n'), ((24931, 24949), 'os.mkdir', 'os.mkdir', (['pred_dir'], {}), '(pred_dir)\n', (24939, 24949), False, 'import os\n'), ((25004, 25027), 'os.path.exists', 'os.path.exists', (['vis_dir'], {}), '(vis_dir)\n', (25018, 25027), False, 'import os\n'), ((25029, 25046), 'os.mkdir', 'os.mkdir', (['vis_dir'], {}), '(vis_dir)\n', (25037, 25046), False, 'import os\n'), ((25452, 25496), 'os.path.join', 'os.path.join', (['pred_dir', 'f"""{bratsid}_seg.npy"""'], {}), "(pred_dir, f'{bratsid}_seg.npy')\n", (25464, 25496), False, 'import os\n'), ((25558, 25603), 'os.path.join', 'os.path.join', (['pred_dir', 'f"""{bratsid}_pred.npy"""'], {}), "(pred_dir, f'{bratsid}_pred.npy')\n", (25570, 25603), False, 'import os\n'), ((25674, 25713), 'os.path.join', 'os.path.join', (['vis_dir', 'f"""{bratsid}.png"""'], {}), "(vis_dir, f'{bratsid}.png')\n", (25686, 25713), False, 'import os\n'), ((25882, 25898), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (25891, 25898), True, 'import matplotlib.pyplot as plt\n'), ((25978, 25991), 'numpy.array', 'np.array', (['gts'], {}), '(gts)\n', (25986, 25991), True, 'import numpy as np\n'), ((25993, 26008), 'numpy.array', 'np.array', (['preds'], {}), '(preds)\n', (26001, 26008), True, 'import numpy as np\n'), ((27050, 27194), 'wandb.init', 'wandb.init', ([], {'tags': "['brain-segmentation', f'fold-{fold}']", 'config': "{'bs': bs, 'epochs': epochs, 'fold': fold}", 'sync_tensorboard': '(True)'}), "(**config, tags=['brain-segmentation', f'fold-{fold}'], config={\n 'bs': bs, 'epochs': epochs, 'fold': fold}, sync_tensorboard=True)\n", (27060, 27194), False, 'import wandb\n'), ((30175, 30207), 'wandb.watch', 'wandb.watch', (['model'], {'log_freq': '(100)'}), '(model, log_freq=100)\n', (30186, 30207), False, 'import wandb\n'), ((4839, 4870), 'os.path.join', 'os.path.join', (['path', '"""train.csv"""'], {}), "(path, 'train.csv')\n", (4851, 4870), False, 'import os\n'), ((4898, 4927), 'os.path.join', 'os.path.join', (['path', '"""val.csv"""'], {}), "(path, 'val.csv')\n", (4910, 4927), False, 'import os\n'), ((5850, 5872), 'numpy.mean', 'np.mean', (['channel_score'], {}), '(channel_score)\n', (5857, 5872), True, 'import numpy as np\n'), ((10687, 10699), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (10697, 10699), True, 'import torch.nn as nn\n'), ((10747, 10764), 'torch.nn.Softmax', 'nn.Softmax', ([], {'dim': '(1)'}), '(dim=1)\n', (10757, 10764), True, 'import torch.nn as nn\n'), ((12015, 12043), 'torch.mean', 'torch.mean', (['per_channel_dice'], {}), '(per_channel_dice)\n', (12025, 12043), False, 'import torch\n'), ((17628, 17670), 'torch.sum', 'torch.sum', (['(input_classes == target_classes)'], {}), '(input_classes == target_classes)\n', (17637, 17670), False, 'import torch\n'), ((18451, 18488), 'numpy.sqrt', 'np.sqrt', (['train_data_loader.batch_size'], {}), '(train_data_loader.batch_size)\n', (18458, 18488), True, 'import numpy as np\n'), ((27029, 27041), 'json.load', 'json.load', (['f'], {}), '(f)\n', (27038, 27041), False, 'import json\n'), ((27828, 27851), 'torchio.RandomAffine', 'tio.RandomAffine', ([], {'p': '(0.5)'}), '(p=0.5)\n', (27844, 27851), True, 'import torchio as tio\n'), ((27861, 27887), 'torchio.RandomBiasField', 'tio.RandomBiasField', ([], {'p': '(0.3)'}), '(p=0.3)\n', (27880, 27887), True, 'import torchio as tio\n'), ((27897, 27923), 'torchio.RandomGhosting', 'tio.RandomGhosting', ([], {'p': '(0.05)'}), '(p=0.05)\n', (27915, 27923), True, 'import torchio as tio\n'), ((27933, 27968), 'torchio.RandomElasticDeformation', 'tio.RandomElasticDeformation', ([], {'p': '(0.2)'}), '(p=0.2)\n', (27961, 27968), True, 'import torchio as tio\n'), ((27978, 28001), 'torchio.RandomSpike', 'tio.RandomSpike', ([], {'p': '(0.05)'}), '(p=0.05)\n', (27993, 28001), True, 'import torchio as tio\n'), ((28011, 28033), 'torchio.RandomNoise', 'tio.RandomNoise', ([], {'p': '(0.1)'}), '(p=0.1)\n', (28026, 28033), True, 'import torchio as tio\n'), ((28043, 28071), 'torchio.RandomAnisotropy', 'tio.RandomAnisotropy', ([], {'p': '(0.05)'}), '(p=0.05)\n', (28063, 28071), True, 'import torchio as tio\n'), ((28081, 28102), 'torchio.RandomFlip', 'tio.RandomFlip', ([], {'p': '(0.5)'}), '(p=0.5)\n', (28095, 28102), True, 'import torchio as tio\n'), ((28145, 28166), 'torchio.RandomBlur', 'tio.RandomBlur', ([], {'p': '(0.1)'}), '(p=0.1)\n', (28159, 28166), True, 'import torchio as tio\n'), ((28176, 28199), 'torchio.RandomGamma', 'tio.RandomGamma', ([], {'p': '(0.15)'}), '(p=0.15)\n', (28191, 28199), True, 'import torchio as tio\n'), ((31394, 31419), 'seg_model_utils.seg_model.UNet3D_v2', 'UNet3D_v2', ([], {'out_channels': '(1)'}), '(out_channels=1)\n', (31403, 31419), False, 'from seg_model_utils.seg_model import UNet3D_v2\n'), ((31453, 31538), 'torch.load', 'torch.load', (['f"""./output/seg_model_256-{fold}/seg_model_256-{fold}_last_epoch.pth"""'], {}), "(f'./output/seg_model_256-{fold}/seg_model_256-{fold}_last_epoch.pth'\n )\n", (31463, 31538), False, 'import torch\n'), ((20515, 20530), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (20528, 20530), False, 'import torch\n'), ((21347, 21362), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (21360, 21362), False, 'import torch\n'), ((23200, 23219), 'torch.flip', 'torch.flip', (['im', '[1]'], {}), '(im, [1])\n', (23210, 23219), False, 'import torch\n'), ((23264, 23283), 'torch.flip', 'torch.flip', (['im', '[2]'], {}), '(im, [2])\n', (23274, 23283), False, 'import torch\n'), ((26061, 26074), 'numpy.array', 'np.array', (['gts'], {}), '(gts)\n', (26069, 26074), True, 'import numpy as np\n'), ((26086, 26101), 'numpy.array', 'np.array', (['preds'], {}), '(preds)\n', (26094, 26101), True, 'import numpy as np\n'), ((13183, 13201), 'torch.zeros', 'torch.zeros', (['shape'], {}), '(shape)\n', (13194, 13201), False, 'import torch\n'), ((13420, 13438), 'torch.zeros', 'torch.zeros', (['shape'], {}), '(shape)\n', (13431, 13438), False, 'import torch\n'), ((23328, 23347), 'torch.flip', 'torch.flip', (['im', '[3]'], {}), '(im, [3])\n', (23338, 23347), False, 'import torch\n'), ((22616, 22669), 'os.path.join', 'os.path.join', (['self.save_dir', 'f"""vis_epoch_{epoch}.png"""'], {}), "(self.save_dir, f'vis_epoch_{epoch}.png')\n", (22628, 22669), False, 'import os\n'), ((23392, 23414), 'torch.flip', 'torch.flip', (['im', '[1, 2]'], {}), '(im, [1, 2])\n', (23402, 23414), False, 'import torch\n'), ((23458, 23480), 'torch.flip', 'torch.flip', (['im', '[1, 3]'], {}), '(im, [1, 3])\n', (23468, 23480), False, 'import torch\n'), ((22766, 22819), 'os.path.join', 'os.path.join', (['self.save_dir', 'f"""vis_epoch_{epoch}.png"""'], {}), "(self.save_dir, f'vis_epoch_{epoch}.png')\n", (22778, 22819), False, 'import os\n'), ((23524, 23549), 'torch.flip', 'torch.flip', (['im', '[1, 2, 3]'], {}), '(im, [1, 2, 3])\n', (23534, 23549), False, 'import torch\n'), ((23592, 23614), 'torch.flip', 'torch.flip', (['im', '[2, 3]'], {}), '(im, [2, 3])\n', (23602, 23614), False, 'import torch\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 14 10:34:31 2020
@author: alan
"""
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from glob import glob
from stable_baselines.results_plotter import load_results, ts2xy
def moving_average(values, window):
"""
Smooth values by doing a moving average
:param values: (numpy array)
:param window: (int)
:return: (numpy array)
"""
weights = np.repeat(1.0, window) / window
return np.convolve(values, weights, 'same')
updates = [8, 16, 32, 64]
agents = [4, 8, 16, 32, 64, 128]
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(48, 50))
fig.suptitle('PPO Image Based Learning', fontsize=70, y=0.92)
# plt.tight_layout()
for update, ax in zip(updates, [ax1, ax2, ax3, ax4]):
ax.spines["top"].set_visible(True)
ax.spines["bottom"].set_visible(True)
ax.spines["right"].set_visible(True)
ax.spines["left"].set_visible(True)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
ax.tick_params(labelsize=30)
for agent in agents:
path = '/home/alan/Documents/RL-Models/Paper/PPO_Line_{0}_{1}'.format(agent, update)
print(path)
dataset = load_results(path)
x, y = ts2xy(dataset, xaxis='walltime_hrs')
y = moving_average(y, 250)
x = x[:-200]
y = y[:-200]
mean_rewards, mean_ts = [], []
n_envs = path.split('/')[-1].split('_')[-2]
n_steps = path.split('/')[-1].split('_')[-1]
label = 'Agents: {0}'.format(n_envs)
ax.plot(x, y, lw=5, label=label)
ax.legend(fontsize=30, loc=0)
ax.grid(linestyle="--")
ax.set_title("Policy Update every {0} timesteps".format(n_steps), fontsize=50)
ax.set_xlabel("Training Time [hrs]", fontsize=40)
ax.set_ylabel("Mean Reward", fontsize=40)
plt.sca(ax)
plt.xticks(range(6))
plt.ylim(0, 400)
| [
"matplotlib.pyplot.ylim",
"stable_baselines.results_plotter.load_results",
"stable_baselines.results_plotter.ts2xy",
"matplotlib.pyplot.sca",
"numpy.convolve",
"matplotlib.pyplot.subplots",
"numpy.repeat"
] | [((635, 671), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {'figsize': '(48, 50)'}), '(2, 2, figsize=(48, 50))\n', (647, 671), True, 'import matplotlib.pyplot as plt\n'), ((505, 541), 'numpy.convolve', 'np.convolve', (['values', 'weights', '"""same"""'], {}), "(values, weights, 'same')\n", (516, 541), True, 'import numpy as np\n'), ((1857, 1868), 'matplotlib.pyplot.sca', 'plt.sca', (['ax'], {}), '(ax)\n', (1864, 1868), True, 'import matplotlib.pyplot as plt\n'), ((1898, 1914), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(400)'], {}), '(0, 400)\n', (1906, 1914), True, 'import matplotlib.pyplot as plt\n'), ((462, 484), 'numpy.repeat', 'np.repeat', (['(1.0)', 'window'], {}), '(1.0, window)\n', (471, 484), True, 'import numpy as np\n'), ((1229, 1247), 'stable_baselines.results_plotter.load_results', 'load_results', (['path'], {}), '(path)\n', (1241, 1247), False, 'from stable_baselines.results_plotter import load_results, ts2xy\n'), ((1263, 1299), 'stable_baselines.results_plotter.ts2xy', 'ts2xy', (['dataset'], {'xaxis': '"""walltime_hrs"""'}), "(dataset, xaxis='walltime_hrs')\n", (1268, 1299), False, 'from stable_baselines.results_plotter import load_results, ts2xy\n')] |
"""
This is a script that implement the SNOPT optimization package to minimize nonlinear constrained optimization problem
in SDOGS.
References:
<NAME>, <NAME>, <NAME>, <NAME>.
SNOPT 7.7 User's Manual.
CCoM Technical Report 18-1, Center for Computational Mathematics, University of California, San Diego.
<NAME>, <NAME> and <NAME>.
SNOPT: An SQP algorithm for large-scale constrained optimization.
SIAM Review 47 (2005), 99-131.
=====================================
Author : <NAME>
Date : Mar. 12, 2022
Location: UC San Diego, La Jolla, CA
=====================================
MIT License
Copyright (c) 2022 <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 os
import inspect
import numpy as np
import scipy.io as io
from dogs import Utils
from dogs import interpolation
from dogs import exterior_uncertainty
from optimize import snopta, SNOPT_options
__all__ = ['triangulation_search_bound_snopt']
def triangulation_search_bound_snopt(sdogs):
"""
Outline
Determine the minimizer of the constant K surrogate inside the known to be safe region.
----------
Parameters
:param sdogs : SafeDogs class object;
----------
Output
:return xc : The minimizer of surrogate model
:return yc : The surrogate model value at the minimizer
:return optm_result: The type optimization result, from global, safe or local
:return xc_safe_est: The safe estimate at the minimizer
"""
inf = 1e+20
# 0: The Delaunay triangulation is constructed at the beginning of each iteration.
# Sc contains the continuous search function value of the center of each Delaunay simplex
# 1: Identify the value of constant K continuous search function at the circumcenter of each Delaunay simplex
Sc = np.zeros(sdogs.tri.shape[0])
Scl = np.zeros(sdogs.tri.shape[0])
Sc_safe = np.zeros(sdogs.tri.shape[0])
for ii in range(np.shape(sdogs.tri)[0]):
R2, xc = Utils.circhyp(sdogs.xi[:, sdogs.tri[ii, :]], sdogs.n)
if R2 < inf:
# initialize with centroid of each simplex
# x = np.dot(sdogs.xi[:, sdogs.tri[ii, :]], np.ones([sdogs.n + 1, 1]) / (sdogs.n + 1))
x = np.mean(sdogs.xi[:, sdogs.tri[ii, :]], axis=1).reshape(-1, 1)
Sc[ii] = sdogs.surrogate_eval(x)
# compute the safe estimate of centroids: if positive, Sc_safe[ii] to be Sc[ii]; else unsafe, Sc_safe to be inf
sc_safe_est = np.max(np.min(sdogs.yS, axis=0) - sdogs.L_safe * np.linalg.norm(x - sdogs.xE))
Sc_safe[ii] = (Sc[ii] if sc_safe_est >= 0 else inf)
# If this simplex contains the DT vertex minimizer of yp
if np.min(np.linalg.norm(sdogs.x_yp_min - sdogs.tri[ii, :])) <= 1e-10:
Scl[ii] = np.copy(Sc[ii])
else:
Scl[ii] = inf
else:
Scl[ii] = inf
Sc[ii] = inf
# 2: Determine the minimizer of continuous search function at those 3 Delaunay simplices.
# optm_result == 0: Global one, the simplex that has minimum value of Sc at circumcenters, might be unsafe
# optm_result == 1: Global one within the safe region.
# optm_result == 2: Local and might be unsafe
index = np.array([np.argmin(Sc), np.argmin(Sc_safe), np.argmin(Scl)])
xm = np.zeros((sdogs.n, 3))
ym = np.zeros(3)
for i in range(3):
temp_x, ym[i] = constant_search_snopt(sdogs.xi[:, sdogs.tri[index[i], :]], sdogs)
xm[:, i] = temp_x.T[0]
sdogs.yc = np.min(ym)
sdogs.xc = xm[:, np.argmin(ym)].reshape(-1, 1)
sdogs.optm_result = np.argmin(ym)
sdogs.xc_safe_est = np.max(np.min(sdogs.yS, axis=0) - sdogs.L_safe * np.linalg.norm(sdogs.xc - sdogs.xE))
# ============================ Continuous search function Minimization =================================
def constant_search_snopt(simplex, sdogs):
"""
Find the minimizer of the search function in a simplex using SNOPT package.
The function F is composed as: 1st - objective
2nd to nth - simplex bounds
(n+1)th to (n+1+m)th - safe constraints
(n+1+m+1)th to ...th - nearest neighbor constraints
:param simplex : Delaunay simplex of interest, n by n+1 matrix.
:param sdogs : SafeDogs class object
"""
inf = 1.0e+20
# ------- ADD THE FOLLOWING LINE WHEN DEBUGGING --------
# simplex = sdogs.xi[:, sdogs.tri[index[i], :]]
# ------- ADD THE FOLLOWING LINE WHEN DEBUGGING --------
# - Determine if the boundary corner exists in simplex:
# If boundary corner detected:
# e(x) = (|| x - x' || + c )^b - c^b, x' in S^k
# else
# e(x) is the regular uncertainty function.
# - eval_indicators: Indicate which vertices of simplex is evaluated
exist, eval_indicators = exterior_uncertainty.unevaluated_vertices_identification(simplex, sdogs.xE)
# If the query simplex only has one evaluated vertex, unique_eval_vertex = 1; else unique_eval_vertex = 0.
unique_eval_vertex = (1 if len(np.where(eval_indicators != 0)[0]) == 1 else 0)
# Find the minimizer of the search function in a simplex using SNOPT package.
R2, xc = Utils.circhyp(simplex, sdogs.n)
# x is the centroid of this simplex
x = np.mean(simplex, axis=1).reshape(-1, 1)
# First find minimizer xr on reduced model, then find the 2D point corresponding to xr. Constrained optm.
A_simplex, b_simplex = Utils.search_simplex_bounds(simplex)
lb_simplex = np.min(simplex, axis=1)
ub_simplex = np.max(simplex, axis=1)
nL = sdogs.n + 1 # The number of constraints which is determined by the number of simplex boundaries.
assert nL == A_simplex.shape[0], 'The No. of simplex constraints is wrong'
# nF: The number of problem functions in F(x), including the objective function, linear and nonlinear constraints.
# ObjRow indicates which row is the objective function in F(x).
ObjRow = 1
# solve for constrained minimization of safe learning within each open ball of the vertices of the query simplex.
# Then choose the one with the minimum continuous function value.
x_solver = np.empty(shape=[sdogs.n, 0])
y_solver = np.empty(shape=[0, ])
for i in range(sdogs.n + 1):
# In n-dimensional simplex, there are n+1 vertices, for each of these vertices, there is a ball such that
# all the points within that ball have the closest evaluated points as the query vertex. This is good for
# building the exterior uncertainty function which needs this closest evaluated data point.
vertex = simplex[:, i].reshape(-1, 1)
# First find the y_safe[vertex]:
val, idx, x_nn = Utils.mindis(vertex, sdogs.xE)
if val > 1e-10:
# This vertex is a unsafe boundary corner point. No safe-guarantee, do not optimize around support points.
continue
else:
# Notice that the safety functions are transformed due to the difficulties in the numerical computation.
safe_bounds = sdogs.yS[:, idx] ** 2
# define the lower and upper bounds of decision variables x, to be the smallest box domain that contains simplex
xlow = np.copy(lb_simplex)
xupp = np.copy(ub_simplex)
if sdogs.n > 1 and unique_eval_vertex == 0:
# The First part of F(x) is the objective function.
# The second part of F(x) is the simplex bounds.
# The third part of functions in F(x) is the safe constraints.
# The fourth part of functions in F(x) is the nearest evaluated data points bound.
# In high dimension, A_simplex make sure that linear_derivative_A won't be all zero.
eval_indices = np.where(eval_indicators != 0)[0]
other_eval_vertices_index = np.where(eval_indices != i)[0]
n_other_eval_v = len(other_eval_vertices_index)
nF = 1 + nL + sdogs.m + n_other_eval_v
Flow = np.hstack((-inf, b_simplex.T[0], np.zeros(sdogs.m), np.zeros(n_other_eval_v)))
Fupp = np.hstack((inf * np.ones(1 + sdogs.n + 1), safe_bounds, inf * np.ones(n_other_eval_v)))
# First part: since constant K surrogate using p(x) - K * e(x), the objective function is nonlinear.
# Second part: The simplex constraints are generated by simplex bounds, all linear.
# Third part: The safety function is L2 norm, nonlinear
# Fourth part: The nearest point bound, nonlinear
# For the nonlinear components, enter any nonzero value in G to indicate the location
# of the nonlinear derivatives (in this case, sdogs.n + (sdogs.m + n_other_eval_v) * sdogs.n ).
# A must be properly defined with the correct derivative values.
linear_derivative_A = np.vstack((np.zeros((1, sdogs.n)), A_simplex, np.zeros((sdogs.m + n_other_eval_v, sdogs.n))))
nonlinear_derivative_G = np.vstack((2 * np.ones((1, sdogs.n)), np.zeros((nL, sdogs.n)),
2 * np.ones((sdogs.m + n_other_eval_v, sdogs.n))))
elif sdogs.n > 1 and unique_eval_vertex == 1:
# For higher-dimensional problem, if there is only one evaluated vertex of such vertex,
# we don't need to bound the nearest point in such simplex.
# The First part of F(x) is the objective function.
# The second part of F(x) is the simplex bounds.
# The third part of functions in F(x) is the safe constraints.
# In high dimension, A_simplex make sure that linear_derivative_A won't be all zero.
nF = 1 + nL + sdogs.m
Flow = np.hstack((-inf, b_simplex.T[0], np.zeros(sdogs.m)))
Fupp = np.hstack((inf * np.ones(1 + nL), safe_bounds))
linear_derivative_A = np.vstack((np.zeros((1, sdogs.n)), A_simplex, np.zeros((sdogs.m, sdogs.n))))
nonlinear_derivative_G = np.vstack((2 * np.ones((1, sdogs.n)), np.zeros((nL, sdogs.n)), 2 * np.ones((sdogs.m, sdogs.n))))
else: # n = 1
# For 1D problem, the simplex constraint is defined in x bounds.
# For 1D problem, the closest point from x to evaluated data points must be this querying vertex.
# 1 obj + M safe con. Plus another 1 redundant constraint to make matrix A contain nonzero terms.
# Since constant using p(x) - K * e(x), the objective function is nonlinear.
# The safety function is L2 norm, nonlinear
# The auxiliary function is linear.
nF = 1 + sdogs.m + 1
Flow = np.hstack((-inf, np.zeros(sdogs.m), -inf))
Fupp = np.hstack((inf, safe_bounds, inf))
linear_derivative_A = np.vstack((np.zeros((1 + sdogs.M, sdogs.n)), np.ones((1, sdogs.n))))
nonlinear_derivative_G = np.vstack((2 * np.ones((1 + sdogs.M, sdogs.n)), np.zeros((1, sdogs.n))))
x0 = x.T[0]
# ------- ADD THE FOLLOWING LINE WHEN DEBUGGING --------
# cd dogs
# ------- ADD THE FOLLOWING LINE WHEN DEBUGGING --------
# save_opt_for_snopt_ck(n, nF, inter_par, xc, R2, K, A_simplex, L_safe, vertex, exist, unique_eval_vertex,
# simplex, M, b, c)
save_opt_for_snopt_ck(sdogs, nF, xc, R2, A_simplex, vertex, exist, unique_eval_vertex, simplex)
options = SNOPT_options()
options.setOption('Solution print', False)
options.setOption('Infinite bound', inf)
options.setOption('Verify level', 3)
options.setOption('Verbose', True)
options.setOption('Print level', -1)
options.setOption('Scale option', 2)
options.setOption('Print frequency', -1)
options.setOption('Major feasibility', 1e-10)
options.setOption('Minor feasibility', 1e-10)
options.setOption('Feasibility tolerance', 1e-5)
options.setOption('Summary', 'No')
result = snopta(dogsobj, sdogs.n, nF, x0=x0, name='SDOGS_snopt', xlow=xlow, xupp=xupp, Flow=Flow, Fupp=Fupp,
ObjRow=ObjRow, A=linear_derivative_A, G=nonlinear_derivative_G, options=options)
x_solver = np.hstack((x_solver, result.x.reshape(-1, 1)))
y_solver = np.hstack((y_solver, result.objective))
yc = np.min(y_solver)
xc = x_solver[:, np.argmin(y_solver)].reshape(-1, 1)
return xc, yc
def folder_path():
current_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
folder = os.path.join(os.path.dirname(current_path), 'snopt_info')
return folder
def save_opt_for_snopt_ck(sdogs, nF, xc, R2, A_simplex, vertex, exist, unique_eval_vertex,
simplex):
var_opt = {}
if sdogs.inter_par.method == "NPS":
var_opt['inter_par_method'] = sdogs.inter_par.method
var_opt['inter_par_w'] = sdogs.inter_par.w
var_opt['inter_par_v'] = sdogs.inter_par.v
var_opt['inter_par_xi'] = sdogs.inter_par.xi
var_opt['n'] = sdogs.n
var_opt['M'] = sdogs.m
var_opt['nF'] = nF
var_opt['xc'] = xc
var_opt['R2'] = R2
var_opt['K'] = sdogs.K
var_opt['A'] = A_simplex
var_opt['b'] = sdogs.b
var_opt['c'] = sdogs.c
var_opt['exist'] = exist
var_opt['L_safe'] = sdogs.L_safe
var_opt['vertex'] = vertex
var_opt['simplex'] = simplex
var_opt['unique_eval_vertex'] = unique_eval_vertex
path = os.path.join(sdogs.snopt_folder, 'opt_info_ck.mat')
io.savemat(path, var_opt)
return
def constant_search_cost_snopt(x):
x = x.reshape(-1, 1)
folder = folder_path()
var_opt = io.loadmat(os.path.join(folder, "opt_info_ck.mat"))
n = var_opt['n'][0, 0]
m = var_opt['M'][0, 0]
xc = var_opt['xc']
R2 = var_opt['R2'][0, 0]
K = var_opt['K'][0, 0]
nF = var_opt['nF'][0, 0]
A = var_opt['A']
b = var_opt['b'][0, 0]
c = var_opt['c'][0, 0]
L_safe = var_opt['L_safe'][0, 0]
vertex = var_opt['vertex']
exist = var_opt['exist'][0, 0]
simplex = var_opt['simplex']
unique_eval_vertex = var_opt['unique_eval_vertex'][0, 0]
xE = var_opt['inter_par_xi']
inter_par = interpolation.InterParams(xE)
inter_par.w = np.copy(var_opt['inter_par_w'])
inter_par.v = np.copy(var_opt['inter_par_v'])
inter_par.xi = np.copy(xE)
# Initialize the output F and G.
F = np.zeros(nF)
p = inter_par.inter_val(x)
gp = inter_par.inter_grad(x)
# The uncertainty function is defined using distance from x to xE
# The estimated safety function is defined using distance from x to vertices of simplex.
if exist == 0: # All vertices of the current simplex are evaluated.
e = R2 - np.linalg.norm(x - xc) ** 2
ge = - 2 * (x - xc)
else: # unevaluated boundary corner point detected.
e, ge, gge = exterior_uncertainty.exterior_uncertainty_eval(x, inter_par.xi, b, c)
F[0] = p - K * e
DM = gp - K * ge
norm2_difference = np.dot((x - vertex).T, x - vertex)
# G1: continuous search model function gradient
G1 = DM.flatten()
# G2: Safety function constraint gradient, flattened version, trick is size = M.
# Notice that the safety functions are transformed due to the difficulties in the numerical computation.
# Here we take L_safe^2 * ||x-vertex||^2_2 <= psi^2(vertex)
G2 = np.tile((2 * L_safe**2 * (x - vertex)).T[0], m)
if n > 1 and unique_eval_vertex == 0:
# nD data has n+1 simplex bounds.
F[1 : 1 + (n + 1)] = (np.dot(A, x)).T[0]
# M safety functions
# Notice that SNOPT use c(x) >= 0, then transform it with negative sign
# [psi(vertex)]^2 >= L_safe^2 * || x - vertex ||^2_2 >= 0
F[1 + (n + 1) : 1 + (n + 1) + m] = L_safe**2 * norm2_difference * np.ones(m)
exist, eval_indicators = exterior_uncertainty.unevaluated_vertices_identification(simplex, inter_par.xi)
eval_indices = np.where(eval_indicators != 0)[0]
i = np.where(np.linalg.norm(simplex - vertex, axis=0) == 0)[0]
other_eval_vertices_index = np.where(eval_indices != i)[0]
other_eval_vertices = simplex[:, other_eval_vertices_index]
# Nearest neighbor bounds
F[1 + (n + 1) + m:] = np.linalg.norm(x - other_eval_vertices, axis=0) ** 2 - np.linalg.norm(x - vertex) ** 2
# G3: closest evaluated point constraint gradient
G3 = 2 * (x - other_eval_vertices) - 2 * (x - vertex)
G = np.hstack((G1, G2, G3.flatten()))
elif n > 1 and unique_eval_vertex == 1:
F[1 : 1 + (n + 1)] = (np.dot(A, x)).T[0]
F[1 + (n + 1) : 1 + (n + 1) + m] = L_safe**2 * norm2_difference * np.ones(m)
G = np.hstack((G1, G2))
else:
# next line is the safe con
F[1 : 1 + m] = L_safe**2 * norm2_difference * np.ones(m)
# Next line is the redundant row.
F[-1] = np.sum(x)
G = np.hstack((G1, G2))
return F, G
def dogsobj(status, x, needF, F, needG, G):
# G is the nonlinear part of the Jacobian
F, G = constant_search_cost_snopt(x)
return status, F, G
| [
"numpy.sum",
"numpy.empty",
"numpy.ones",
"numpy.argmin",
"numpy.shape",
"numpy.mean",
"numpy.linalg.norm",
"numpy.tile",
"dogs.Utils.search_simplex_bounds",
"os.path.join",
"numpy.copy",
"os.path.dirname",
"numpy.max",
"dogs.exterior_uncertainty.exterior_uncertainty_eval",
"optimize.sno... | [((2887, 2915), 'numpy.zeros', 'np.zeros', (['sdogs.tri.shape[0]'], {}), '(sdogs.tri.shape[0])\n', (2895, 2915), True, 'import numpy as np\n'), ((2942, 2970), 'numpy.zeros', 'np.zeros', (['sdogs.tri.shape[0]'], {}), '(sdogs.tri.shape[0])\n', (2950, 2970), True, 'import numpy as np\n'), ((2997, 3025), 'numpy.zeros', 'np.zeros', (['sdogs.tri.shape[0]'], {}), '(sdogs.tri.shape[0])\n', (3005, 3025), True, 'import numpy as np\n'), ((4515, 4537), 'numpy.zeros', 'np.zeros', (['(sdogs.n, 3)'], {}), '((sdogs.n, 3))\n', (4523, 4537), True, 'import numpy as np\n'), ((4564, 4575), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (4572, 4575), True, 'import numpy as np\n'), ((4756, 4766), 'numpy.min', 'np.min', (['ym'], {}), '(ym)\n', (4762, 4766), True, 'import numpy as np\n'), ((4855, 4868), 'numpy.argmin', 'np.argmin', (['ym'], {}), '(ym)\n', (4864, 4868), True, 'import numpy as np\n'), ((6185, 6260), 'dogs.exterior_uncertainty.unevaluated_vertices_identification', 'exterior_uncertainty.unevaluated_vertices_identification', (['simplex', 'sdogs.xE'], {}), '(simplex, sdogs.xE)\n', (6241, 6260), False, 'from dogs import exterior_uncertainty\n'), ((6551, 6582), 'dogs.Utils.circhyp', 'Utils.circhyp', (['simplex', 'sdogs.n'], {}), '(simplex, sdogs.n)\n', (6564, 6582), False, 'from dogs import Utils\n'), ((6809, 6845), 'dogs.Utils.search_simplex_bounds', 'Utils.search_simplex_bounds', (['simplex'], {}), '(simplex)\n', (6836, 6845), False, 'from dogs import Utils\n'), ((6863, 6886), 'numpy.min', 'np.min', (['simplex'], {'axis': '(1)'}), '(simplex, axis=1)\n', (6869, 6886), True, 'import numpy as np\n'), ((6904, 6927), 'numpy.max', 'np.max', (['simplex'], {'axis': '(1)'}), '(simplex, axis=1)\n', (6910, 6927), True, 'import numpy as np\n'), ((7522, 7550), 'numpy.empty', 'np.empty', ([], {'shape': '[sdogs.n, 0]'}), '(shape=[sdogs.n, 0])\n', (7530, 7550), True, 'import numpy as np\n'), ((7566, 7585), 'numpy.empty', 'np.empty', ([], {'shape': '[0]'}), '(shape=[0])\n', (7574, 7585), True, 'import numpy as np\n'), ((13971, 13987), 'numpy.min', 'np.min', (['y_solver'], {}), '(y_solver)\n', (13977, 13987), True, 'import numpy as np\n'), ((15120, 15171), 'os.path.join', 'os.path.join', (['sdogs.snopt_folder', '"""opt_info_ck.mat"""'], {}), "(sdogs.snopt_folder, 'opt_info_ck.mat')\n", (15132, 15171), False, 'import os\n'), ((15176, 15201), 'scipy.io.savemat', 'io.savemat', (['path', 'var_opt'], {}), '(path, var_opt)\n', (15186, 15201), True, 'import scipy.io as io\n'), ((15861, 15890), 'dogs.interpolation.InterParams', 'interpolation.InterParams', (['xE'], {}), '(xE)\n', (15886, 15890), False, 'from dogs import interpolation\n'), ((15909, 15940), 'numpy.copy', 'np.copy', (["var_opt['inter_par_w']"], {}), "(var_opt['inter_par_w'])\n", (15916, 15940), True, 'import numpy as np\n'), ((15959, 15990), 'numpy.copy', 'np.copy', (["var_opt['inter_par_v']"], {}), "(var_opt['inter_par_v'])\n", (15966, 15990), True, 'import numpy as np\n'), ((16010, 16021), 'numpy.copy', 'np.copy', (['xE'], {}), '(xE)\n', (16017, 16021), True, 'import numpy as np\n'), ((16068, 16080), 'numpy.zeros', 'np.zeros', (['nF'], {}), '(nF)\n', (16076, 16080), True, 'import numpy as np\n'), ((16672, 16706), 'numpy.dot', 'np.dot', (['(x - vertex).T', '(x - vertex)'], {}), '((x - vertex).T, x - vertex)\n', (16678, 16706), True, 'import numpy as np\n'), ((17050, 17099), 'numpy.tile', 'np.tile', (['(2 * L_safe ** 2 * (x - vertex)).T[0]', 'm'], {}), '((2 * L_safe ** 2 * (x - vertex)).T[0], m)\n', (17057, 17099), True, 'import numpy as np\n'), ((3098, 3151), 'dogs.Utils.circhyp', 'Utils.circhyp', (['sdogs.xi[:, sdogs.tri[ii, :]]', 'sdogs.n'], {}), '(sdogs.xi[:, sdogs.tri[ii, :]], sdogs.n)\n', (3111, 3151), False, 'from dogs import Utils\n'), ((8063, 8093), 'dogs.Utils.mindis', 'Utils.mindis', (['vertex', 'sdogs.xE'], {}), '(vertex, sdogs.xE)\n', (8075, 8093), False, 'from dogs import Utils\n'), ((14204, 14233), 'os.path.dirname', 'os.path.dirname', (['current_path'], {}), '(current_path)\n', (14219, 14233), False, 'import os\n'), ((15327, 15366), 'os.path.join', 'os.path.join', (['folder', '"""opt_info_ck.mat"""'], {}), "(folder, 'opt_info_ck.mat')\n", (15339, 15366), False, 'import os\n'), ((16535, 16604), 'dogs.exterior_uncertainty.exterior_uncertainty_eval', 'exterior_uncertainty.exterior_uncertainty_eval', (['x', 'inter_par.xi', 'b', 'c'], {}), '(x, inter_par.xi, b, c)\n', (16581, 16604), False, 'from dogs import exterior_uncertainty\n'), ((17527, 17606), 'dogs.exterior_uncertainty.unevaluated_vertices_identification', 'exterior_uncertainty.unevaluated_vertices_identification', (['simplex', 'inter_par.xi'], {}), '(simplex, inter_par.xi)\n', (17583, 17606), False, 'from dogs import exterior_uncertainty\n'), ((3047, 3066), 'numpy.shape', 'np.shape', (['sdogs.tri'], {}), '(sdogs.tri)\n', (3055, 3066), True, 'import numpy as np\n'), ((4437, 4450), 'numpy.argmin', 'np.argmin', (['Sc'], {}), '(Sc)\n', (4446, 4450), True, 'import numpy as np\n'), ((4452, 4470), 'numpy.argmin', 'np.argmin', (['Sc_safe'], {}), '(Sc_safe)\n', (4461, 4470), True, 'import numpy as np\n'), ((4472, 4486), 'numpy.argmin', 'np.argmin', (['Scl'], {}), '(Scl)\n', (4481, 4486), True, 'import numpy as np\n'), ((4902, 4926), 'numpy.min', 'np.min', (['sdogs.yS'], {'axis': '(0)'}), '(sdogs.yS, axis=0)\n', (4908, 4926), True, 'import numpy as np\n'), ((6631, 6655), 'numpy.mean', 'np.mean', (['simplex'], {'axis': '(1)'}), '(simplex, axis=1)\n', (6638, 6655), True, 'import numpy as np\n'), ((8582, 8601), 'numpy.copy', 'np.copy', (['lb_simplex'], {}), '(lb_simplex)\n', (8589, 8601), True, 'import numpy as np\n'), ((8621, 8640), 'numpy.copy', 'np.copy', (['ub_simplex'], {}), '(ub_simplex)\n', (8628, 8640), True, 'import numpy as np\n'), ((13001, 13016), 'optimize.SNOPT_options', 'SNOPT_options', ([], {}), '()\n', (13014, 13016), False, 'from optimize import snopta, SNOPT_options\n'), ((13618, 13808), 'optimize.snopta', 'snopta', (['dogsobj', 'sdogs.n', 'nF'], {'x0': 'x0', 'name': '"""SDOGS_snopt"""', 'xlow': 'xlow', 'xupp': 'xupp', 'Flow': 'Flow', 'Fupp': 'Fupp', 'ObjRow': 'ObjRow', 'A': 'linear_derivative_A', 'G': 'nonlinear_derivative_G', 'options': 'options'}), "(dogsobj, sdogs.n, nF, x0=x0, name='SDOGS_snopt', xlow=xlow, xupp=\n xupp, Flow=Flow, Fupp=Fupp, ObjRow=ObjRow, A=linear_derivative_A, G=\n nonlinear_derivative_G, options=options)\n", (13624, 13808), False, 'from optimize import snopta, SNOPT_options\n'), ((13921, 13960), 'numpy.hstack', 'np.hstack', (['(y_solver, result.objective)'], {}), '((y_solver, result.objective))\n', (13930, 13960), True, 'import numpy as np\n'), ((17482, 17492), 'numpy.ones', 'np.ones', (['m'], {}), '(m)\n', (17489, 17492), True, 'import numpy as np\n'), ((17630, 17660), 'numpy.where', 'np.where', (['(eval_indicators != 0)'], {}), '(eval_indicators != 0)\n', (17638, 17660), True, 'import numpy as np\n'), ((17771, 17798), 'numpy.where', 'np.where', (['(eval_indices != i)'], {}), '(eval_indices != i)\n', (17779, 17798), True, 'import numpy as np\n'), ((18381, 18400), 'numpy.hstack', 'np.hstack', (['(G1, G2)'], {}), '((G1, G2))\n', (18390, 18400), True, 'import numpy as np\n'), ((18571, 18580), 'numpy.sum', 'np.sum', (['x'], {}), '(x)\n', (18577, 18580), True, 'import numpy as np\n'), ((18594, 18613), 'numpy.hstack', 'np.hstack', (['(G1, G2)'], {}), '((G1, G2))\n', (18603, 18613), True, 'import numpy as np\n'), ((3948, 3963), 'numpy.copy', 'np.copy', (['Sc[ii]'], {}), '(Sc[ii])\n', (3955, 3963), True, 'import numpy as np\n'), ((4944, 4979), 'numpy.linalg.norm', 'np.linalg.norm', (['(sdogs.xc - sdogs.xE)'], {}), '(sdogs.xc - sdogs.xE)\n', (4958, 4979), True, 'import numpy as np\n'), ((14152, 14174), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (14172, 14174), False, 'import inspect\n'), ((16401, 16423), 'numpy.linalg.norm', 'np.linalg.norm', (['(x - xc)'], {}), '(x - xc)\n', (16415, 16423), True, 'import numpy as np\n'), ((17213, 17225), 'numpy.dot', 'np.dot', (['A', 'x'], {}), '(A, x)\n', (17219, 17225), True, 'import numpy as np\n'), ((17935, 17982), 'numpy.linalg.norm', 'np.linalg.norm', (['(x - other_eval_vertices)'], {'axis': '(0)'}), '(x - other_eval_vertices, axis=0)\n', (17949, 17982), True, 'import numpy as np\n'), ((17990, 18016), 'numpy.linalg.norm', 'np.linalg.norm', (['(x - vertex)'], {}), '(x - vertex)\n', (18004, 18016), True, 'import numpy as np\n'), ((18357, 18367), 'numpy.ones', 'np.ones', (['m'], {}), '(m)\n', (18364, 18367), True, 'import numpy as np\n'), ((18502, 18512), 'numpy.ones', 'np.ones', (['m'], {}), '(m)\n', (18509, 18512), True, 'import numpy as np\n'), ((3363, 3409), 'numpy.mean', 'np.mean', (['sdogs.xi[:, sdogs.tri[ii, :]]'], {'axis': '(1)'}), '(sdogs.xi[:, sdogs.tri[ii, :]], axis=1)\n', (3370, 3409), True, 'import numpy as np\n'), ((3633, 3657), 'numpy.min', 'np.min', (['sdogs.yS'], {'axis': '(0)'}), '(sdogs.yS, axis=0)\n', (3639, 3657), True, 'import numpy as np\n'), ((3861, 3910), 'numpy.linalg.norm', 'np.linalg.norm', (['(sdogs.x_yp_min - sdogs.tri[ii, :])'], {}), '(sdogs.x_yp_min - sdogs.tri[ii, :])\n', (3875, 3910), True, 'import numpy as np\n'), ((4799, 4812), 'numpy.argmin', 'np.argmin', (['ym'], {}), '(ym)\n', (4808, 4812), True, 'import numpy as np\n'), ((6407, 6437), 'numpy.where', 'np.where', (['(eval_indicators != 0)'], {}), '(eval_indicators != 0)\n', (6415, 6437), True, 'import numpy as np\n'), ((9142, 9172), 'numpy.where', 'np.where', (['(eval_indicators != 0)'], {}), '(eval_indicators != 0)\n', (9150, 9172), True, 'import numpy as np\n'), ((9220, 9247), 'numpy.where', 'np.where', (['(eval_indices != i)'], {}), '(eval_indices != i)\n', (9228, 9247), True, 'import numpy as np\n'), ((12248, 12282), 'numpy.hstack', 'np.hstack', (['(inf, safe_bounds, inf)'], {}), '((inf, safe_bounds, inf))\n', (12257, 12282), True, 'import numpy as np\n'), ((14009, 14028), 'numpy.argmin', 'np.argmin', (['y_solver'], {}), '(y_solver)\n', (14018, 14028), True, 'import numpy as np\n'), ((17685, 17725), 'numpy.linalg.norm', 'np.linalg.norm', (['(simplex - vertex)'], {'axis': '(0)'}), '(simplex - vertex, axis=0)\n', (17699, 17725), True, 'import numpy as np\n'), ((18264, 18276), 'numpy.dot', 'np.dot', (['A', 'x'], {}), '(A, x)\n', (18270, 18276), True, 'import numpy as np\n'), ((3675, 3703), 'numpy.linalg.norm', 'np.linalg.norm', (['(x - sdogs.xE)'], {}), '(x - sdogs.xE)\n', (3689, 3703), True, 'import numpy as np\n'), ((9427, 9444), 'numpy.zeros', 'np.zeros', (['sdogs.m'], {}), '(sdogs.m)\n', (9435, 9444), True, 'import numpy as np\n'), ((9446, 9470), 'numpy.zeros', 'np.zeros', (['n_other_eval_v'], {}), '(n_other_eval_v)\n', (9454, 9470), True, 'import numpy as np\n'), ((10289, 10311), 'numpy.zeros', 'np.zeros', (['(1, sdogs.n)'], {}), '((1, sdogs.n))\n', (10297, 10311), True, 'import numpy as np\n'), ((10324, 10369), 'numpy.zeros', 'np.zeros', (['(sdogs.m + n_other_eval_v, sdogs.n)'], {}), '((sdogs.m + n_other_eval_v, sdogs.n))\n', (10332, 10369), True, 'import numpy as np\n'), ((10451, 10474), 'numpy.zeros', 'np.zeros', (['(nL, sdogs.n)'], {}), '((nL, sdogs.n))\n', (10459, 10474), True, 'import numpy as np\n'), ((9513, 9537), 'numpy.ones', 'np.ones', (['(1 + sdogs.n + 1)'], {}), '(1 + sdogs.n + 1)\n', (9520, 9537), True, 'import numpy as np\n'), ((9558, 9581), 'numpy.ones', 'np.ones', (['n_other_eval_v'], {}), '(n_other_eval_v)\n', (9565, 9581), True, 'import numpy as np\n'), ((10428, 10449), 'numpy.ones', 'np.ones', (['(1, sdogs.n)'], {}), '((1, sdogs.n))\n', (10435, 10449), True, 'import numpy as np\n'), ((10532, 10576), 'numpy.ones', 'np.ones', (['(sdogs.m + n_other_eval_v, sdogs.n)'], {}), '((sdogs.m + n_other_eval_v, sdogs.n))\n', (10539, 10576), True, 'import numpy as np\n'), ((11228, 11245), 'numpy.zeros', 'np.zeros', (['sdogs.m'], {}), '(sdogs.m)\n', (11236, 11245), True, 'import numpy as np\n'), ((11372, 11394), 'numpy.zeros', 'np.zeros', (['(1, sdogs.n)'], {}), '((1, sdogs.n))\n', (11380, 11394), True, 'import numpy as np\n'), ((11407, 11435), 'numpy.zeros', 'np.zeros', (['(sdogs.m, sdogs.n)'], {}), '((sdogs.m, sdogs.n))\n', (11415, 11435), True, 'import numpy as np\n'), ((11517, 11540), 'numpy.zeros', 'np.zeros', (['(nL, sdogs.n)'], {}), '((nL, sdogs.n))\n', (11525, 11540), True, 'import numpy as np\n'), ((12199, 12216), 'numpy.zeros', 'np.zeros', (['sdogs.m'], {}), '(sdogs.m)\n', (12207, 12216), True, 'import numpy as np\n'), ((12336, 12368), 'numpy.zeros', 'np.zeros', (['(1 + sdogs.M, sdogs.n)'], {}), '((1 + sdogs.M, sdogs.n))\n', (12344, 12368), True, 'import numpy as np\n'), ((12370, 12391), 'numpy.ones', 'np.ones', (['(1, sdogs.n)'], {}), '((1, sdogs.n))\n', (12377, 12391), True, 'import numpy as np\n'), ((12483, 12505), 'numpy.zeros', 'np.zeros', (['(1, sdogs.n)'], {}), '((1, sdogs.n))\n', (12491, 12505), True, 'import numpy as np\n'), ((11288, 11303), 'numpy.ones', 'np.ones', (['(1 + nL)'], {}), '(1 + nL)\n', (11295, 11303), True, 'import numpy as np\n'), ((11494, 11515), 'numpy.ones', 'np.ones', (['(1, sdogs.n)'], {}), '((1, sdogs.n))\n', (11501, 11515), True, 'import numpy as np\n'), ((11546, 11573), 'numpy.ones', 'np.ones', (['(sdogs.m, sdogs.n)'], {}), '((sdogs.m, sdogs.n))\n', (11553, 11573), True, 'import numpy as np\n'), ((12450, 12481), 'numpy.ones', 'np.ones', (['(1 + sdogs.M, sdogs.n)'], {}), '((1 + sdogs.M, sdogs.n))\n', (12457, 12481), True, 'import numpy as np\n')] |
from numpy import linalg as LA
import numpy as np
MAX_SIG_VALUE = 10000000
def get_avg_gradient(gradient_list, num_of_workers):
summed_gradient = gradient_list[0]
i = 0
for gradient in gradient_list:
i += 1
if i == 1:
continue
j = 0
for gradient_part in gradient:
summed_gradient[j] = np.add(summed_gradient[j], gradient_part)
j += 1
avg_gradient = []
for gradient_part in summed_gradient:
avg_gradient.append(gradient_part / num_of_workers)
return avg_gradient
def get_gradient_diff(previous_gradient, new_gradient):
gradient_diff = []
for i in range(len(previous_gradient)):
gradient_diff.append(np.subtract(new_gradient[i], previous_gradient[i]))
return gradient_diff
def get_aggregate_gradient_update(previous_gradient, new_gradient):
gradient_diff = []
for i in range(len(previous_gradient)):
gradient_diff.append(np.subtract(new_gradient[i], previous_gradient[i]))
aggregate_sum = 0
for gradient in gradient_diff:
aggregate_sum += gradient.sum()
return aggregate_sum
def get_l2_norm_of_gradients(gradient_list):
l2_norm_list = []
for gradient in gradient_list:
raveled_gradient = np.ravel(gradient)
l2_norm_list.append(LA.norm(raveled_gradient, 2))
return LA.norm(l2_norm_list, 2)
def get_significance_value(previous_gradient, new_gradient):
aggregate_update = get_aggregate_gradient_update(previous_gradient, new_gradient)
print("Aggregate update: " + str(aggregate_update))
previous_gradient_value = 0
for gradient in previous_gradient:
previous_gradient_value += gradient.sum()
print("Previous gradient value: " + str(previous_gradient_value))
return abs(aggregate_update / previous_gradient_value)
def get_significance_value_2(previous_gradient, new_gradient):
gradient_diff = get_gradient_diff(previous_gradient, new_gradient)
gradient_diff_value = get_l2_norm_of_gradients(gradient_diff)
previous_gradient_value = get_l2_norm_of_gradients(previous_gradient)
if previous_gradient_value <= 0:
return MAX_SIG_VALUE
else:
return abs(gradient_diff_value / previous_gradient_value)
def get_significance_value_3(current_gradient, updated_gradient, summed_gradient, grad_counter):
current_gradient = get_sum_of_two_gradients(current_gradient, summed_gradient)
updated_gradient = get_sum_of_two_gradients(updated_gradient, summed_gradient)
current_avg_gradient = divide_gradient_by_constant(current_gradient, grad_counter + 1)
updated_gradient_val = get_l2_norm_of_gradients(updated_gradient)
current_avg_gradient_value = get_l2_norm_of_gradients(current_avg_gradient)
print(current_avg_gradient_value)
# current_avg_gradient = get_sum_of_two_gradients(current_avg_gradient, summed_gradient)
if current_avg_gradient_value <= 0:
return MAX_SIG_VALUE, updated_gradient, current_gradient
else:
return abs(updated_gradient_val / current_avg_gradient_value), updated_gradient, current_gradient
def get_significance_value_4(avg_gradient, updated_gradient):
# current_gradient = get_sum_of_two_gradients(current_gradient, summed_gradient)
updated_gradient = get_sum_of_two_gradients(updated_gradient, avg_gradient)
# current_avg_gradient = divide_gradient_by_constant(current_gradient, grad_counter+1)
updated_gradient_val = get_l2_norm_of_gradients(updated_gradient)
current_avg_gradient_value = get_l2_norm_of_gradients(avg_gradient)
# current_avg_gradient = get_sum_of_two_gradients(current_avg_gradient, summed_gradient)
if current_avg_gradient_value <= 0:
return MAX_SIG_VALUE, updated_gradient
else:
return abs(updated_gradient_val / current_avg_gradient_value), updated_gradient
def get_initial_threshold(initial_gradient):
l2_norm_list = []
linf_norm_list = []
for gradient in initial_gradient:
raveled_gradient = np.ravel(gradient)
l2_norm_list.append(LA.norm(raveled_gradient, 2))
linf_norm_list.append(LA.norm(raveled_gradient, np.inf))
initial_threshold = LA.norm(l2_norm_list, 2) / LA.norm(linf_norm_list, np.inf)
return initial_threshold
def get_new_threshold(loss_list, worker_count, lr_change, previous_threshold):
avg_loss = 0
for loss in loss_list:
avg_loss = avg_loss + loss
avg_loss = avg_loss / worker_count
# print("Momentum correction")
# print(avg_loss)
# return lr_change * avg_loss * previous_threshold
return previous_threshold * 0.9
def get_new_threshold_2(momentum_correction, lr_change, previous_threshold):
return lr_change * momentum_correction * previous_threshold
def get_gradient_difference(new_gradient, previous_gradient):
gradient_diff = []
for i in range(len(previous_gradient)):
gradient_diff.append(np.subtract(new_gradient[i], previous_gradient[i]))
l2_norm_diff = get_l2_norm_of_gradients(gradient_diff)
print(l2_norm_diff)
if l2_norm_diff > 0:
return True, gradient_diff
else:
return False, None
def get_momentum_correction(gradient_list, num_of_workers, batch_size):
summed_gradient = get_gradient_summation(gradient_list)
for i in range(len(summed_gradient)):
summed_gradient[i] = summed_gradient[i] / (num_of_workers * batch_size)
l2_norm = get_l2_norm_of_gradients(summed_gradient) / batch_size
return l2_norm
def get_momentum_correction_2(summed_gradient, batch_size):
thresh = []
print(len(summed_gradient))
for i in range(len(summed_gradient)):
raveled_gradient = np.ravel(summed_gradient[i])
ind = np.argpartition(raveled_gradient, -4, axis=None)[-4:]
thresh.append(np.amin(raveled_gradient[ind]))
# summed_gradient[i] = summed_gradient[i] / batch_size
l2_norm = LA.norm(thresh, 2)
return l2_norm / batch_size
def get_gradient_summation(gradient_list):
summed_gradient = gradient_list[0]
i = 0
for gradient in gradient_list:
i += 1
if i == 1:
continue
j = 0
for gradient_part in gradient:
summed_gradient[j] = np.add(summed_gradient[j], gradient_part)
j += 1
return summed_gradient
def get_max_gradients(gradient_list):
max_gradient = gradient_list[0]
max_grad_value = get_l2_norm_of_gradients(max_gradient)
for i in range(len(gradient_list)):
if i == 0:
continue
new_grad_val = get_l2_norm_of_gradients(gradient_list[i])
if new_grad_val > max_grad_value:
max_gradient = gradient_list[i]
max_grad_value = new_grad_val
return max_gradient, max_grad_value
def get_sum_of_two_gradients(gradient_1, gradient_2):
for i in range(len(gradient_1)):
gradient_1[i] = np.add(gradient_1[i], gradient_2[i])
return gradient_1
def divide_gradient_by_constant(gradient, constant):
for i in range(len(gradient)):
gradient[i] = gradient[i] / constant
return gradient
# b = np.arange(9).reshape((3, 3))
# added_list = [a, b]
# g_list = [added_list, added_list]
# # print(get_avg_gradient(g_list, 2))
# new_a = np.arange(2, 20).reshape((3, 3, 2))
# new_b = np.arange(2, 11).reshape((3, 3))
# new_list = [new_a, new_b]
# # print(get_aggregate_gradient_update(added_list, new_list))
# # print(get_significance_value(added_list, new_list))
# print(get_initial_threshold(added_list))
| [
"numpy.subtract",
"numpy.amin",
"numpy.ravel",
"numpy.argpartition",
"numpy.linalg.norm",
"numpy.add"
] | [((1359, 1383), 'numpy.linalg.norm', 'LA.norm', (['l2_norm_list', '(2)'], {}), '(l2_norm_list, 2)\n', (1366, 1383), True, 'from numpy import linalg as LA\n'), ((5902, 5920), 'numpy.linalg.norm', 'LA.norm', (['thresh', '(2)'], {}), '(thresh, 2)\n', (5909, 5920), True, 'from numpy import linalg as LA\n'), ((1270, 1288), 'numpy.ravel', 'np.ravel', (['gradient'], {}), '(gradient)\n', (1278, 1288), True, 'import numpy as np\n'), ((4013, 4031), 'numpy.ravel', 'np.ravel', (['gradient'], {}), '(gradient)\n', (4021, 4031), True, 'import numpy as np\n'), ((4180, 4204), 'numpy.linalg.norm', 'LA.norm', (['l2_norm_list', '(2)'], {}), '(l2_norm_list, 2)\n', (4187, 4204), True, 'from numpy import linalg as LA\n'), ((4207, 4238), 'numpy.linalg.norm', 'LA.norm', (['linf_norm_list', 'np.inf'], {}), '(linf_norm_list, np.inf)\n', (4214, 4238), True, 'from numpy import linalg as LA\n'), ((5674, 5702), 'numpy.ravel', 'np.ravel', (['summed_gradient[i]'], {}), '(summed_gradient[i])\n', (5682, 5702), True, 'import numpy as np\n'), ((6878, 6914), 'numpy.add', 'np.add', (['gradient_1[i]', 'gradient_2[i]'], {}), '(gradient_1[i], gradient_2[i])\n', (6884, 6914), True, 'import numpy as np\n'), ((356, 397), 'numpy.add', 'np.add', (['summed_gradient[j]', 'gradient_part'], {}), '(summed_gradient[j], gradient_part)\n', (362, 397), True, 'import numpy as np\n'), ((720, 770), 'numpy.subtract', 'np.subtract', (['new_gradient[i]', 'previous_gradient[i]'], {}), '(new_gradient[i], previous_gradient[i])\n', (731, 770), True, 'import numpy as np\n'), ((964, 1014), 'numpy.subtract', 'np.subtract', (['new_gradient[i]', 'previous_gradient[i]'], {}), '(new_gradient[i], previous_gradient[i])\n', (975, 1014), True, 'import numpy as np\n'), ((1317, 1345), 'numpy.linalg.norm', 'LA.norm', (['raveled_gradient', '(2)'], {}), '(raveled_gradient, 2)\n', (1324, 1345), True, 'from numpy import linalg as LA\n'), ((4060, 4088), 'numpy.linalg.norm', 'LA.norm', (['raveled_gradient', '(2)'], {}), '(raveled_gradient, 2)\n', (4067, 4088), True, 'from numpy import linalg as LA\n'), ((4120, 4153), 'numpy.linalg.norm', 'LA.norm', (['raveled_gradient', 'np.inf'], {}), '(raveled_gradient, np.inf)\n', (4127, 4153), True, 'from numpy import linalg as LA\n'), ((4918, 4968), 'numpy.subtract', 'np.subtract', (['new_gradient[i]', 'previous_gradient[i]'], {}), '(new_gradient[i], previous_gradient[i])\n', (4929, 4968), True, 'import numpy as np\n'), ((5717, 5765), 'numpy.argpartition', 'np.argpartition', (['raveled_gradient', '(-4)'], {'axis': 'None'}), '(raveled_gradient, -4, axis=None)\n', (5732, 5765), True, 'import numpy as np\n'), ((5793, 5823), 'numpy.amin', 'np.amin', (['raveled_gradient[ind]'], {}), '(raveled_gradient[ind])\n', (5800, 5823), True, 'import numpy as np\n'), ((6223, 6264), 'numpy.add', 'np.add', (['summed_gradient[j]', 'gradient_part'], {}), '(summed_gradient[j], gradient_part)\n', (6229, 6264), True, 'import numpy as np\n')] |
import os
import json
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
import torch.nn.functional as F
def get_task(data_path='data', subset='train', index=0, print_path=False):
"""
gets a task for the needed subset
:subset: subset of the task train/eval/test
:index: parameter for returning the tasks of a given index
:print_path: if set = True prints the path of the subtask
:returns: the dictionary of the subtask
"""
data_path = Path(data_path)
training_path = data_path / 'training'
evaluation_path = data_path / 'evaluation'
test_path = data_path / 'test'
training_tasks = sorted(os.listdir(training_path))
evaluation_tasks = sorted(os.listdir(evaluation_path))
test_tasks = sorted(os.listdir(test_path))
if subset == 'train':
task_file = str(training_path / training_tasks[index])
elif subset == 'eval':
task_file = str(evaluation_path / evaluation_tasks[index])
else:
task_file = str(test_path / test_tasks[index])
with open(task_file, 'r') as f:
task = json.load(f)
if print_path == True:
print(task_file)
return task
def plot_task(task):
"""
plots the training samples for train and test tasks
:task: task which is wanted to plot
"""
cmap = colors.ListedColormap(
['#000000', '#0074D9','#FF4136','#2ECC40','#FFDC00',
'#AAAAAA', '#F012BE', '#FF851B', '#7FDBFF', '#870C25'])
norm = colors.Normalize(vmin=0, vmax=9)
n = len(task["train"]) + len(task["test"])
fig, axs = plt.subplots(2, n, figsize=(4*n,8), dpi=50)
plt.subplots_adjust(wspace=0, hspace=0)
fig_num = 0
for i, t in enumerate(task["train"]):
t_in, t_out = np.array(t["input"]), np.array(t["output"])
axs[0][fig_num].imshow(t_in, cmap=cmap, norm=norm)
axs[0][fig_num].set_title(f'Train-{i} in')
axs[1][fig_num].imshow(t_out, cmap=cmap, norm=norm)
axs[1][fig_num].set_title(f'Train-{i} out')
fig_num += 1
for i, t in enumerate(task["test"]):
t_in, t_out = np.array(t["input"]), np.array(t.get('output', [[0,0],[0,0]]))
axs[0][fig_num].imshow(t_in, cmap=cmap, norm=norm)
axs[0][fig_num].set_title(f'Test-{i} in')
axs[1][fig_num].imshow(t_out, cmap=cmap, norm=norm)
axs[1][fig_num].set_title(f'Test-{i} out')
fig_num += 1
plt.tight_layout()
plt.show()
def check_dim(data_path, dataset='train'):
"""
checks the dimensions of the tasks
:dataset: type of dataset to check the dimension of
:returns: dictionary of the tasks and the length of the different subtypes of tasks
"""
type_1 = []
type_1_1 = []
type_1_2 = []
type_1_3 = []
type_1_4 = []
type_2 = []
type_2_1 = []
type_2_2 = []
type_2_3 = []
leng = 400
if dataset == 'test':
leng=100
for t in range(0, leng):
task = get_task(data_path, dataset, t)
inp = []
out = []
for i in task['train']:
inp.append(np.array(i['input']).shape)
out.append(np.array(i['output']).shape)
if all(x == inp[0] for x in inp):
type_1.append(t)
if all(x == inp[0] for x in out):
type_1_1.append(t)
else:
if all(x == out[0] for x in out):
if (out[0][0]*out[0][1])<(inp[0][0]*inp[0][1]):
type_1_2.append(t)
else:
type_1_3.append(t)
else:
type_1_4.append(t)
else:
type_2.append(t)
if all(inp[x] == out[x] for x in [0,1]):
type_2_1.append(t)
else:
if (out[0][0]*out[0][1])<(inp[0][0]*inp[0][1]):
type_2_2.append(t)
else:
type_2_3.append(t)
return {'t1':type_1,'t1_1':type_1_1,'t1_2':type_1_2,'t1_3':type_1_3,'t1_4':type_1_4,
't2':type_2, 't2_1':type_2_1,'t2_2':type_2_2,'t2_3':type_2_3}
def dimension_explained(data_path, dataset = 'train'):
"""
prints the various types of tasks and their caracteristics
:dataset: type of dataset to show the caracteristics of
"""
print('------------', dataset, ' shapes ------------')
dic = check_dim(data_path, dataset)
print('t1 all inputs are equal: ', len(dic['t1']), 'of which: ')
print('t1_1 also output equal: ', len(dic['t1_1']))
print('t1_2 output smaller but fixed: ', len(dic['t1_2']))
print('t1_3 output bigger but fixed: ', len(dic['t1_3']))
print('t1_4 output size depends on input: ', len(dic['t1_4']))
print('t2 input different: ', len(dic['t2']), 'of which: ')
print('t2_1 output equal to input: ', len(dic['t2_1']))
print('t2_2 output smaller: ', len(dic['t2_2']))
print('t2_3 output bigger: ', len(dic['t2_3']))
def pad_crop(x, desired_w, desired_h, current_w, current_h, goal):
"""
pads or crops array into desired shape
:x: array to reshape
:desired_w: desired width
:desired_h: desired height
:current_w: width of array to reshape
:current_h: height of array to reshape
:goal: if set to 'pad' pads the array, if set to 'crop' crops the array
:returns: padded or cropped array
"""
diff_w = np.abs(desired_w-current_w)
if diff_w % 2 == 0:
if goal == 'pad':
x = F.pad(x, (0, 0, int(diff_w/2), int(diff_w/2)), mode='constant', value=0)
elif goal == 'crop':
if -int(diff_w/2) == 0:
x = x[:, :, int(diff_w/2):, :]
else:
x = x[:, :, int(diff_w/2):-int(diff_w/2), :]
else:
pass
else:
if goal == 'pad':
x = F.pad(x, (0, 0, int(diff_w/2)+1, int(diff_w/2)), mode='constant', value=0)
elif goal == 'crop':
if -int(diff_w/2) == 0:
x = x[:, :, int(diff_w/2)+1:, :]
else:
x = x[:, :, int(diff_w/2)+1:-int(diff_w/2), :]
else:
pass
diff_h = np.abs(desired_h-current_h)
if diff_h % 2 == 0:
if goal == 'pad':
x = F.pad(x, (int(diff_h/2), int(diff_h/2), 0, 0), mode='constant', value=0)
elif goal == 'crop':
if (-int(diff_h/2)) == 0:
x = x[:, :, :, int(diff_h/2):]
else:
x = x[:, :, :, int(diff_h/2):-int(diff_h/2)]
else:
pass
else:
if goal == 'pad':
x = F.pad(x, (int(diff_h/2)+1, int(diff_h/2), 0, 0), mode='constant', value=0)
elif goal == 'crop':
if (-int(diff_h/2)) == 0:
x = x[:, :, :, int(diff_h/2)+1:]
else:
x = x[:, :, :, int(diff_h/2)+1:-int(diff_h/2)]
else:
pass
return x
def expand(x):
"""
expands an array to 10 channels (one for each color)
:x: array to expand
:returns: expanded array
"""
img = np.array([np.zeros((x.shape[0], x.shape[1]))+i for i in range(10)])
img = (x-img == 0)*1
return img
| [
"os.listdir",
"matplotlib.pyplot.tight_layout",
"json.load",
"matplotlib.pyplot.show",
"numpy.abs",
"matplotlib.colors.Normalize",
"numpy.zeros",
"pathlib.Path",
"numpy.array",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.subplots",
"matplotlib.colors.ListedColormap"
] | [((527, 542), 'pathlib.Path', 'Path', (['data_path'], {}), '(data_path)\n', (531, 542), False, 'from pathlib import Path\n'), ((1361, 1498), 'matplotlib.colors.ListedColormap', 'colors.ListedColormap', (["['#000000', '#0074D9', '#FF4136', '#2ECC40', '#FFDC00', '#AAAAAA',\n '#F012BE', '#FF851B', '#7FDBFF', '#870C25']"], {}), "(['#000000', '#0074D9', '#FF4136', '#2ECC40',\n '#FFDC00', '#AAAAAA', '#F012BE', '#FF851B', '#7FDBFF', '#870C25'])\n", (1382, 1498), False, 'from matplotlib import colors\n'), ((1513, 1545), 'matplotlib.colors.Normalize', 'colors.Normalize', ([], {'vmin': '(0)', 'vmax': '(9)'}), '(vmin=0, vmax=9)\n', (1529, 1545), False, 'from matplotlib import colors\n'), ((1609, 1655), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', 'n'], {'figsize': '(4 * n, 8)', 'dpi': '(50)'}), '(2, n, figsize=(4 * n, 8), dpi=50)\n', (1621, 1655), True, 'import matplotlib.pyplot as plt\n'), ((1657, 1696), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0)', 'hspace': '(0)'}), '(wspace=0, hspace=0)\n', (1676, 1696), True, 'import matplotlib.pyplot as plt\n'), ((2438, 2456), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2454, 2456), True, 'import matplotlib.pyplot as plt\n'), ((2461, 2471), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2469, 2471), True, 'import matplotlib.pyplot as plt\n'), ((5394, 5423), 'numpy.abs', 'np.abs', (['(desired_w - current_w)'], {}), '(desired_w - current_w)\n', (5400, 5423), True, 'import numpy as np\n'), ((6150, 6179), 'numpy.abs', 'np.abs', (['(desired_h - current_h)'], {}), '(desired_h - current_h)\n', (6156, 6179), True, 'import numpy as np\n'), ((697, 722), 'os.listdir', 'os.listdir', (['training_path'], {}), '(training_path)\n', (707, 722), False, 'import os\n'), ((754, 781), 'os.listdir', 'os.listdir', (['evaluation_path'], {}), '(evaluation_path)\n', (764, 781), False, 'import os\n'), ((807, 828), 'os.listdir', 'os.listdir', (['test_path'], {}), '(test_path)\n', (817, 828), False, 'import os\n'), ((1130, 1142), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1139, 1142), False, 'import json\n'), ((1778, 1798), 'numpy.array', 'np.array', (["t['input']"], {}), "(t['input'])\n", (1786, 1798), True, 'import numpy as np\n'), ((1800, 1821), 'numpy.array', 'np.array', (["t['output']"], {}), "(t['output'])\n", (1808, 1821), True, 'import numpy as np\n'), ((2129, 2149), 'numpy.array', 'np.array', (["t['input']"], {}), "(t['input'])\n", (2137, 2149), True, 'import numpy as np\n'), ((7075, 7109), 'numpy.zeros', 'np.zeros', (['(x.shape[0], x.shape[1])'], {}), '((x.shape[0], x.shape[1]))\n', (7083, 7109), True, 'import numpy as np\n'), ((3102, 3122), 'numpy.array', 'np.array', (["i['input']"], {}), "(i['input'])\n", (3110, 3122), True, 'import numpy as np\n'), ((3153, 3174), 'numpy.array', 'np.array', (["i['output']"], {}), "(i['output'])\n", (3161, 3174), True, 'import numpy as np\n')] |
'''
Parameter comparison (photometric v. kinematic)
'''
################################################################################
# Import modules
#-------------------------------------------------------------------------------
from astropy.table import Table
import numpy as np
import matplotlib.pyplot as plt
################################################################################
################################################################################
# Read in data
#-------------------------------------------------------------------------------
data_directory = ''
data_filename = 'Pipe3D-master_file_vflag_BB_minimize_chi10_smooth2p27_mapFit_N2O2_HIdr2_noWords_v5.txt'
data = Table.read(data_directory + data_filename,
format='ascii.commented_header')
################################################################################
################################################################################
# Parameter to plot
#-------------------------------------------------------------------------------
param = 'ba'
if param == 'phi':
photo_param = 'NSA_phi'
kinem_param = 'phi_map'
kinem_param_err = 'phi_err_map'
param_min = 0
param_max = 180
x_label = 'photometric position angle [$^\circ$]'
y_label = 'kinematic position angle [$^\circ$]'
elif param == 'ba':
photo_param = 'NSA_ba'
kinem_param = 'ba_map'
kinem_param_err = 'ba_err_map'
param_min = 0
param_max = 1
x_label = 'photometric axis ratio'
y_label = 'kinematic axis ratio'
################################################################################
################################################################################
# Sample criteria
#-------------------------------------------------------------------------------
bad_boolean = np.logical_or.reduce([data['M90_map'] == -99,
data['M90_disk_map'] == -99,
data['alpha_map'] > 99,
data['ba_map'] > 0.998])
sample = data[~bad_boolean]
################################################################################
################################################################################
# Separate galaxies by their CMD classification
#-------------------------------------------------------------------------------
# Green valley
gboolarray = sample['CMD_class'] == 2
# Blue cloud
bboolarray = sample['CMD_class'] == 1
# Red sequence
rboolarray = sample['CMD_class'] == 3
GVdata = sample[gboolarray]
Bdata = sample[bboolarray]
Rdata = sample[rboolarray]
################################################################################
################################################################################
# Plot parameter (photometric v. kinematic)
#-------------------------------------------------------------------------------
plt.figure()
plt.errorbar(Rdata[photo_param],
Rdata[kinem_param],
#yerr=Rdata[kinem_param_err],
fmt='r.',
fillstyle='none',
label='Red sequence')
plt.errorbar(Bdata[photo_param],
Bdata[kinem_param],
#yerr=Bdata[kinem_param_err],
fmt='b+',
label='Blue cloud')
plt.errorbar(GVdata[photo_param],
GVdata[kinem_param],
#yerr=GVdata[kinem_param_err],
fmt='g*',
label='Green valley')
plt.plot([param_min,param_max], [param_min,param_max], 'k', zorder=2.5)
if param == 'phi':
plt.plot([param_min,param_max], [param_max,2*param_max], 'k', zorder=2.6)
if param == 'ba':
plt.ylim([-0.1,1.1])
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.legend()
plt.tight_layout()
#plt.show()
plt.savefig(data_directory + 'Images/' + param + '_comp_v5.eps',
format='eps',
dpi=300)
################################################################################
| [
"astropy.table.Table.read",
"matplotlib.pyplot.savefig",
"numpy.logical_or.reduce",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.tight_layout",
"matplotlib.py... | [((718, 793), 'astropy.table.Table.read', 'Table.read', (['(data_directory + data_filename)'], {'format': '"""ascii.commented_header"""'}), "(data_directory + data_filename, format='ascii.commented_header')\n", (728, 793), False, 'from astropy.table import Table\n'), ((1854, 1982), 'numpy.logical_or.reduce', 'np.logical_or.reduce', (["[data['M90_map'] == -99, data['M90_disk_map'] == -99, data['alpha_map'] > \n 99, data['ba_map'] > 0.998]"], {}), "([data['M90_map'] == -99, data['M90_disk_map'] == -99, \n data['alpha_map'] > 99, data['ba_map'] > 0.998])\n", (1874, 1982), True, 'import numpy as np\n'), ((2946, 2958), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2956, 2958), True, 'import matplotlib.pyplot as plt\n'), ((2960, 3067), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['Rdata[photo_param]', 'Rdata[kinem_param]'], {'fmt': '"""r."""', 'fillstyle': '"""none"""', 'label': '"""Red sequence"""'}), "(Rdata[photo_param], Rdata[kinem_param], fmt='r.', fillstyle=\n 'none', label='Red sequence')\n", (2972, 3067), True, 'import matplotlib.pyplot as plt\n'), ((3164, 3251), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['Bdata[photo_param]', 'Bdata[kinem_param]'], {'fmt': '"""b+"""', 'label': '"""Blue cloud"""'}), "(Bdata[photo_param], Bdata[kinem_param], fmt='b+', label=\n 'Blue cloud')\n", (3176, 3251), True, 'import matplotlib.pyplot as plt\n'), ((3334, 3425), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['GVdata[photo_param]', 'GVdata[kinem_param]'], {'fmt': '"""g*"""', 'label': '"""Green valley"""'}), "(GVdata[photo_param], GVdata[kinem_param], fmt='g*', label=\n 'Green valley')\n", (3346, 3425), True, 'import matplotlib.pyplot as plt\n'), ((3509, 3582), 'matplotlib.pyplot.plot', 'plt.plot', (['[param_min, param_max]', '[param_min, param_max]', '"""k"""'], {'zorder': '(2.5)'}), "([param_min, param_max], [param_min, param_max], 'k', zorder=2.5)\n", (3517, 3582), True, 'import matplotlib.pyplot as plt\n'), ((3723, 3742), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['x_label'], {}), '(x_label)\n', (3733, 3742), True, 'import matplotlib.pyplot as plt\n'), ((3743, 3762), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['y_label'], {}), '(y_label)\n', (3753, 3762), True, 'import matplotlib.pyplot as plt\n'), ((3764, 3776), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (3774, 3776), True, 'import matplotlib.pyplot as plt\n'), ((3778, 3796), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3794, 3796), True, 'import matplotlib.pyplot as plt\n'), ((3810, 3902), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(data_directory + 'Images/' + param + '_comp_v5.eps')"], {'format': '"""eps"""', 'dpi': '(300)'}), "(data_directory + 'Images/' + param + '_comp_v5.eps', format=\n 'eps', dpi=300)\n", (3821, 3902), True, 'import matplotlib.pyplot as plt\n'), ((3604, 3681), 'matplotlib.pyplot.plot', 'plt.plot', (['[param_min, param_max]', '[param_max, 2 * param_max]', '"""k"""'], {'zorder': '(2.6)'}), "([param_min, param_max], [param_max, 2 * param_max], 'k', zorder=2.6)\n", (3612, 3681), True, 'import matplotlib.pyplot as plt\n'), ((3701, 3722), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[-0.1, 1.1]'], {}), '([-0.1, 1.1])\n', (3709, 3722), True, 'import matplotlib.pyplot as plt\n')] |
# -*- coding: utf-8 -*-
import pandas as pd
import sqlite3 as lite
import numpy as np
import ee
import os
from treecover.sentinel import stmt, date_ranges, funs, val_cols, gen_fetch_stmt_and_headers, fetch_and_write_sqlite
"""
The methods in this file are not used anymore. compute_features is used in a similar manner in sentinel.py.
"""
bastin_db = pd.read_csv('data/bastin_db_cleaned.csv')
db_folder = 'data/sentinel/'
lib_extension_path = './libsqlitefunctions.so'
def compute_features(t_start, t_end, part=None):
"""
Computes min, max, mean, std, lower& upper quartile for the median values of the retrieved band values and the NDVI
within the passed timeframe (as datestring 'YYYY-MM-DD'). Note that data is only available from ~2018-12-15 to
2019-08-31. Currently used to extract the seasons within that timeframe.
"""
region_to_bounds = {}
err_rows = []
all_regs = pd.unique(bastin_db.dryland_assessment_region)
for region in all_regs:
filtered = bastin_db[bastin_db["dryland_assessment_region"] == region]
region_to_bounds[region] = (filtered.index.min(), filtered.index.max() + 1)
fetch_stmt, new_cols = gen_fetch_stmt_and_headers()
if part is not None:
new_cols = [f"{c}_{part}" for c in new_cols]
reg_abbr = []
ret_df = bastin_db.reindex(bastin_db.columns.tolist() + new_cols,axis='columns', copy=True)
ret_df.drop(columns=bastin_db.columns, inplace=True)
for reg in all_regs:
reg_abbr.append(''.join(x for x in reg if x.isupper()))
idx_start = region_to_bounds[reg][0]
idx_end = region_to_bounds[reg][1]
with lite.connect(db_folder + reg + '.db') as con:
con.enable_load_extension(True)
con.load_extension(lib_extension_path)
print(f'Computing features for {reg} from {t_start} to {t_end}')
try:
# will any be invalid if I just join by date? -> no, luckily never happens for this set.
# inv_ids = con.execute("select distinct(id) from sentinel where strftime('%H:%M', time, 'unixepoch') in('23:59','00:00')").fetchall()
# if len(inv_ids) > 0:
# raise(f'WARN: need to re-run again for ids around midnight: {inv_ids}')
curr_stmt = fetch_stmt.replace('?', str(tuple(range(idx_start, idx_end))), 1)
data_rows = con.execute(curr_stmt, (t_start, t_end)).fetchall()
data_df = pd.DataFrame(data_rows).set_index([0],drop=True).round(5)
ret_df.loc[data_df.index, new_cols] = data_df.to_numpy()
except Exception as e:
print(reg, e)
err_rows.append(reg)
print(f'Completed feature extraction from {t_start} to {t_end}')
if len(err_rows) > 0:
print('Had errors for regions: ', err_rows)
return ret_df
def run(area='NorternAfrica'):
ee.Initialize()
start = "2017-06-01" # only available since 2018-12...
end = "2019-08-31"
regions = [
"Australia",
"CentralAsia",
"EastSouthAmerica",
"Europe",
"HornAfrica",
"MiddleEast",
"NorthAmerica",
"NorthernAfrica",
"Sahel",
"SouthernAfrica",
"SouthWestAsia",
"WestSouthAmerica",
]
region_to_batch = {}
bastin_df = pd.read_csv("data/bastin_db_cleaned.csv",
usecols=["longitude", "latitude", "dryland_assessment_region"])
for region in regions:
filtered = bastin_df[bastin_df["dryland_assessment_region"] == region]
region_to_batch[region] = (filtered.index.min(), filtered.index.max() + 1)
bastin_df.drop("dryland_assessment_region", axis=1, inplace=True)
i = region_to_batch[area][0]
f_name = f"data/sentinel/{area}.db"
db_exists = os.path.isfile(f_name)
with lite.connect(f_name) as con:
if db_exists:
last_id = con.execute('SELECT MAX(id) FROM sentinel').fetchone()[0]
if last_id is not None:
i = last_id + 1
else:
con.execute(stmt)
print('starting at index ', i)
fetch_and_write_sqlite(con, bastin_df, start, end, i=i, i_max=region_to_batch[area][1])
def compute_three_seasons_features():
"""
computes the features from the raw postgres data and saves them. The columns are named as the query function,
but with a _0, _1, _2 appended.
"""
all_cols = []
all_dfs = []
for i, date_range in enumerate(date_ranges):
date_df = compute_features(date_range[0], date_range[1], i)
all_cols += date_df.columns.to_list()
all_dfs.append(date_df)
bastin_extended = bastin_db.reindex(bastin_db.columns.tolist() + all_cols,axis='columns', copy=True)
for date_df in all_dfs:
bastin_extended[date_df.columns] = date_df.to_numpy()
bastin_extended.to_parquet(db_folder + f'features_three_months_full.parquet')
# todo: scale them all -> but better do that in the train method.
def enhance_three_seasons_features():
""" using the importances from the boosted tree: exclude useless features, calculated some differences. """
orig_df = pd.read_parquet('data/features_three_months_full.parquet')
# these were not so useful
drop_avg_q = [c for c in orig_df.columns if ('quartile' in c or 'avg' in c) and not any(b in c for b in ('B12', 'B4', 'NDVI'))]
drop_bands = [c for c in orig_df.columns if any(b in c for b in ('veg_pc', 'B7', 'B8', 'B11', 'B6'))]
improved_df = orig_df[orig_df.columns.symmetric_difference(drop_avg_q+drop_bands)]
improved_df = pd.read_parquet('data/features_three_months_improved.parquet')
# for the most useful bands, add global diff
for b in ('B1', 'B2', 'B12', 'B4', 'NDVI', 'B3'):
for f in funs:
if b in ('B1', 'B2', 'B3') and f in ('lower_quartile', 'upper_quartile', 'avg'):
continue
row_names = [f'{f}({b}_m)_{i}' for i in range(3)]
improved_df.loc[:,f'diff_{f}({b})'] = improved_df.apply(lambda row: np.abs(np.max(row[row_names])-np.min(row[row_names])), axis=1)
improved_df.to_parquet('data/features_three_months_improved.parquet')
def compute_monthly_features():
"""
exports the vegetation index & band 1,5,9,12 - based features. Saves them both by month for the LSTM and aggregated
for the GBR (min, max, median) in the hope it would pick up changes over the year from that.
"""
bastin_db = pd.read_csv('data/bastin_db_cleaned.csv')
region_to_bounds = {}
calc_all = True
err_rows = []
all_regs = pd.unique(bastin_db.dryland_assessment_region)
for region in all_regs:
filtered = bastin_db[bastin_db["dryland_assessment_region"] == region]
region_to_bounds[region] = (filtered.index.min(), filtered.index.max() + 1)
fetch_stmt, new_cols = gen_temporal_fetch_stmt_and_headers(calc_all)
min_cols = [f'{col}_MIN' for col in new_cols]
max_cols = [f'{col}_MAX' for col in new_cols]
med_cols = [f'{col}_MED' for col in new_cols]
gbr_cols = min_cols + max_cols + med_cols
ret_df = bastin_db.reindex(bastin_db.columns.tolist() + gbr_cols,axis='columns', copy=True)
full_data = None
for reg in all_regs:
idx_start = region_to_bounds[reg][0]
idx_end = region_to_bounds[reg][1]
with lite.connect(db_folder + reg + '.db') as con:
con.enable_load_extension(True)
con.load_extension(lib_extension_path)
print(f'Computing features for {reg}')
try:
# will any be invalid if I just join by date? -> no, luckily never happens for this set.
# inv_ids = con.execute("select distinct(id) from sentinel where strftime('%H:%M', time, 'unixepoch') in('23:59','00:00')").fetchall()
# if len(inv_ids) > 0:
# raise(f'WARN: need to re-run again for ids around midnight: {inv_ids}')
curr_stmt = fetch_stmt.replace('?', str(tuple(range(idx_start, idx_end))), 1)
data_rows = con.execute(curr_stmt).fetchall()
data_df = pd.DataFrame(data_rows).set_index([0],drop=True).round(5)
data_df.columns = ['year_month'] + new_cols
# extract min, max, median from the fetched data, leaving out the first column (year_month)
grouped = data_df.iloc[:,1:].groupby([0]) # id
uniq_idx = pd.unique(data_df.index) # .id
ret_df.loc[uniq_idx, min_cols] = grouped.min().to_numpy()
ret_df.loc[uniq_idx, max_cols] = grouped.max().to_numpy()
ret_df.loc[uniq_idx, med_cols] = grouped.median().to_numpy()
data_df['id'] = data_df.index
if full_data is None:
full_data = data_df
else:
full_data = full_data.append(data_df, ignore_index=True)
except Exception as e:
print(reg, e)
err_rows.append(reg)
if len(err_rows) > 0:
print('Had errors for regions: ', err_rows)
ret_df.to_parquet('data/vegetation_index_features_aggregated_all.parquet', index=True)
full_data.to_parquet('data/vegetation_index_features_full_all.parquet', index=False)
print(f'Completed feature extraction.')
def gen_temporal_fetch_stmt_and_headers(use_all = False):
""" fetches the statistics over the image region based on the monthly medians + the calculated indices """
# blue: B2, green: B3, red: B4, NIR: B8
stmt = "select id, year_month"
headers = []
cols = val_cols if use_all else ["B1", "B5", "B9", "B12"]
for band in cols + ['ENDVI', "NDVI", "GDVI", "MSAVI2", "SAVI"]:
for fun in ['min', 'max', 'avg','lower_quartile', 'upper_quartile', 'stdev']:
stmt += f', {fun}({band}_m)'
headers.append(f'{fun}({band}_m)')
stmt += " from (select "
stmt += "id, strftime('%Y-%m', time, 'unixepoch') as year_month, longitude, latitude, "
stmt += ', '.join(f'median({b}) as {b}_m' for b in cols)
stmt += ", (1.0*(median(B8)+median(B3))-2*median(B2)) / (median(B8)+median(B3)+2*median(B2)) as ENDVI_m"
stmt += ", 1.0*(median(B8)-median(B4))/(median(B8)+median(B4)) as NDVI_m "
stmt += ", 1.0*median(B8)-median(B3) as GDVI_m "
stmt += ", 0.5*((2*median(B8)+1)-sqrt( square(2*median(B8)+1)-8*(median(B8)-median(B4) ))) as MSAVI2_m"
stmt += ", 1.5*(median(B8)-median(B4))/(median(B8)+median(B4)+0.5) as SAVI_m" # L = 0.5
stmt += " from sentinel where"
stmt += " id in ? and (HAS_CLOUDFLAG = 0 and MSK_CLDPRB is null or MSK_CLDPRB <0.1 and MSK_SNWPRB < 0.1)"
stmt += " group by year_month, id, longitude, latitude) group by id, year_month"
return stmt, headers
"""
# not used -> but might be useful for learning on images.
def prepare_image_data(t_start, t_end, reg, idx_start, idx_end, full_df):
# Modifies the passed df to append the RGB and NDVI values for the 8x7 pixels, scaled to [-1,1]
import .image_reshaper as ir
from sklearn.preprocessing import MinMaxScaler
# initialise scaler manually.
ndvi_scaler = MinMaxScaler(feature_range=(0,255))
ndvi_scaler.scale_=255/2
ndvi_scaler.data_min_=-1,
ndvi_scaler.data_max=1
ndvi_scaler.min_=255/2
mode = 'interp'
params = ['nearest']
size = [8,7]
include_ndvi = True
missing = []
img_cols = ["TCI_R", "TCI_G", "TCI_B"]
stmt = "select id, longitude, latitude, " + ', '.join(f'median({b}) as {b}_m' for b in img_cols)
if include_ndvi:
stmt += ", (1.0*median(B8)-median(B5))/(median(B8)+median(B5)) as NDVI_m"
stmt += " from sentinel where "
stmt += "id in ? and (HAS_CLOUDFLAG = 0 and MSK_CLDPRB is NULL or MSK_CLDPRB <0.1 and MSK_SNWPRB < 0.1) and "
stmt += "date(time, 'unixepoch') between ? and ? group by id, longitude, latitude order by id, longitude, latitude"
with lite.connect(db_folder + reg + '.db') as con:
con.enable_load_extension(True)
con.load_extension(lib_extension_path)
print(f'Computing features for {reg} from {t_start} to {t_end}')
curr_stmt = stmt.replace('?', str(tuple(range(idx_start, idx_end))), 1)
data_rows = con.execute(curr_stmt, (t_start, t_end)).fetchall()
data_df = pd.DataFrame(data_rows).set_index([0],drop=True)
for i in pd.unique(data_df.index):
img_df = data_df.loc[i]
try:
img_df.iloc[:,-1] = ndvi_scaler.transform(img_df.iloc[:,-1].to_numpy().reshape(-1,1)).round()
img_arr = img_df.iloc[:, 2:].to_numpy(dtype=np.uint8)
dim = (pd.unique(img_df.iloc[:, 0]).size, pd.unique(img_df.iloc[:,1]).size, img_arr.shape[1])
test = img_arr.reshape(dim)
except (ValueError, pd.core.indexing.IndexingError): # or did sth else go wrong if just 1 value???
print(f'i={i}: could not reshape due to missing values because of cloud filter')
missing.append(i)
continue
# convert into 8x7 if necessary
reshaped = ir.reshape_image_array(test, mode, params, size)
img_row = ndvi_scaler.inverse_transform(reshaped.reshape(1, 8*7*4))[0]
full_df.iloc[i, 6:] = img_row
print(f'{len(missing)} images are missing due to cloud filter: {missing}')
# wet season & summer in OZ
t_start = '2018-12-01'
t_end = '2019-02-28'
def generate_RGB_ndvi_raw_data():
#generates the df with the raw band values scaled to -1, 1 for logistic regression. The columns are named according
#to the schema: {band name}_{x_index}_{y_index} where x and y start at the top left corner of the image.
bands = ["R", "G", "B", "ndvi"]
col_names = []
for lon_idx in range(8):
for lat_idx in range(7):
for band in bands:
col_names.append(f'{band}_{lon_idx}_{lat_idx}')
region_to_bounds = {}
# let's take regions during wet season for starters.
all_regs = ['Australia', 'SouthernAfrica', 'NorthernAfrica', "EastSouthAmerica", "WestSouthAmerica"]
# pd.unique(bastin_db.dryland_assessment_region)
for region in all_regs:
filtered = bastin_db[bastin_db["dryland_assessment_region"] == region]
region_to_bounds[region] = (filtered.index.min(), filtered.index.max() + 1)
ret_df = bastin_db.reindex(bastin_db.columns.tolist() + col_names,axis='columns', copy=True)
for reg in all_regs:
idx_start = region_to_bounds[reg][0]
idx_end = region_to_bounds[reg][1]
prepare_image_data(t_start, t_end, reg, idx_start, idx_end, ret_df)
ret_df.to_parquet(db_folder + f'features_WetSeason_test.parquet')
"""
| [
"pandas.DataFrame",
"treecover.sentinel.fetch_and_write_sqlite",
"pandas.read_csv",
"pandas.unique",
"os.path.isfile",
"numpy.max",
"sqlite3.connect",
"pandas.read_parquet",
"numpy.min",
"treecover.sentinel.gen_fetch_stmt_and_headers",
"ee.Initialize"
] | [((352, 393), 'pandas.read_csv', 'pd.read_csv', (['"""data/bastin_db_cleaned.csv"""'], {}), "('data/bastin_db_cleaned.csv')\n", (363, 393), True, 'import pandas as pd\n'), ((908, 954), 'pandas.unique', 'pd.unique', (['bastin_db.dryland_assessment_region'], {}), '(bastin_db.dryland_assessment_region)\n', (917, 954), True, 'import pandas as pd\n'), ((1173, 1201), 'treecover.sentinel.gen_fetch_stmt_and_headers', 'gen_fetch_stmt_and_headers', ([], {}), '()\n', (1199, 1201), False, 'from treecover.sentinel import stmt, date_ranges, funs, val_cols, gen_fetch_stmt_and_headers, fetch_and_write_sqlite\n'), ((2902, 2917), 'ee.Initialize', 'ee.Initialize', ([], {}), '()\n', (2915, 2917), False, 'import ee\n'), ((3346, 3455), 'pandas.read_csv', 'pd.read_csv', (['"""data/bastin_db_cleaned.csv"""'], {'usecols': "['longitude', 'latitude', 'dryland_assessment_region']"}), "('data/bastin_db_cleaned.csv', usecols=['longitude', 'latitude',\n 'dryland_assessment_region'])\n", (3357, 3455), True, 'import pandas as pd\n'), ((3832, 3854), 'os.path.isfile', 'os.path.isfile', (['f_name'], {}), '(f_name)\n', (3846, 3854), False, 'import os\n'), ((5195, 5253), 'pandas.read_parquet', 'pd.read_parquet', (['"""data/features_three_months_full.parquet"""'], {}), "('data/features_three_months_full.parquet')\n", (5210, 5253), True, 'import pandas as pd\n'), ((5643, 5705), 'pandas.read_parquet', 'pd.read_parquet', (['"""data/features_three_months_improved.parquet"""'], {}), "('data/features_three_months_improved.parquet')\n", (5658, 5705), True, 'import pandas as pd\n'), ((6521, 6562), 'pandas.read_csv', 'pd.read_csv', (['"""data/bastin_db_cleaned.csv"""'], {}), "('data/bastin_db_cleaned.csv')\n", (6532, 6562), True, 'import pandas as pd\n'), ((6642, 6688), 'pandas.unique', 'pd.unique', (['bastin_db.dryland_assessment_region'], {}), '(bastin_db.dryland_assessment_region)\n', (6651, 6688), True, 'import pandas as pd\n'), ((3864, 3884), 'sqlite3.connect', 'lite.connect', (['f_name'], {}), '(f_name)\n', (3876, 3884), True, 'import sqlite3 as lite\n'), ((4154, 4246), 'treecover.sentinel.fetch_and_write_sqlite', 'fetch_and_write_sqlite', (['con', 'bastin_df', 'start', 'end'], {'i': 'i', 'i_max': 'region_to_batch[area][1]'}), '(con, bastin_df, start, end, i=i, i_max=\n region_to_batch[area][1])\n', (4176, 4246), False, 'from treecover.sentinel import stmt, date_ranges, funs, val_cols, gen_fetch_stmt_and_headers, fetch_and_write_sqlite\n'), ((1641, 1678), 'sqlite3.connect', 'lite.connect', (["(db_folder + reg + '.db')"], {}), "(db_folder + reg + '.db')\n", (1653, 1678), True, 'import sqlite3 as lite\n'), ((7393, 7430), 'sqlite3.connect', 'lite.connect', (["(db_folder + reg + '.db')"], {}), "(db_folder + reg + '.db')\n", (7405, 7430), True, 'import sqlite3 as lite\n'), ((8506, 8530), 'pandas.unique', 'pd.unique', (['data_df.index'], {}), '(data_df.index)\n', (8515, 8530), True, 'import pandas as pd\n'), ((6099, 6121), 'numpy.max', 'np.max', (['row[row_names]'], {}), '(row[row_names])\n', (6105, 6121), True, 'import numpy as np\n'), ((6122, 6144), 'numpy.min', 'np.min', (['row[row_names]'], {}), '(row[row_names])\n', (6128, 6144), True, 'import numpy as np\n'), ((2465, 2488), 'pandas.DataFrame', 'pd.DataFrame', (['data_rows'], {}), '(data_rows)\n', (2477, 2488), True, 'import pandas as pd\n'), ((8173, 8196), 'pandas.DataFrame', 'pd.DataFrame', (['data_rows'], {}), '(data_rows)\n', (8185, 8196), True, 'import pandas as pd\n')] |
import sys
from caffe.io import load_image
from skimage.util import view_as_windows
import os
import numpy as np
from .kMeansFeatureExtractor import *
from .lmdbWriter import open_csv
imageDim = (512,512,3)
rfSize = 16
numPatches = 50
images = os.listdir('../data/resized/trainOriginal')
labels_dict = open_csv('../data/trainLabels.csv')
values = list(labels_dict.values())
total_numPatches = values.count(0)*40 + (values.count(1) + values.count(2) + values.count(3) + values.count(4)) * 140
patches = np.zeros((total_numPatches, rfSize*rfSize*3))
whitening = True
maxIter = 50
batchSize = 1000
j = 0
values = list(labels_dict.values())
for each in images:
if labels_dict[each.split('.')[0]] > 0:
numPatches = 140
else:
numPatches = 40
img = load_image('../data/resized/trainOriginal/' + each)
windows = view_as_windows(img, (rfSize, rfSize, 3))
r = np.random.randint(0, windows.shape[0] - windows.shape[3], (numPatches,))
c = np.random.randint(0, windows.shape[1]- windows.shape[4], (numPatches,))
for i in range(0, numPatches):
patch = np.reshape(windows[r[i],c[i],0,:], windows.shape[3]*windows.shape[4]*windows.shape[5])
patches[j,:] = patch
if j % 100 == 0:
print("Extracted {0}th patch of {1} patches totally".format(j,total_numPatches))
j += 1
numCentroids = int(np.sqrt(total_numPatches/2))
patchesMean = np.mean(patches, axis=1, dtype=np.float32, keepdims=True)
patchesVar = np.var(patches, axis=1, dtype=np.float32, keepdims=True)
offsetMatrix = 10.0 * np.ones(patchesVar.shape)
patches = (patches - patchesMean) / np.sqrt(patchesVar + offsetMatrix)
if whitening:
C = np.cov(patches, y=None, rowvar=0, ddof=1).T
M = np.mean(patches, axis=0, dtype=np.float32, keepdims=False)
W, V = np.linalg.eig(C)
P = np.dot(np.dot(V, np.diag(np.diag(np.sqrt(1./(np.diagflat(W) + 0.1))))), V.T)
patches = np.dot((patches - M), P)
estimator = KMeans(numCentroids, maxIter, batchSize)
remain = patches.shape[0] % batchSize
patches = patches[:patches.shape[0] - remain:]
init, centroids = estimator.fit(patches)
np.save('train_centroids_windowsize_{0}'.format(rfSize), centroids)
np.save('train_initialCentroids_windowsize_{0}'.format(rfSize), init)
np.save('train_mean_windowsize_{0}'.format(rfSize), M)
np.save('train_eigenvectors_windowsize_{0}'.format(rfSize), P)
| [
"caffe.io.load_image",
"numpy.diagflat",
"numpy.zeros",
"numpy.ones",
"numpy.linalg.eig",
"numpy.mean",
"numpy.random.randint",
"numpy.reshape",
"numpy.cov",
"numpy.dot",
"skimage.util.view_as_windows",
"numpy.var",
"os.listdir",
"numpy.sqrt"
] | [((258, 301), 'os.listdir', 'os.listdir', (['"""../data/resized/trainOriginal"""'], {}), "('../data/resized/trainOriginal')\n", (268, 301), False, 'import os\n'), ((522, 571), 'numpy.zeros', 'np.zeros', (['(total_numPatches, rfSize * rfSize * 3)'], {}), '((total_numPatches, rfSize * rfSize * 3))\n', (530, 571), True, 'import numpy as np\n'), ((1461, 1518), 'numpy.mean', 'np.mean', (['patches'], {'axis': '(1)', 'dtype': 'np.float32', 'keepdims': '(True)'}), '(patches, axis=1, dtype=np.float32, keepdims=True)\n', (1468, 1518), True, 'import numpy as np\n'), ((1533, 1589), 'numpy.var', 'np.var', (['patches'], {'axis': '(1)', 'dtype': 'np.float32', 'keepdims': '(True)'}), '(patches, axis=1, dtype=np.float32, keepdims=True)\n', (1539, 1589), True, 'import numpy as np\n'), ((807, 858), 'caffe.io.load_image', 'load_image', (["('../data/resized/trainOriginal/' + each)"], {}), "('../data/resized/trainOriginal/' + each)\n", (817, 858), False, 'from caffe.io import load_image\n'), ((874, 915), 'skimage.util.view_as_windows', 'view_as_windows', (['img', '(rfSize, rfSize, 3)'], {}), '(img, (rfSize, rfSize, 3))\n', (889, 915), False, 'from skimage.util import view_as_windows\n'), ((925, 997), 'numpy.random.randint', 'np.random.randint', (['(0)', '(windows.shape[0] - windows.shape[3])', '(numPatches,)'], {}), '(0, windows.shape[0] - windows.shape[3], (numPatches,))\n', (942, 997), True, 'import numpy as np\n'), ((1007, 1079), 'numpy.random.randint', 'np.random.randint', (['(0)', '(windows.shape[1] - windows.shape[4])', '(numPatches,)'], {}), '(0, windows.shape[1] - windows.shape[4], (numPatches,))\n', (1024, 1079), True, 'import numpy as np\n'), ((1415, 1444), 'numpy.sqrt', 'np.sqrt', (['(total_numPatches / 2)'], {}), '(total_numPatches / 2)\n', (1422, 1444), True, 'import numpy as np\n'), ((1613, 1638), 'numpy.ones', 'np.ones', (['patchesVar.shape'], {}), '(patchesVar.shape)\n', (1620, 1638), True, 'import numpy as np\n'), ((1676, 1710), 'numpy.sqrt', 'np.sqrt', (['(patchesVar + offsetMatrix)'], {}), '(patchesVar + offsetMatrix)\n', (1683, 1710), True, 'import numpy as np\n'), ((1790, 1848), 'numpy.mean', 'np.mean', (['patches'], {'axis': '(0)', 'dtype': 'np.float32', 'keepdims': '(False)'}), '(patches, axis=0, dtype=np.float32, keepdims=False)\n', (1797, 1848), True, 'import numpy as np\n'), ((1861, 1877), 'numpy.linalg.eig', 'np.linalg.eig', (['C'], {}), '(C)\n', (1874, 1877), True, 'import numpy as np\n'), ((1979, 2001), 'numpy.dot', 'np.dot', (['(patches - M)', 'P'], {}), '(patches - M, P)\n', (1985, 2001), True, 'import numpy as np\n'), ((1132, 1229), 'numpy.reshape', 'np.reshape', (['windows[r[i], c[i], 0, :]', '(windows.shape[3] * windows.shape[4] * windows.shape[5])'], {}), '(windows[r[i], c[i], 0, :], windows.shape[3] * windows.shape[4] *\n windows.shape[5])\n', (1142, 1229), True, 'import numpy as np\n'), ((1737, 1778), 'numpy.cov', 'np.cov', (['patches'], {'y': 'None', 'rowvar': '(0)', 'ddof': '(1)'}), '(patches, y=None, rowvar=0, ddof=1)\n', (1743, 1778), True, 'import numpy as np\n'), ((1932, 1946), 'numpy.diagflat', 'np.diagflat', (['W'], {}), '(W)\n', (1943, 1946), True, 'import numpy as np\n')] |
#!/usr/bin/env python
"""
MIT License
Copyright (c) 2020-2021 <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 multiprocessing
import yaml
from astropy import units as u
from astropy.coordinates import solar_system_ephemeris, get_body
import numpy as np
from tqdm import tqdm
from .solar_body import SolarBody
def load(spacecraft_frame, ephem="jpl", num_workers=None):
"""
Function to get the coordinates of solar bodies.
Parameters
----------
spacecraft_frame : astropy.coordinates.builtin_frames.gcrs.GCRS
Spacecraft reference frame relative to the Earth's centre of mass
with the same orientation as BCRS/ICRS.
ephem : str, optional
Ephemeris selection.
num_workers : int, optional
Number of workers for multiprocessing.
Raises
------
ValueError
Error if solar bodies file is empty.
Returns
-------
solar_bodies : list
Solar system bodies and their properties.
"""
# Set ephemeris data
solar_system_ephemeris.set(ephem)
# Load solar bodies of interest from config
# TODO: implement default and optional paths
with open("data/solar_bodies.yml", "r") as solar_bodies_file:
solar_bodies_dump = yaml.safe_load(solar_bodies_file)
# Check for empty solar bodies file
if solar_bodies_dump is None:
raise ValueError("Empty solar bodies file")
# Create list of included solar bodies to supply to multiprocessing
solar_bodies_list = [(solar_body_name, solar_body_info, spacecraft_frame)
for solar_body_name, solar_body_info
in solar_bodies_dump.items()
if solar_body_info["included"]]
# Generate solar body objects
# TODO: value checking
solar_bodies = []
# Create worker pool
with multiprocessing.Pool(num_workers) as p:
# Create progress bar
with tqdm(total=len(solar_bodies_list), desc="Solar Body Generation") as pbar:
# Iterate through solar bodies
for solar_body_object in p.imap(load_worker, solar_bodies_list):
# Add solar body object to list
solar_bodies.append(solar_body_object)
# Update progress bar
pbar.update()
return solar_bodies
def load_worker(worker_params):
"""
Worker function for loading solar bodies.
Parameters
----------
worker_params : tuple
Parameters for the worker, including the solar body name,
solar body information, and satellite reference frame.
Returns
-------
solar_body_object : solarBody
Solar body object.
"""
# Unpack worker parameter tuple
solar_body_name, solar_body_info, spacecraft_frame = worker_params
# Calculate solar body coordinates from ephemeris data
solar_body_coords = get_body(solar_body_name, spacecraft_frame.obstime)
# Convert to spacecraft frame coordinates
solar_body_coords = solar_body_coords.transform_to(spacecraft_frame)
# Find slant range between satellite and solar body
slant_range = solar_body_coords.distance
# Calculate solar body angular radius
solar_body_radius = solar_body_info["radius"] * u.m
solar_body_angular_radius = np.arcsin(solar_body_radius / slant_range)
# Load soft radius constraints
solar_body_soft_radius = solar_body_info["soft_radius"] * u.deg
# Create solar body object
solar_body_object = SolarBody(solar_body_name,
solar_body_coords,
solar_body_radius,
solar_body_angular_radius,
solar_body_soft_radius)
return solar_body_object
| [
"astropy.coordinates.get_body",
"astropy.coordinates.solar_system_ephemeris.set",
"numpy.arcsin",
"yaml.safe_load",
"multiprocessing.Pool"
] | [((2006, 2039), 'astropy.coordinates.solar_system_ephemeris.set', 'solar_system_ephemeris.set', (['ephem'], {}), '(ephem)\n', (2032, 2039), False, 'from astropy.coordinates import solar_system_ephemeris, get_body\n'), ((3886, 3937), 'astropy.coordinates.get_body', 'get_body', (['solar_body_name', 'spacecraft_frame.obstime'], {}), '(solar_body_name, spacecraft_frame.obstime)\n', (3894, 3937), False, 'from astropy.coordinates import solar_system_ephemeris, get_body\n'), ((4291, 4333), 'numpy.arcsin', 'np.arcsin', (['(solar_body_radius / slant_range)'], {}), '(solar_body_radius / slant_range)\n', (4300, 4333), True, 'import numpy as np\n'), ((2232, 2265), 'yaml.safe_load', 'yaml.safe_load', (['solar_bodies_file'], {}), '(solar_bodies_file)\n', (2246, 2265), False, 'import yaml\n'), ((2835, 2868), 'multiprocessing.Pool', 'multiprocessing.Pool', (['num_workers'], {}), '(num_workers)\n', (2855, 2868), False, 'import multiprocessing\n')] |
from Kfold import k_fold
import numpy as np
def cv_estimate(fit_fn, pred_fn, loss_fn, X, y, n_folds, **varargin):
"""
Input:
model = fit_fn(X_train, y_train)
y_hat = pred_fn(X_test)
L = loss_fn(y_hat, y_test)
X, 设计矩阵, shape=(n_sampels,dim)
y, 类标签, shape=(n_samples,)
n_folds, 交叉验证需要的fold
可选参数:
varargin= {'randomizeorder':randomize_order,'testfolds':test_folds}
分别表示:是否对原数据进行打乱:{0,1}
额外指定的test_folds: [np.array_1,np.array_2,...,np.array_folds]
"""
randomize_order = varargin.get('randomizeorder', False) # 0 代表不对数据进行打乱
test_folds = varargin.get('testfolds', []) # 获取额外指定的测试fold
n_samples = X.shape[0]
if not test_folds: # 如果未指定测试用的fold
train_folds, test_folds = k_fold(n_samples, n_folds, randomize_order)
else:
all_index = set(range(n_samples))
train_folds = [np.array(list(all_index-set(single_array))) for single_array in test_folds]
loss = np.zeros((n_samples, ))
for f in range(len(train_folds)):
X_train = X[train_folds[f]]; X_test = X[test_folds[f]]
y_train = y[train_folds[f]]; y_test = y[test_folds[f]]
model = fit_fn(X_train, y_train)
y_hat_index, _ = pred_fn(model, X_test)
y_hat = model.support[y_hat_index]
loss[test_folds[f]] = loss_fn(y_hat, y_test)
mu = np.mean(loss)
se = np.std(loss)/np.power(n_samples,0.5)
return mu, se
| [
"numpy.std",
"numpy.power",
"numpy.zeros",
"numpy.mean",
"Kfold.k_fold"
] | [((989, 1011), 'numpy.zeros', 'np.zeros', (['(n_samples,)'], {}), '((n_samples,))\n', (997, 1011), True, 'import numpy as np\n'), ((1372, 1385), 'numpy.mean', 'np.mean', (['loss'], {}), '(loss)\n', (1379, 1385), True, 'import numpy as np\n'), ((783, 826), 'Kfold.k_fold', 'k_fold', (['n_samples', 'n_folds', 'randomize_order'], {}), '(n_samples, n_folds, randomize_order)\n', (789, 826), False, 'from Kfold import k_fold\n'), ((1395, 1407), 'numpy.std', 'np.std', (['loss'], {}), '(loss)\n', (1401, 1407), True, 'import numpy as np\n'), ((1408, 1432), 'numpy.power', 'np.power', (['n_samples', '(0.5)'], {}), '(n_samples, 0.5)\n', (1416, 1432), True, 'import numpy as np\n')] |
import argparse
import os
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
import random
from functools import partial
from multiprocessing.pool import Pool
import cv2
import numpy as np
import tqdm
from albumentations.augmentations.functional import random_crop
def generate_oof_masks(mask_file, img_dir="masks", oof_predictions_dir=None, img_size=640, masks_per_file=10):
os.makedirs(img_dir, exist_ok=True)
os.makedirs(os.path.join(img_dir, "original"), exist_ok=True)
os.makedirs(os.path.join(img_dir, "solution"), exist_ok=True)
mask_dir = os.path.join("/home/selim/datasets/spacenet/train_mask_binned")
pred_dir = os.path.join(oof_predictions_dir, "full_oof")
mask = cv2.imread(os.path.join(mask_dir, mask_file[:-4] .replace("RGB", "MS")+ ".tif"), cv2.IMREAD_GRAYSCALE)
mask[mask > 0] = 255
solution_mask = cv2.imread(os.path.join(pred_dir, mask_file[:-4]+".png"), cv2.IMREAD_GRAYSCALE)
id = mask_file[:-4]
for i in range(masks_per_file):
h_start, w_start = random.random(), random.random()
crop = random_crop(mask, img_size, img_size, h_start, w_start)
if np.sum(crop) < 2000 * 255 and random.random() < 0.9:
continue
solution_crop = random_crop(solution_mask, img_size, img_size, h_start, w_start)
cv2.imwrite(os.path.join(img_dir, "original", "{}_{}oof.png".format(id, i)), crop)
cv2.imwrite(os.path.join(img_dir, "solution", "{}_{}oof.png".format(id, i)), solution_crop)
if __name__ == '__main__':
parser = argparse.ArgumentParser("Synthetic Mask Generator")
arg = parser.add_argument
arg('--out_dir', default='/home/selim/datasets/spacenet/masks_apls')
arg('--workers', type=int, default=12)
arg('--oof_predictions_dir', type=str, default="/home/selim/kaggle/oof_preds/")
args = parser.parse_args()
mask_files = os.listdir(os.path.join(args.oof_predictions_dir, "full_oof"))
with Pool(processes=args.workers) as p:
with tqdm.tqdm(total=len(mask_files)) as pbar:
for i, v in tqdm.tqdm(enumerate(p.imap_unordered(partial(generate_oof_masks, img_dir=args.out_dir, oof_predictions_dir=args.oof_predictions_dir, masks_per_file=10), mask_files))):
pbar.update()
| [
"functools.partial",
"numpy.sum",
"os.makedirs",
"argparse.ArgumentParser",
"random.random",
"multiprocessing.pool.Pool",
"os.path.join",
"albumentations.augmentations.functional.random_crop"
] | [((444, 479), 'os.makedirs', 'os.makedirs', (['img_dir'], {'exist_ok': '(True)'}), '(img_dir, exist_ok=True)\n', (455, 479), False, 'import os\n'), ((627, 690), 'os.path.join', 'os.path.join', (['"""/home/selim/datasets/spacenet/train_mask_binned"""'], {}), "('/home/selim/datasets/spacenet/train_mask_binned')\n", (639, 690), False, 'import os\n'), ((706, 751), 'os.path.join', 'os.path.join', (['oof_predictions_dir', '"""full_oof"""'], {}), "(oof_predictions_dir, 'full_oof')\n", (718, 751), False, 'import os\n'), ((1589, 1640), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""Synthetic Mask Generator"""'], {}), "('Synthetic Mask Generator')\n", (1612, 1640), False, 'import argparse\n'), ((496, 529), 'os.path.join', 'os.path.join', (['img_dir', '"""original"""'], {}), "(img_dir, 'original')\n", (508, 529), False, 'import os\n'), ((562, 595), 'os.path.join', 'os.path.join', (['img_dir', '"""solution"""'], {}), "(img_dir, 'solution')\n", (574, 595), False, 'import os\n'), ((922, 969), 'os.path.join', 'os.path.join', (['pred_dir', "(mask_file[:-4] + '.png')"], {}), "(pred_dir, mask_file[:-4] + '.png')\n", (934, 969), False, 'import os\n'), ((1126, 1181), 'albumentations.augmentations.functional.random_crop', 'random_crop', (['mask', 'img_size', 'img_size', 'h_start', 'w_start'], {}), '(mask, img_size, img_size, h_start, w_start)\n', (1137, 1181), False, 'from albumentations.augmentations.functional import random_crop\n'), ((1292, 1356), 'albumentations.augmentations.functional.random_crop', 'random_crop', (['solution_mask', 'img_size', 'img_size', 'h_start', 'w_start'], {}), '(solution_mask, img_size, img_size, h_start, w_start)\n', (1303, 1356), False, 'from albumentations.augmentations.functional import random_crop\n'), ((1931, 1981), 'os.path.join', 'os.path.join', (['args.oof_predictions_dir', '"""full_oof"""'], {}), "(args.oof_predictions_dir, 'full_oof')\n", (1943, 1981), False, 'import os\n'), ((1992, 2020), 'multiprocessing.pool.Pool', 'Pool', ([], {'processes': 'args.workers'}), '(processes=args.workers)\n', (1996, 2020), False, 'from multiprocessing.pool import Pool\n'), ((1078, 1093), 'random.random', 'random.random', ([], {}), '()\n', (1091, 1093), False, 'import random\n'), ((1095, 1110), 'random.random', 'random.random', ([], {}), '()\n', (1108, 1110), False, 'import random\n'), ((1193, 1205), 'numpy.sum', 'np.sum', (['crop'], {}), '(crop)\n', (1199, 1205), True, 'import numpy as np\n'), ((1223, 1238), 'random.random', 'random.random', ([], {}), '()\n', (1236, 1238), False, 'import random\n'), ((2143, 2262), 'functools.partial', 'partial', (['generate_oof_masks'], {'img_dir': 'args.out_dir', 'oof_predictions_dir': 'args.oof_predictions_dir', 'masks_per_file': '(10)'}), '(generate_oof_masks, img_dir=args.out_dir, oof_predictions_dir=args.\n oof_predictions_dir, masks_per_file=10)\n', (2150, 2262), False, 'from functools import partial\n')] |
import os
import numpy as np
import torchio as tio
from natsort import natsorted
from pydicom import dcmread
from scipy import interpolate
from skimage import morphology
from skimage.measure import find_contours
class Mask:
"""
Class that hold any structures aligned with a reference CT.
:param tio.LABEL mask:
Path to the mask or a tio.Label.
:param string ct_path:
Path to the CT folder.
:param List[pydicom.dataset.FileDataset] ds_cts:
CT Dataset.
"""
def __init__(self, mask, ct_path=None, ds_cts=None, structures=None):
if ct_path is None and ds_cts is None:
raise ValueError('At least ct_path should be provided')
self.masks = mask if not isinstance(mask, str) else tio.LabelMap(mask)
self.structures = structures
self.masks_itk = self.masks.as_sitk()
self.transform = tio.OneHot()
self.one_hot_masks = self.transform(self.masks)
self.n_masks = self.one_hot_masks.shape[0] - 1
self.ct_files = natsorted([os.path.join(ct_path, ct) for ct in os.listdir(ct_path)
if ct.endswith("dcm")])
self.ds_ct = ds_cts or [dcmread(ct_file, force=True) for ct_file in self.ct_files]
self.ds_ct.reverse()
def coordinates(self, mask):
"""
Give the coordinates of the corresponding structures in the RCS and the SOP Instance UID.
:param mask: mask.
:type mask: :class:`torch.Tensor`
:return: List of ROI contour sequence.
:rtype: list[(str,list[int])]
"""
mask = mask.numpy().astype(bool)
referenced_contour_data = []
for s in range(mask.shape[-1]):
# removing holes using a large value to be sure all the holes are removed
img = morphology.remove_small_holes(mask[..., s], 100000, in_place=True)
contours = find_contours(img)
for contour in contours:
if len(contour):
x = np.array(contour[:, 1])
y = np.array(contour[:, 0])
n_points = len(x)
# s is how much we want the spline to stick the points. If too high, interpolation 'moves away'
# from the real outline. If too small, it creates a crenellation
# ToDo check per=False
if n_points > 3:
tck = interpolate.splprep([x, y], per=True, s=n_points // 10., quiet=2)
xi, yi = interpolate.splev(tck[1], tck[0])
contour = list(zip(xi, yi))
mask_coordinates = []
for coord in contour:
r, c = coord
x, y, z = self.masks_itk.TransformContinuousIndexToPhysicalPoint([c, r, s])
mask_coordinates.append(round(x, 4))
mask_coordinates.append(round(y, 4))
mask_coordinates.append(round(z, 4))
referenced_contour_data.append((self.ds_ct[s].SOPInstanceUID, mask_coordinates))
return referenced_contour_data
| [
"pydicom.dcmread",
"skimage.morphology.remove_small_holes",
"torchio.LabelMap",
"scipy.interpolate.splprep",
"torchio.OneHot",
"skimage.measure.find_contours",
"numpy.array",
"scipy.interpolate.splev",
"os.path.join",
"os.listdir"
] | [((888, 900), 'torchio.OneHot', 'tio.OneHot', ([], {}), '()\n', (898, 900), True, 'import torchio as tio\n'), ((761, 779), 'torchio.LabelMap', 'tio.LabelMap', (['mask'], {}), '(mask)\n', (773, 779), True, 'import torchio as tio\n'), ((1815, 1881), 'skimage.morphology.remove_small_holes', 'morphology.remove_small_holes', (['mask[..., s]', '(100000)'], {'in_place': '(True)'}), '(mask[..., s], 100000, in_place=True)\n', (1844, 1881), False, 'from skimage import morphology\n'), ((1905, 1923), 'skimage.measure.find_contours', 'find_contours', (['img'], {}), '(img)\n', (1918, 1923), False, 'from skimage.measure import find_contours\n'), ((1047, 1072), 'os.path.join', 'os.path.join', (['ct_path', 'ct'], {}), '(ct_path, ct)\n', (1059, 1072), False, 'import os\n'), ((1194, 1222), 'pydicom.dcmread', 'dcmread', (['ct_file'], {'force': '(True)'}), '(ct_file, force=True)\n', (1201, 1222), False, 'from pydicom import dcmread\n'), ((1083, 1102), 'os.listdir', 'os.listdir', (['ct_path'], {}), '(ct_path)\n', (1093, 1102), False, 'import os\n'), ((2018, 2041), 'numpy.array', 'np.array', (['contour[:, 1]'], {}), '(contour[:, 1])\n', (2026, 2041), True, 'import numpy as np\n'), ((2066, 2089), 'numpy.array', 'np.array', (['contour[:, 0]'], {}), '(contour[:, 0])\n', (2074, 2089), True, 'import numpy as np\n'), ((2439, 2505), 'scipy.interpolate.splprep', 'interpolate.splprep', (['[x, y]'], {'per': '(True)', 's': '(n_points // 10.0)', 'quiet': '(2)'}), '([x, y], per=True, s=n_points // 10.0, quiet=2)\n', (2458, 2505), False, 'from scipy import interpolate\n'), ((2538, 2571), 'scipy.interpolate.splev', 'interpolate.splev', (['tck[1]', 'tck[0]'], {}), '(tck[1], tck[0])\n', (2555, 2571), False, 'from scipy import interpolate\n')] |
# bestballsim/tests/test_byes.py
# -*- coding: utf-8 -*-
# Copyright (C) 2021 <NAME>
# Licensed under the MIT License
import numpy as np
from numpy.core.numeric import ones
import pandas as pd
import pytest
from bestballsim.byes import *
def onesie_data(n=2, w=16):
return np.random.randint(low=1, high=30, size=(n, w))
@pytest.fixture
def season_data(test_directory):
return pd.read_csv(test_directory / 'season_data.csv')
@pytest.fixture
def weekly_data(test_directory):
return pd.read_csv(test_directory / 'weekly_data.csv')
def test_addbye_invalid_n_same_bye(tprint):
"""Tests byesim on the onesie positions with invalid n_same_bye"""
players = onesie_data()
with pytest.raises(ValueError):
new_players = addbye(players, n_same_bye=3)
def test_addbye_2D_valid_n_same_bye():
"""Tests byesim on the onesie positions with valid n_same_bye"""
players = onesie_data()
new_players = addbye(players, n_same_bye=0)
assert new_players[0, 0] == 0
assert new_players[1, 0] != 0
players = onesie_data(n=4)
new_players = addbye(players, n_same_bye=1)
assert new_players[0, 0] == 0
assert new_players[1, 0] != 0
assert new_players[2, 0] != 0
assert new_players[3, 0] == 0
def test_addbye_3D_valid_n_same_bye(tprint):
"""Tests byesim on the onesie positions with valid n_same_bye"""
players = onesie_data()
rows = 5
sp = shuffled_players(players, rows=rows)
new_players = addbye(sp, n_same_bye=0)
assert np.array_equal(new_players[:, 0, 0], np.zeros(rows))
assert np.array_equal(new_players[:, 1, 1], np.zeros(rows))
players = onesie_data(n=4)
rows = 5
sp = shuffled_players(players, rows=rows)
new_players = addbye(sp, n_same_bye=1)
assert np.array_equal(new_players[:, 0, 0], np.zeros(rows))
assert np.array_equal(new_players[:, 1, 1], np.zeros(rows))
assert np.array_equal(new_players[:, 3, 0], np.zeros(rows))
def test_shuffled_indices():
"""Tests shuffled_indices"""
# test that shuffle changes order
high = 16
rows = 1
players = onesie_data()
idx = shuffled_indices(0, high, rows)
assert idx.shape == (rows, high)
shuffled_players = players[:, idx[0]]
assert players.tolist() != shuffled_players.tolist()
assert set(players[0]) == set(shuffled_players[0])
def test_bb_scoring_onesie():
"""Tests bb_scoring for onesie position"""
players = np.array([[1, 2, 3, 10], [10, 10, 10, 1]])
assert np.array_equal(bbscoring(players, 1), np.array([10, 10, 10, 10]))
def test_bb_scoring_multi(tprint):
"""Tests bb_scoring for multiplayer position"""
players = (
np.array([
[1, 2, 2, 1],
[10, 4, 1, 1],
[20, 20, 20, 20]
])
)
scoring = bbscoring(players, 2)
expected_scoring = np.array([[20] * 4, [10, 4, 2, 1]])
assert np.array_equal(scoring, expected_scoring)
def test_shuffled_players(tprint):
"""Tests shuffled_players"""
players = onesie_data()
low = 0
high = players.shape[1]
rows = 5
new_players = shuffled_players(players, low, high, rows)
assert new_players.shape == (rows, players.shape[0], players.shape[1])
def test_byesim(tprint):
"""Tests byesim"""
n_players = 5
players = onesie_data(n=n_players)
sp = shuffled_players(players, low=0, high=players.shape[1], rows=n_players)
bs = byesim(players, n_same_bye=2, n_slots=1, shuffles=1)
| [
"pandas.read_csv",
"numpy.zeros",
"pytest.raises",
"numpy.random.randint",
"numpy.array",
"numpy.array_equal"
] | [((283, 329), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(1)', 'high': '(30)', 'size': '(n, w)'}), '(low=1, high=30, size=(n, w))\n', (300, 329), True, 'import numpy as np\n'), ((392, 439), 'pandas.read_csv', 'pd.read_csv', (["(test_directory / 'season_data.csv')"], {}), "(test_directory / 'season_data.csv')\n", (403, 439), True, 'import pandas as pd\n'), ((502, 549), 'pandas.read_csv', 'pd.read_csv', (["(test_directory / 'weekly_data.csv')"], {}), "(test_directory / 'weekly_data.csv')\n", (513, 549), True, 'import pandas as pd\n'), ((2436, 2478), 'numpy.array', 'np.array', (['[[1, 2, 3, 10], [10, 10, 10, 1]]'], {}), '([[1, 2, 3, 10], [10, 10, 10, 1]])\n', (2444, 2478), True, 'import numpy as np\n'), ((2669, 2726), 'numpy.array', 'np.array', (['[[1, 2, 2, 1], [10, 4, 1, 1], [20, 20, 20, 20]]'], {}), '([[1, 2, 2, 1], [10, 4, 1, 1], [20, 20, 20, 20]])\n', (2677, 2726), True, 'import numpy as np\n'), ((2844, 2879), 'numpy.array', 'np.array', (['[[20] * 4, [10, 4, 2, 1]]'], {}), '([[20] * 4, [10, 4, 2, 1]])\n', (2852, 2879), True, 'import numpy as np\n'), ((2891, 2932), 'numpy.array_equal', 'np.array_equal', (['scoring', 'expected_scoring'], {}), '(scoring, expected_scoring)\n', (2905, 2932), True, 'import numpy as np\n'), ((704, 729), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (717, 729), False, 'import pytest\n'), ((1547, 1561), 'numpy.zeros', 'np.zeros', (['rows'], {}), '(rows)\n', (1555, 1561), True, 'import numpy as np\n'), ((1611, 1625), 'numpy.zeros', 'np.zeros', (['rows'], {}), '(rows)\n', (1619, 1625), True, 'import numpy as np\n'), ((1809, 1823), 'numpy.zeros', 'np.zeros', (['rows'], {}), '(rows)\n', (1817, 1823), True, 'import numpy as np\n'), ((1873, 1887), 'numpy.zeros', 'np.zeros', (['rows'], {}), '(rows)\n', (1881, 1887), True, 'import numpy as np\n'), ((1937, 1951), 'numpy.zeros', 'np.zeros', (['rows'], {}), '(rows)\n', (1945, 1951), True, 'import numpy as np\n'), ((2528, 2554), 'numpy.array', 'np.array', (['[10, 10, 10, 10]'], {}), '([10, 10, 10, 10])\n', (2536, 2554), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
from typing import List
from mcos.covariance_transformer import AbstractCovarianceTransformer
from mcos.error_estimator import AbstractErrorEstimator
from mcos.observation_simulator import AbstractObservationSimulator, MuCovLedoitWolfObservationSimulator, \
MuCovObservationSimulator, MuCovJackknifeObservationSimulator
from mcos.optimizer import AbstractOptimizer
from mcos.utils import convert_price_history
def simulate_optimizations(
obs_simulator: AbstractObservationSimulator,
n_sims: int,
optimizers: List[AbstractOptimizer],
error_estimator: AbstractErrorEstimator,
covariance_transformers: List[AbstractCovarianceTransformer]
) -> pd.DataFrame:
error_estimates = {optimizer.name: [] for optimizer in optimizers}
for i in range(n_sims):
mu_hat, cov_hat = obs_simulator.simulate()
for transformer in covariance_transformers:
cov_hat = transformer.transform(cov_hat, obs_simulator.n_observations)
for optimizer in optimizers:
allocation = optimizer.allocate(mu_hat, cov_hat)
optimal_allocation = optimizer.allocate(obs_simulator.mu, obs_simulator.cov)
estimation = error_estimator.estimate(obs_simulator.mu, obs_simulator.cov, allocation, optimal_allocation)
error_estimates[optimizer.name].append(estimation)
return pd.DataFrame([
{
'optimizer': optimizer.name,
'mean': np.mean(error_estimates[optimizer.name]),
'stdev': np.std(error_estimates[optimizer.name])
} for optimizer in optimizers
]).set_index('optimizer')
def simulate_optimizations_from_price_history(
price_history: pd.DataFrame,
simulator_name: str,
n_observations:int,
n_sims: int,
optimizers: List[AbstractOptimizer],
error_estimator: AbstractErrorEstimator,
covariance_transformers: List[AbstractCovarianceTransformer]):
mu, cov = convert_price_history(price_history)
if simulator_name.lower() == "mucovledoitwolf":
sim = MuCovLedoitWolfObservationSimulator(mu, cov, n_observations)
elif simulator_name.lower() == "mucov":
sim = MuCovObservationSimulator(mu, cov, n_observations)
elif simulator_name.lower() == "jackknife":
sim = MuCovJackknifeObservationSimulator(mu, cov, n_observations)
else:
raise ValueError("Invalid observation simulator name")
return simulate_optimizations(sim, n_sims, optimizers, error_estimator, covariance_transformers)
| [
"mcos.utils.convert_price_history",
"mcos.observation_simulator.MuCovJackknifeObservationSimulator",
"numpy.std",
"numpy.mean",
"mcos.observation_simulator.MuCovObservationSimulator",
"mcos.observation_simulator.MuCovLedoitWolfObservationSimulator"
] | [((2011, 2047), 'mcos.utils.convert_price_history', 'convert_price_history', (['price_history'], {}), '(price_history)\n', (2032, 2047), False, 'from mcos.utils import convert_price_history\n'), ((2115, 2175), 'mcos.observation_simulator.MuCovLedoitWolfObservationSimulator', 'MuCovLedoitWolfObservationSimulator', (['mu', 'cov', 'n_observations'], {}), '(mu, cov, n_observations)\n', (2150, 2175), False, 'from mcos.observation_simulator import AbstractObservationSimulator, MuCovLedoitWolfObservationSimulator, MuCovObservationSimulator, MuCovJackknifeObservationSimulator\n'), ((2234, 2284), 'mcos.observation_simulator.MuCovObservationSimulator', 'MuCovObservationSimulator', (['mu', 'cov', 'n_observations'], {}), '(mu, cov, n_observations)\n', (2259, 2284), False, 'from mcos.observation_simulator import AbstractObservationSimulator, MuCovLedoitWolfObservationSimulator, MuCovObservationSimulator, MuCovJackknifeObservationSimulator\n'), ((2347, 2406), 'mcos.observation_simulator.MuCovJackknifeObservationSimulator', 'MuCovJackknifeObservationSimulator', (['mu', 'cov', 'n_observations'], {}), '(mu, cov, n_observations)\n', (2381, 2406), False, 'from mcos.observation_simulator import AbstractObservationSimulator, MuCovLedoitWolfObservationSimulator, MuCovObservationSimulator, MuCovJackknifeObservationSimulator\n'), ((1496, 1536), 'numpy.mean', 'np.mean', (['error_estimates[optimizer.name]'], {}), '(error_estimates[optimizer.name])\n', (1503, 1536), True, 'import numpy as np\n'), ((1559, 1598), 'numpy.std', 'np.std', (['error_estimates[optimizer.name]'], {}), '(error_estimates[optimizer.name])\n', (1565, 1598), True, 'import numpy as np\n')] |
import os
import sys
import numpy as np
import ConfigParser
from mpi4py import MPI
from rexfw.communicators.mpi import MPICommunicator
from rexfw.convenience import create_directories
from cPickle import dump
from ensemble_hic.setup_functions import make_replica_schedule, parse_config_file
mpicomm = MPI.COMM_WORLD
rank = mpicomm.Get_rank()
size = mpicomm.Get_size()
config_file = sys.argv[1]
n_replicas = size - 1
settings = parse_config_file(config_file)
comm = MPICommunicator()
re_params = settings['replica']
if re_params['schedule'] in ('linear', 'exponential'):
schedule = make_replica_schedule(re_params, n_replicas)
elif re_params['schedule'][-3:] == '.py':
# exec(open(re_params['schedule']).read())
import numpy as np
from scipy import stats
from mpi4py import MPI
space = np.linspace(0, 1, n_replicas)
m = float(re_params['gauss_mean'])#.65
s = float(re_params['gauss_std'])#0.2
delta_betas = stats.norm.pdf(space, m, s)
delta_betas = [0] + delta_betas
betas = np.cumsum(delta_betas)
betas /= betas[-1]
schedule = {'lammda': betas, 'beta': betas}
else:
schedule = np.load(re_params['schedule'])
cont_folder = settings['general']['cont_folder']
output_folder = settings['general']['output_folder']
if output_folder[-1] != '/':
output_folder += '/'
if rank == 0:
from ensemble_hic.setup_functions import setup_default_re_master
from rexfw.convenience import create_directories
from shutil import copy2
## Setup replica exchange
master = setup_default_re_master(n_replicas, cont_folder, comm)
## run replica exchange
offset = int(settings['replica']['offset'])
master.run(int(re_params['n_samples']) + 1,
swap_interval=int(re_params['swap_interval']),
status_interval=int(re_params['print_status_interval']),
dump_interval=int(re_params['samples_dump_interval']),
dump_step=int(re_params['samples_dump_step']),
statistics_update_interval=int(re_params['statistics_update_interval']),
offset=offset)
## kill replicas
master.terminate_replicas()
else:
from rexfw.replicas import Replica
from rexfw.slaves import Slave
from rexfw.proposers.re import REProposer
from isd2.samplers.gibbs import GibbsSampler
from ensemble_hic.setup_functions import make_posterior, make_subsamplers
from ensemble_hic.setup_functions import setup_initial_state
from ensemble_hic.replica import CompatibleReplica
posterior = make_posterior(settings)
for replica_parameter in schedule:
posterior[replica_parameter].set(schedule[replica_parameter][rank - 1])
initial_state = setup_initial_state(settings['initial_state'], posterior)
if not 'norm' in initial_state.variables:
posterior['norm'].set(np.max(posterior.likelihoods['ensemble_contacts'].error_model.data) / float(settings['general']['n_structures']))
initial_state.update_variables(structures=np.load(cont_folder + 'init_states.npy')[rank - 1])
initial_state.update_variables(norm=np.load(cont_folder + 'init_norms.npy')[rank - 1])
settings['structures_hmc'].update(timestep=np.load(cont_folder + 'timesteps.npy')[rank - 1])
subsamplers = make_subsamplers(posterior, initial_state.variables,
settings['structures_hmc'])
sampler = GibbsSampler(pdf=posterior, state=initial_state,
subsamplers=subsamplers)
proposer = REProposer('prop{}'.format(rank))
proposers = {proposer.name: proposer}
replica = CompatibleReplica('replica{}'.format(rank), initial_state,
posterior,
GibbsSampler,
{'subsamplers': subsamplers},
proposers, output_folder, comm)
slave = Slave({'replica{}'.format(rank): replica}, comm)
slave.listen()
| [
"numpy.load",
"ensemble_hic.setup_functions.make_posterior",
"rexfw.communicators.mpi.MPICommunicator",
"scipy.stats.norm.pdf",
"numpy.cumsum",
"isd2.samplers.gibbs.GibbsSampler",
"ensemble_hic.setup_functions.setup_default_re_master",
"ensemble_hic.setup_functions.parse_config_file",
"ensemble_hic.... | [((430, 460), 'ensemble_hic.setup_functions.parse_config_file', 'parse_config_file', (['config_file'], {}), '(config_file)\n', (447, 460), False, 'from ensemble_hic.setup_functions import make_replica_schedule, parse_config_file\n'), ((469, 486), 'rexfw.communicators.mpi.MPICommunicator', 'MPICommunicator', ([], {}), '()\n', (484, 486), False, 'from rexfw.communicators.mpi import MPICommunicator\n'), ((590, 634), 'ensemble_hic.setup_functions.make_replica_schedule', 'make_replica_schedule', (['re_params', 'n_replicas'], {}), '(re_params, n_replicas)\n', (611, 634), False, 'from ensemble_hic.setup_functions import make_replica_schedule, parse_config_file\n'), ((1540, 1594), 'ensemble_hic.setup_functions.setup_default_re_master', 'setup_default_re_master', (['n_replicas', 'cont_folder', 'comm'], {}), '(n_replicas, cont_folder, comm)\n', (1563, 1594), False, 'from ensemble_hic.setup_functions import setup_default_re_master\n'), ((2560, 2584), 'ensemble_hic.setup_functions.make_posterior', 'make_posterior', (['settings'], {}), '(settings)\n', (2574, 2584), False, 'from ensemble_hic.setup_functions import make_posterior, make_subsamplers\n'), ((2725, 2782), 'ensemble_hic.setup_functions.setup_initial_state', 'setup_initial_state', (["settings['initial_state']", 'posterior'], {}), "(settings['initial_state'], posterior)\n", (2744, 2782), False, 'from ensemble_hic.setup_functions import setup_initial_state\n'), ((3277, 3362), 'ensemble_hic.setup_functions.make_subsamplers', 'make_subsamplers', (['posterior', 'initial_state.variables', "settings['structures_hmc']"], {}), "(posterior, initial_state.variables, settings['structures_hmc']\n )\n", (3293, 3362), False, 'from ensemble_hic.setup_functions import make_posterior, make_subsamplers\n'), ((3408, 3481), 'isd2.samplers.gibbs.GibbsSampler', 'GibbsSampler', ([], {'pdf': 'posterior', 'state': 'initial_state', 'subsamplers': 'subsamplers'}), '(pdf=posterior, state=initial_state, subsamplers=subsamplers)\n', (3420, 3481), False, 'from isd2.samplers.gibbs import GibbsSampler\n'), ((814, 843), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'n_replicas'], {}), '(0, 1, n_replicas)\n', (825, 843), True, 'import numpy as np\n'), ((947, 974), 'scipy.stats.norm.pdf', 'stats.norm.pdf', (['space', 'm', 's'], {}), '(space, m, s)\n', (961, 974), False, 'from scipy import stats\n'), ((1023, 1045), 'numpy.cumsum', 'np.cumsum', (['delta_betas'], {}), '(delta_betas)\n', (1032, 1045), True, 'import numpy as np\n'), ((1140, 1170), 'numpy.load', 'np.load', (["re_params['schedule']"], {}), "(re_params['schedule'])\n", (1147, 1170), True, 'import numpy as np\n'), ((2859, 2926), 'numpy.max', 'np.max', (["posterior.likelihoods['ensemble_contacts'].error_model.data"], {}), "(posterior.likelihoods['ensemble_contacts'].error_model.data)\n", (2865, 2926), True, 'import numpy as np\n'), ((3019, 3059), 'numpy.load', 'np.load', (["(cont_folder + 'init_states.npy')"], {}), "(cont_folder + 'init_states.npy')\n", (3026, 3059), True, 'import numpy as np\n'), ((3111, 3150), 'numpy.load', 'np.load', (["(cont_folder + 'init_norms.npy')"], {}), "(cont_folder + 'init_norms.npy')\n", (3118, 3150), True, 'import numpy as np\n'), ((3209, 3247), 'numpy.load', 'np.load', (["(cont_folder + 'timesteps.npy')"], {}), "(cont_folder + 'timesteps.npy')\n", (3216, 3247), True, 'import numpy as np\n')] |
#!/usr/bin/env python
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
soa = np.array([[0, 0, 0, 0, 0, 1], [0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0], [0, 0, 0, -1, 0, 0]])
X, Y, Z, U, V, W = zip(*soa)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.quiver(X, Y, Z, U, V, W)
ax.set_xlim([-1, 1])
ax.set_ylim([-1, 1])
ax.set_zlim([-1, 1])
plt.show()
| [
"matplotlib.pyplot.figure",
"numpy.array",
"matplotlib.pyplot.show"
] | [((122, 217), 'numpy.array', 'np.array', (['[[0, 0, 0, 0, 0, 1], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, -1, \n 0, 0]]'], {}), '([[0, 0, 0, 0, 0, 1], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0,\n 0, -1, 0, 0]])\n', (130, 217), True, 'import numpy as np\n'), ((266, 278), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (276, 278), True, 'import matplotlib.pyplot as plt\n'), ((413, 423), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (421, 423), True, 'import matplotlib.pyplot as plt\n')] |
import json
import argparse
from operator import itemgetter
from collections import namedtuple
import subprocess
import os
import numpy as np
import matplotlib.pyplot as plt
import sklearn
from sklearn.tree import export_graphviz
import kite.ranking.ranklearning as ranklearning
from logging import getLogger, DEBUG, INFO, StreamHandler
from sys import stdout
handler = StreamHandler(stdout)
logger = getLogger()
logger.addHandler(handler)
divider = '=' * 80
def load_dataset(path, min_training_examples=10):
"""Load a dataset from the given path."""
with open(path) as f:
train_data = json.load(f)
# Load training data
queries = dict()
example_ids = dict()
features = dict()
relevance = dict()
for item in train_data['Data']:
query_id = item['query_id']
if query_id not in queries:
queries[query_id] = {
'query_text': item['query_text'],
'query_code': item['query_code'],
'query_id': query_id}
example_ids[query_id] = []
features[query_id] = []
relevance[query_id] = []
example_ids[query_id].append(item['snapshot_id'])
features[query_id].append(item['features'])
relevance[query_id].append(item['label'])
data = []
for hash_id in queries:
query = ranklearning.Query(queries[hash_id], features[hash_id],
relevance[hash_id], example_ids[hash_id])
if len(query.relations) > 0:
data.append(query)
return ranklearning.Dataset(train_data['FeatureLabels'], data, train_data['FeaturerOptions'])
def main():
# Command line args
parser = argparse.ArgumentParser()
parser.add_argument('train')
parser.add_argument('--test', type=str)
parser.add_argument('--validate', type=str)
parser.add_argument('--normalizer',
choices=['min_max', 'mean_std'],
default='mean_std')
parser.add_argument('--kfold', type=int, default=-1)
parser.add_argument('--model',
choices=['linear', 'rbf', 'mart'], default='mart')
parser.add_argument('--loss_function',
choices=['hinge_loss', 'cross_entropy'],
default='cross_entropy')
parser.add_argument('--init_weight', nargs='+', type=float)
parser.add_argument('--random_init', action='store_true')
parser.add_argument('--num_seeds', type=int, default=10)
parser.add_argument('--t', type=int, default=10, help='cut-off T for NDCG')
parser.add_argument('--ir_measure', choices=['ndcg'])
parser.add_argument('--root', type=str, default="training_output")
parser.add_argument('--base', type=str, required=True)
parser.add_argument('--use_sklearn_trees', action='store_true')
parser.add_argument('--num_steps', type=int, default=100)
parser.add_argument('--learning_rate', type=float, default=1.)
parser.add_argument('--cv_learning_rates',
nargs='+', type=float, default=[1.])
parser.add_argument('--max_depth', type=int, default=5)
parser.add_argument('--min_samples_leaf', type=int, default=3)
parser.add_argument('--verbosity', default=0, type=int)
args = parser.parse_args()
if args.verbosity > 0:
logger.setLevel(DEBUG)
else:
logger.setLevel(INFO)
ranklearning.logger = logger
# set up model paramters
num_steps = args.num_steps
learning_rate = args.learning_rate
max_depth = args.max_depth
min_samples_leaf = args.min_samples_leaf
# set up loss function
logger.info('[Training] set up loss function')
loss = None
if args.loss_function == 'hinge_loss':
loss = ranklearning.HingeLoss()
elif args.loss_function == 'cross_entropy':
loss = ranklearning.CrossEntropyLoss()
else:
exit("Loss function '%s' is not supported" % args.loss_function)
# set up ir
logger.info('[Training] set up ir measurer')
ir = None
if args.ir_measure == 'ndcg':
ir = ranklearning.NDCG(cutoff=args.t)
elif args.ir_measure is not None:
exit("IR measure '%s' is not supported" % args.ir_measure)
# cross validate if requested
if args.validate is not None or args.kfold > 0:
if args.validate is not None and args.kfold > 0:
exit('cannot specify both --validate and --kfold')
if args.model == 'mart':
best_config = cross_validation_mart(args, loss, ir)
learning_rate, max_depth, num_steps = best_config
else:
logger.warn('cross validation is only for MART. Proceed with default parameters')
if args.random_init:
if args.model == 'linear':
best_random_weight = choose_init_random_weight(args, loss, ir)
else:
logger.warn('random init is only valid for linear models now. Proceed with an initial all-zero vector.')
info = divider + '\n'
info += '[Training] learning_rate: %f\n' % learning_rate
info += '[Training] max_depth: %d\n' % max_depth
info += '[Training] num_steps: %d\n' % num_steps
info += '[Training] learner: %s\n' % args.model
if args.random_init and args.model == 'linear':
info += '[Training] random_init: true\n'
else:
info += '[Training] random_init: false\n'
if args.ir_measure is None:
info += '[Training] use ir: none\n'
else:
info += '[Training] use ir: %s\n' % args.ir_measure
if args.init_weight is not None:
info += '[Training] initial weights: %s\n' % ' '.join(str(w) for w in args.init_weight)
info += '[Training] loss function: %s\n' % args.loss_function
info += divider
logger.info(info)
# Load training data
logger.info('[Training] loading training data...')
train_data = load_dataset(args.train)
logger.info('[Training] num of relations: %d' % train_data.num_relations())
# Build the normalizer
logger.info('[Training] setting up the normalizer...')
if args.normalizer == 'mean_std':
normalizer = ranklearning.meanstd_normalizer(train_data.features())
else:
normalizer = ranklearning.minmax_normalizer(train_data.features())
# Normalize the training data
logger.info('[Training] normalizing the training data...')
for query in train_data.queries:
query.features = normalizer(query.features)
# Set up test data
if args.test is not None:
logger.info('[Training] loading test data...')
test_data = load_dataset(args.test)
for query in test_data.queries:
query.features = normalizer(query.features)
# Set up learner
learner = None
if args.model == 'linear':
if args.init_weight is not None:
if len(args.init_weight) != train_data.nd:
error = 'length of init weight %d not match with feature length %d' % (len(args.init_weight), train_data.nd)
exit(error)
weight = args.init_weight
elif args.random_init:
weight = best_random_weight
else:
weight = np.zeros(train_data.nd, dtype=float)
learner = ranklearning.LinearRankLearner(weight, train_data.nd)
elif args.model == 'rbf':
learner = ranklearning.KernelRankLearner(
train_data.features(), kernel=ranklearning.Rbf(-1.))
elif args.model == 'mart':
logger.info('[Training] use sklearn trees: %s' % str(args.use_sklearn_trees))
learner = ranklearning.BoostedTreeLearner(
train_data.queries,
use_sklearn_trees=args.use_sklearn_trees,
max_depth=max_depth,
min_samples_leaf=min_samples_leaf)
else:
exit('Learner %s is not supported' % args.model)
# set up trainer
if loss is not None and learner is not None:
if ir is None:
trainer = ranklearning.FullLossTrainer(
train_data.queries, learner, loss, seed_rate=learning_rate)
else:
trainer = ranklearning.IRTrainer(
train_data.queries, learner, loss, ir, seed_rate=learning_rate)
#
# training
#
train_loss = []
test_loss = []
train_ir = []
test_ir = []
for i in range(num_steps):
trainer.step()
if args.ir_measure is None:
ir_scorer = ranklearning.NDCG()
else:
ir_scorer = trainer.ir
ir_score = ranklearning.compute_dataset_irscore(
train_data.queries, trainer.learner.current, ir_scorer)
train_ir.append(ir_score)
if args.test is not None:
ir_score = ranklearning.compute_dataset_irscore(
test_data.queries, trainer.learner.current, ir_scorer)
test_ir.append(ir_score)
loss_score = ranklearning.compute_dataset_loss(
train_data.queries, trainer.learner.current, trainer.loss)
train_loss.append(loss_score)
if args.test is not None:
loss_score = ranklearning.compute_dataset_loss(
test_data.queries, trainer.learner.current, trainer.loss)
test_loss.append(loss_score)
logger.debug('-------- Report --------')
logger.debug('[Training] ir score at step %d: %f' % (i, train_ir[-1]))
logger.debug('[Training] loss score at step %d: %f' % (i, train_loss[-1]))
logger.debug('[Test] ir score at step %d: %f' % (i, test_ir[-1]))
logger.debug('[Test] loss score at step %d: %f' % (i, test_loss[-1]))
logger.info('-------- Training Overview --------')
logger.info('[Training] ir score at step %d: %f' % (i, train_ir[-1]))
logger.info('[Training] loss score at step %d: %f' % (i, train_loss[-1]))
logger.info('[Test] ir score at step %d: %f' % (i, test_ir[-1]))
logger.info('[Test] loss score at step %d: %f' % (i, test_loss[-1]))
train_loss = np.array(train_loss)
test_loss = np.array(test_loss)
train_ir = np.array(train_ir)
test_ir = np.array(test_ir)
#
# Generate the final output file for test data
#
directory = os.path.join(args.root, args.base)
if not os.path.exists(directory):
os.makedirs(directory)
if args.test is not None:
fname = os.path.join(args.root, args.base, 'test-results.json')
f = open(fname, 'w')
for query in test_data.queries:
payload = dict()
payload['query_id'] = query.info['query_id']
payload['query_text'] = query.info['query_text']
payload['query_code'] = query.info['query_code']
payload['labels'] = list()
payload['example_ids'] = list()
payload['expected_rank'] = list()
payload['scores'] = list()
payload['features'] = list()
payload['featurelabels'] = test_data.featurelabels
scores = trainer.learner.current(query.features)
ranking = ranklearning.ranks_from_scores(scores)
expected_rankings = ranklearning.ranks_from_scores(query.relevance)
if args.ir_measure is not None:
payload['ndcg'] = trainer.ir(query.relevance, scores)
else:
ir_scorer = ranklearning.NDCG()
payload['ndcg'] = ir_scorer(query.relevance, scores)
for r in ranking:
payload['labels'].append(float(query.relevance[r]))
payload['example_ids'].append(query.example_ids[r])
payload['expected_rank'].append(expected_rankings.index(r))
payload['scores'].append(scores[r])
payload['features'].append(query.features[r].tolist())
json.dump(payload, f)
f.close()
#
# Write model as json if requested
#
fname = os.path.join(args.root, args.base, 'model.json')
f = open(fname, 'w')
ranker = {
"Normalizer": {
"Offset": normalizer.offset.tolist(),
"Scale": normalizer.scale.tolist(),
},
"Scorer": learner.current.to_json(),
"FeatureLabels": train_data.featurelabels,
"FeaturerOptions": train_data.options,
}
if isinstance(learner.current, ranklearning.LinearScorer):
ranker["ScorerType"] = "Linear"
elif isinstance(learner.current, ranklearning.KernelScorer):
ranker["ScorerType"] = "RbfKernel"
elif isinstance(learner.current, ranklearning.TreeEnsembleScorer):
ranker["ScorerType"] = "TreeEnsemble"
else:
logger.warning("Unknown model type: %s" % learner.current)
with open(fname, "w") as f:
json.dump(ranker, f)
f.close()
#
# Plot basic training info
#
logger.info("[Training] plotting loss function...")
plt.clf()
plt.subplot2grid((1, 3), (0, 0), colspan=2) # make space for legend
plt.plot(train_loss, label='training')
if args.test is not None:
plt.plot(test_loss, label='test')
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.xlabel('iteration #')
plt.ylabel('Loss fucntion')
filename = os.path.join(args.root, args.base, "loss.pdf")
plt.savefig(filename)
logger.info("[Training] plotting IR measure")
plt.clf()
plt.subplot2grid((1, 3), (0, 0), colspan=2) # make space for legend
plt.plot(train_ir, label='training')
if args.test is not None:
plt.plot(test_ir, label='test')
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.xlabel('iteration #')
plt.ylabel('IR measure')
filename = os.path.join(args.root, args.base, "ndcg.pdf")
plt.savefig(filename)
#
# visualize the model
#
if args.model == 'mart' and args.use_sklearn_trees:
logger.info("[Training] visualizing model...")
for i, t in enumerate(learner.current.trees):
filename = os.path.join(args.root, args.base, str(i) + '.dot')
pngfilename = os.path.join(args.root, args.base, str(i) + '.png')
with open(filename, 'w') as f:
export_graphviz(t.tree, out_file=f,
feature_names=train_data.featurelabels)
command = ['dot', '-Tpng', filename, "-o", pngfilename]
try:
subprocess.check_call(command)
except:
exit("Could not run graphviz to produce visualization")
def split_dataset(train_data, validate_data, kfold):
if validate_data is not None:
yield train_data, validate_data
else:
folds = sklearn.cross_validation.KFold(len(train_data.queries), kfold)
for train_index, validate_index in folds:
yield (ranklearning.Dataset(
train_data.featurelabels,
itemgetter(*train_index)(train_data.queries),
train_data.options),
ranklearning.Dataset(
train_data.featurelabels,
itemgetter(*validate_index)(train_data.queries),
train_data.options))
def choose_init_random_weight(args, loss, ir):
train_data = load_dataset(args.train)
Config = namedtuple('Config', ['weight', 'score'])
# normalize the features
if args.normalizer == "mean_std":
normalizer = ranklearning.meanstd_normalizer(train_data.features())
else:
normalizer = ranklearning.minmax_normalizer(train_data.features())
for query in train_data.queries:
query.features = normalizer(query.features)
# try as many random initial seeds as args.num_seeds
ir_scores = []
for seed in range(args.num_seeds):
weight = np.random.uniform(size=train_data.nd)
learner = ranklearning.LinearRankLearner(weight, train_data.nd)
trainer = ranklearning.IRTrainer(
train_data.queries,
learner, loss, ir,
seed_rate=args.learning_rate)
for i in range(args.num_steps):
trainer.step()
ir_score = ranklearning.compute_dataset_irscore(
train_data.queries, trainer.learner.current, trainer.ir)
logger.info(divider)
logger.debug('%d-th initial random weights: %s' % (seed, ' '.join(str(w) for w in weight)))
logger.info('%d-th final random weights: %s' % (seed, ' '.join(str(w) for w in trainer.learner.current.w)))
logger.info('IR score: %f' % ir_score)
ir_scores.append(Config(trainer.learner.current.w, ir_score))
ir_scores.sort(key=itemgetter(-1))
weight = ir_scores[-1].weight
score = ir_scores[-1].score
logger.info('Chosen weights: %s, IR score: %f' % (' '.join(str(w) for w in weight), score))
return weight
def cross_validation_mart(args, loss, ir):
train_data = load_dataset(args.train)
validate_data = None
if args.validate is not None:
validate_data = load_dataset(args.validate)
Config = namedtuple(
'Config', ['learning_rate', 'max_depth', 'num_step', 'score'])
logger.info('[Cross-validation] starting...')
grid_search = []
for learning_rate in args.cv_learning_rates:
for max_depth in range(1, args.max_depth + 1):
ir_scores = []
folds = split_dataset(train_data, validate_data, args.kfold)
for training, validation in folds:
if args.normalizer == "mean_std":
normalizer = ranklearning.meanstd_normalizer(
training.features())
else:
normalizer = ranklearning.minmax_normalizer(
training.features())
for query in training.queries:
query.features = normalizer(query.features)
for query in validation.queries:
query.features = normalizer(query.features)
learner = ranklearning.BoostedTreeLearner(
training.queries,
use_sklearn_trees=args.use_sklearn_trees,
max_depth=max_depth,
min_samples_leaf=args.min_samples_leaf)
trainer = ranklearning.IRTrainer(
training.queries,
learner, loss, ir,
seed_rate=learning_rate)
fold_scores = []
for i in range(args.num_steps):
trainer.step()
ir_score = ranklearning.compute_dataset_irscore(
validation.queries, trainer.learner.current,
trainer.ir)
n = len(ir_scores) + 1
info = '[Cross-validation] '
info += '(split %d of %d) ' % (n, args.kfold)
info += 'score: %f, ' % ir_score
info += 'learning_rate: %f, ' % learning_rate
info += 'max_depth: %d, step: %d' % (max_depth, i)
logger.debug(info)
fold_scores.append(ir_score)
ir_scores.append(fold_scores)
ir_scores = np.asarray(ir_scores)
ir_scores = np.mean(ir_scores, axis=0)
grid_search.extend([Config(learning_rate, max_depth, i, score)
for i, score in enumerate(ir_scores)])
#
# Plotting
#
directory = os.path.join(args.root, args.base)
if not os.path.exists(directory):
os.makedirs(directory)
# Plot the best performance for each max_depth
scores = []
for i in range(1, args.max_depth + 1):
candidates = filter(lambda x: x.max_depth == i, grid_search)
scores.append(max(candidates, key=lambda x: x.score).score)
plt.clf()
plt.subplot2grid((1, 3), (0, 0), colspan=2) # make space for legend
plt.plot(scores, 'ro', label='Best ir score for each max_depth')
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.xlabel('max depth')
plt.ylabel('ndcg')
filename = os.path.join(args.root, args.base, 'cv-max_depth.pdf')
plt.savefig(filename)
# Plot model performance as a function of number of iterations
plt.clf()
num_learning_rates = len(args.cv_learning_rates)
for i, l in enumerate(args.cv_learning_rates):
ax = plt.subplot2grid((num_learning_rates, 3), (i, 0), colspan=2)
ax.set_title('learning_rate: %f' % l)
for d in range(1, args.max_depth + 1):
candidates = filter(lambda x: x.learning_rate == l
and x.max_depth == d, grid_search)
scores = [c.score for c in candidates]
ax.plot(scores, label=('max_depth=%d' % d))
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
ax.set_ylabel('ndcg')
plt.xlabel('iteration')
filename = os.path.join(args.root, args.base, 'cv-iteration.pdf')
plt.savefig(filename)
#
# Find the best config
#
grid_search.sort(key=itemgetter(-1))
best_config = grid_search[::-1][0]
info = divider + '\n'
info += '[Cross-validation] '
info += 'Best setup: learning_rate: %f, ' % best_config.learning_rate
info += 'max_depth: %d,' % best_config.max_depth
info += 'step: %d. IR-score: %f' % (best_config.num_step, best_config.score)
info += '\n[Cross-validation] Using this configuration for training\n'
info += divider + '\n'
logger.info(info)
return (best_config.learning_rate,
best_config.max_depth, best_config.num_step)
if __name__ == '__main__':
main()
| [
"kite.ranking.ranklearning.Rbf",
"argparse.ArgumentParser",
"matplotlib.pyplot.clf",
"kite.ranking.ranklearning.LinearRankLearner",
"matplotlib.pyplot.subplot2grid",
"logging.getLogger",
"numpy.mean",
"os.path.join",
"subprocess.check_call",
"kite.ranking.ranklearning.Dataset",
"kite.ranking.ran... | [((377, 398), 'logging.StreamHandler', 'StreamHandler', (['stdout'], {}), '(stdout)\n', (390, 398), False, 'from logging import getLogger, DEBUG, INFO, StreamHandler\n'), ((408, 419), 'logging.getLogger', 'getLogger', ([], {}), '()\n', (417, 419), False, 'from logging import getLogger, DEBUG, INFO, StreamHandler\n'), ((1567, 1658), 'kite.ranking.ranklearning.Dataset', 'ranklearning.Dataset', (["train_data['FeatureLabels']", 'data', "train_data['FeaturerOptions']"], {}), "(train_data['FeatureLabels'], data, train_data[\n 'FeaturerOptions'])\n", (1587, 1658), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((1705, 1730), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1728, 1730), False, 'import argparse\n'), ((9941, 9961), 'numpy.array', 'np.array', (['train_loss'], {}), '(train_loss)\n', (9949, 9961), True, 'import numpy as np\n'), ((9978, 9997), 'numpy.array', 'np.array', (['test_loss'], {}), '(test_loss)\n', (9986, 9997), True, 'import numpy as np\n'), ((10014, 10032), 'numpy.array', 'np.array', (['train_ir'], {}), '(train_ir)\n', (10022, 10032), True, 'import numpy as np\n'), ((10047, 10064), 'numpy.array', 'np.array', (['test_ir'], {}), '(test_ir)\n', (10055, 10064), True, 'import numpy as np\n'), ((10146, 10180), 'os.path.join', 'os.path.join', (['args.root', 'args.base'], {}), '(args.root, args.base)\n', (10158, 10180), False, 'import os\n'), ((11841, 11889), 'os.path.join', 'os.path.join', (['args.root', 'args.base', '"""model.json"""'], {}), "(args.root, args.base, 'model.json')\n", (11853, 11889), False, 'import os\n'), ((12800, 12809), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (12807, 12809), True, 'import matplotlib.pyplot as plt\n'), ((12814, 12857), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(1, 3)', '(0, 0)'], {'colspan': '(2)'}), '((1, 3), (0, 0), colspan=2)\n', (12830, 12857), True, 'import matplotlib.pyplot as plt\n'), ((12887, 12925), 'matplotlib.pyplot.plot', 'plt.plot', (['train_loss'], {'label': '"""training"""'}), "(train_loss, label='training')\n", (12895, 12925), True, 'import matplotlib.pyplot as plt\n'), ((13003, 13065), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'bbox_to_anchor': '(1.05, 1)', 'loc': '(2)', 'borderaxespad': '(0.0)'}), '(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0)\n', (13013, 13065), True, 'import matplotlib.pyplot as plt\n'), ((13069, 13094), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""iteration #"""'], {}), "('iteration #')\n", (13079, 13094), True, 'import matplotlib.pyplot as plt\n'), ((13099, 13126), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Loss fucntion"""'], {}), "('Loss fucntion')\n", (13109, 13126), True, 'import matplotlib.pyplot as plt\n'), ((13143, 13189), 'os.path.join', 'os.path.join', (['args.root', 'args.base', '"""loss.pdf"""'], {}), "(args.root, args.base, 'loss.pdf')\n", (13155, 13189), False, 'import os\n'), ((13194, 13215), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename)\n', (13205, 13215), True, 'import matplotlib.pyplot as plt\n'), ((13271, 13280), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (13278, 13280), True, 'import matplotlib.pyplot as plt\n'), ((13285, 13328), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(1, 3)', '(0, 0)'], {'colspan': '(2)'}), '((1, 3), (0, 0), colspan=2)\n', (13301, 13328), True, 'import matplotlib.pyplot as plt\n'), ((13358, 13394), 'matplotlib.pyplot.plot', 'plt.plot', (['train_ir'], {'label': '"""training"""'}), "(train_ir, label='training')\n", (13366, 13394), True, 'import matplotlib.pyplot as plt\n'), ((13470, 13532), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'bbox_to_anchor': '(1.05, 1)', 'loc': '(2)', 'borderaxespad': '(0.0)'}), '(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0)\n', (13480, 13532), True, 'import matplotlib.pyplot as plt\n'), ((13536, 13561), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""iteration #"""'], {}), "('iteration #')\n", (13546, 13561), True, 'import matplotlib.pyplot as plt\n'), ((13566, 13590), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""IR measure"""'], {}), "('IR measure')\n", (13576, 13590), True, 'import matplotlib.pyplot as plt\n'), ((13607, 13653), 'os.path.join', 'os.path.join', (['args.root', 'args.base', '"""ndcg.pdf"""'], {}), "(args.root, args.base, 'ndcg.pdf')\n", (13619, 13653), False, 'import os\n'), ((13658, 13679), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename)\n', (13669, 13679), True, 'import matplotlib.pyplot as plt\n'), ((15217, 15258), 'collections.namedtuple', 'namedtuple', (['"""Config"""', "['weight', 'score']"], {}), "('Config', ['weight', 'score'])\n", (15227, 15258), False, 'from collections import namedtuple\n'), ((16963, 17036), 'collections.namedtuple', 'namedtuple', (['"""Config"""', "['learning_rate', 'max_depth', 'num_step', 'score']"], {}), "('Config', ['learning_rate', 'max_depth', 'num_step', 'score'])\n", (16973, 17036), False, 'from collections import namedtuple\n'), ((19387, 19421), 'os.path.join', 'os.path.join', (['args.root', 'args.base'], {}), '(args.root, args.base)\n', (19399, 19421), False, 'import os\n'), ((19744, 19753), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (19751, 19753), True, 'import matplotlib.pyplot as plt\n'), ((19758, 19801), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(1, 3)', '(0, 0)'], {'colspan': '(2)'}), '((1, 3), (0, 0), colspan=2)\n', (19774, 19801), True, 'import matplotlib.pyplot as plt\n'), ((19831, 19895), 'matplotlib.pyplot.plot', 'plt.plot', (['scores', '"""ro"""'], {'label': '"""Best ir score for each max_depth"""'}), "(scores, 'ro', label='Best ir score for each max_depth')\n", (19839, 19895), True, 'import matplotlib.pyplot as plt\n'), ((19901, 19963), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'bbox_to_anchor': '(1.05, 1)', 'loc': '(2)', 'borderaxespad': '(0.0)'}), '(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0)\n', (19911, 19963), True, 'import matplotlib.pyplot as plt\n'), ((19967, 19990), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""max depth"""'], {}), "('max depth')\n", (19977, 19990), True, 'import matplotlib.pyplot as plt\n'), ((19995, 20013), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""ndcg"""'], {}), "('ndcg')\n", (20005, 20013), True, 'import matplotlib.pyplot as plt\n'), ((20030, 20084), 'os.path.join', 'os.path.join', (['args.root', 'args.base', '"""cv-max_depth.pdf"""'], {}), "(args.root, args.base, 'cv-max_depth.pdf')\n", (20042, 20084), False, 'import os\n'), ((20089, 20110), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename)\n', (20100, 20110), True, 'import matplotlib.pyplot as plt\n'), ((20183, 20192), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (20190, 20192), True, 'import matplotlib.pyplot as plt\n'), ((20806, 20829), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""iteration"""'], {}), "('iteration')\n", (20816, 20829), True, 'import matplotlib.pyplot as plt\n'), ((20846, 20900), 'os.path.join', 'os.path.join', (['args.root', 'args.base', '"""cv-iteration.pdf"""'], {}), "(args.root, args.base, 'cv-iteration.pdf')\n", (20858, 20900), False, 'import os\n'), ((20905, 20926), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename)\n', (20916, 20926), True, 'import matplotlib.pyplot as plt\n'), ((611, 623), 'json.load', 'json.load', (['f'], {}), '(f)\n', (620, 623), False, 'import json\n'), ((1354, 1455), 'kite.ranking.ranklearning.Query', 'ranklearning.Query', (['queries[hash_id]', 'features[hash_id]', 'relevance[hash_id]', 'example_ids[hash_id]'], {}), '(queries[hash_id], features[hash_id], relevance[hash_id],\n example_ids[hash_id])\n', (1372, 1455), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((3765, 3789), 'kite.ranking.ranklearning.HingeLoss', 'ranklearning.HingeLoss', ([], {}), '()\n', (3787, 3789), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((4095, 4127), 'kite.ranking.ranklearning.NDCG', 'ranklearning.NDCG', ([], {'cutoff': 'args.t'}), '(cutoff=args.t)\n', (4112, 4127), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((7217, 7270), 'kite.ranking.ranklearning.LinearRankLearner', 'ranklearning.LinearRankLearner', (['weight', 'train_data.nd'], {}), '(weight, train_data.nd)\n', (7247, 7270), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((8487, 8584), 'kite.ranking.ranklearning.compute_dataset_irscore', 'ranklearning.compute_dataset_irscore', (['train_data.queries', 'trainer.learner.current', 'ir_scorer'], {}), '(train_data.queries, trainer.learner.\n current, ir_scorer)\n', (8523, 8584), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((8853, 8950), 'kite.ranking.ranklearning.compute_dataset_loss', 'ranklearning.compute_dataset_loss', (['train_data.queries', 'trainer.learner.current', 'trainer.loss'], {}), '(train_data.queries, trainer.learner.\n current, trainer.loss)\n', (8886, 8950), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((10192, 10217), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (10206, 10217), False, 'import os\n'), ((10227, 10249), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (10238, 10249), False, 'import os\n'), ((10297, 10352), 'os.path.join', 'os.path.join', (['args.root', 'args.base', '"""test-results.json"""'], {}), "(args.root, args.base, 'test-results.json')\n", (10309, 10352), False, 'import os\n'), ((12658, 12678), 'json.dump', 'json.dump', (['ranker', 'f'], {}), '(ranker, f)\n', (12667, 12678), False, 'import json\n'), ((12964, 12997), 'matplotlib.pyplot.plot', 'plt.plot', (['test_loss'], {'label': '"""test"""'}), "(test_loss, label='test')\n", (12972, 12997), True, 'import matplotlib.pyplot as plt\n'), ((13433, 13464), 'matplotlib.pyplot.plot', 'plt.plot', (['test_ir'], {'label': '"""test"""'}), "(test_ir, label='test')\n", (13441, 13464), True, 'import matplotlib.pyplot as plt\n'), ((15710, 15747), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'train_data.nd'}), '(size=train_data.nd)\n', (15727, 15747), True, 'import numpy as np\n'), ((15766, 15819), 'kite.ranking.ranklearning.LinearRankLearner', 'ranklearning.LinearRankLearner', (['weight', 'train_data.nd'], {}), '(weight, train_data.nd)\n', (15796, 15819), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((15838, 15934), 'kite.ranking.ranklearning.IRTrainer', 'ranklearning.IRTrainer', (['train_data.queries', 'learner', 'loss', 'ir'], {'seed_rate': 'args.learning_rate'}), '(train_data.queries, learner, loss, ir, seed_rate=\n args.learning_rate)\n', (15860, 15934), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((19433, 19458), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (19447, 19458), False, 'import os\n'), ((19468, 19490), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (19479, 19490), False, 'import os\n'), ((20310, 20370), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(num_learning_rates, 3)', '(i, 0)'], {'colspan': '(2)'}), '((num_learning_rates, 3), (i, 0), colspan=2)\n', (20326, 20370), True, 'import matplotlib.pyplot as plt\n'), ((3853, 3884), 'kite.ranking.ranklearning.CrossEntropyLoss', 'ranklearning.CrossEntropyLoss', ([], {}), '()\n', (3882, 3884), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((7933, 8026), 'kite.ranking.ranklearning.FullLossTrainer', 'ranklearning.FullLossTrainer', (['train_data.queries', 'learner', 'loss'], {'seed_rate': 'learning_rate'}), '(train_data.queries, learner, loss, seed_rate=\n learning_rate)\n', (7961, 8026), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((8075, 8166), 'kite.ranking.ranklearning.IRTrainer', 'ranklearning.IRTrainer', (['train_data.queries', 'learner', 'loss', 'ir'], {'seed_rate': 'learning_rate'}), '(train_data.queries, learner, loss, ir, seed_rate=\n learning_rate)\n', (8097, 8166), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((8398, 8417), 'kite.ranking.ranklearning.NDCG', 'ranklearning.NDCG', ([], {}), '()\n', (8415, 8417), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((8685, 8781), 'kite.ranking.ranklearning.compute_dataset_irscore', 'ranklearning.compute_dataset_irscore', (['test_data.queries', 'trainer.learner.current', 'ir_scorer'], {}), '(test_data.queries, trainer.learner.\n current, ir_scorer)\n', (8721, 8781), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((9058, 9154), 'kite.ranking.ranklearning.compute_dataset_loss', 'ranklearning.compute_dataset_loss', (['test_data.queries', 'trainer.learner.current', 'trainer.loss'], {}), '(test_data.queries, trainer.learner.\n current, trainer.loss)\n', (9091, 9154), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((10988, 11026), 'kite.ranking.ranklearning.ranks_from_scores', 'ranklearning.ranks_from_scores', (['scores'], {}), '(scores)\n', (11018, 11026), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((11059, 11106), 'kite.ranking.ranklearning.ranks_from_scores', 'ranklearning.ranks_from_scores', (['query.relevance'], {}), '(query.relevance)\n', (11089, 11106), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((11735, 11756), 'json.dump', 'json.dump', (['payload', 'f'], {}), '(payload, f)\n', (11744, 11756), False, 'import json\n'), ((16057, 16155), 'kite.ranking.ranklearning.compute_dataset_irscore', 'ranklearning.compute_dataset_irscore', (['train_data.queries', 'trainer.learner.current', 'trainer.ir'], {}), '(train_data.queries, trainer.learner.\n current, trainer.ir)\n', (16093, 16155), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((16554, 16568), 'operator.itemgetter', 'itemgetter', (['(-1)'], {}), '(-1)\n', (16564, 16568), False, 'from operator import itemgetter\n'), ((19123, 19144), 'numpy.asarray', 'np.asarray', (['ir_scores'], {}), '(ir_scores)\n', (19133, 19144), True, 'import numpy as np\n'), ((19169, 19195), 'numpy.mean', 'np.mean', (['ir_scores'], {'axis': '(0)'}), '(ir_scores, axis=0)\n', (19176, 19195), True, 'import numpy as np\n'), ((20993, 21007), 'operator.itemgetter', 'itemgetter', (['(-1)'], {}), '(-1)\n', (21003, 21007), False, 'from operator import itemgetter\n'), ((7162, 7198), 'numpy.zeros', 'np.zeros', (['train_data.nd'], {'dtype': 'float'}), '(train_data.nd, dtype=float)\n', (7170, 7198), True, 'import numpy as np\n'), ((7551, 7705), 'kite.ranking.ranklearning.BoostedTreeLearner', 'ranklearning.BoostedTreeLearner', (['train_data.queries'], {'use_sklearn_trees': 'args.use_sklearn_trees', 'max_depth': 'max_depth', 'min_samples_leaf': 'min_samples_leaf'}), '(train_data.queries, use_sklearn_trees=args.\n use_sklearn_trees, max_depth=max_depth, min_samples_leaf=min_samples_leaf)\n', (7582, 7705), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((11268, 11287), 'kite.ranking.ranklearning.NDCG', 'ranklearning.NDCG', ([], {}), '()\n', (11285, 11287), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((14098, 14173), 'sklearn.tree.export_graphviz', 'export_graphviz', (['t.tree'], {'out_file': 'f', 'feature_names': 'train_data.featurelabels'}), '(t.tree, out_file=f, feature_names=train_data.featurelabels)\n', (14113, 14173), False, 'from sklearn.tree import export_graphviz\n'), ((14307, 14337), 'subprocess.check_call', 'subprocess.check_call', (['command'], {}), '(command)\n', (14328, 14337), False, 'import subprocess\n'), ((17915, 18077), 'kite.ranking.ranklearning.BoostedTreeLearner', 'ranklearning.BoostedTreeLearner', (['training.queries'], {'use_sklearn_trees': 'args.use_sklearn_trees', 'max_depth': 'max_depth', 'min_samples_leaf': 'args.min_samples_leaf'}), '(training.queries, use_sklearn_trees=args.\n use_sklearn_trees, max_depth=max_depth, min_samples_leaf=args.\n min_samples_leaf)\n', (17946, 18077), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((18176, 18265), 'kite.ranking.ranklearning.IRTrainer', 'ranklearning.IRTrainer', (['training.queries', 'learner', 'loss', 'ir'], {'seed_rate': 'learning_rate'}), '(training.queries, learner, loss, ir, seed_rate=\n learning_rate)\n', (18198, 18265), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((7393, 7415), 'kite.ranking.ranklearning.Rbf', 'ranklearning.Rbf', (['(-1.0)'], {}), '(-1.0)\n', (7409, 7415), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((18470, 18568), 'kite.ranking.ranklearning.compute_dataset_irscore', 'ranklearning.compute_dataset_irscore', (['validation.queries', 'trainer.learner.current', 'trainer.ir'], {}), '(validation.queries, trainer.learner.\n current, trainer.ir)\n', (18506, 18568), True, 'import kite.ranking.ranklearning as ranklearning\n'), ((14813, 14837), 'operator.itemgetter', 'itemgetter', (['*train_index'], {}), '(*train_index)\n', (14823, 14837), False, 'from operator import itemgetter\n'), ((15019, 15046), 'operator.itemgetter', 'itemgetter', (['*validate_index'], {}), '(*validate_index)\n', (15029, 15046), False, 'from operator import itemgetter\n')] |
from __future__ import print_function, absolute_import, division
import glob
import os
import numpy as np
from .utils import expand_path
class BaseDatasetLoader(object):
short_name = None
def load(self):
raise NotImplementedError('should be implemented in subclass')
class MSMBuilderDatasetLoader(BaseDatasetLoader):
short_name = 'msmbuilder'
def __init__(self, path, fmt=None, verbose=False):
self.path = path
self.fmt = fmt
self.verbose = verbose
def load(self):
from msmbuilder.dataset import dataset
ds = dataset(self.path, mode='r', fmt=self.fmt, verbose=self.verbose)
print('Dataset provenance:\n')
print(ds.provenance)
return ds, None
class NumpyDatasetLoader(BaseDatasetLoader):
short_name = 'numpy'
def __init__(self, filenames):
self.filenames = filenames
def load(self):
filenames = sorted(glob.glob(expand_path(self.filenames)))
if len(filenames) == 0:
raise RuntimeError('no filenames matched by pattern: %s' %
self.filenames)
ds = [np.load(f) for f in filenames]
return ds, None
class MDTrajDatasetLoader(BaseDatasetLoader):
short_name = 'mdtraj'
def __init__(self, trajectories, topology=None, stride=1, verbose=False):
self.trajectories = trajectories
self.topology = topology
self.stride = stride
self.verbose = verbose
def load(self):
import mdtraj
filenames = sorted(glob.glob(expand_path(self.trajectories)))
if len(filenames) == 0:
raise RuntimeError('no filenames matched by pattern: %s' %
self.trajectories)
top = self.topology
kwargs = {}
if top is not None:
top = expand_path(self.topology)
kwargs = {'top': top}
X = []
y = None
for fn in filenames:
if self.verbose:
print('[mdtraj] loading %s' % fn)
X.append(mdtraj.load(fn, stride=self.stride, **kwargs))
return X, y
class FilenameDatasetLoader(BaseDatasetLoader):
"""Just pass a bunch of filenames to the first step of the pipeline
The pipeline will do the loading.
"""
short_name = 'filename'
def __init__(self, trajectories, abs_path=True):
self.traj_glob = trajectories
self.abs_path = abs_path
def load(self):
filenames = sorted(glob.glob(expand_path(self.traj_glob)))
if len(filenames) == 0:
raise RuntimeError('no filenames matched by pattern: %s' %
self.traj_glob)
if self.abs_path:
filenames = [os.path.abspath(fn) for fn in filenames]
return filenames, None
class JoblibDatasetLoader(BaseDatasetLoader):
short_name = 'joblib'
def __init__(self, filenames, x_name=None, y_name=None,
system_joblib=False):
self.filenames = filenames
self.x_name = x_name
self.y_name = y_name
self.system_joblib = system_joblib
def load(self):
if self.system_joblib:
import joblib
else:
from sklearn.externals import joblib
X, y = [], []
filenames = sorted(glob.glob(expand_path(self.filenames)))
if len(filenames) == 0:
raise RuntimeError('no filenames matched by pattern: %s' %
self.filenames)
for fn in filenames:
obj = joblib.load(fn)
if isinstance(obj, (list, np.ndarray)):
X.append(obj)
else:
X.append(obj[self.x_name])
y.append(obj[self.y_name])
if len(X) == 1:
X = X[0]
if len(y) == 1:
y = y[0]
elif len(y) == 0:
y = None
return X, y
class SklearnDatasetLoader(BaseDatasetLoader):
short_name = 'sklearn_dataset'
def __init__(self, method, x_name='data', y_name='target', **kwargs):
self.method = method
self.x_name = x_name
self.y_name = y_name
self.kwargs = kwargs
def load(self):
import sklearn.datasets
try:
loader = getattr(sklearn.datasets, self.method)
except AttributeError:
raise RuntimeError('no %s in sklearn.datasets' % self.method)
bunch = loader(**self.kwargs)
X = bunch[self.x_name]
y = bunch[self.y_name]
return X, y
| [
"os.path.abspath",
"numpy.load",
"mdtraj.load",
"sklearn.externals.joblib.load",
"msmbuilder.dataset.dataset"
] | [((585, 649), 'msmbuilder.dataset.dataset', 'dataset', (['self.path'], {'mode': '"""r"""', 'fmt': 'self.fmt', 'verbose': 'self.verbose'}), "(self.path, mode='r', fmt=self.fmt, verbose=self.verbose)\n", (592, 649), False, 'from msmbuilder.dataset import dataset\n'), ((1137, 1147), 'numpy.load', 'np.load', (['f'], {}), '(f)\n', (1144, 1147), True, 'import numpy as np\n'), ((3557, 3572), 'sklearn.externals.joblib.load', 'joblib.load', (['fn'], {}), '(fn)\n', (3568, 3572), False, 'from sklearn.externals import joblib\n'), ((2065, 2110), 'mdtraj.load', 'mdtraj.load', (['fn'], {'stride': 'self.stride'}), '(fn, stride=self.stride, **kwargs)\n', (2076, 2110), False, 'import mdtraj\n'), ((2745, 2764), 'os.path.abspath', 'os.path.abspath', (['fn'], {}), '(fn)\n', (2760, 2764), False, 'import os\n')] |
import numpy as np
import unittest
import xarray as xr
import xinterp
da_2d_real = xr.DataArray(
np.array(((0, 0.5, 1), (1, 1.5, 2))),
coords={'x': [0, 1], 'y': [0, 0.5, 1]},
dims=('x', 'y')
)
da_2d_singular = xr.DataArray(
np.array(((0, 0.5, 1), )),
coords={'x': [0, ], 'y': [0, 0.5, 1]},
dims=('x', 'y')
)
class Test2DInterp(unittest.TestCase):
def test_2d_real_within_bounds(self):
result = da_2d_real.interp.interpnd(x=[0, 0.5, 1], y=[0, 0.25, 0.5, 0.75, 1])
xr.testing.assert_equal(
result,
xr.DataArray(
np.array([[ 0. , 0.25, 0.5 , 0.75, 1. ],
[ 0.5 , 0.75, 1. , 1.25, 1.5 ],
[ 1. , 1.25, 1.5 , 1.75, 2. ]]),
coords={
'x': [0, 0.5, 1],
'y': [0, 0.25, 0.5, 0.75, 1]
},
dims=('x', 'y'),
)
)
def test_2d_real_outside_bounds(self):
# Extrapolate outside the bounds
result = da_2d_real.interp.interpnd(x=[0, 1], y=[-0.1, 0.5, 1.1], bounds_error=False)
xr.testing.assert_allclose(
result,
xr.DataArray(
np.array([[-0.1, 0.5, 1.1],
[0.9, 1.5, 2.1]]),
coords={
'x': [0, 1],
'y': [-0.1, 0.5, 1.1]
},
dims=('x', 'y'),
)
)
# Fill value outside the bounds
result = da_2d_real.interp.interpnd(x=[0, 1], y=[-0.1, 0.5, 1.1], bounds_error=False, fill_value=-100)
xr.testing.assert_allclose(
result,
xr.DataArray(
np.array([[-100, 0.5, -100],
[-100, 1.5, -100]]),
coords={
'x': [0, 1],
'y': [-0.1, 0.5, 1.1]
},
dims=('x', 'y'),
)
)
# Throw an error if the bounds are exceeded
self.assertRaises(ValueError, da_2d_real.interp.interpnd, x=[0, 1], y=[-0.1, 0.5, 1.1], bounds_error=True)
def test_2d_real_complex(self):
pass
def test_2d_extra_dimensions(self):
result = da_2d_singular.interp.interpnd(x=[0, 1], y=[0, 0.5, 1], z=[0, 1])
xr.testing.assert_equal(
result,
xr.DataArray(
np.array([[[0., 0.],
[0.5, 0.5],
[1., 1.]],
[[0., 0.],
[0.5, 0.5],
[1., 1.]]]),
coords={
'x': [0, 1],
'y': [0, 0.5, 1.0],
'z': [0, 1],
},
dims=('x', 'y', 'z'),
)
)
def test_2d_underdimensioned(self):
# TODO: Implemenet this case in xinterp!
result = da_2d_real.interp.interpnd(x=[0, 1])
xr.testing.assert_equal(
result,
xr.DataArray(
np.array(((0, 0.5, 1), (1, 1.5, 2))),
coords={
'x': [0, 1],
'y': [0, 0.5, 1]
},
dims=('x', 'y'),
)
)
| [
"numpy.array"
] | [((102, 138), 'numpy.array', 'np.array', (['((0, 0.5, 1), (1, 1.5, 2))'], {}), '(((0, 0.5, 1), (1, 1.5, 2)))\n', (110, 138), True, 'import numpy as np\n'), ((242, 266), 'numpy.array', 'np.array', (['((0, 0.5, 1),)'], {}), '(((0, 0.5, 1),))\n', (250, 266), True, 'import numpy as np\n'), ((610, 712), 'numpy.array', 'np.array', (['[[0.0, 0.25, 0.5, 0.75, 1.0], [0.5, 0.75, 1.0, 1.25, 1.5], [1.0, 1.25, 1.5,\n 1.75, 2.0]]'], {}), '([[0.0, 0.25, 0.5, 0.75, 1.0], [0.5, 0.75, 1.0, 1.25, 1.5], [1.0, \n 1.25, 1.5, 1.75, 2.0]])\n', (618, 712), True, 'import numpy as np\n'), ((1282, 1327), 'numpy.array', 'np.array', (['[[-0.1, 0.5, 1.1], [0.9, 1.5, 2.1]]'], {}), '([[-0.1, 0.5, 1.1], [0.9, 1.5, 2.1]])\n', (1290, 1327), True, 'import numpy as np\n'), ((1780, 1828), 'numpy.array', 'np.array', (['[[-100, 0.5, -100], [-100, 1.5, -100]]'], {}), '([[-100, 0.5, -100], [-100, 1.5, -100]])\n', (1788, 1828), True, 'import numpy as np\n'), ((2468, 2559), 'numpy.array', 'np.array', (['[[[0.0, 0.0], [0.5, 0.5], [1.0, 1.0]], [[0.0, 0.0], [0.5, 0.5], [1.0, 1.0]]]'], {}), '([[[0.0, 0.0], [0.5, 0.5], [1.0, 1.0]], [[0.0, 0.0], [0.5, 0.5], [\n 1.0, 1.0]]])\n', (2476, 2559), True, 'import numpy as np\n'), ((3145, 3181), 'numpy.array', 'np.array', (['((0, 0.5, 1), (1, 1.5, 2))'], {}), '(((0, 0.5, 1), (1, 1.5, 2)))\n', (3153, 3181), True, 'import numpy as np\n')] |
import itertools
import functools
import numpy as np
import pandas as pd
import pickle
from scipy import integrate
import scipy.optimize
import timeit
import global_PATHs
from dataset_handling import filter_dataset, prepare_data
from PINN_RK import PinnModel
from power_system_functions import create_system_matrices, ode_right_hand_side_solve, create_SMIB_system
from read_runge_kutta_parameters import read_runge_kutta_parameters
# --------------------------
# Timing function to compare the performance of RK-PINNs versus classical implicit and explicit solution schemes,
# used to produce the results shown in the paper.
# --------------------------
# Implementation to solve the full implicit Runge-Kutta scheme
def solve_RK_stages(x_init,
delta_t,
u,
kM_init,
n_runge_kutta_stages,
IRK_alpha,
IRK_beta,
A, B, C, D, F, ):
Resid_P = functools.partial(RK_residual,
x_0=x_init,
delta_t=delta_t,
u=u,
n_runge_kutta_stages=n_runge_kutta_stages,
IRK_alpha=IRK_alpha, A=A, B=B,
C=C, D=D,
F=F)
h_RK = scipy.optimize.newton_krylov(Resid_P, kM_init, f_tol=1.0e-13, verbose=False)
x_prediction = x_init.reshape((-1, 1)) + delta_t * (h_RK @ IRK_beta.T)
return x_prediction
def RK_residual(h_k, x_0, delta_t, u, n_runge_kutta_stages, IRK_alpha, A, B, C, D, F):
x_0_extended = np.repeat(x_0.reshape((-1, 1)), repeats=n_runge_kutta_stages, axis=1)
u_extended = np.repeat(u.reshape((-1, 1)), repeats=n_runge_kutta_stages, axis=1)
x_adjusted = x_0_extended + delta_t * (h_k @ IRK_alpha.T)
FCX = D @ np.sin(C @ x_adjusted)
f_h_k = A @ x_adjusted + F @ FCX + B @ u_extended
return h_k - f_h_k
def solve_mapped_RK(solver_func_RK, x_init, delta_t, u, kM_init):
solver_results = map(solver_func_RK, x_init, delta_t, u, kM_init)
list_solver_results = list(solver_results)
states_results = np.concatenate([single_solver_result.T for single_solver_result in list_solver_results], axis=0)
return states_results
# --------------------------
# functions to run integration schemes implemented in scipy.integrate
def solve_ode(t_span,
t_eval,
states_initial,
u, A, B, C, D, F,
tolerance=2.3e-14,
method='RK45'):
ode_solution = integrate.solve_ivp(ode_right_hand_side_solve,
t_span=t_span,
y0=states_initial.flatten(),
args=[u, A, B, C, D, F],
t_eval=t_eval,
rtol=tolerance,
method=method)
return ode_solution.y
def solve_mapped_ode(solver_func, t_span, t_eval, states_initial, u):
solver_results = map(solver_func, t_span, t_eval, states_initial, u)
list_solver_results = list(solver_results)
states_results = np.concatenate([single_solver_result.T for single_solver_result in list_solver_results], axis=0)
return states_results
# --------------------------
with open(global_PATHs.PATH_datasets / 'complete_dataset.pickle', "rb") as f:
complete_data = pickle.load(f)
power_system = create_SMIB_system()
A, B, C, D, F, G, u_0, x_0 = create_system_matrices(power_system=power_system)
# timing function parameters: repetitions is within each execution, and repeats is the number of executions of the
# timit command.
n_repetitions = 20
n_repeats = 5
# values to explore for the time steps and the number of Runge-Kutta stages in the different schemes
time_steps_list = np.array([0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0])
n_runge_kutta_stages_list = list([4, 32])
# list to store all results
result_dict_list = list()
# time various implicit Runge-Kutta (IRK) methods
for time_step, n_runge_kutta_stages in itertools.product(time_steps_list, n_runge_kutta_stages_list):
delta_t = time_step
indices_time_steps = np.isin(np.around(complete_data['time'][:, 0], decimals=5), time_step)
dataset_filtered_pre = filter_dataset(dataset=complete_data, filter_indices=indices_time_steps)
indices_single = np.zeros(51, dtype=bool)
indices_single[0::5] = True
indices_reduced_dataset_power = np.logical_and(np.repeat(indices_single, repeats=51),
np.tile(indices_single, 51))
dataset_filtered = filter_dataset(dataset=dataset_filtered_pre, filter_indices=indices_reduced_dataset_power)
states_initial = dataset_filtered['states_initial']
t_span = np.concatenate([dataset_filtered['time'] * 0,
dataset_filtered['time']], axis=1)
u_disturbance = dataset_filtered['power'] @ G.T
u = u_0.T + u_disturbance
t_eval = dataset_filtered["time"]
IRK_alpha, IRK_beta, IRK_gamma = read_runge_kutta_parameters(runge_kutta_stages=n_runge_kutta_stages)
x_init = states_initial
FCX = np.sin(x_init @ C.T) @ D.T
k0 = x_init @ A.T + FCX @ F.T + u @ B.T
xM = np.repeat(np.expand_dims(x_init, axis=2), repeats=n_runge_kutta_stages, axis=2)
kM = np.repeat(np.expand_dims(k0, axis=2), repeats=n_runge_kutta_stages, axis=2)
xM = xM + delta_t * kM @ np.diag(IRK_gamma.flatten())
xM_T = np.transpose(xM, axes=[0, 2, 1])
# Pass through f(x)
FCX_T = np.sin(xM_T @ C.T) @ D.T
kM_init_T = xM_T @ A.T + FCX_T @ F.T + np.expand_dims(u @ B.T, axis=1)
kM_init = np.transpose(kM_init_T, axes=[0, 2, 1])
solver_func_rk = functools.partial(solve_RK_stages,
n_runge_kutta_stages=n_runge_kutta_stages,
IRK_alpha=IRK_alpha,
IRK_beta=IRK_beta,
A=A, B=B, C=C, D=D, F=F)
total_time_rk = timeit.repeat('solve_mapped_ode(solver_func_rk, x_init, t_eval, u, kM_init)',
number=n_repetitions,
repeat=n_repeats,
globals=globals(),
)
rk_results = solve_mapped_ode(solver_func_rk, x_init, t_eval, u, kM_init)
error_rk = rk_results - dataset_filtered['states_results']
print(f'Delta t = {time_step}s')
print(f'RK-{n_runge_kutta_stages}: {np.max(np.abs(error_rk))}')
print(f'RK-{n_runge_kutta_stages}: {min(total_time_rk) / n_repetitions / 121}s')
result_dict = {'method': 'IRK',
'n_runge_kutta_stages': n_runge_kutta_stages,
'time_step': time_step,
'time_min': min(total_time_rk) / n_repetitions / 121,
'max_error': np.max(np.abs(error_rk))}
result_dict_list.append(result_dict)
# time Radau method
for time_step in time_steps_list:
delta_t = time_step
indices_time_steps = np.isin(np.around(complete_data['time'][:, 0], decimals=5), time_step)
dataset_filtered_pre = filter_dataset(dataset=complete_data, filter_indices=indices_time_steps)
indices_single = np.zeros(51, dtype=bool)
indices_single[0::5] = True
indices_reduced_dataset_power = np.logical_and(np.repeat(indices_single, repeats=51),
np.tile(indices_single, 51))
dataset_filtered = filter_dataset(dataset=dataset_filtered_pre, filter_indices=indices_reduced_dataset_power)
states_initial = dataset_filtered['states_initial']
t_span = np.concatenate([dataset_filtered['time'] * 0,
dataset_filtered['time']], axis=1)
u_disturbance = dataset_filtered['power'] @ G.T
u = u_0.T + u_disturbance
t_eval = dataset_filtered["time"]
solver_func_radau = functools.partial(solve_ode, A=A, B=B, C=C, D=D, F=F, method='Radau')
total_time_radau = timeit.repeat('solve_mapped_ode(solver_func_radau, t_span, t_eval, states_initial, u)',
number=n_repetitions,
repeat=n_repeats,
globals=globals(),
)
radau_results = solve_mapped_ode(solver_func_radau, t_span, t_eval, states_initial, u)
error_radau = radau_results - dataset_filtered['states_results']
print(f'Delta t = {time_step}s')
print(f'Radau: {np.max(np.abs(error_radau))}')
print(f'Radau: {min(total_time_radau) / n_repetitions / 121}')
result_dict = {'method': 'Radau',
'n_runge_kutta_stages': 1,
'time_step': time_step,
'time_min': min(total_time_radau) / n_repetitions / 121,
'max_error': np.max(np.abs(error_radau))}
result_dict_list.append(result_dict)
# time RK-45 method
for time_step in time_steps_list:
delta_t = time_step
indices_time_steps = np.isin(np.around(complete_data['time'][:, 0], decimals=5), time_step)
dataset_filtered_pre = filter_dataset(dataset=complete_data, filter_indices=indices_time_steps)
indices_single = np.zeros(51, dtype=bool)
indices_single[0::5] = True
indices_reduced_dataset_power = np.logical_and(np.repeat(indices_single, repeats=51),
np.tile(indices_single, 51))
dataset_filtered = filter_dataset(dataset=dataset_filtered_pre, filter_indices=indices_reduced_dataset_power)
states_initial = dataset_filtered['states_initial']
t_span = np.concatenate([dataset_filtered['time'] * 0,
dataset_filtered['time']], axis=1)
u_disturbance = dataset_filtered['power'] @ G.T
u = u_0.T + u_disturbance
t_eval = dataset_filtered["time"]
solver_func_rk45 = functools.partial(solve_ode, A=A, B=B, C=C, D=D, F=F, method='RK45')
total_time_rk45 = timeit.repeat('solve_mapped_ode(solver_func_rk45, t_span, t_eval, states_initial, u)',
number=n_repetitions,
repeat=n_repeats,
globals=globals(),
)
rk45_results = solve_mapped_ode(solver_func_rk45, t_span, t_eval, states_initial, u)
error_rk45 = rk45_results - dataset_filtered['states_results']
print(f'Delta t = {time_step}s')
print(f'RK45: {np.max(np.abs(error_rk45))}')
print(f'RK45: {min(total_time_rk45) / n_repetitions / 121}')
result_dict = {'method': 'RK45',
'n_runge_kutta_stages': 0,
'time_step': time_step,
'time_min': min(total_time_rk45) / n_repetitions / 121,
'max_error': np.max(np.abs(error_rk45))}
result_dict_list.append(result_dict)
# time a RK-PINN
for time_step, n_runge_kutta_stages in itertools.product(time_steps_list, n_runge_kutta_stages_list):
delta_t = time_step
model = PinnModel(neurons_in_hidden_layer=[50],
n_runge_kutta_stages=n_runge_kutta_stages,
power_system=power_system,
case='normal')
indices_time_steps = np.isin(np.around(complete_data['time'][:, 0], decimals=5), time_step)
dataset_filtered_pre = filter_dataset(dataset=complete_data, filter_indices=indices_time_steps)
indices_single = np.zeros(51, dtype=bool)
indices_single[0::5] = True
indices_reduced_dataset_power = np.logical_and(np.repeat(indices_single, repeats=51),
np.tile(indices_single, 51))
dataset_filtered = filter_dataset(dataset=dataset_filtered_pre, filter_indices=indices_reduced_dataset_power)
X_test, y_test = prepare_data(dataset_filtered, n_runge_kutta_stages=n_runge_kutta_stages, n_states=2)
total_time_PINN = timeit.repeat('model.predict(X_test)',
number=n_repetitions,
repeat=n_repeats,
globals=globals(),
)
error_PINN = model.predict(X_test) - dataset_filtered['states_results']
result_dict = {'method': 'PINN',
'n_runge_kutta_stages': n_runge_kutta_stages,
'time_step': time_step,
'time_min': min(total_time_PINN) / n_repetitions / 121,
'max_error': np.max(np.abs(error_PINN))}
print(f'Delta t = {time_step}s')
print(f'PINN: {np.max(np.abs(error_PINN))}')
print(f'PINN: {min(total_time_PINN) / n_repetitions / 121}')
result_dict_list.append(result_dict)
# time a larger PINN
for time_step, n_runge_kutta_stages in itertools.product(time_steps_list, n_runge_kutta_stages_list):
delta_t = time_step
model = PinnModel(neurons_in_hidden_layer=[500, 500, 500],
n_runge_kutta_stages=n_runge_kutta_stages,
power_system=power_system)
indices_time_steps = np.isin(np.around(complete_data['time'][:, 0], decimals=5), time_step)
dataset_filtered_pre = filter_dataset(dataset=complete_data, filter_indices=indices_time_steps)
indices_single = np.zeros(51, dtype=bool)
indices_single[0::5] = True
indices_reduced_dataset_power = np.logical_and(np.repeat(indices_single, repeats=51),
np.tile(indices_single, 51))
dataset_filtered = filter_dataset(dataset=dataset_filtered_pre, filter_indices=indices_reduced_dataset_power)
X_test, y_test = prepare_data(dataset_filtered, n_runge_kutta_stages=n_runge_kutta_stages, n_states=2)
total_time_PINN = timeit.repeat('model.predict(X_test)',
number=n_repetitions,
repeat=n_repeats,
globals=globals(),
)
error_PINN = model.predict(X_test) - dataset_filtered['states_results']
result_dict = {'method': 'PINN_larger',
'n_runge_kutta_stages': n_runge_kutta_stages,
'time_step': time_step,
'time_min': min(total_time_PINN) / n_repetitions / 121,
'max_error': np.max(np.abs(error_PINN))}
print(f'Delta t = {time_step}s')
print(f'PINN: {np.max(np.abs(error_PINN))}')
print(f'PINN: {min(total_time_PINN) / n_repetitions / 121}')
result_dict_list.append(result_dict)
# concatenate all results and write into a table
results = np.hstack([np.stack([element['method'] for element in result_dict_list]).reshape((-1, 1)),
np.stack([element['n_runge_kutta_stages'] for element in result_dict_list]).reshape((-1, 1)),
np.stack([element['time_step'] for element in result_dict_list]).reshape((-1, 1)),
np.stack([element['time_min'] for element in result_dict_list]).reshape((-1, 1)),
np.stack([element['max_error'] for element in result_dict_list]).reshape((-1, 1))])
results_pd = pd.DataFrame(results)
with open(global_PATHs.PATH_data / 'timing_metrics' / 'timing_table.pickle', 'wb') as f:
pickle.dump(results_pd, f)
| [
"pickle.dump",
"numpy.abs",
"power_system_functions.create_system_matrices",
"dataset_handling.filter_dataset",
"numpy.around",
"pickle.load",
"numpy.sin",
"numpy.tile",
"pandas.DataFrame",
"power_system_functions.create_SMIB_system",
"numpy.transpose",
"itertools.product",
"numpy.repeat",
... | [((3625, 3645), 'power_system_functions.create_SMIB_system', 'create_SMIB_system', ([], {}), '()\n', (3643, 3645), False, 'from power_system_functions import create_system_matrices, ode_right_hand_side_solve, create_SMIB_system\n'), ((3676, 3725), 'power_system_functions.create_system_matrices', 'create_system_matrices', ([], {'power_system': 'power_system'}), '(power_system=power_system)\n', (3698, 3725), False, 'from power_system_functions import create_system_matrices, ode_right_hand_side_solve, create_SMIB_system\n'), ((4020, 4066), 'numpy.array', 'np.array', (['[0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0]'], {}), '([0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0])\n', (4028, 4066), True, 'import numpy as np\n'), ((4261, 4322), 'itertools.product', 'itertools.product', (['time_steps_list', 'n_runge_kutta_stages_list'], {}), '(time_steps_list, n_runge_kutta_stages_list)\n', (4278, 4322), False, 'import itertools\n'), ((11326, 11387), 'itertools.product', 'itertools.product', (['time_steps_list', 'n_runge_kutta_stages_list'], {}), '(time_steps_list, n_runge_kutta_stages_list)\n', (11343, 11387), False, 'import itertools\n'), ((13209, 13270), 'itertools.product', 'itertools.product', (['time_steps_list', 'n_runge_kutta_stages_list'], {}), '(time_steps_list, n_runge_kutta_stages_list)\n', (13226, 13270), False, 'import itertools\n'), ((15609, 15630), 'pandas.DataFrame', 'pd.DataFrame', (['results'], {}), '(results)\n', (15621, 15630), True, 'import pandas as pd\n'), ((1015, 1177), 'functools.partial', 'functools.partial', (['RK_residual'], {'x_0': 'x_init', 'delta_t': 'delta_t', 'u': 'u', 'n_runge_kutta_stages': 'n_runge_kutta_stages', 'IRK_alpha': 'IRK_alpha', 'A': 'A', 'B': 'B', 'C': 'C', 'D': 'D', 'F': 'F'}), '(RK_residual, x_0=x_init, delta_t=delta_t, u=u,\n n_runge_kutta_stages=n_runge_kutta_stages, IRK_alpha=IRK_alpha, A=A, B=\n B, C=C, D=D, F=F)\n', (1032, 1177), False, 'import functools\n'), ((2258, 2358), 'numpy.concatenate', 'np.concatenate', (['[single_solver_result.T for single_solver_result in list_solver_results]'], {'axis': '(0)'}), '([single_solver_result.T for single_solver_result in\n list_solver_results], axis=0)\n', (2272, 2358), True, 'import numpy as np\n'), ((3332, 3432), 'numpy.concatenate', 'np.concatenate', (['[single_solver_result.T for single_solver_result in list_solver_results]'], {'axis': '(0)'}), '([single_solver_result.T for single_solver_result in\n list_solver_results], axis=0)\n', (3346, 3432), True, 'import numpy as np\n'), ((3592, 3606), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (3603, 3606), False, 'import pickle\n'), ((4478, 4550), 'dataset_handling.filter_dataset', 'filter_dataset', ([], {'dataset': 'complete_data', 'filter_indices': 'indices_time_steps'}), '(dataset=complete_data, filter_indices=indices_time_steps)\n', (4492, 4550), False, 'from dataset_handling import filter_dataset, prepare_data\n'), ((4575, 4599), 'numpy.zeros', 'np.zeros', (['(51)'], {'dtype': 'bool'}), '(51, dtype=bool)\n', (4583, 4599), True, 'import numpy as np\n'), ((4831, 4926), 'dataset_handling.filter_dataset', 'filter_dataset', ([], {'dataset': 'dataset_filtered_pre', 'filter_indices': 'indices_reduced_dataset_power'}), '(dataset=dataset_filtered_pre, filter_indices=\n indices_reduced_dataset_power)\n', (4845, 4926), False, 'from dataset_handling import filter_dataset, prepare_data\n'), ((4993, 5078), 'numpy.concatenate', 'np.concatenate', (["[dataset_filtered['time'] * 0, dataset_filtered['time']]"], {'axis': '(1)'}), "([dataset_filtered['time'] * 0, dataset_filtered['time']], axis=1\n )\n", (5007, 5078), True, 'import numpy as np\n'), ((5271, 5339), 'read_runge_kutta_parameters.read_runge_kutta_parameters', 'read_runge_kutta_parameters', ([], {'runge_kutta_stages': 'n_runge_kutta_stages'}), '(runge_kutta_stages=n_runge_kutta_stages)\n', (5298, 5339), False, 'from read_runge_kutta_parameters import read_runge_kutta_parameters\n'), ((5705, 5737), 'numpy.transpose', 'np.transpose', (['xM'], {'axes': '[0, 2, 1]'}), '(xM, axes=[0, 2, 1])\n', (5717, 5737), True, 'import numpy as np\n'), ((5892, 5931), 'numpy.transpose', 'np.transpose', (['kM_init_T'], {'axes': '[0, 2, 1]'}), '(kM_init_T, axes=[0, 2, 1])\n', (5904, 5931), True, 'import numpy as np\n'), ((5956, 6107), 'functools.partial', 'functools.partial', (['solve_RK_stages'], {'n_runge_kutta_stages': 'n_runge_kutta_stages', 'IRK_alpha': 'IRK_alpha', 'IRK_beta': 'IRK_beta', 'A': 'A', 'B': 'B', 'C': 'C', 'D': 'D', 'F': 'F'}), '(solve_RK_stages, n_runge_kutta_stages=\n n_runge_kutta_stages, IRK_alpha=IRK_alpha, IRK_beta=IRK_beta, A=A, B=B,\n C=C, D=D, F=F)\n', (5973, 6107), False, 'import functools\n'), ((7437, 7509), 'dataset_handling.filter_dataset', 'filter_dataset', ([], {'dataset': 'complete_data', 'filter_indices': 'indices_time_steps'}), '(dataset=complete_data, filter_indices=indices_time_steps)\n', (7451, 7509), False, 'from dataset_handling import filter_dataset, prepare_data\n'), ((7534, 7558), 'numpy.zeros', 'np.zeros', (['(51)'], {'dtype': 'bool'}), '(51, dtype=bool)\n', (7542, 7558), True, 'import numpy as np\n'), ((7790, 7885), 'dataset_handling.filter_dataset', 'filter_dataset', ([], {'dataset': 'dataset_filtered_pre', 'filter_indices': 'indices_reduced_dataset_power'}), '(dataset=dataset_filtered_pre, filter_indices=\n indices_reduced_dataset_power)\n', (7804, 7885), False, 'from dataset_handling import filter_dataset, prepare_data\n'), ((7952, 8037), 'numpy.concatenate', 'np.concatenate', (["[dataset_filtered['time'] * 0, dataset_filtered['time']]"], {'axis': '(1)'}), "([dataset_filtered['time'] * 0, dataset_filtered['time']], axis=1\n )\n", (7966, 8037), True, 'import numpy as np\n'), ((8217, 8286), 'functools.partial', 'functools.partial', (['solve_ode'], {'A': 'A', 'B': 'B', 'C': 'C', 'D': 'D', 'F': 'F', 'method': '"""Radau"""'}), "(solve_ode, A=A, B=B, C=C, D=D, F=F, method='Radau')\n", (8234, 8286), False, 'import functools\n'), ((9467, 9539), 'dataset_handling.filter_dataset', 'filter_dataset', ([], {'dataset': 'complete_data', 'filter_indices': 'indices_time_steps'}), '(dataset=complete_data, filter_indices=indices_time_steps)\n', (9481, 9539), False, 'from dataset_handling import filter_dataset, prepare_data\n'), ((9564, 9588), 'numpy.zeros', 'np.zeros', (['(51)'], {'dtype': 'bool'}), '(51, dtype=bool)\n', (9572, 9588), True, 'import numpy as np\n'), ((9820, 9915), 'dataset_handling.filter_dataset', 'filter_dataset', ([], {'dataset': 'dataset_filtered_pre', 'filter_indices': 'indices_reduced_dataset_power'}), '(dataset=dataset_filtered_pre, filter_indices=\n indices_reduced_dataset_power)\n', (9834, 9915), False, 'from dataset_handling import filter_dataset, prepare_data\n'), ((9982, 10067), 'numpy.concatenate', 'np.concatenate', (["[dataset_filtered['time'] * 0, dataset_filtered['time']]"], {'axis': '(1)'}), "([dataset_filtered['time'] * 0, dataset_filtered['time']], axis=1\n )\n", (9996, 10067), True, 'import numpy as np\n'), ((10246, 10314), 'functools.partial', 'functools.partial', (['solve_ode'], {'A': 'A', 'B': 'B', 'C': 'C', 'D': 'D', 'F': 'F', 'method': '"""RK45"""'}), "(solve_ode, A=A, B=B, C=C, D=D, F=F, method='RK45')\n", (10263, 10314), False, 'import functools\n'), ((11429, 11558), 'PINN_RK.PinnModel', 'PinnModel', ([], {'neurons_in_hidden_layer': '[50]', 'n_runge_kutta_stages': 'n_runge_kutta_stages', 'power_system': 'power_system', 'case': '"""normal"""'}), "(neurons_in_hidden_layer=[50], n_runge_kutta_stages=\n n_runge_kutta_stages, power_system=power_system, case='normal')\n", (11438, 11558), False, 'from PINN_RK import PinnModel\n'), ((11752, 11824), 'dataset_handling.filter_dataset', 'filter_dataset', ([], {'dataset': 'complete_data', 'filter_indices': 'indices_time_steps'}), '(dataset=complete_data, filter_indices=indices_time_steps)\n', (11766, 11824), False, 'from dataset_handling import filter_dataset, prepare_data\n'), ((11849, 11873), 'numpy.zeros', 'np.zeros', (['(51)'], {'dtype': 'bool'}), '(51, dtype=bool)\n', (11857, 11873), True, 'import numpy as np\n'), ((12105, 12200), 'dataset_handling.filter_dataset', 'filter_dataset', ([], {'dataset': 'dataset_filtered_pre', 'filter_indices': 'indices_reduced_dataset_power'}), '(dataset=dataset_filtered_pre, filter_indices=\n indices_reduced_dataset_power)\n', (12119, 12200), False, 'from dataset_handling import filter_dataset, prepare_data\n'), ((12220, 12309), 'dataset_handling.prepare_data', 'prepare_data', (['dataset_filtered'], {'n_runge_kutta_stages': 'n_runge_kutta_stages', 'n_states': '(2)'}), '(dataset_filtered, n_runge_kutta_stages=n_runge_kutta_stages,\n n_states=2)\n', (12232, 12309), False, 'from dataset_handling import filter_dataset, prepare_data\n'), ((13312, 13437), 'PINN_RK.PinnModel', 'PinnModel', ([], {'neurons_in_hidden_layer': '[500, 500, 500]', 'n_runge_kutta_stages': 'n_runge_kutta_stages', 'power_system': 'power_system'}), '(neurons_in_hidden_layer=[500, 500, 500], n_runge_kutta_stages=\n n_runge_kutta_stages, power_system=power_system)\n', (13321, 13437), False, 'from PINN_RK import PinnModel\n'), ((13608, 13680), 'dataset_handling.filter_dataset', 'filter_dataset', ([], {'dataset': 'complete_data', 'filter_indices': 'indices_time_steps'}), '(dataset=complete_data, filter_indices=indices_time_steps)\n', (13622, 13680), False, 'from dataset_handling import filter_dataset, prepare_data\n'), ((13705, 13729), 'numpy.zeros', 'np.zeros', (['(51)'], {'dtype': 'bool'}), '(51, dtype=bool)\n', (13713, 13729), True, 'import numpy as np\n'), ((13961, 14056), 'dataset_handling.filter_dataset', 'filter_dataset', ([], {'dataset': 'dataset_filtered_pre', 'filter_indices': 'indices_reduced_dataset_power'}), '(dataset=dataset_filtered_pre, filter_indices=\n indices_reduced_dataset_power)\n', (13975, 14056), False, 'from dataset_handling import filter_dataset, prepare_data\n'), ((14076, 14165), 'dataset_handling.prepare_data', 'prepare_data', (['dataset_filtered'], {'n_runge_kutta_stages': 'n_runge_kutta_stages', 'n_states': '(2)'}), '(dataset_filtered, n_runge_kutta_stages=n_runge_kutta_stages,\n n_states=2)\n', (14088, 14165), False, 'from dataset_handling import filter_dataset, prepare_data\n'), ((15726, 15752), 'pickle.dump', 'pickle.dump', (['results_pd', 'f'], {}), '(results_pd, f)\n', (15737, 15752), False, 'import pickle\n'), ((1942, 1964), 'numpy.sin', 'np.sin', (['(C @ x_adjusted)'], {}), '(C @ x_adjusted)\n', (1948, 1964), True, 'import numpy as np\n'), ((4385, 4435), 'numpy.around', 'np.around', (["complete_data['time'][:, 0]"], {'decimals': '(5)'}), "(complete_data['time'][:, 0], decimals=5)\n", (4394, 4435), True, 'import numpy as np\n'), ((4685, 4722), 'numpy.repeat', 'np.repeat', (['indices_single'], {'repeats': '(51)'}), '(indices_single, repeats=51)\n', (4694, 4722), True, 'import numpy as np\n'), ((4776, 4803), 'numpy.tile', 'np.tile', (['indices_single', '(51)'], {}), '(indices_single, 51)\n', (4783, 4803), True, 'import numpy as np\n'), ((5384, 5404), 'numpy.sin', 'np.sin', (['(x_init @ C.T)'], {}), '(x_init @ C.T)\n', (5390, 5404), True, 'import numpy as np\n'), ((5476, 5506), 'numpy.expand_dims', 'np.expand_dims', (['x_init'], {'axis': '(2)'}), '(x_init, axis=2)\n', (5490, 5506), True, 'import numpy as np\n'), ((5566, 5592), 'numpy.expand_dims', 'np.expand_dims', (['k0'], {'axis': '(2)'}), '(k0, axis=2)\n', (5580, 5592), True, 'import numpy as np\n'), ((5776, 5794), 'numpy.sin', 'np.sin', (['(xM_T @ C.T)'], {}), '(xM_T @ C.T)\n', (5782, 5794), True, 'import numpy as np\n'), ((5845, 5876), 'numpy.expand_dims', 'np.expand_dims', (['(u @ B.T)'], {'axis': '(1)'}), '(u @ B.T, axis=1)\n', (5859, 5876), True, 'import numpy as np\n'), ((7344, 7394), 'numpy.around', 'np.around', (["complete_data['time'][:, 0]"], {'decimals': '(5)'}), "(complete_data['time'][:, 0], decimals=5)\n", (7353, 7394), True, 'import numpy as np\n'), ((7644, 7681), 'numpy.repeat', 'np.repeat', (['indices_single'], {'repeats': '(51)'}), '(indices_single, repeats=51)\n', (7653, 7681), True, 'import numpy as np\n'), ((7735, 7762), 'numpy.tile', 'np.tile', (['indices_single', '(51)'], {}), '(indices_single, 51)\n', (7742, 7762), True, 'import numpy as np\n'), ((9374, 9424), 'numpy.around', 'np.around', (["complete_data['time'][:, 0]"], {'decimals': '(5)'}), "(complete_data['time'][:, 0], decimals=5)\n", (9383, 9424), True, 'import numpy as np\n'), ((9674, 9711), 'numpy.repeat', 'np.repeat', (['indices_single'], {'repeats': '(51)'}), '(indices_single, repeats=51)\n', (9683, 9711), True, 'import numpy as np\n'), ((9765, 9792), 'numpy.tile', 'np.tile', (['indices_single', '(51)'], {}), '(indices_single, 51)\n', (9772, 9792), True, 'import numpy as np\n'), ((11659, 11709), 'numpy.around', 'np.around', (["complete_data['time'][:, 0]"], {'decimals': '(5)'}), "(complete_data['time'][:, 0], decimals=5)\n", (11668, 11709), True, 'import numpy as np\n'), ((11959, 11996), 'numpy.repeat', 'np.repeat', (['indices_single'], {'repeats': '(51)'}), '(indices_single, repeats=51)\n', (11968, 11996), True, 'import numpy as np\n'), ((12050, 12077), 'numpy.tile', 'np.tile', (['indices_single', '(51)'], {}), '(indices_single, 51)\n', (12057, 12077), True, 'import numpy as np\n'), ((13515, 13565), 'numpy.around', 'np.around', (["complete_data['time'][:, 0]"], {'decimals': '(5)'}), "(complete_data['time'][:, 0], decimals=5)\n", (13524, 13565), True, 'import numpy as np\n'), ((13815, 13852), 'numpy.repeat', 'np.repeat', (['indices_single'], {'repeats': '(51)'}), '(indices_single, repeats=51)\n', (13824, 13852), True, 'import numpy as np\n'), ((13906, 13933), 'numpy.tile', 'np.tile', (['indices_single', '(51)'], {}), '(indices_single, 51)\n', (13913, 13933), True, 'import numpy as np\n'), ((7162, 7178), 'numpy.abs', 'np.abs', (['error_rk'], {}), '(error_rk)\n', (7168, 7178), True, 'import numpy as np\n'), ((9189, 9208), 'numpy.abs', 'np.abs', (['error_radau'], {}), '(error_radau)\n', (9195, 9208), True, 'import numpy as np\n'), ((11201, 11219), 'numpy.abs', 'np.abs', (['error_rk45'], {}), '(error_rk45)\n', (11207, 11219), True, 'import numpy as np\n'), ((12924, 12942), 'numpy.abs', 'np.abs', (['error_PINN'], {}), '(error_PINN)\n', (12930, 12942), True, 'import numpy as np\n'), ((14787, 14805), 'numpy.abs', 'np.abs', (['error_PINN'], {}), '(error_PINN)\n', (14793, 14805), True, 'import numpy as np\n'), ((15082, 15143), 'numpy.stack', 'np.stack', (["[element['method'] for element in result_dict_list]"], {}), "([element['method'] for element in result_dict_list])\n", (15090, 15143), True, 'import numpy as np\n'), ((15184, 15259), 'numpy.stack', 'np.stack', (["[element['n_runge_kutta_stages'] for element in result_dict_list]"], {}), "([element['n_runge_kutta_stages'] for element in result_dict_list])\n", (15192, 15259), True, 'import numpy as np\n'), ((15300, 15364), 'numpy.stack', 'np.stack', (["[element['time_step'] for element in result_dict_list]"], {}), "([element['time_step'] for element in result_dict_list])\n", (15308, 15364), True, 'import numpy as np\n'), ((15405, 15468), 'numpy.stack', 'np.stack', (["[element['time_min'] for element in result_dict_list]"], {}), "([element['time_min'] for element in result_dict_list])\n", (15413, 15468), True, 'import numpy as np\n'), ((15509, 15573), 'numpy.stack', 'np.stack', (["[element['max_error'] for element in result_dict_list]"], {}), "([element['max_error'] for element in result_dict_list])\n", (15517, 15573), True, 'import numpy as np\n'), ((6792, 6808), 'numpy.abs', 'np.abs', (['error_rk'], {}), '(error_rk)\n', (6798, 6808), True, 'import numpy as np\n'), ((8848, 8867), 'numpy.abs', 'np.abs', (['error_radau'], {}), '(error_radau)\n', (8854, 8867), True, 'import numpy as np\n'), ((10865, 10883), 'numpy.abs', 'np.abs', (['error_rk45'], {}), '(error_rk45)\n', (10871, 10883), True, 'import numpy as np\n'), ((13012, 13030), 'numpy.abs', 'np.abs', (['error_PINN'], {}), '(error_PINN)\n', (13018, 13030), True, 'import numpy as np\n'), ((14875, 14893), 'numpy.abs', 'np.abs', (['error_PINN'], {}), '(error_PINN)\n', (14881, 14893), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split
from stop_words import get_stop_words
class ClassifierBuilder:
def __init__(self):
self._X_test = None
self._y_test = None
self._vectorizer_path = None
self._weights_path = None
self._tests_path = None
self._tests_num = None
self._test_quality_iters = None
def save_vectorizer(self, path: str) -> 'ClassifierBuilder':
self._vectorizer_path = path
return self
def save_weights(self, path: str) -> 'ClassifierBuilder':
self._weights_path = path
return self
def save_tests(self, path: str) -> 'ClassifierBuilder':
self._tests_path = path
if self._X_test is None:
self._tests_num = 0
else:
self._tests_num = len(self._X_test)
return self
def test_quality(self, iters: int, X_test=None, y_test=None):
self._X_test = X_test
self._y_test = y_test
self._test_quality_iters = iters
return self
def build(self, texts: list, topics: list):
token_pattern = r"(?u)\b\w\w+\b"
vectorizer = CountVectorizer(
token_pattern=token_pattern,
stop_words=get_stop_words('russian')
)
X = vectorizer.fit_transform(texts)
transformer = TfidfTransformer()
X = transformer.fit_transform(X)
if self._vectorizer_path is not None:
with open(self._vectorizer_path, 'w') as f:
for key, value in vectorizer.vocabulary_.items():
f.write("%s " % key)
f.write("%s \n" % value)
classifier = SGDClassifier(
loss="log", class_weight='balanced',
penalty='l1', alpha=0.0000009, n_jobs=-1
)
if self._test_quality_iters is not None:
for i in range(self._test_quality_iters):
X_train, X_test, y_train, y_test = train_test_split(X, topics, test_size=0.33)
classifier.fit(X_train, y_train)
predicted = classifier.predict(X_test)
print('Accuracy', np.mean(predicted == y_test))
if self._X_test is not None:
X_test = self._X_test
y_test = self._y_test
classifier.fit(X, topics)
sorted_topics = np.unique(topics)
X_transformed = transformer.transform(vectorizer.transform(X_test))
predicted = classifier.predict(X_transformed)
print('Accuracy on real tests:', np.mean(predicted == y_test))
# vocabulary = vectorizer.get_feature_names() : for human friendly features
if self._tests_path is not None:
with open(self._tests_path, 'w') as t:
t.write("%s %s\n" % (self._tests_num, X.shape[1]))
for index in range(len(X_test)):
doc = X_transformed[index]
probs = classifier.predict_proba(doc)
for item in probs[0]:
t.write("%s " % item)
t.write("\n")
orig_doc = X_test[index]
t.write("%s \n" % orig_doc)
for item in doc.toarray()[0]:
t.write("%s " % item)
t.write("\n")
print(orig_doc)
pred_topics = {}
for i in range(len(probs[0])):
probability = probs[0][i]
topic = sorted_topics[i]
pred_topics[topic] = probability
print(sorted(pred_topics.items(), key=lambda kv: kv[1], reverse=True))
print("______")
if self._weights_path is not None or self._tests_path is not None:
with open(self._weights_path, 'w') as f:
f.write("%s " % classifier.coef_.shape[0]) # amount of classes
f.write("%s \n" % classifier.coef_.shape[1]) # amount of features
for line in classifier.classes_:
f.write("%s \n" % line)
for line in classifier.coef_:
for index, item in enumerate(line):
if item != 0.0:
f.write("%s %s " % (index, item))
f.write("\n")
for item in classifier.intercept_:
f.write("%s " % item)
return classifier
def split_data(df, tests_amount):
X_train, X_test, y_train, y_test = [], [], [], []
for i in range(df.shape[0]):
try: # ???
row = df.iloc[i]
if i < tests_amount:
X_test.append(row['text'])
y_test.append(row['tags'])
else:
X_train.append(row['text'])
y_train.append(row['tags'])
except:
print("key error at %s" % i)
continue
return X_train, X_test, y_train, y_test
def main():
df = pd.read_csv('news_lenta.csv', nrows=500000)
df = df.dropna()
df = df[df['tags'] != 'Все']
tests_amount = 10
X_train, X_test, y_train, y_test = split_data(df, tests_amount)
ClassifierBuilder() \
.test_quality(1, X_test, y_test) \
.save_vectorizer('cnt_vectorizer') \
.save_weights('classifier_weights') \
.save_tests('sklearn_prediction') \
.build(X_train, y_train)
if __name__ == "__main__":
main()
| [
"stop_words.get_stop_words",
"sklearn.linear_model.SGDClassifier",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"numpy.mean",
"sklearn.feature_extraction.text.TfidfTransformer",
"numpy.unique"
] | [((5263, 5306), 'pandas.read_csv', 'pd.read_csv', (['"""news_lenta.csv"""'], {'nrows': '(500000)'}), "('news_lenta.csv', nrows=500000)\n", (5274, 5306), True, 'import pandas as pd\n'), ((1498, 1516), 'sklearn.feature_extraction.text.TfidfTransformer', 'TfidfTransformer', ([], {}), '()\n', (1514, 1516), False, 'from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\n'), ((1835, 1928), 'sklearn.linear_model.SGDClassifier', 'SGDClassifier', ([], {'loss': '"""log"""', 'class_weight': '"""balanced"""', 'penalty': '"""l1"""', 'alpha': '(9e-07)', 'n_jobs': '(-1)'}), "(loss='log', class_weight='balanced', penalty='l1', alpha=\n 9e-07, n_jobs=-1)\n", (1848, 1928), False, 'from sklearn.linear_model import SGDClassifier\n'), ((2502, 2519), 'numpy.unique', 'np.unique', (['topics'], {}), '(topics)\n', (2511, 2519), True, 'import numpy as np\n'), ((1396, 1421), 'stop_words.get_stop_words', 'get_stop_words', (['"""russian"""'], {}), "('russian')\n", (1410, 1421), False, 'from stop_words import get_stop_words\n'), ((2117, 2160), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'topics'], {'test_size': '(0.33)'}), '(X, topics, test_size=0.33)\n', (2133, 2160), False, 'from sklearn.model_selection import train_test_split\n'), ((2703, 2731), 'numpy.mean', 'np.mean', (['(predicted == y_test)'], {}), '(predicted == y_test)\n', (2710, 2731), True, 'import numpy as np\n'), ((2299, 2327), 'numpy.mean', 'np.mean', (['(predicted == y_test)'], {}), '(predicted == y_test)\n', (2306, 2327), True, 'import numpy as np\n')] |
from os import listdir
import numpy
from sklearn.model_selection import StratifiedKFold
from CR_WOA_DEF import CRWOA
from LIN_WOA_DEF import LINWOA
import scipy.io
from multiprocessing import Pool
from functools import partial
from KNNCV import KNNCrossValidation
from NNCV import NNCrossValidation
from NB import NBCrossValidation
def read_data(path):
data=scipy.io.loadmat(path)
train=data['train']
label=data['label']
return train,label
def PAR(reruns,P,T,path,M):
p=Pool(2)
if(M=='LINWOA'):
PF=partial(PLIN,P=P,T=T,path=path)
elif(M=='CRWOA'):
PF=partial(PCR,P=P,T=T,path=path)
output=p.map(PF,range(0,reruns))
p.close()
Cost=numpy.zeros(reruns,dtype=numpy.float64)
CC=numpy.zeros([reruns,T],dtype=numpy.float64)
Pos=[]
for i in range(0,reruns):
unpack=output[i]
Cost[i]=unpack[0]
Pos.append(unpack[1])
CC[i,:]=unpack[2]
return Cost,Pos,CC
def PLIN(re,P,T,path):
train,label=read_data(path)
cv=StratifiedKFold(n_splits=10,shuffle=True,random_state=re)
a,b,c=LINWOA(train,label,cv,P,T)
return a,b,c
def PCR(re,P,T,path):
train,label=read_data(path)
cv=StratifiedKFold(n_splits=10,shuffle=True,random_state=re)
a,b,c=CRWOA(train,label,cv,P,T)
return a,b,c
def knn(train,label,reruns):
acc=numpy.zeros((reruns,10))
for i in range(0,reruns):
cv=StratifiedKFold(n_splits=10,shuffle=True,random_state=i)
for k in range(1,11):
acc[i,k-1]=KNNCrossValidation(train,label,cv,k)
ACC=numpy.max(acc,axis=1)
return 1-ACC
def total_classes(label):
unique=[]
for i in label:
if i not in unique:
unique.append(i)
total_class=len(unique)
return total_class
def nn(train,label,reruns):
dim=train.shape[1]
ul=int(max(10,numpy.floor(numpy.sqrt(dim*total_classes(label)))))
acc=numpy.zeros((reruns,ul))
for i in range(0,reruns):
cv=StratifiedKFold(n_splits=10,shuffle=True,random_state=i)
for nn in range(1,ul):
acc[i,nn-1]=NNCrossValidation(train,label,cv,nn)
ACC=numpy.max(acc,axis=1)
return 1-ACC
def nb(train,label,reruns):
acc=numpy.zeros((reruns))
for i in range(0,reruns):
cv=StratifiedKFold(n_splits=10,shuffle=True,random_state=i)
acc[i]=NBCrossValidation(train,label,cv)
return 1-acc
def main():
path='./datasets'
direc=sorted(listdir(path))
print(direc)
total_reruns=10
Population=4
Total_iter=50
Cost=numpy.zeros([len(direc),total_reruns,5],dtype=numpy.float64)
CC=numpy.zeros([len(direc),total_reruns,Total_iter,5],dtype=numpy.float64)
Pos4=[]
Pos5=[]
for i in range(0,len(direc)):
data_path=path+'/'+direc[i]
print(data_path)
train,label=read_data(data_path)
Cost[i,:,0]=knn(train,label,total_reruns)
Cost[i,:,1]=nn(train,label,total_reruns)
Cost[i,:,2]=nb(train,label,total_reruns)
Cost[i,:,3],Elite_pos,CC[i,:,:,3]=PAR(total_reruns,Population,Total_iter,data_path,'LINWOA')
Pos4.append(Elite_pos)
Cost[i,:,4],Elite_pos,CC[i,:,:,4]=PAR(total_reruns,Population,Total_iter,data_path,'CRWOA')
Pos5.append(Elite_pos)
return Cost,Pos4,Pos5,CC
Cost,Pos4,Pos5,CC = main()
| [
"CR_WOA_DEF.CRWOA",
"functools.partial",
"numpy.zeros",
"NB.NBCrossValidation",
"LIN_WOA_DEF.LINWOA",
"numpy.max",
"sklearn.model_selection.StratifiedKFold",
"multiprocessing.Pool",
"KNNCV.KNNCrossValidation",
"NNCV.NNCrossValidation",
"os.listdir"
] | [((493, 500), 'multiprocessing.Pool', 'Pool', (['(2)'], {}), '(2)\n', (497, 500), False, 'from multiprocessing import Pool\n'), ((689, 729), 'numpy.zeros', 'numpy.zeros', (['reruns'], {'dtype': 'numpy.float64'}), '(reruns, dtype=numpy.float64)\n', (700, 729), False, 'import numpy\n'), ((736, 781), 'numpy.zeros', 'numpy.zeros', (['[reruns, T]'], {'dtype': 'numpy.float64'}), '([reruns, T], dtype=numpy.float64)\n', (747, 781), False, 'import numpy\n'), ((1015, 1074), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': '(10)', 'shuffle': '(True)', 'random_state': 're'}), '(n_splits=10, shuffle=True, random_state=re)\n', (1030, 1074), False, 'from sklearn.model_selection import StratifiedKFold\n'), ((1083, 1113), 'LIN_WOA_DEF.LINWOA', 'LINWOA', (['train', 'label', 'cv', 'P', 'T'], {}), '(train, label, cv, P, T)\n', (1089, 1113), False, 'from LIN_WOA_DEF import LINWOA\n'), ((1189, 1248), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': '(10)', 'shuffle': '(True)', 'random_state': 're'}), '(n_splits=10, shuffle=True, random_state=re)\n', (1204, 1248), False, 'from sklearn.model_selection import StratifiedKFold\n'), ((1257, 1286), 'CR_WOA_DEF.CRWOA', 'CRWOA', (['train', 'label', 'cv', 'P', 'T'], {}), '(train, label, cv, P, T)\n', (1262, 1286), False, 'from CR_WOA_DEF import CRWOA\n'), ((1338, 1363), 'numpy.zeros', 'numpy.zeros', (['(reruns, 10)'], {}), '((reruns, 10))\n', (1349, 1363), False, 'import numpy\n'), ((1563, 1585), 'numpy.max', 'numpy.max', (['acc'], {'axis': '(1)'}), '(acc, axis=1)\n', (1572, 1585), False, 'import numpy\n'), ((1906, 1931), 'numpy.zeros', 'numpy.zeros', (['(reruns, ul)'], {}), '((reruns, ul))\n', (1917, 1931), False, 'import numpy\n'), ((2129, 2151), 'numpy.max', 'numpy.max', (['acc'], {'axis': '(1)'}), '(acc, axis=1)\n', (2138, 2151), False, 'import numpy\n'), ((2205, 2224), 'numpy.zeros', 'numpy.zeros', (['reruns'], {}), '(reruns)\n', (2216, 2224), False, 'import numpy\n'), ((533, 567), 'functools.partial', 'partial', (['PLIN'], {'P': 'P', 'T': 'T', 'path': 'path'}), '(PLIN, P=P, T=T, path=path)\n', (540, 567), False, 'from functools import partial\n'), ((1404, 1462), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': '(10)', 'shuffle': '(True)', 'random_state': 'i'}), '(n_splits=10, shuffle=True, random_state=i)\n', (1419, 1462), False, 'from sklearn.model_selection import StratifiedKFold\n'), ((1972, 2030), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': '(10)', 'shuffle': '(True)', 'random_state': 'i'}), '(n_splits=10, shuffle=True, random_state=i)\n', (1987, 2030), False, 'from sklearn.model_selection import StratifiedKFold\n'), ((2268, 2326), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': '(10)', 'shuffle': '(True)', 'random_state': 'i'}), '(n_splits=10, shuffle=True, random_state=i)\n', (2283, 2326), False, 'from sklearn.model_selection import StratifiedKFold\n'), ((2340, 2375), 'NB.NBCrossValidation', 'NBCrossValidation', (['train', 'label', 'cv'], {}), '(train, label, cv)\n', (2357, 2375), False, 'from NB import NBCrossValidation\n'), ((2447, 2460), 'os.listdir', 'listdir', (['path'], {}), '(path)\n', (2454, 2460), False, 'from os import listdir\n'), ((598, 631), 'functools.partial', 'partial', (['PCR'], {'P': 'P', 'T': 'T', 'path': 'path'}), '(PCR, P=P, T=T, path=path)\n', (605, 631), False, 'from functools import partial\n'), ((1514, 1553), 'KNNCV.KNNCrossValidation', 'KNNCrossValidation', (['train', 'label', 'cv', 'k'], {}), '(train, label, cv, k)\n', (1532, 1553), False, 'from KNNCV import KNNCrossValidation\n'), ((2084, 2123), 'NNCV.NNCrossValidation', 'NNCrossValidation', (['train', 'label', 'cv', 'nn'], {}), '(train, label, cv, nn)\n', (2101, 2123), False, 'from NNCV import NNCrossValidation\n')] |
"""
Main program
"""
import numpy as np
from mpi4py import MPI
import sys
from src.os_util import my_mkdir
from src.input_parser import get_input_variables, get_c_list
import src.parallel_util as put
from src.snr import opt_pulsar_snr
import src.signals as signals
import src.snr as snr
import src.generate_sim_quants as gsq
import src.constants as const
#####
# initializing MPI
comm = MPI.COMM_WORLD
# get the total number of processors
n_proc = comm.Get_size()
# get the id of processor
proc_id = comm.Get_rank()
# ID of main processor
root_process = 0
if proc_id == root_process:
print("--- DM - PTA - MC ---")
print()
print(" v1.0")
print()
print(" Running on " + str(n_proc) + " processors")
print()
print("---")
print()
print("Reading input file...")
print()
in_filename = sys.argv[-1]
in_dict = get_input_variables(in_filename)
if proc_id == root_process:
print("Done reading input file!")
print()
print(" Input variables:")
for key in in_dict:
print(" " + key + " : " + str(in_dict[key]))
print()
print("---")
print()
# tell ehich processors what to compute for
job_list = None
job_list_recv = None
if proc_id == root_process:
# number of jobs to do
num_jobs = in_dict["NUM_UNIVERSE"]
total_job_list = []
for ui in range(num_jobs):
total_job_list.append([ui])
job_list = put.generate_job_list(n_proc, np.array(total_job_list))
job_list_recv = comm.scatter(job_list, root=root_process)
if proc_id == root_process:
print(" Determining simulation variables...")
print()
dt = const.week_to_s * in_dict["DT_WEEK"]
obs_T = const.yr_to_s * in_dict["T_YR"]
# number of time points
Nt = int(obs_T / dt)
t_grid = np.linspace(0, dt * Nt, num=Nt, endpoint=False)
t_grid_yr = t_grid / const.yr_to_s
v_bar = const.km_s_to_kpc_yr * in_dict["V_BAR_KM_PER_SEC"]
v_0 = const.km_s_to_kpc_yr * in_dict["V_0_KM_PER_SEC"]
v_E = const.km_s_to_kpc_yr * in_dict["V_E_KM_PER_SEC"]
v_Esc = const.km_s_to_kpc_yr * in_dict["V_ESC_KM_PER_SEC"]
max_R = in_dict["R_FACTOR"] * v_bar * t_grid_yr[-1]
if proc_id == root_process:
verbose = True
else:
verbose = False
[num_objects, max_R, log10_M_min] = gsq.set_num_objects(
max_R,
log10_f=in_dict["LOG10_F"],
log10_M=in_dict["LOG10_M"],
use_HMF=in_dict["USE_HMF"],
HMF_path=in_dict["HMF_PATH"],
log10_M_min=in_dict["LOG10_M_MIN"],
min_num_object=in_dict["MIN_NUM_OBJECT"],
verbose=verbose,
)
# generate positions of pulsars (same across all universes)
dhat_list = gsq.gen_dhats(in_dict["NUM_PULSAR"])
if proc_id == root_process:
print(" Number of time points = " + str(Nt))
print(" Number of subhalos per pulsar/earth = " + str(num_objects))
print(" Radius of simulation sphere = " + str(max_R) + " kpc")
print()
if in_dict["USE_HMF"]:
print(" Halo mass function M_min = " + str(10 ** log10_M_min) + " M_sol")
print()
print("---")
print()
snr_list = []
for job in range(len(job_list_recv)):
if job_list_recv[job, 0] != -1:
uni_id = job_list_recv[job, 0]
if in_dict["CALC_TYPE"] == "pulsar":
if proc_id == root_process and job == 0:
print("Starting PULSAR term calculation...")
print()
print(" Generating signals and computing optimal pulsar SNR...")
for pul in range(in_dict["NUM_PULSAR"]):
r0_list = gsq.gen_positions(max_R, num_objects)
v_list = gsq.gen_velocities(v_0, v_Esc, v_E, num_objects)
mass_list = gsq.gen_masses(
num_objects,
use_HMF=in_dict["USE_HMF"],
log10_M=in_dict["LOG10_M"],
HMF_path=in_dict["HMF_PATH"],
log10_M_min=log10_M_min,
)
conc_list = get_c_list(
mass_list,
in_dict["USE_FORM"],
in_dict["USE_CM"],
c=in_dict["C"],
cM_path=in_dict["CM_PATH"],
)
d_hat = dhat_list[pul]
dphi = signals.dphi_dop_chunked(
t_grid_yr,
mass_list,
r0_list,
v_list,
d_hat,
use_form=in_dict["USE_FORM"],
conc=conc_list,
use_chunk=in_dict["USE_CHUNK"],
chunk_size=in_dict["CHUNK_SIZE"],
)
ht = signals.subtract_signal(t_grid, dphi)
snr_val = snr.opt_pulsar_snr(
ht, in_dict["T_RMS_NS"], in_dict["DT_WEEK"]
)
snr_list.append([uni_id, pul, snr_val])
if proc_id == root_process and job == len(job_list_recv) - 1:
print(" Done computing SNR!")
print()
print("Returning data to main processor...")
print()
if in_dict["CALC_TYPE"] == "earth":
if proc_id == root_process:
print("Starting EARTH term calculation...")
print()
print(" Generating signals and computing optimal Earth SNR...")
r0_list = gsq.gen_positions(max_R, num_objects)
v_list = gsq.gen_velocities(v_0, v_Esc, v_E, num_objects)
mass_list = gsq.gen_masses(
num_objects,
use_HMF=in_dict["USE_HMF"],
log10_M=in_dict["LOG10_M"],
HMF_path=in_dict["HMF_PATH"],
log10_M_min=log10_M_min,
)
conc_list = get_c_list(
mass_list,
in_dict["USE_FORM"],
in_dict["USE_CM"],
c=in_dict["C"],
cM_path=in_dict["CM_PATH"],
)
dphi_vec = signals.dphi_dop_chunked_vec(
t_grid_yr,
mass_list,
r0_list,
v_list,
use_form=in_dict["USE_FORM"],
conc=conc_list,
use_chunk=in_dict["USE_CHUNK"],
chunk_size=in_dict["CHUNK_SIZE"],
) # (Nt, 3)
ht_list = np.zeros((in_dict["NUM_PULSAR"], Nt))
for pul in range(in_dict["NUM_PULSAR"]):
d_hat = dhat_list[pul]
dphi = np.einsum("ij,j->i", dphi_vec, d_hat)
ht = signals.subtract_signal(t_grid, dphi)
ht_list[pul, :] = ht
snr_val = snr.opt_earth_snr(
ht_list, in_dict["T_RMS_NS"], in_dict["DT_WEEK"]
)
snr_list.append([uni_id, -1, snr_val])
if proc_id == root_process and job == len(job_list_recv) - 1:
print(" Done computing SNR!")
print()
print("Returning data to main processor...")
print()
# return data back to root
all_snr_list = comm.gather(snr_list, root=root_process)
# write to output file
if proc_id == root_process:
print("Done returning data!")
print()
print("Writing data to output file...")
my_mkdir(in_dict["OUTPUT_DIR"])
file = open(
in_dict["OUTPUT_DIR"]
+ "snr_"
+ in_dict["CALC_TYPE"]
+ "_"
+ in_dict["RUN_DESCRIP"]
+ ".txt",
"w",
)
for i in range(n_proc):
for j in range(len(all_snr_list[i])):
# universe_index = universe_index_list[int(all_A_stat_list[i][j][0])]
snr_final = all_snr_list[i][j][1]
file.write(
str(int(all_snr_list[i][j][0]))
+ " , "
+ str(all_snr_list[i][j][1])
+ " , "
+ str(all_snr_list[i][j][2])
)
file.write("\n")
file.close()
print("Done writing data!")
print("---")
print()
| [
"src.generate_sim_quants.gen_velocities",
"src.generate_sim_quants.gen_dhats",
"src.signals.subtract_signal",
"src.signals.dphi_dop_chunked_vec",
"src.generate_sim_quants.set_num_objects",
"numpy.zeros",
"numpy.einsum",
"src.input_parser.get_c_list",
"src.os_util.my_mkdir",
"numpy.array",
"numpy... | [((863, 895), 'src.input_parser.get_input_variables', 'get_input_variables', (['in_filename'], {}), '(in_filename)\n', (882, 895), False, 'from src.input_parser import get_input_variables, get_c_list\n'), ((1772, 1819), 'numpy.linspace', 'np.linspace', (['(0)', '(dt * Nt)'], {'num': 'Nt', 'endpoint': '(False)'}), '(0, dt * Nt, num=Nt, endpoint=False)\n', (1783, 1819), True, 'import numpy as np\n'), ((2247, 2496), 'src.generate_sim_quants.set_num_objects', 'gsq.set_num_objects', (['max_R'], {'log10_f': "in_dict['LOG10_F']", 'log10_M': "in_dict['LOG10_M']", 'use_HMF': "in_dict['USE_HMF']", 'HMF_path': "in_dict['HMF_PATH']", 'log10_M_min': "in_dict['LOG10_M_MIN']", 'min_num_object': "in_dict['MIN_NUM_OBJECT']", 'verbose': 'verbose'}), "(max_R, log10_f=in_dict['LOG10_F'], log10_M=in_dict[\n 'LOG10_M'], use_HMF=in_dict['USE_HMF'], HMF_path=in_dict['HMF_PATH'],\n log10_M_min=in_dict['LOG10_M_MIN'], min_num_object=in_dict[\n 'MIN_NUM_OBJECT'], verbose=verbose)\n", (2266, 2496), True, 'import src.generate_sim_quants as gsq\n'), ((2591, 2627), 'src.generate_sim_quants.gen_dhats', 'gsq.gen_dhats', (["in_dict['NUM_PULSAR']"], {}), "(in_dict['NUM_PULSAR'])\n", (2604, 2627), True, 'import src.generate_sim_quants as gsq\n'), ((7300, 7331), 'src.os_util.my_mkdir', 'my_mkdir', (["in_dict['OUTPUT_DIR']"], {}), "(in_dict['OUTPUT_DIR'])\n", (7308, 7331), False, 'from src.os_util import my_mkdir\n'), ((1454, 1478), 'numpy.array', 'np.array', (['total_job_list'], {}), '(total_job_list)\n', (1462, 1478), True, 'import numpy as np\n'), ((5396, 5433), 'src.generate_sim_quants.gen_positions', 'gsq.gen_positions', (['max_R', 'num_objects'], {}), '(max_R, num_objects)\n', (5413, 5433), True, 'import src.generate_sim_quants as gsq\n'), ((5456, 5504), 'src.generate_sim_quants.gen_velocities', 'gsq.gen_velocities', (['v_0', 'v_Esc', 'v_E', 'num_objects'], {}), '(v_0, v_Esc, v_E, num_objects)\n', (5474, 5504), True, 'import src.generate_sim_quants as gsq\n'), ((5530, 5673), 'src.generate_sim_quants.gen_masses', 'gsq.gen_masses', (['num_objects'], {'use_HMF': "in_dict['USE_HMF']", 'log10_M': "in_dict['LOG10_M']", 'HMF_path': "in_dict['HMF_PATH']", 'log10_M_min': 'log10_M_min'}), "(num_objects, use_HMF=in_dict['USE_HMF'], log10_M=in_dict[\n 'LOG10_M'], HMF_path=in_dict['HMF_PATH'], log10_M_min=log10_M_min)\n", (5544, 5673), True, 'import src.generate_sim_quants as gsq\n'), ((5789, 5899), 'src.input_parser.get_c_list', 'get_c_list', (['mass_list', "in_dict['USE_FORM']", "in_dict['USE_CM']"], {'c': "in_dict['C']", 'cM_path': "in_dict['CM_PATH']"}), "(mass_list, in_dict['USE_FORM'], in_dict['USE_CM'], c=in_dict['C'\n ], cM_path=in_dict['CM_PATH'])\n", (5799, 5899), False, 'from src.input_parser import get_input_variables, get_c_list\n'), ((6014, 6202), 'src.signals.dphi_dop_chunked_vec', 'signals.dphi_dop_chunked_vec', (['t_grid_yr', 'mass_list', 'r0_list', 'v_list'], {'use_form': "in_dict['USE_FORM']", 'conc': 'conc_list', 'use_chunk': "in_dict['USE_CHUNK']", 'chunk_size': "in_dict['CHUNK_SIZE']"}), "(t_grid_yr, mass_list, r0_list, v_list,\n use_form=in_dict['USE_FORM'], conc=conc_list, use_chunk=in_dict[\n 'USE_CHUNK'], chunk_size=in_dict['CHUNK_SIZE'])\n", (6042, 6202), True, 'import src.signals as signals\n'), ((6371, 6408), 'numpy.zeros', 'np.zeros', (["(in_dict['NUM_PULSAR'], Nt)"], {}), "((in_dict['NUM_PULSAR'], Nt))\n", (6379, 6408), True, 'import numpy as np\n'), ((6685, 6752), 'src.snr.opt_earth_snr', 'snr.opt_earth_snr', (['ht_list', "in_dict['T_RMS_NS']", "in_dict['DT_WEEK']"], {}), "(ht_list, in_dict['T_RMS_NS'], in_dict['DT_WEEK'])\n", (6702, 6752), True, 'import src.snr as snr\n'), ((3540, 3577), 'src.generate_sim_quants.gen_positions', 'gsq.gen_positions', (['max_R', 'num_objects'], {}), '(max_R, num_objects)\n', (3557, 3577), True, 'import src.generate_sim_quants as gsq\n'), ((3604, 3652), 'src.generate_sim_quants.gen_velocities', 'gsq.gen_velocities', (['v_0', 'v_Esc', 'v_E', 'num_objects'], {}), '(v_0, v_Esc, v_E, num_objects)\n', (3622, 3652), True, 'import src.generate_sim_quants as gsq\n'), ((3682, 3825), 'src.generate_sim_quants.gen_masses', 'gsq.gen_masses', (['num_objects'], {'use_HMF': "in_dict['USE_HMF']", 'log10_M': "in_dict['LOG10_M']", 'HMF_path': "in_dict['HMF_PATH']", 'log10_M_min': 'log10_M_min'}), "(num_objects, use_HMF=in_dict['USE_HMF'], log10_M=in_dict[\n 'LOG10_M'], HMF_path=in_dict['HMF_PATH'], log10_M_min=log10_M_min)\n", (3696, 3825), True, 'import src.generate_sim_quants as gsq\n'), ((3969, 4079), 'src.input_parser.get_c_list', 'get_c_list', (['mass_list', "in_dict['USE_FORM']", "in_dict['USE_CM']"], {'c': "in_dict['C']", 'cM_path': "in_dict['CM_PATH']"}), "(mass_list, in_dict['USE_FORM'], in_dict['USE_CM'], c=in_dict['C'\n ], cM_path=in_dict['CM_PATH'])\n", (3979, 4079), False, 'from src.input_parser import get_input_variables, get_c_list\n'), ((4258, 4449), 'src.signals.dphi_dop_chunked', 'signals.dphi_dop_chunked', (['t_grid_yr', 'mass_list', 'r0_list', 'v_list', 'd_hat'], {'use_form': "in_dict['USE_FORM']", 'conc': 'conc_list', 'use_chunk': "in_dict['USE_CHUNK']", 'chunk_size': "in_dict['CHUNK_SIZE']"}), "(t_grid_yr, mass_list, r0_list, v_list, d_hat,\n use_form=in_dict['USE_FORM'], conc=conc_list, use_chunk=in_dict[\n 'USE_CHUNK'], chunk_size=in_dict['CHUNK_SIZE'])\n", (4282, 4449), True, 'import src.signals as signals\n'), ((4662, 4699), 'src.signals.subtract_signal', 'signals.subtract_signal', (['t_grid', 'dphi'], {}), '(t_grid, dphi)\n', (4685, 4699), True, 'import src.signals as signals\n'), ((4727, 4790), 'src.snr.opt_pulsar_snr', 'snr.opt_pulsar_snr', (['ht', "in_dict['T_RMS_NS']", "in_dict['DT_WEEK']"], {}), "(ht, in_dict['T_RMS_NS'], in_dict['DT_WEEK'])\n", (4745, 4790), True, 'import src.snr as snr\n'), ((6527, 6564), 'numpy.einsum', 'np.einsum', (['"""ij,j->i"""', 'dphi_vec', 'd_hat'], {}), "('ij,j->i', dphi_vec, d_hat)\n", (6536, 6564), True, 'import numpy as np\n'), ((6587, 6624), 'src.signals.subtract_signal', 'signals.subtract_signal', (['t_grid', 'dphi'], {}), '(t_grid, dphi)\n', (6610, 6624), True, 'import src.signals as signals\n')] |
# As usual, a bit of setup
import numpy as np
import matplotlib.pyplot as plt
from cs231n.classifiers.cnn import *
from cs231n.data_utils import get_CIFAR10_data
from cs231n.gradient_check import eval_numerical_gradient_array, eval_numerical_gradient
from cs231n.layers import *
from cs231n.fast_layers import *
from cs231n.solver import Solver
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
def rel_error(x, y):
""" returns relative error """
return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))
# Load the (preprocessed) CIFAR10 data.
data = get_CIFAR10_data()
for k, v in data.items():
print('%s: ' % k, v.shape)
x_shape = (2, 3, 4, 4)
w_shape = (3, 3, 4, 4)
x = np.linspace(-0.1, 0.5, num=np.prod(x_shape)).reshape(x_shape)
w = np.linspace(-0.2, 0.3, num=np.prod(w_shape)).reshape(w_shape)
b = np.linspace(-0.1, 0.2, num=3)
conv_param = {'stride': 2, 'pad': 1}
out, _ = conv_forward_naive(x, w, b, conv_param)
correct_out = np.array([[[[-0.08759809, -0.10987781],
[-0.18387192, -0.2109216 ]],
[[ 0.21027089, 0.21661097],
[ 0.22847626, 0.23004637]],
[[ 0.50813986, 0.54309974],
[ 0.64082444, 0.67101435]]],
[[[-0.98053589, -1.03143541],
[-1.19128892, -1.24695841]],
[[ 0.69108355, 0.66880383],
[ 0.59480972, 0.56776003]],
[[ 2.36270298, 2.36904306],
[ 2.38090835, 2.38247847]]]])
# Compare your output to ours; difference should be around e-8
print('Testing conv_forward_naive')
print('difference: ', rel_error(out, correct_out)) | [
"numpy.abs",
"cs231n.data_utils.get_CIFAR10_data",
"numpy.array",
"numpy.linspace",
"numpy.prod"
] | [((683, 701), 'cs231n.data_utils.get_CIFAR10_data', 'get_CIFAR10_data', ([], {}), '()\n', (699, 701), False, 'from cs231n.data_utils import get_CIFAR10_data\n'), ((940, 969), 'numpy.linspace', 'np.linspace', (['(-0.1)', '(0.2)'], {'num': '(3)'}), '(-0.1, 0.2, num=3)\n', (951, 969), True, 'import numpy as np\n'), ((1071, 1435), 'numpy.array', 'np.array', (['[[[[-0.08759809, -0.10987781], [-0.18387192, -0.2109216]], [[0.21027089, \n 0.21661097], [0.22847626, 0.23004637]], [[0.50813986, 0.54309974], [\n 0.64082444, 0.67101435]]], [[[-0.98053589, -1.03143541], [-1.19128892, \n -1.24695841]], [[0.69108355, 0.66880383], [0.59480972, 0.56776003]], [[\n 2.36270298, 2.36904306], [2.38090835, 2.38247847]]]]'], {}), '([[[[-0.08759809, -0.10987781], [-0.18387192, -0.2109216]], [[\n 0.21027089, 0.21661097], [0.22847626, 0.23004637]], [[0.50813986, \n 0.54309974], [0.64082444, 0.67101435]]], [[[-0.98053589, -1.03143541],\n [-1.19128892, -1.24695841]], [[0.69108355, 0.66880383], [0.59480972, \n 0.56776003]], [[2.36270298, 2.36904306], [2.38090835, 2.38247847]]]])\n', (1079, 1435), True, 'import numpy as np\n'), ((575, 588), 'numpy.abs', 'np.abs', (['(x - y)'], {}), '(x - y)\n', (581, 588), True, 'import numpy as np\n'), ((835, 851), 'numpy.prod', 'np.prod', (['x_shape'], {}), '(x_shape)\n', (842, 851), True, 'import numpy as np\n'), ((901, 917), 'numpy.prod', 'np.prod', (['w_shape'], {}), '(w_shape)\n', (908, 917), True, 'import numpy as np\n'), ((609, 618), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (615, 618), True, 'import numpy as np\n'), ((621, 630), 'numpy.abs', 'np.abs', (['y'], {}), '(y)\n', (627, 630), True, 'import numpy as np\n')] |
# Copyright (c) 2020, <NAME>, Honda Research Institute Europe GmbH, and
# Technical University of Darmstadt.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of <NAME>, Honda Research Institute Europe GmbH,
# or Technical University of Darmstadt, 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 <NAME>, HONDA RESEARCH INSTITUTE EUROPE GMBH,
# OR TECHNICAL UNIVERSITY OF DARMSTADT 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 random
import time
from typing import Callable, List, Optional
import numpy as np
import pytest
import torch as to
from tests.conftest import m_needs_bullet, m_needs_cuda
from torch.distributions.multivariate_normal import MultivariateNormal
import pyrado
from pyrado.algorithms.step_based.gae import GAE
from pyrado.algorithms.step_based.ppo import PPO
from pyrado.algorithms.utils import RolloutSavingWrapper
from pyrado.domain_randomization.default_randomizers import create_default_randomizer
from pyrado.environment_wrappers.domain_randomization import DomainRandWrapperLive
from pyrado.environments.sim_base import SimEnv
from pyrado.exploration.stochastic_action import NormalActNoiseExplStrat
from pyrado.logger import set_log_prefix_dir
from pyrado.policies.base import Policy
from pyrado.policies.feed_back.fnn import FNN
from pyrado.policies.feed_forward.dummy import IdlePolicy
from pyrado.sampling.bootstrapping import bootstrap_ci
from pyrado.sampling.cvar_sampler import select_cvar
from pyrado.sampling.data_format import to_format
from pyrado.sampling.hyper_sphere import sample_from_hyper_sphere_surface
from pyrado.sampling.parallel_rollout_sampler import ParallelRolloutSampler
from pyrado.sampling.parameter_exploration_sampler import ParameterExplorationSampler, ParameterSamplingResult
from pyrado.sampling.rollout import rollout
from pyrado.sampling.sampler_pool import SamplerPool
from pyrado.sampling.sequences import (
sequence_add_init,
sequence_const,
sequence_nlog2,
sequence_plus_one,
sequence_rec_double,
sequence_rec_sqrt,
)
from pyrado.sampling.step_sequence import StepSequence
from pyrado.utils.data_types import RenderMode
@pytest.mark.parametrize(
"arg",
[
[1],
[2, 3],
[4, 6, 2, 88, 3, 45, 7, 21, 22, 23, 24, 44, 45, 56, 67, 78, 89],
],
)
def test_sampler_pool(arg):
pool = SamplerPool(len(arg))
result = pool.invoke_all_map(_cb_test_eachhandler, arg)
pool.stop()
assert result == list(map(lambda x: x * 2, arg))
def _cb_test_eachhandler(G, arg):
time.sleep(random.randint(1, 5))
return arg * 2
def _cb_test_collecthandler(G, num):
nsample = random.randint(5, 15)
return nsample, nsample
@pytest.mark.parametrize("num_threads", [1, 2, 4])
@pytest.mark.parametrize("min_samples", [10, 20, 40])
def test_sampler_collect(num_threads: int, min_samples: int):
pool = SamplerPool(num_threads)
# Run the collector
cr, cn = pool.run_collect(min_samples, _cb_test_collecthandler)
pool.stop()
assert min_samples <= cn
assert min_samples <= sum(cr)
@pytest.mark.parametrize("num_threads", [1, 2, 4])
@pytest.mark.parametrize("min_samples", [10, 20, 40])
@pytest.mark.parametrize("min_runs", [10, 20, 40])
def test_sampler_collect_minrun(num_threads: int, min_samples: int, min_runs: int):
pool = SamplerPool(num_threads)
# Run the collector
cr, cn = pool.run_collect(min_samples, _cb_test_collecthandler, min_runs=min_runs)
pool.stop()
assert min_samples <= cn
assert min_samples <= sum(cr)
assert min_runs <= len(cr)
@pytest.mark.parametrize("data_type", [(None, None), (to.int32, np.int32)])
def test_to_format(data_type: tuple):
# Create some tensors to convert
ndarray = np.random.rand(3, 2).astype(dtype=np.float64)
tensor = to.rand(3, 2).type(dtype=to.float64)
# Test the conversion and typing from numpy to PyTorch
converted_ndarray = to_format(ndarray, "torch", data_type[0])
assert isinstance(converted_ndarray, to.Tensor)
new_type = to.float64 if data_type[0] is None else data_type[0] # passing None must not change the type
assert converted_ndarray.dtype == new_type
# Test the conversion and typing from PyTorch to numpy
converted_tensor = to_format(tensor, "numpy", data_type[1])
assert isinstance(converted_tensor, np.ndarray)
new_type = np.float64 if data_type[1] is None else data_type[1] # passing None must not change the type
assert converted_tensor.dtype == new_type
@pytest.mark.parametrize("epsilon", [1, 0.5, 0.1])
@pytest.mark.parametrize("num_ro", [10, 20])
def test_select_cvar(epsilon: float, num_ro: int):
# Create rollouts with known discounted rewards
rollouts = [StepSequence(rewards=[i], observations=[i], actions=[i]) for i in range(num_ro)]
# Shuffle data to put in
ro_shuf = list(rollouts)
random.shuffle(ro_shuf)
# Select cvar quantile
ro_cv = select_cvar(ro_shuf, epsilon, 1)
# Compute expected return of subselection
cv = sum(map(lambda ro: ro.discounted_return(1), ro_cv)) / len(ro_cv)
# This should be equal to the epsilon-quantile of the integer sequence
nq = int(num_ro * epsilon)
cv_expected = sum(range(nq)) / nq
assert cv == cv_expected
@pytest.mark.parametrize(
"num_dim, method",
[
(1, "uniform"),
(1, "uniform"),
(3, "uniform"),
(3, "normal"),
(3, "Marsaglia"),
(4, "uniform"),
(4, "normal"),
(4, "Marsaglia"),
(15, "uniform"),
(15, "normal"),
],
)
def test_sample_from_unit_sphere_surface(num_dim: int, method: str):
s = sample_from_hyper_sphere_surface(num_dim, method)
assert 0.95 <= to.norm(s, p=2) <= 1.05
@pytest.mark.parametrize(
["env", "policy"],
[
("default_bob", "idle_policy"),
("default_bob", "dummy_policy"),
("default_bob", "time_policy"),
("default_bob", "pst_policy"),
("default_bob", "linear_policy"),
("default_bob", "fnn_policy"),
("default_bob", "rnn_policy"),
("default_bob", "lstm_policy"),
("default_bob", "gru_policy"),
("default_bob", "adn_policy"),
("default_bob", "nf_policy"),
("default_bob", "thfnn_policy"),
("default_bob", "thgru_policy"),
],
ids=[
"bob_idle",
"bob_dummy",
"bob_time",
"bob_pst",
"bob_lin",
"bob_fnn",
"bob_rnn",
"bob_lstm",
"bob_gru",
"bob_adn",
"bob_nf",
"bob_thfnn",
"bob_thgru",
],
indirect=True,
)
def test_rollout_wo_exploration(env: SimEnv, policy: Policy):
ro = rollout(env, policy, render_mode=RenderMode())
assert isinstance(ro, StepSequence)
assert len(ro) <= env.max_steps
@pytest.mark.parametrize("env", ["default_bob", "default_qbb"], ids=["bob", "qbb"], indirect=True)
def test_rollout_wo_policy(env: SimEnv):
def policy(obs):
# Callable must receive and return tensors
return to.from_numpy(env.spec.act_space.sample_uniform())
ro = rollout(env, policy, render_mode=RenderMode())
assert isinstance(ro, StepSequence)
assert len(ro) <= env.max_steps
@pytest.mark.parametrize(
"mean, cov",
[(to.tensor([5.0, 7.0]), to.tensor([[2.0, 0.0], [0.0, 2.0]]))],
ids=["2dim"],
)
def test_reparametrization_trick(mean, cov):
for seed in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
# Sampling the the PyTorch distribution class
distr_mvn = MultivariateNormal(mean, cov)
to.manual_seed(seed)
smpl_distr = distr_mvn.sample()
# The reparametrization trick done by PyTorch
to.manual_seed(seed)
smpl_distr_reparam = distr_mvn.sample()
# The reparametrization trick done by hand
to.manual_seed(seed)
smpl_reparam = mean + to.cholesky(cov, upper=False).mv(to.randn_like(mean))
to.testing.assert_allclose(smpl_distr, smpl_distr_reparam)
to.testing.assert_allclose(smpl_distr, smpl_reparam)
to.testing.assert_allclose(smpl_distr_reparam, smpl_reparam)
@pytest.mark.parametrize("plot", [False, pytest.param(True, marks=pytest.mark.visual)])
@pytest.mark.parametrize(
"sequence, x_init",
[
(sequence_const, np.array([2])),
(sequence_plus_one, np.array([2])),
(sequence_add_init, np.array([2])),
(sequence_rec_double, np.array([2])),
(sequence_rec_sqrt, np.array([2])),
(sequence_nlog2, np.array([2])),
(sequence_const, np.array([1, 2, 3])),
(sequence_plus_one, np.array([1, 2, 3])),
(sequence_add_init, np.array([1, 2, 3])),
(sequence_rec_double, np.array([1, 2, 3])),
(sequence_rec_sqrt, np.array([1, 2, 3])),
(sequence_nlog2, np.array([1, 2, 3])),
],
)
def test_sequences(sequence: Callable, x_init: np.ndarray, plot: bool):
# Get the full sequence
_, x_full = sequence(x_init, 5, float)
assert x_full is not None
if plot:
import matplotlib.pyplot as plt
# Plot the sequences
for i in range(x_full.shape[1]):
plt.stem(x_full[:, i], label=str(x_init[i]))
plt.legend()
plt.show()
@pytest.mark.parametrize("sample", [np.array([30, 37, 36, 43, 42, 43, 43, 46, 41, 42])])
@pytest.mark.parametrize("seed", [1, 12, 123], ids=["seed1", "seed1", "seed123"])
def test_boostrap_methods(sample, seed):
# Emperical bootstrap
m_bs, ci_bs_lo, ci_bs_up = bootstrap_ci(sample, np.mean, num_reps=20, alpha=0.1, ci_sides=2, seed=seed)
# Percentile bootstrap
# Add one to the seed because with the MD5 seed calculation and so on, the lower quantiles are actually equal by
# chance. This seems to be the one-in-a-million case for this.
pyrado.set_seed(seed + 1)
resampled = np.random.choice(sample, (sample.shape[0], 20), replace=True)
means = np.apply_along_axis(np.mean, 0, resampled)
ci_lo, ci_up = np.percentile(means, [5, 95])
# You should operate on the deltas (emperical bootsrap) and not directly on the statistic from the resampled data
# (percentile bootsrap)
assert ci_lo != ci_bs_lo
assert ci_up != ci_bs_up
@pytest.mark.parametrize(
"data",
[np.random.normal(10, 1, (40,)), np.random.normal((1, 7, 13), (1, 1, 1), (40, 3))],
ids=["1dim-data", "3dim-data"],
)
@pytest.mark.parametrize("num_reps", [100, 1000, 10000], ids=["100reps", "1000reps", "10000reps"])
@pytest.mark.parametrize("seed", [1, 12, 123], ids=["seed1", "seed12", "seed123"])
def test_bootsrapping(data, num_reps, seed):
# Fully-fledged example
bootstrap_ci(data, np.mean, num_reps, alpha=0.05, ci_sides=2, studentized=True, bias_correction=True, seed=seed)
m, ci_lo, ci_up = bootstrap_ci(
data, np.mean, num_reps, alpha=0.05, ci_sides=2, studentized=False, bias_correction=False, seed=seed
)
assert np.all(m >= ci_lo)
assert np.all(m <= ci_up)
m_bc, ci_lo, ci_up = bootstrap_ci(
data, np.mean, num_reps, alpha=0.05, ci_sides=2, studentized=False, bias_correction=True, seed=seed
)
assert np.all(m_bc != m)
m, ci_lo, ci_up = bootstrap_ci(data, np.mean, num_reps, alpha=0.05, ci_sides=1, studentized=False, seed=seed)
m_t, ci_lo_t, ci_up_t = bootstrap_ci(data, np.mean, num_reps, alpha=0.05, ci_sides=1, studentized=True, seed=seed)
assert m == pytest.approx(m_t)
assert np.all(m_t >= ci_lo_t)
assert np.all(m_t <= ci_up_t)
# Bounds are different (not generally wider) when assuming a t-distribution
assert np.all(ci_lo != ci_lo_t)
assert np.all(ci_up != ci_up_t)
@pytest.mark.parametrize(
["env", "policy"],
[
("default_bob", "fnn_policy"),
],
ids=["bob_fnnpol"],
indirect=True,
)
@pytest.mark.parametrize(
["num_init_states_per_domain", "fixed_init_state", "num_domains"],
[
(1, False, 1),
(1, True, 1),
(9, False, 1),
(9, True, 1),
],
ids=["1rops-randinit", "1rops-fixedinit", "9rops-randinit", "9rops-fixedinit"],
)
@pytest.mark.parametrize("num_workers", [1, 4], ids=["1worker", "4workers"])
def test_param_expl_sampler(
env: SimEnv,
policy: Policy,
num_init_states_per_domain: int,
fixed_init_state: bool,
num_domains: int,
num_workers: int,
):
pyrado.set_seed(0)
# Add randomizer
pert = create_default_randomizer(env)
env = DomainRandWrapperLive(env, pert)
# Create the sampler
sampler = ParameterExplorationSampler(env, policy, num_init_states_per_domain, num_domains, num_workers=num_workers)
# Use some random parameters
num_ps = 7
params = to.rand(num_ps, policy.num_param)
if fixed_init_state:
# Sample a custom init state
init_states = [env.init_space.sample_uniform()] * num_init_states_per_domain
else:
# Let the sampler forward to the env to randomly sample an init state
init_states = None
# Do the sampling
samples = sampler.sample(param_sets=params, init_states=init_states)
# Check if the correct number of rollouts has been sampled
assert num_ps == len(samples)
num_rollouts_per_param = num_init_states_per_domain * num_domains
assert num_ps * num_rollouts_per_param == samples.num_rollouts
for ps in samples:
assert len(ps.rollouts) == num_rollouts_per_param
# Compare rollouts that should be matching
for idx in range(num_rollouts_per_param):
# Use the first parameter set as pivot
piter = iter(samples)
pivot = next(piter).rollouts[idx]
# Iterate through others
for ops in piter:
other_ro = ops.rollouts[idx]
# Compare domain params
assert pivot.rollout_info["domain_param"] == other_ro.rollout_info["domain_param"]
# Compare first observation a.k.a. init state
assert pivot[0].observation == pytest.approx(other_ro[0].observation)
@pytest.mark.parametrize("env", ["default_bob"], indirect=True, ids=["bob"])
@pytest.mark.parametrize(
"policy",
[
"linear_policy",
"fnn_policy",
"rnn_policy",
"lstm_policy",
"gru_policy",
"adn_policy",
"nf_policy",
"thfnn_policy",
"thgru_policy",
],
ids=["lin", "fnn", "rnn", "lstm", "gru", "adn", "nf", "thfnn", "thgru"],
indirect=True,
)
@pytest.mark.parametrize("num_workers", [1, 4], ids=["1worker", "4workers"])
def test_parameter_exploration_sampler(env: SimEnv, policy: Policy, num_workers: int):
# Use some random parameters
num_ps = 7
params = to.rand(num_ps, policy.num_param)
sampler = ParameterExplorationSampler(
env, policy, num_init_states_per_domain=1, num_domains=1, num_workers=num_workers
)
psr = sampler.sample(param_sets=params)
assert isinstance(psr, ParameterSamplingResult)
assert len(psr.rollouts) >= 1 * 1 * num_ps
@pytest.mark.parametrize("policy", ["dummy_policy", "idle_policy"], ids=["dummy", "idle"], indirect=True)
@pytest.mark.parametrize("env", ["default_qbb"], ids=["qbb"], indirect=True)
@pytest.mark.parametrize("num_params", [2])
@pytest.mark.parametrize("num_init_states_per_domain", [2])
@pytest.mark.parametrize("num_domains", [2])
@pytest.mark.parametrize("set_init_states", [False, True], ids=["wo_init_states", "w_init_states"])
def test_parameter_exploration_sampler_deterministic(
env: SimEnv,
policy: Policy,
num_params: int,
num_init_states_per_domain: int,
num_domains: int,
set_init_states: bool,
):
param_sets = to.rand(num_params, policy.num_param)
if set_init_states:
init_states = [env.spec.state_space.sample_uniform() for _ in range(num_init_states_per_domain * num_domains)]
else:
init_states = None
nums_workers = (1, 2, 4)
all_results = []
for num_workers in nums_workers:
# Reset the seed every time because sample() uses the root sampler. This does not matter for regular runs, but
# for this tests it is very relevant.
pyrado.set_seed(0)
all_results.append(
ParameterExplorationSampler(
env,
policy,
num_init_states_per_domain=num_init_states_per_domain,
num_domains=num_domains,
num_workers=num_workers,
seed=0,
).sample(param_sets=param_sets, init_states=init_states)
)
# Test that the rollouts for all number of workers are equal.
for psr_a, psr_b in [(a, b) for a in all_results for b in all_results]:
assert psr_a.parameters == pytest.approx(psr_b.parameters)
assert psr_a.mean_returns == pytest.approx(psr_b.mean_returns)
assert psr_a.num_rollouts == psr_b.num_rollouts
assert len(psr_a.rollouts) == len(psr_b.rollouts)
for ros_a, ros_b in zip(psr_a.rollouts, psr_b.rollouts):
for ro_a, ro_b in zip(ros_a, ros_b):
assert ro_a.rewards == pytest.approx(ro_b.rewards)
assert ro_a.observations == pytest.approx(ro_b.observations)
assert ro_a.actions == pytest.approx(ro_b.actions)
@pytest.mark.parametrize("env", ["default_bob"], indirect=True, ids=["bob"])
@pytest.mark.parametrize(
"policy",
[
"linear_policy",
"fnn_policy",
"rnn_policy",
"lstm_policy",
"gru_policy",
"adn_policy",
"nf_policy",
"thfnn_policy",
"thgru_policy",
],
ids=["lin", "fnn", "rnn", "lstm", "gru", "adn", "nf", "thfnn", "thgru"],
indirect=True,
)
@pytest.mark.parametrize("num_workers", [1, 4], ids=["1worker", "4workers"])
def test_parallel_rollout_sampler(env: SimEnv, policy: Policy, num_workers: int):
min_rollouts = num_workers * 2 # make sure every worker samples at least once
sampler = ParallelRolloutSampler(env, policy, num_workers, min_rollouts=min_rollouts)
ros = sampler.sample()
assert isinstance(ros, list)
assert len(ros) >= min_rollouts
@m_needs_cuda
@pytest.mark.wrapper
@pytest.mark.parametrize(
"env",
[
"default_bob",
"default_qbb",
],
indirect=True,
)
@pytest.mark.parametrize(
"policy",
[
"fnn_policy",
"fnn_policy_cuda",
"lstm_policy",
"lstm_policy_cuda",
],
ids=["fnn", "fnn_cuda", "lstm", "lstm_cuda"],
indirect=True,
)
@pytest.mark.parametrize("num_workers", [1, 2], ids=["1worker", "2workers"])
def test_cuda_sampling_w_dr(env: SimEnv, policy: Policy, num_workers: int):
randomizer = create_default_randomizer(env)
env = DomainRandWrapperLive(env, randomizer)
sampler = ParallelRolloutSampler(env, policy, num_workers=num_workers, min_rollouts=4)
samples = sampler.sample()
assert samples is not None
@pytest.mark.parametrize(
"env",
["default_pend", pytest.param("default_qqsurcs_bt", marks=m_needs_bullet)],
ids=["pend", "qqsurcs_bt"],
indirect=True,
)
@pytest.mark.parametrize("policy", ["dummy_policy", "idle_policy"], ids=["dummy", "idle"], indirect=True)
@pytest.mark.parametrize("num_rollouts", [1, 4, 6])
@pytest.mark.parametrize("num_workers", [1, 4])
def test_sequential_equals_parallel(env: SimEnv, policy: Policy, num_rollouts: int, num_workers: int):
# Do the rollouts explicitly sequentially without a sampler.
# Do not set the init state to check if this was sampled correctly.
ros_sequential = []
for i in range(num_rollouts):
ros_sequential.append(rollout(env, policy, eval=True, seed=0, sub_seed=0, sub_sub_seed=i))
# Do the rollouts in parallel with a sampler.
# Do not set the init state to check if this was sampled correctly.
sampler = ParallelRolloutSampler(env, policy, num_workers=num_workers, min_rollouts=num_rollouts, seed=0)
ros_parallel = sampler.sample()
assert len(ros_parallel) == num_rollouts
for ro_s, ro_p in zip(ros_sequential, ros_parallel):
assert ro_s.rewards == pytest.approx(ro_p.rewards)
assert ro_s.observations == pytest.approx(ro_p.observations)
assert ro_s.actions == pytest.approx(ro_p.actions)
@pytest.mark.parametrize("policy", ["dummy_policy"], indirect=True)
@pytest.mark.parametrize("env", ["default_qbb"], ids=["qbb"], indirect=True)
@pytest.mark.parametrize("min_rollouts", [2, 4, 6]) # Once less, equal, and more rollouts than workers.
@pytest.mark.parametrize("init_states", [None, 2])
@pytest.mark.parametrize("domain_params", [None, [{"gravity_const": 10}]])
def test_parallel_sampling_deterministic_wo_min_steps(
env: SimEnv,
policy: Policy,
min_rollouts: Optional[int],
init_states: Optional[int],
domain_params: Optional[List[dict]],
):
env.max_steps = 20
if init_states is not None:
init_states = [env.spec.state_space.sample_uniform() for _ in range(init_states)]
nums_workers = (1, 2, 4)
all_rollouts = []
for num_workers in nums_workers:
# Act an exploration strategy to test if that works too (it should as the policy gets pickled and distributed
# anyway).
all_rollouts.append(
ParallelRolloutSampler(
env,
NormalActNoiseExplStrat(policy, std_init=1.0),
num_workers=num_workers,
min_rollouts=min_rollouts,
seed=0,
).sample(init_states=init_states, domain_params=domain_params)
)
# Test that the rollouts are actually different, i.e., that not the same seed is used for all rollouts.
for ros in all_rollouts:
for ro_a, ro_b in [(a, b) for a in ros for b in ros if a is not b]:
# The idle policy iy deterministic and always outputs the zero action. Hence, do not check that the actions
# are different when using the idle policy.
if isinstance(policy, IdlePolicy):
# The Quanser Ball Balancer is a deterministic environment (conditioned on the initial state). As the
# idle policy is a deterministic policy, this will result in the rollouts being equivalent for each
# initial state, so do not check for difference if the initial states where set.
if init_states is None:
assert ro_a.rewards != pytest.approx(ro_b.rewards)
assert ro_a.observations != pytest.approx(ro_b.observations)
else:
assert ro_a.rewards != pytest.approx(ro_b.rewards)
assert ro_a.observations != pytest.approx(ro_b.observations)
assert ro_a.actions != pytest.approx(ro_b.actions)
# Test that the rollouts for all number of workers are equal.
for ros_a, ros_b in [(a, b) for a in all_rollouts for b in all_rollouts]:
assert len(ros_a) == len(ros_b)
for ro_a, ro_b in zip(ros_a, ros_b):
assert ro_a.rewards == pytest.approx(ro_b.rewards)
assert ro_a.observations == pytest.approx(ro_b.observations)
assert ro_a.actions == pytest.approx(ro_b.actions)
@pytest.mark.parametrize("policy", ["dummy_policy"], indirect=True)
@pytest.mark.parametrize("env", ["default_qbb"], ids=["qbb"], indirect=True)
@pytest.mark.parametrize("min_rollouts", [None, 2, 4, 6]) # Once less, equal, and more rollouts than workers.
@pytest.mark.parametrize("min_steps", [2, 10])
@pytest.mark.parametrize("domain_params", [None, [{"gravity_const": 10}]])
def test_parallel_sampling_deterministic_w_min_steps(
env: SimEnv,
policy: Policy,
min_rollouts: Optional[int],
min_steps: int,
domain_params: Optional[List[dict]],
):
env.max_steps = 20
nums_workers = (1, 2, 4)
all_rollouts = []
for num_workers in nums_workers:
# Act an exploration strategy to test if that works too (it should as the policy gets pickled and distributed
# anyway).
all_rollouts.append(
ParallelRolloutSampler(
env,
NormalActNoiseExplStrat(policy, std_init=1.0),
num_workers=num_workers,
min_rollouts=min_rollouts,
min_steps=min_steps * env.max_steps,
seed=0,
).sample(domain_params=domain_params)
)
# Test that the rollouts are actually different, i.e., that not the same seed is used for all rollouts.
for ros in all_rollouts:
for ro_a, ro_b in [(a, b) for a in ros for b in ros if a is not b]:
# The idle policy iy deterministic and always outputs the zero action. Hence, do not check that the actions
# are different when using the idle policy.
if not isinstance(policy, IdlePolicy):
assert ro_a.rewards != pytest.approx(ro_b.rewards)
assert ro_a.observations != pytest.approx(ro_b.observations)
assert ro_a.actions != pytest.approx(ro_b.actions)
# Test that the rollouts for all number of workers are equal.
for ros_a, ros_b in [(a, b) for a in all_rollouts for b in all_rollouts]:
assert sum([len(ro) for ro in ros_a]) == sum([len(ro) for ro in ros_b])
assert sum([len(ro) for ro in ros_a]) >= min_steps * env.max_steps
assert sum([len(ro) for ro in ros_b]) >= min_steps * env.max_steps
assert len(ros_a) == len(ros_b)
if min_rollouts is not None:
assert len(ros_a) >= min_rollouts
assert len(ros_b) >= min_rollouts
for ro_a, ro_b in zip(ros_a, ros_b):
assert ro_a.rewards == pytest.approx(ro_b.rewards)
assert ro_a.observations == pytest.approx(ro_b.observations)
assert ro_a.actions == pytest.approx(ro_b.actions)
@pytest.mark.parametrize("env", ["default_bob"], ids=["bob"], indirect=True)
@pytest.mark.parametrize("policy", ["fnn_policy"], indirect=True)
@pytest.mark.parametrize("algo", [PPO])
@pytest.mark.parametrize("min_rollouts", [2, 4, 6]) # Once less, equal, and more rollouts than workers.
def test_parallel_sampling_deterministic_smoke_test_wo_min_steps(
tmpdir_factory, env: SimEnv, policy: Policy, algo, min_rollouts: int
):
env.max_steps = 20
seeds = (0, 1)
nums_workers = (1, 2, 4)
logging_results = []
rollout_results: List[List[List[List[StepSequence]]]] = []
for seed in seeds:
logging_results.append((seed, []))
rollout_results.append([])
for num_workers in nums_workers:
pyrado.set_seed(seed)
policy.init_param(None)
ex_dir = str(tmpdir_factory.mktemp(f"seed={seed}-num_workers={num_workers}"))
set_log_prefix_dir(ex_dir)
vfcn = FNN(input_size=env.obs_space.flat_dim, output_size=1, hidden_sizes=[16, 16], hidden_nonlin=to.tanh)
critic = GAE(vfcn, gamma=0.98, lamda=0.95, batch_size=32, lr=1e-3, standardize_adv=False)
alg = algo(ex_dir, env, policy, critic, max_iter=3, min_rollouts=min_rollouts, num_workers=num_workers)
alg.sampler = RolloutSavingWrapper(alg.sampler)
alg.train()
with open(f"{ex_dir}/progress.csv") as f:
logging_results[-1][1].append(str(f.read()))
rollout_results[-1].append(alg.sampler.rollouts)
# Test that the observations for all number of workers are equal.
for rollouts in rollout_results:
for ros_a, ros_b in [(a, b) for a in rollouts for b in rollouts]:
assert len(ros_a) == len(ros_b)
for ro_a, ro_b in zip(ros_a, ros_b):
assert len(ro_a) == len(ro_b)
for r_a, r_b in zip(ro_a, ro_b):
assert r_a.observations == pytest.approx(r_b.observations)
# Test that different seeds actually produce different results.
for results_a, results_b in [
(a, b) for seed_a, a in logging_results for seed_b, b in logging_results if seed_a != seed_b
]:
for result_a, result_b in [(a, b) for a in results_a for b in results_b if a is not b]:
assert result_a != result_b
# Test that same seeds produce same results.
for _, results in logging_results:
for result_a, result_b in [(a, b) for a in results for b in results]:
assert result_a == result_b
@pytest.mark.parametrize("env", ["default_bob"], ids=["bob"], indirect=True)
@pytest.mark.parametrize("policy", ["fnn_policy"], indirect=True)
@pytest.mark.parametrize("algo", [PPO])
@pytest.mark.parametrize("min_rollouts", [2, 4, 6]) # Once less, equal, and more rollouts than workers.
@pytest.mark.parametrize("min_steps", [2, 10])
def test_parallel_sampling_deterministic_smoke_test_w_min_steps(
tmpdir_factory, env: SimEnv, policy: Policy, algo, min_rollouts: int, min_steps: int
):
env.max_steps = 20
seeds = (0, 1)
nums_workers = (1, 2, 4)
logging_results = []
rollout_results: List[List[List[List[StepSequence]]]] = []
for seed in seeds:
logging_results.append((seed, []))
rollout_results.append([])
for num_workers in nums_workers:
pyrado.set_seed(seed)
policy.init_param(None)
ex_dir = str(tmpdir_factory.mktemp(f"seed={seed}-num_workers={num_workers}"))
set_log_prefix_dir(ex_dir)
vfcn = FNN(input_size=env.obs_space.flat_dim, output_size=1, hidden_sizes=[16, 16], hidden_nonlin=to.tanh)
critic = GAE(vfcn, gamma=0.98, lamda=0.95, batch_size=32, lr=1e-3, standardize_adv=False)
alg = algo(
ex_dir,
env,
policy,
critic,
max_iter=3,
min_rollouts=min_rollouts,
min_steps=min_steps * env.max_steps,
num_workers=num_workers,
)
alg.sampler = RolloutSavingWrapper(alg.sampler)
alg.train()
with open(f"{ex_dir}/progress.csv") as f:
logging_results[-1][1].append(str(f.read()))
rollout_results[-1].append(alg.sampler.rollouts)
# Test that the observations for all number of workers are equal.
for rollouts in rollout_results:
for ros_a, ros_b in [(a, b) for a in rollouts for b in rollouts]:
assert len(ros_a) == len(ros_b)
for ro_a, ro_b in zip(ros_a, ros_b):
assert len(ro_a) == len(ro_b)
for r_a, r_b in zip(ro_a, ro_b):
assert r_a.observations == pytest.approx(r_b.observations)
# Test that different seeds actually produce different results.
for results_a, results_b in [
(a, b) for seed_a, a in logging_results for seed_b, b in logging_results if seed_a != seed_b
]:
for result_a, result_b in [(a, b) for a in results_a for b in results_b if a is not b]:
assert result_a != result_b
# Test that same seeds produce same results.
for _, results in logging_results:
for result_a, result_b in [(a, b) for a in results for b in results]:
assert result_a == result_b
| [
"pyrado.sampling.parallel_rollout_sampler.ParallelRolloutSampler",
"torch.testing.assert_allclose",
"random.shuffle",
"numpy.random.normal",
"pyrado.sampling.hyper_sphere.sample_from_hyper_sphere_surface",
"pytest.mark.parametrize",
"pyrado.domain_randomization.default_randomizers.create_default_randomi... | [((3428, 3542), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""arg"""', '[[1], [2, 3], [4, 6, 2, 88, 3, 45, 7, 21, 22, 23, 24, 44, 45, 56, 67, 78, 89]]'], {}), "('arg', [[1], [2, 3], [4, 6, 2, 88, 3, 45, 7, 21, 22,\n 23, 24, 44, 45, 56, 67, 78, 89]])\n", (3451, 3542), False, 'import pytest\n'), ((3970, 4019), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""num_threads"""', '[1, 2, 4]'], {}), "('num_threads', [1, 2, 4])\n", (3993, 4019), False, 'import pytest\n'), ((4021, 4073), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""min_samples"""', '[10, 20, 40]'], {}), "('min_samples', [10, 20, 40])\n", (4044, 4073), False, 'import pytest\n'), ((4348, 4397), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""num_threads"""', '[1, 2, 4]'], {}), "('num_threads', [1, 2, 4])\n", (4371, 4397), False, 'import pytest\n'), ((4399, 4451), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""min_samples"""', '[10, 20, 40]'], {}), "('min_samples', [10, 20, 40])\n", (4422, 4451), False, 'import pytest\n'), ((4453, 4502), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""min_runs"""', '[10, 20, 40]'], {}), "('min_runs', [10, 20, 40])\n", (4476, 4502), False, 'import pytest\n'), ((4850, 4924), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""data_type"""', '[(None, None), (to.int32, np.int32)]'], {}), "('data_type', [(None, None), (to.int32, np.int32)])\n", (4873, 4924), False, 'import pytest\n'), ((5778, 5827), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""epsilon"""', '[1, 0.5, 0.1]'], {}), "('epsilon', [1, 0.5, 0.1])\n", (5801, 5827), False, 'import pytest\n'), ((5829, 5872), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""num_ro"""', '[10, 20]'], {}), "('num_ro', [10, 20])\n", (5852, 5872), False, 'import pytest\n'), ((6531, 6746), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""num_dim, method"""', "[(1, 'uniform'), (1, 'uniform'), (3, 'uniform'), (3, 'normal'), (3,\n 'Marsaglia'), (4, 'uniform'), (4, 'normal'), (4, 'Marsaglia'), (15,\n 'uniform'), (15, 'normal')]"], {}), "('num_dim, method', [(1, 'uniform'), (1, 'uniform'),\n (3, 'uniform'), (3, 'normal'), (3, 'Marsaglia'), (4, 'uniform'), (4,\n 'normal'), (4, 'Marsaglia'), (15, 'uniform'), (15, 'normal')])\n", (6554, 6746), False, 'import pytest\n'), ((7010, 7682), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["['env', 'policy']", "[('default_bob', 'idle_policy'), ('default_bob', 'dummy_policy'), (\n 'default_bob', 'time_policy'), ('default_bob', 'pst_policy'), (\n 'default_bob', 'linear_policy'), ('default_bob', 'fnn_policy'), (\n 'default_bob', 'rnn_policy'), ('default_bob', 'lstm_policy'), (\n 'default_bob', 'gru_policy'), ('default_bob', 'adn_policy'), (\n 'default_bob', 'nf_policy'), ('default_bob', 'thfnn_policy'), (\n 'default_bob', 'thgru_policy')]"], {'ids': "['bob_idle', 'bob_dummy', 'bob_time', 'bob_pst', 'bob_lin', 'bob_fnn',\n 'bob_rnn', 'bob_lstm', 'bob_gru', 'bob_adn', 'bob_nf', 'bob_thfnn',\n 'bob_thgru']", 'indirect': '(True)'}), "(['env', 'policy'], [('default_bob', 'idle_policy'),\n ('default_bob', 'dummy_policy'), ('default_bob', 'time_policy'), (\n 'default_bob', 'pst_policy'), ('default_bob', 'linear_policy'), (\n 'default_bob', 'fnn_policy'), ('default_bob', 'rnn_policy'), (\n 'default_bob', 'lstm_policy'), ('default_bob', 'gru_policy'), (\n 'default_bob', 'adn_policy'), ('default_bob', 'nf_policy'), (\n 'default_bob', 'thfnn_policy'), ('default_bob', 'thgru_policy')], ids=[\n 'bob_idle', 'bob_dummy', 'bob_time', 'bob_pst', 'bob_lin', 'bob_fnn',\n 'bob_rnn', 'bob_lstm', 'bob_gru', 'bob_adn', 'bob_nf', 'bob_thfnn',\n 'bob_thgru'], indirect=True)\n", (7033, 7682), False, 'import pytest\n'), ((8079, 8180), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""env"""', "['default_bob', 'default_qbb']"], {'ids': "['bob', 'qbb']", 'indirect': '(True)'}), "('env', ['default_bob', 'default_qbb'], ids=['bob',\n 'qbb'], indirect=True)\n", (8102, 8180), False, 'import pytest\n'), ((10581, 10666), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""seed"""', '[1, 12, 123]'], {'ids': "['seed1', 'seed1', 'seed123']"}), "('seed', [1, 12, 123], ids=['seed1', 'seed1', 'seed123']\n )\n", (10604, 10666), False, 'import pytest\n'), ((11633, 11734), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""num_reps"""', '[100, 1000, 10000]'], {'ids': "['100reps', '1000reps', '10000reps']"}), "('num_reps', [100, 1000, 10000], ids=['100reps',\n '1000reps', '10000reps'])\n", (11656, 11734), False, 'import pytest\n'), ((11732, 11817), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""seed"""', '[1, 12, 123]'], {'ids': "['seed1', 'seed12', 'seed123']"}), "('seed', [1, 12, 123], ids=['seed1', 'seed12',\n 'seed123'])\n", (11755, 11817), False, 'import pytest\n'), ((12891, 13005), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["['env', 'policy']", "[('default_bob', 'fnn_policy')]"], {'ids': "['bob_fnnpol']", 'indirect': '(True)'}), "(['env', 'policy'], [('default_bob', 'fnn_policy')],\n ids=['bob_fnnpol'], indirect=True)\n", (12914, 13005), False, 'import pytest\n'), ((13037, 13280), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["['num_init_states_per_domain', 'fixed_init_state', 'num_domains']", '[(1, False, 1), (1, True, 1), (9, False, 1), (9, True, 1)]'], {'ids': "['1rops-randinit', '1rops-fixedinit', '9rops-randinit', '9rops-fixedinit']"}), "(['num_init_states_per_domain', 'fixed_init_state',\n 'num_domains'], [(1, False, 1), (1, True, 1), (9, False, 1), (9, True, \n 1)], ids=['1rops-randinit', '1rops-fixedinit', '9rops-randinit',\n '9rops-fixedinit'])\n", (13060, 13280), False, 'import pytest\n'), ((13323, 13398), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""num_workers"""', '[1, 4]'], {'ids': "['1worker', '4workers']"}), "('num_workers', [1, 4], ids=['1worker', '4workers'])\n", (13346, 13398), False, 'import pytest\n'), ((15213, 15288), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""env"""', "['default_bob']"], {'indirect': '(True)', 'ids': "['bob']"}), "('env', ['default_bob'], indirect=True, ids=['bob'])\n", (15236, 15288), False, 'import pytest\n'), ((15290, 15558), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""policy"""', "['linear_policy', 'fnn_policy', 'rnn_policy', 'lstm_policy', 'gru_policy',\n 'adn_policy', 'nf_policy', 'thfnn_policy', 'thgru_policy']"], {'ids': "['lin', 'fnn', 'rnn', 'lstm', 'gru', 'adn', 'nf', 'thfnn', 'thgru']", 'indirect': '(True)'}), "('policy', ['linear_policy', 'fnn_policy',\n 'rnn_policy', 'lstm_policy', 'gru_policy', 'adn_policy', 'nf_policy',\n 'thfnn_policy', 'thgru_policy'], ids=['lin', 'fnn', 'rnn', 'lstm',\n 'gru', 'adn', 'nf', 'thfnn', 'thgru'], indirect=True)\n", (15313, 15558), False, 'import pytest\n'), ((15646, 15721), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""num_workers"""', '[1, 4]'], {'ids': "['1worker', '4workers']"}), "('num_workers', [1, 4], ids=['1worker', '4workers'])\n", (15669, 15721), False, 'import pytest\n'), ((16190, 16299), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""policy"""', "['dummy_policy', 'idle_policy']"], {'ids': "['dummy', 'idle']", 'indirect': '(True)'}), "('policy', ['dummy_policy', 'idle_policy'], ids=[\n 'dummy', 'idle'], indirect=True)\n", (16213, 16299), False, 'import pytest\n'), ((16296, 16371), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""env"""', "['default_qbb']"], {'ids': "['qbb']", 'indirect': '(True)'}), "('env', ['default_qbb'], ids=['qbb'], indirect=True)\n", (16319, 16371), False, 'import pytest\n'), ((16373, 16415), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""num_params"""', '[2]'], {}), "('num_params', [2])\n", (16396, 16415), False, 'import pytest\n'), ((16417, 16475), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""num_init_states_per_domain"""', '[2]'], {}), "('num_init_states_per_domain', [2])\n", (16440, 16475), False, 'import pytest\n'), ((16477, 16520), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""num_domains"""', '[2]'], {}), "('num_domains', [2])\n", (16500, 16520), False, 'import pytest\n'), ((16522, 16625), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""set_init_states"""', '[False, True]'], {'ids': "['wo_init_states', 'w_init_states']"}), "('set_init_states', [False, True], ids=[\n 'wo_init_states', 'w_init_states'])\n", (16545, 16625), False, 'import pytest\n'), ((18432, 18507), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""env"""', "['default_bob']"], {'indirect': '(True)', 'ids': "['bob']"}), "('env', ['default_bob'], indirect=True, ids=['bob'])\n", (18455, 18507), False, 'import pytest\n'), ((18509, 18777), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""policy"""', "['linear_policy', 'fnn_policy', 'rnn_policy', 'lstm_policy', 'gru_policy',\n 'adn_policy', 'nf_policy', 'thfnn_policy', 'thgru_policy']"], {'ids': "['lin', 'fnn', 'rnn', 'lstm', 'gru', 'adn', 'nf', 'thfnn', 'thgru']", 'indirect': '(True)'}), "('policy', ['linear_policy', 'fnn_policy',\n 'rnn_policy', 'lstm_policy', 'gru_policy', 'adn_policy', 'nf_policy',\n 'thfnn_policy', 'thgru_policy'], ids=['lin', 'fnn', 'rnn', 'lstm',\n 'gru', 'adn', 'nf', 'thfnn', 'thgru'], indirect=True)\n", (18532, 18777), False, 'import pytest\n'), ((18865, 18940), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""num_workers"""', '[1, 4]'], {'ids': "['1worker', '4workers']"}), "('num_workers', [1, 4], ids=['1worker', '4workers'])\n", (18888, 18940), False, 'import pytest\n'), ((19330, 19407), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""env"""', "['default_bob', 'default_qbb']"], {'indirect': '(True)'}), "('env', ['default_bob', 'default_qbb'], indirect=True)\n", (19353, 19407), False, 'import pytest\n'), ((19447, 19619), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""policy"""', "['fnn_policy', 'fnn_policy_cuda', 'lstm_policy', 'lstm_policy_cuda']"], {'ids': "['fnn', 'fnn_cuda', 'lstm', 'lstm_cuda']", 'indirect': '(True)'}), "('policy', ['fnn_policy', 'fnn_policy_cuda',\n 'lstm_policy', 'lstm_policy_cuda'], ids=['fnn', 'fnn_cuda', 'lstm',\n 'lstm_cuda'], indirect=True)\n", (19470, 19619), False, 'import pytest\n'), ((19671, 19746), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""num_workers"""', '[1, 2]'], {'ids': "['1worker', '2workers']"}), "('num_workers', [1, 2], ids=['1worker', '2workers'])\n", (19694, 19746), False, 'import pytest\n'), ((20248, 20357), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""policy"""', "['dummy_policy', 'idle_policy']"], {'ids': "['dummy', 'idle']", 'indirect': '(True)'}), "('policy', ['dummy_policy', 'idle_policy'], ids=[\n 'dummy', 'idle'], indirect=True)\n", (20271, 20357), False, 'import pytest\n'), ((20354, 20404), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""num_rollouts"""', '[1, 4, 6]'], {}), "('num_rollouts', [1, 4, 6])\n", (20377, 20404), False, 'import pytest\n'), ((20406, 20452), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""num_workers"""', '[1, 4]'], {}), "('num_workers', [1, 4])\n", (20429, 20452), False, 'import pytest\n'), ((21412, 21478), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""policy"""', "['dummy_policy']"], {'indirect': '(True)'}), "('policy', ['dummy_policy'], indirect=True)\n", (21435, 21478), False, 'import pytest\n'), ((21480, 21555), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""env"""', "['default_qbb']"], {'ids': "['qbb']", 'indirect': '(True)'}), "('env', ['default_qbb'], ids=['qbb'], indirect=True)\n", (21503, 21555), False, 'import pytest\n'), ((21557, 21607), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""min_rollouts"""', '[2, 4, 6]'], {}), "('min_rollouts', [2, 4, 6])\n", (21580, 21607), False, 'import pytest\n'), ((21662, 21711), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""init_states"""', '[None, 2]'], {}), "('init_states', [None, 2])\n", (21685, 21711), False, 'import pytest\n'), ((21713, 21786), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""domain_params"""', "[None, [{'gravity_const': 10}]]"], {}), "('domain_params', [None, [{'gravity_const': 10}]])\n", (21736, 21786), False, 'import pytest\n'), ((24324, 24390), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""policy"""', "['dummy_policy']"], {'indirect': '(True)'}), "('policy', ['dummy_policy'], indirect=True)\n", (24347, 24390), False, 'import pytest\n'), ((24392, 24467), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""env"""', "['default_qbb']"], {'ids': "['qbb']", 'indirect': '(True)'}), "('env', ['default_qbb'], ids=['qbb'], indirect=True)\n", (24415, 24467), False, 'import pytest\n'), ((24469, 24525), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""min_rollouts"""', '[None, 2, 4, 6]'], {}), "('min_rollouts', [None, 2, 4, 6])\n", (24492, 24525), False, 'import pytest\n'), ((24580, 24625), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""min_steps"""', '[2, 10]'], {}), "('min_steps', [2, 10])\n", (24603, 24625), False, 'import pytest\n'), ((24627, 24700), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""domain_params"""', "[None, [{'gravity_const': 10}]]"], {}), "('domain_params', [None, [{'gravity_const': 10}]])\n", (24650, 24700), False, 'import pytest\n'), ((26952, 27027), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""env"""', "['default_bob']"], {'ids': "['bob']", 'indirect': '(True)'}), "('env', ['default_bob'], ids=['bob'], indirect=True)\n", (26975, 27027), False, 'import pytest\n'), ((27029, 27093), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""policy"""', "['fnn_policy']"], {'indirect': '(True)'}), "('policy', ['fnn_policy'], indirect=True)\n", (27052, 27093), False, 'import pytest\n'), ((27095, 27133), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""algo"""', '[PPO]'], {}), "('algo', [PPO])\n", (27118, 27133), False, 'import pytest\n'), ((27135, 27185), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""min_rollouts"""', '[2, 4, 6]'], {}), "('min_rollouts', [2, 4, 6])\n", (27158, 27185), False, 'import pytest\n'), ((29486, 29561), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""env"""', "['default_bob']"], {'ids': "['bob']", 'indirect': '(True)'}), "('env', ['default_bob'], ids=['bob'], indirect=True)\n", (29509, 29561), False, 'import pytest\n'), ((29563, 29627), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""policy"""', "['fnn_policy']"], {'indirect': '(True)'}), "('policy', ['fnn_policy'], indirect=True)\n", (29586, 29627), False, 'import pytest\n'), ((29629, 29667), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""algo"""', '[PPO]'], {}), "('algo', [PPO])\n", (29652, 29667), False, 'import pytest\n'), ((29669, 29719), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""min_rollouts"""', '[2, 4, 6]'], {}), "('min_rollouts', [2, 4, 6])\n", (29692, 29719), False, 'import pytest\n'), ((29774, 29819), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""min_steps"""', '[2, 10]'], {}), "('min_steps', [2, 10])\n", (29797, 29819), False, 'import pytest\n'), ((3917, 3938), 'random.randint', 'random.randint', (['(5)', '(15)'], {}), '(5, 15)\n', (3931, 3938), False, 'import random\n'), ((4147, 4171), 'pyrado.sampling.sampler_pool.SamplerPool', 'SamplerPool', (['num_threads'], {}), '(num_threads)\n', (4158, 4171), False, 'from pyrado.sampling.sampler_pool import SamplerPool\n'), ((4598, 4622), 'pyrado.sampling.sampler_pool.SamplerPool', 'SamplerPool', (['num_threads'], {}), '(num_threads)\n', (4609, 4622), False, 'from pyrado.sampling.sampler_pool import SamplerPool\n'), ((5194, 5235), 'pyrado.sampling.data_format.to_format', 'to_format', (['ndarray', '"""torch"""', 'data_type[0]'], {}), "(ndarray, 'torch', data_type[0])\n", (5203, 5235), False, 'from pyrado.sampling.data_format import to_format\n'), ((5527, 5567), 'pyrado.sampling.data_format.to_format', 'to_format', (['tensor', '"""numpy"""', 'data_type[1]'], {}), "(tensor, 'numpy', data_type[1])\n", (5536, 5567), False, 'from pyrado.sampling.data_format import to_format\n'), ((6135, 6158), 'random.shuffle', 'random.shuffle', (['ro_shuf'], {}), '(ro_shuf)\n', (6149, 6158), False, 'import random\n'), ((6199, 6231), 'pyrado.sampling.cvar_sampler.select_cvar', 'select_cvar', (['ro_shuf', 'epsilon', '(1)'], {}), '(ro_shuf, epsilon, 1)\n', (6210, 6231), False, 'from pyrado.sampling.cvar_sampler import select_cvar\n'), ((6914, 6963), 'pyrado.sampling.hyper_sphere.sample_from_hyper_sphere_surface', 'sample_from_hyper_sphere_surface', (['num_dim', 'method'], {}), '(num_dim, method)\n', (6946, 6963), False, 'from pyrado.sampling.hyper_sphere import sample_from_hyper_sphere_surface\n'), ((10760, 10836), 'pyrado.sampling.bootstrapping.bootstrap_ci', 'bootstrap_ci', (['sample', 'np.mean'], {'num_reps': '(20)', 'alpha': '(0.1)', 'ci_sides': '(2)', 'seed': 'seed'}), '(sample, np.mean, num_reps=20, alpha=0.1, ci_sides=2, seed=seed)\n', (10772, 10836), False, 'from pyrado.sampling.bootstrapping import bootstrap_ci\n'), ((11053, 11078), 'pyrado.set_seed', 'pyrado.set_seed', (['(seed + 1)'], {}), '(seed + 1)\n', (11068, 11078), False, 'import pyrado\n'), ((11095, 11156), 'numpy.random.choice', 'np.random.choice', (['sample', '(sample.shape[0], 20)'], {'replace': '(True)'}), '(sample, (sample.shape[0], 20), replace=True)\n', (11111, 11156), True, 'import numpy as np\n'), ((11169, 11211), 'numpy.apply_along_axis', 'np.apply_along_axis', (['np.mean', '(0)', 'resampled'], {}), '(np.mean, 0, resampled)\n', (11188, 11211), True, 'import numpy as np\n'), ((11231, 11260), 'numpy.percentile', 'np.percentile', (['means', '[5, 95]'], {}), '(means, [5, 95])\n', (11244, 11260), True, 'import numpy as np\n'), ((11891, 12008), 'pyrado.sampling.bootstrapping.bootstrap_ci', 'bootstrap_ci', (['data', 'np.mean', 'num_reps'], {'alpha': '(0.05)', 'ci_sides': '(2)', 'studentized': '(True)', 'bias_correction': '(True)', 'seed': 'seed'}), '(data, np.mean, num_reps, alpha=0.05, ci_sides=2, studentized=\n True, bias_correction=True, seed=seed)\n', (11903, 12008), False, 'from pyrado.sampling.bootstrapping import bootstrap_ci\n'), ((12027, 12146), 'pyrado.sampling.bootstrapping.bootstrap_ci', 'bootstrap_ci', (['data', 'np.mean', 'num_reps'], {'alpha': '(0.05)', 'ci_sides': '(2)', 'studentized': '(False)', 'bias_correction': '(False)', 'seed': 'seed'}), '(data, np.mean, num_reps, alpha=0.05, ci_sides=2, studentized=\n False, bias_correction=False, seed=seed)\n', (12039, 12146), False, 'from pyrado.sampling.bootstrapping import bootstrap_ci\n'), ((12167, 12185), 'numpy.all', 'np.all', (['(m >= ci_lo)'], {}), '(m >= ci_lo)\n', (12173, 12185), True, 'import numpy as np\n'), ((12197, 12215), 'numpy.all', 'np.all', (['(m <= ci_up)'], {}), '(m <= ci_up)\n', (12203, 12215), True, 'import numpy as np\n'), ((12242, 12360), 'pyrado.sampling.bootstrapping.bootstrap_ci', 'bootstrap_ci', (['data', 'np.mean', 'num_reps'], {'alpha': '(0.05)', 'ci_sides': '(2)', 'studentized': '(False)', 'bias_correction': '(True)', 'seed': 'seed'}), '(data, np.mean, num_reps, alpha=0.05, ci_sides=2, studentized=\n False, bias_correction=True, seed=seed)\n', (12254, 12360), False, 'from pyrado.sampling.bootstrapping import bootstrap_ci\n'), ((12381, 12398), 'numpy.all', 'np.all', (['(m_bc != m)'], {}), '(m_bc != m)\n', (12387, 12398), True, 'import numpy as np\n'), ((12422, 12518), 'pyrado.sampling.bootstrapping.bootstrap_ci', 'bootstrap_ci', (['data', 'np.mean', 'num_reps'], {'alpha': '(0.05)', 'ci_sides': '(1)', 'studentized': '(False)', 'seed': 'seed'}), '(data, np.mean, num_reps, alpha=0.05, ci_sides=1, studentized=\n False, seed=seed)\n', (12434, 12518), False, 'from pyrado.sampling.bootstrapping import bootstrap_ci\n'), ((12542, 12637), 'pyrado.sampling.bootstrapping.bootstrap_ci', 'bootstrap_ci', (['data', 'np.mean', 'num_reps'], {'alpha': '(0.05)', 'ci_sides': '(1)', 'studentized': '(True)', 'seed': 'seed'}), '(data, np.mean, num_reps, alpha=0.05, ci_sides=1, studentized=\n True, seed=seed)\n', (12554, 12637), False, 'from pyrado.sampling.bootstrapping import bootstrap_ci\n'), ((12679, 12701), 'numpy.all', 'np.all', (['(m_t >= ci_lo_t)'], {}), '(m_t >= ci_lo_t)\n', (12685, 12701), True, 'import numpy as np\n'), ((12713, 12735), 'numpy.all', 'np.all', (['(m_t <= ci_up_t)'], {}), '(m_t <= ci_up_t)\n', (12719, 12735), True, 'import numpy as np\n'), ((12827, 12851), 'numpy.all', 'np.all', (['(ci_lo != ci_lo_t)'], {}), '(ci_lo != ci_lo_t)\n', (12833, 12851), True, 'import numpy as np\n'), ((12863, 12887), 'numpy.all', 'np.all', (['(ci_up != ci_up_t)'], {}), '(ci_up != ci_up_t)\n', (12869, 12887), True, 'import numpy as np\n'), ((13581, 13599), 'pyrado.set_seed', 'pyrado.set_seed', (['(0)'], {}), '(0)\n', (13596, 13599), False, 'import pyrado\n'), ((13633, 13663), 'pyrado.domain_randomization.default_randomizers.create_default_randomizer', 'create_default_randomizer', (['env'], {}), '(env)\n', (13658, 13663), False, 'from pyrado.domain_randomization.default_randomizers import create_default_randomizer\n'), ((13674, 13706), 'pyrado.environment_wrappers.domain_randomization.DomainRandWrapperLive', 'DomainRandWrapperLive', (['env', 'pert'], {}), '(env, pert)\n', (13695, 13706), False, 'from pyrado.environment_wrappers.domain_randomization import DomainRandWrapperLive\n'), ((13747, 13857), 'pyrado.sampling.parameter_exploration_sampler.ParameterExplorationSampler', 'ParameterExplorationSampler', (['env', 'policy', 'num_init_states_per_domain', 'num_domains'], {'num_workers': 'num_workers'}), '(env, policy, num_init_states_per_domain,\n num_domains, num_workers=num_workers)\n', (13774, 13857), False, 'from pyrado.sampling.parameter_exploration_sampler import ParameterExplorationSampler, ParameterSamplingResult\n'), ((13916, 13949), 'torch.rand', 'to.rand', (['num_ps', 'policy.num_param'], {}), '(num_ps, policy.num_param)\n', (13923, 13949), True, 'import torch as to\n'), ((15870, 15903), 'torch.rand', 'to.rand', (['num_ps', 'policy.num_param'], {}), '(num_ps, policy.num_param)\n', (15877, 15903), True, 'import torch as to\n'), ((15919, 16033), 'pyrado.sampling.parameter_exploration_sampler.ParameterExplorationSampler', 'ParameterExplorationSampler', (['env', 'policy'], {'num_init_states_per_domain': '(1)', 'num_domains': '(1)', 'num_workers': 'num_workers'}), '(env, policy, num_init_states_per_domain=1,\n num_domains=1, num_workers=num_workers)\n', (15946, 16033), False, 'from pyrado.sampling.parameter_exploration_sampler import ParameterExplorationSampler, ParameterSamplingResult\n'), ((16839, 16876), 'torch.rand', 'to.rand', (['num_params', 'policy.num_param'], {}), '(num_params, policy.num_param)\n', (16846, 16876), True, 'import torch as to\n'), ((19120, 19195), 'pyrado.sampling.parallel_rollout_sampler.ParallelRolloutSampler', 'ParallelRolloutSampler', (['env', 'policy', 'num_workers'], {'min_rollouts': 'min_rollouts'}), '(env, policy, num_workers, min_rollouts=min_rollouts)\n', (19142, 19195), False, 'from pyrado.sampling.parallel_rollout_sampler import ParallelRolloutSampler\n'), ((19840, 19870), 'pyrado.domain_randomization.default_randomizers.create_default_randomizer', 'create_default_randomizer', (['env'], {}), '(env)\n', (19865, 19870), False, 'from pyrado.domain_randomization.default_randomizers import create_default_randomizer\n'), ((19881, 19919), 'pyrado.environment_wrappers.domain_randomization.DomainRandWrapperLive', 'DomainRandWrapperLive', (['env', 'randomizer'], {}), '(env, randomizer)\n', (19902, 19919), False, 'from pyrado.environment_wrappers.domain_randomization import DomainRandWrapperLive\n'), ((19935, 20011), 'pyrado.sampling.parallel_rollout_sampler.ParallelRolloutSampler', 'ParallelRolloutSampler', (['env', 'policy'], {'num_workers': 'num_workers', 'min_rollouts': '(4)'}), '(env, policy, num_workers=num_workers, min_rollouts=4)\n', (19957, 20011), False, 'from pyrado.sampling.parallel_rollout_sampler import ParallelRolloutSampler\n'), ((20987, 21087), 'pyrado.sampling.parallel_rollout_sampler.ParallelRolloutSampler', 'ParallelRolloutSampler', (['env', 'policy'], {'num_workers': 'num_workers', 'min_rollouts': 'num_rollouts', 'seed': '(0)'}), '(env, policy, num_workers=num_workers, min_rollouts=\n num_rollouts, seed=0)\n', (21009, 21087), False, 'from pyrado.sampling.parallel_rollout_sampler import ParallelRolloutSampler\n'), ((3823, 3843), 'random.randint', 'random.randint', (['(1)', '(5)'], {}), '(1, 5)\n', (3837, 3843), False, 'import random\n'), ((5992, 6048), 'pyrado.sampling.step_sequence.StepSequence', 'StepSequence', ([], {'rewards': '[i]', 'observations': '[i]', 'actions': '[i]'}), '(rewards=[i], observations=[i], actions=[i])\n', (6004, 6048), False, 'from pyrado.sampling.step_sequence import StepSequence\n'), ((6983, 6998), 'torch.norm', 'to.norm', (['s'], {'p': '(2)'}), '(s, p=2)\n', (6990, 6998), True, 'import torch as to\n'), ((8789, 8818), 'torch.distributions.multivariate_normal.MultivariateNormal', 'MultivariateNormal', (['mean', 'cov'], {}), '(mean, cov)\n', (8807, 8818), False, 'from torch.distributions.multivariate_normal import MultivariateNormal\n'), ((8827, 8847), 'torch.manual_seed', 'to.manual_seed', (['seed'], {}), '(seed)\n', (8841, 8847), True, 'import torch as to\n'), ((8951, 8971), 'torch.manual_seed', 'to.manual_seed', (['seed'], {}), '(seed)\n', (8965, 8971), True, 'import torch as to\n'), ((9080, 9100), 'torch.manual_seed', 'to.manual_seed', (['seed'], {}), '(seed)\n', (9094, 9100), True, 'import torch as to\n'), ((9194, 9252), 'torch.testing.assert_allclose', 'to.testing.assert_allclose', (['smpl_distr', 'smpl_distr_reparam'], {}), '(smpl_distr, smpl_distr_reparam)\n', (9220, 9252), True, 'import torch as to\n'), ((9261, 9313), 'torch.testing.assert_allclose', 'to.testing.assert_allclose', (['smpl_distr', 'smpl_reparam'], {}), '(smpl_distr, smpl_reparam)\n', (9287, 9313), True, 'import torch as to\n'), ((9322, 9382), 'torch.testing.assert_allclose', 'to.testing.assert_allclose', (['smpl_distr_reparam', 'smpl_reparam'], {}), '(smpl_distr_reparam, smpl_reparam)\n', (9348, 9382), True, 'import torch as to\n'), ((10457, 10469), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (10467, 10469), True, 'import matplotlib.pyplot as plt\n'), ((10478, 10488), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10486, 10488), True, 'import matplotlib.pyplot as plt\n'), ((9426, 9470), 'pytest.param', 'pytest.param', (['(True)'], {'marks': 'pytest.mark.visual'}), '(True, marks=pytest.mark.visual)\n', (9438, 9470), False, 'import pytest\n'), ((10527, 10577), 'numpy.array', 'np.array', (['[30, 37, 36, 43, 42, 43, 43, 46, 41, 42]'], {}), '([30, 37, 36, 43, 42, 43, 43, 46, 41, 42])\n', (10535, 10577), True, 'import numpy as np\n'), ((12649, 12667), 'pytest.approx', 'pytest.approx', (['m_t'], {}), '(m_t)\n', (12662, 12667), False, 'import pytest\n'), ((11511, 11541), 'numpy.random.normal', 'np.random.normal', (['(10)', '(1)', '(40,)'], {}), '(10, 1, (40,))\n', (11527, 11541), True, 'import numpy as np\n'), ((11543, 11591), 'numpy.random.normal', 'np.random.normal', (['(1, 7, 13)', '(1, 1, 1)', '(40, 3)'], {}), '((1, 7, 13), (1, 1, 1), (40, 3))\n', (11559, 11591), True, 'import numpy as np\n'), ((17320, 17338), 'pyrado.set_seed', 'pyrado.set_seed', (['(0)'], {}), '(0)\n', (17335, 17338), False, 'import pyrado\n'), ((20135, 20191), 'pytest.param', 'pytest.param', (['"""default_qqsurcs_bt"""'], {'marks': 'm_needs_bullet'}), "('default_qqsurcs_bt', marks=m_needs_bullet)\n", (20147, 20191), False, 'import pytest\n'), ((5014, 5034), 'numpy.random.rand', 'np.random.rand', (['(3)', '(2)'], {}), '(3, 2)\n', (5028, 5034), True, 'import numpy as np\n'), ((5073, 5086), 'torch.rand', 'to.rand', (['(3)', '(2)'], {}), '(3, 2)\n', (5080, 5086), True, 'import torch as to\n'), ((7986, 7998), 'pyrado.utils.data_types.RenderMode', 'RenderMode', ([], {}), '()\n', (7996, 7998), False, 'from pyrado.utils.data_types import RenderMode\n'), ((8399, 8411), 'pyrado.utils.data_types.RenderMode', 'RenderMode', ([], {}), '()\n', (8409, 8411), False, 'from pyrado.utils.data_types import RenderMode\n'), ((8540, 8561), 'torch.tensor', 'to.tensor', (['[5.0, 7.0]'], {}), '([5.0, 7.0])\n', (8549, 8561), True, 'import torch as to\n'), ((8563, 8598), 'torch.tensor', 'to.tensor', (['[[2.0, 0.0], [0.0, 2.0]]'], {}), '([[2.0, 0.0], [0.0, 2.0]])\n', (8572, 8598), True, 'import torch as to\n'), ((9554, 9567), 'numpy.array', 'np.array', (['[2]'], {}), '([2])\n', (9562, 9567), True, 'import numpy as np\n'), ((9598, 9611), 'numpy.array', 'np.array', (['[2]'], {}), '([2])\n', (9606, 9611), True, 'import numpy as np\n'), ((9642, 9655), 'numpy.array', 'np.array', (['[2]'], {}), '([2])\n', (9650, 9655), True, 'import numpy as np\n'), ((9688, 9701), 'numpy.array', 'np.array', (['[2]'], {}), '([2])\n', (9696, 9701), True, 'import numpy as np\n'), ((9732, 9745), 'numpy.array', 'np.array', (['[2]'], {}), '([2])\n', (9740, 9745), True, 'import numpy as np\n'), ((9773, 9786), 'numpy.array', 'np.array', (['[2]'], {}), '([2])\n', (9781, 9786), True, 'import numpy as np\n'), ((9814, 9833), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (9822, 9833), True, 'import numpy as np\n'), ((9864, 9883), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (9872, 9883), True, 'import numpy as np\n'), ((9914, 9933), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (9922, 9933), True, 'import numpy as np\n'), ((9966, 9985), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (9974, 9985), True, 'import numpy as np\n'), ((10016, 10035), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (10024, 10035), True, 'import numpy as np\n'), ((10063, 10082), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (10071, 10082), True, 'import numpy as np\n'), ((17887, 17918), 'pytest.approx', 'pytest.approx', (['psr_b.parameters'], {}), '(psr_b.parameters)\n', (17900, 17918), False, 'import pytest\n'), ((17956, 17989), 'pytest.approx', 'pytest.approx', (['psr_b.mean_returns'], {}), '(psr_b.mean_returns)\n', (17969, 17989), False, 'import pytest\n'), ((20781, 20848), 'pyrado.sampling.rollout.rollout', 'rollout', (['env', 'policy'], {'eval': '(True)', 'seed': '(0)', 'sub_seed': '(0)', 'sub_sub_seed': 'i'}), '(env, policy, eval=True, seed=0, sub_seed=0, sub_sub_seed=i)\n', (20788, 20848), False, 'from pyrado.sampling.rollout import rollout\n'), ((21253, 21280), 'pytest.approx', 'pytest.approx', (['ro_p.rewards'], {}), '(ro_p.rewards)\n', (21266, 21280), False, 'import pytest\n'), ((21317, 21349), 'pytest.approx', 'pytest.approx', (['ro_p.observations'], {}), '(ro_p.observations)\n', (21330, 21349), False, 'import pytest\n'), ((21381, 21408), 'pytest.approx', 'pytest.approx', (['ro_p.actions'], {}), '(ro_p.actions)\n', (21394, 21408), False, 'import pytest\n'), ((27696, 27717), 'pyrado.set_seed', 'pyrado.set_seed', (['seed'], {}), '(seed)\n', (27711, 27717), False, 'import pyrado\n'), ((27856, 27882), 'pyrado.logger.set_log_prefix_dir', 'set_log_prefix_dir', (['ex_dir'], {}), '(ex_dir)\n', (27874, 27882), False, 'from pyrado.logger import set_log_prefix_dir\n'), ((27902, 28005), 'pyrado.policies.feed_back.fnn.FNN', 'FNN', ([], {'input_size': 'env.obs_space.flat_dim', 'output_size': '(1)', 'hidden_sizes': '[16, 16]', 'hidden_nonlin': 'to.tanh'}), '(input_size=env.obs_space.flat_dim, output_size=1, hidden_sizes=[16, 16],\n hidden_nonlin=to.tanh)\n', (27905, 28005), False, 'from pyrado.policies.feed_back.fnn import FNN\n'), ((28023, 28109), 'pyrado.algorithms.step_based.gae.GAE', 'GAE', (['vfcn'], {'gamma': '(0.98)', 'lamda': '(0.95)', 'batch_size': '(32)', 'lr': '(0.001)', 'standardize_adv': '(False)'}), '(vfcn, gamma=0.98, lamda=0.95, batch_size=32, lr=0.001, standardize_adv=\n False)\n', (28026, 28109), False, 'from pyrado.algorithms.step_based.gae import GAE\n'), ((28246, 28279), 'pyrado.algorithms.utils.RolloutSavingWrapper', 'RolloutSavingWrapper', (['alg.sampler'], {}), '(alg.sampler)\n', (28266, 28279), False, 'from pyrado.algorithms.utils import RolloutSavingWrapper\n'), ((30292, 30313), 'pyrado.set_seed', 'pyrado.set_seed', (['seed'], {}), '(seed)\n', (30307, 30313), False, 'import pyrado\n'), ((30452, 30478), 'pyrado.logger.set_log_prefix_dir', 'set_log_prefix_dir', (['ex_dir'], {}), '(ex_dir)\n', (30470, 30478), False, 'from pyrado.logger import set_log_prefix_dir\n'), ((30498, 30601), 'pyrado.policies.feed_back.fnn.FNN', 'FNN', ([], {'input_size': 'env.obs_space.flat_dim', 'output_size': '(1)', 'hidden_sizes': '[16, 16]', 'hidden_nonlin': 'to.tanh'}), '(input_size=env.obs_space.flat_dim, output_size=1, hidden_sizes=[16, 16],\n hidden_nonlin=to.tanh)\n', (30501, 30601), False, 'from pyrado.policies.feed_back.fnn import FNN\n'), ((30619, 30705), 'pyrado.algorithms.step_based.gae.GAE', 'GAE', (['vfcn'], {'gamma': '(0.98)', 'lamda': '(0.95)', 'batch_size': '(32)', 'lr': '(0.001)', 'standardize_adv': '(False)'}), '(vfcn, gamma=0.98, lamda=0.95, batch_size=32, lr=0.001, standardize_adv=\n False)\n', (30622, 30705), False, 'from pyrado.algorithms.step_based.gae import GAE\n'), ((31022, 31055), 'pyrado.algorithms.utils.RolloutSavingWrapper', 'RolloutSavingWrapper', (['alg.sampler'], {}), '(alg.sampler)\n', (31042, 31055), False, 'from pyrado.algorithms.utils import RolloutSavingWrapper\n'), ((9164, 9183), 'torch.randn_like', 'to.randn_like', (['mean'], {}), '(mean)\n', (9177, 9183), True, 'import torch as to\n'), ((15171, 15209), 'pytest.approx', 'pytest.approx', (['other_ro[0].observation'], {}), '(other_ro[0].observation)\n', (15184, 15209), False, 'import pytest\n'), ((24157, 24184), 'pytest.approx', 'pytest.approx', (['ro_b.rewards'], {}), '(ro_b.rewards)\n', (24170, 24184), False, 'import pytest\n'), ((24225, 24257), 'pytest.approx', 'pytest.approx', (['ro_b.observations'], {}), '(ro_b.observations)\n', (24238, 24257), False, 'import pytest\n'), ((24293, 24320), 'pytest.approx', 'pytest.approx', (['ro_b.actions'], {}), '(ro_b.actions)\n', (24306, 24320), False, 'import pytest\n'), ((26785, 26812), 'pytest.approx', 'pytest.approx', (['ro_b.rewards'], {}), '(ro_b.rewards)\n', (26798, 26812), False, 'import pytest\n'), ((26853, 26885), 'pytest.approx', 'pytest.approx', (['ro_b.observations'], {}), '(ro_b.observations)\n', (26866, 26885), False, 'import pytest\n'), ((26921, 26948), 'pytest.approx', 'pytest.approx', (['ro_b.actions'], {}), '(ro_b.actions)\n', (26934, 26948), False, 'import pytest\n'), ((9131, 9160), 'torch.cholesky', 'to.cholesky', (['cov'], {'upper': '(False)'}), '(cov, upper=False)\n', (9142, 9160), True, 'import torch as to\n'), ((17379, 17542), 'pyrado.sampling.parameter_exploration_sampler.ParameterExplorationSampler', 'ParameterExplorationSampler', (['env', 'policy'], {'num_init_states_per_domain': 'num_init_states_per_domain', 'num_domains': 'num_domains', 'num_workers': 'num_workers', 'seed': '(0)'}), '(env, policy, num_init_states_per_domain=\n num_init_states_per_domain, num_domains=num_domains, num_workers=\n num_workers, seed=0)\n', (17406, 17542), False, 'from pyrado.sampling.parameter_exploration_sampler import ParameterExplorationSampler, ParameterSamplingResult\n'), ((18257, 18284), 'pytest.approx', 'pytest.approx', (['ro_b.rewards'], {}), '(ro_b.rewards)\n', (18270, 18284), False, 'import pytest\n'), ((18329, 18361), 'pytest.approx', 'pytest.approx', (['ro_b.observations'], {}), '(ro_b.observations)\n', (18342, 18361), False, 'import pytest\n'), ((18401, 18428), 'pytest.approx', 'pytest.approx', (['ro_b.actions'], {}), '(ro_b.actions)\n', (18414, 18428), False, 'import pytest\n'), ((23720, 23747), 'pytest.approx', 'pytest.approx', (['ro_b.rewards'], {}), '(ro_b.rewards)\n', (23733, 23747), False, 'import pytest\n'), ((23792, 23824), 'pytest.approx', 'pytest.approx', (['ro_b.observations'], {}), '(ro_b.observations)\n', (23805, 23824), False, 'import pytest\n'), ((23864, 23891), 'pytest.approx', 'pytest.approx', (['ro_b.actions'], {}), '(ro_b.actions)\n', (23877, 23891), False, 'import pytest\n'), ((25989, 26016), 'pytest.approx', 'pytest.approx', (['ro_b.rewards'], {}), '(ro_b.rewards)\n', (26002, 26016), False, 'import pytest\n'), ((26061, 26093), 'pytest.approx', 'pytest.approx', (['ro_b.observations'], {}), '(ro_b.observations)\n', (26074, 26093), False, 'import pytest\n'), ((26133, 26160), 'pytest.approx', 'pytest.approx', (['ro_b.actions'], {}), '(ro_b.actions)\n', (26146, 26160), False, 'import pytest\n'), ((22463, 22508), 'pyrado.exploration.stochastic_action.NormalActNoiseExplStrat', 'NormalActNoiseExplStrat', (['policy'], {'std_init': '(1.0)'}), '(policy, std_init=1.0)\n', (22486, 22508), False, 'from pyrado.exploration.stochastic_action import NormalActNoiseExplStrat\n'), ((23554, 23581), 'pytest.approx', 'pytest.approx', (['ro_b.rewards'], {}), '(ro_b.rewards)\n', (23567, 23581), False, 'import pytest\n'), ((23630, 23662), 'pytest.approx', 'pytest.approx', (['ro_b.observations'], {}), '(ro_b.observations)\n', (23643, 23662), False, 'import pytest\n'), ((25241, 25286), 'pyrado.exploration.stochastic_action.NormalActNoiseExplStrat', 'NormalActNoiseExplStrat', (['policy'], {'std_init': '(1.0)'}), '(policy, std_init=1.0)\n', (25264, 25286), False, 'from pyrado.exploration.stochastic_action import NormalActNoiseExplStrat\n'), ((28897, 28928), 'pytest.approx', 'pytest.approx', (['r_b.observations'], {}), '(r_b.observations)\n', (28910, 28928), False, 'import pytest\n'), ((31673, 31704), 'pytest.approx', 'pytest.approx', (['r_b.observations'], {}), '(r_b.observations)\n', (31686, 31704), False, 'import pytest\n')] |
"""Miscellaneous functions that do not fit into other modules. You can find here for example functions for train / test split,
function for rolling windows, function that clean the dataframe for print in table or function that will add gaps to time series
data where are no data so two remote points are not joined in plot."""
from __future__ import annotations
import json
import textwrap
from typing import overload
import pandas as pd
import numpy as np
import mylogging
from .preprocessing import remove_the_outliers
def rolling_windows(data: np.ndarray, window: int) -> np.ndarray:
"""Generate matrix of rolling windows.
Example:
>>> rolling_windows(np.array([1, 2, 3, 4, 5]), window=2)
array([[1, 2],
[2, 3],
[3, 4],
[4, 5]])
Args:
data (np.ndarray): Array data input.
window (int): Number of values in created window.
Returns:
np.ndarray: Array of defined windows
"""
shape = data.shape[:-1] + (data.shape[-1] - window + 1, window)
strides = data.strides + (data.strides[-1],)
return np.lib.stride_tricks.as_strided(data, shape=shape, strides=strides)
@overload
def split(data: pd.DataFrame, predicts: int = 7) -> tuple[pd.DataFrame, pd.Series]:
...
@overload
def split(data: np.ndarray, predicts: int = 7) -> tuple[np.ndarray, np.ndarray]:
...
def split(data, predicts=7):
"""Divide data set on train and test set. Predicted column is supposed to be 0. This is mostly for time series predictions,
so in test set there is only predicted column that can be directly used for error criterion evaluation. So this function is
different than usual train / test split.
Args:
data (pd.DataFrame | np.ndarray): Time series data. ndim has to be 2, reshape if necessary.
predicts (int, optional): Number of predicted values. Defaults to 7.
Returns:
tuple[pd.DataFrame | np.ndarray, pd.Series | np.ndarray]: Train set and test set. If input in numpy array, then also output in array,
if dataframe input, then dataframe output.
Example:
>>> data = np.array([[1], [2], [3], [4]])
>>> train, test = split(data, predicts=2)
>>> train
array([[1],
[2]])
>>> test
array([3, 4])
"""
if isinstance(data, pd.DataFrame):
train = data.iloc[:-predicts, :]
test = data.iloc[-predicts:, 0]
else:
train = data[:-predicts, :]
test = data[-predicts:, 0]
return train, test
def add_none_to_gaps(df: pd.DataFrame) -> pd.DataFrame:
"""If empty windows in sampled signal, it will add None values (one row) to the empty window start.
Reason is to correct plotting. Points are connected, but not between two gaps.
Args:
df (pd.DataFrame): Dataframe with time index.
Returns:
pd.DataFrame: Dataframe with None row inserted in time gaps.
Raises:
NotImplementedError: String values are not supported, use only numeric columns.
Note:
Df will be converted to float64 dtypes, to be able to use np.nan.
Example:
>>> data = pd.DataFrame([[0, 1]] * 7, index=[0.1, 0.2, 0.3, 1.0, 1.1, 1.2, 2.0])
>>> data
0 1
0.1 0 1
0.2 0 1
0.3 0 1
1.0 0 1
1.1 0 1
1.2 0 1
2.0 0 1
>>> df_gaps = add_none_to_gaps(data)
>>> df_gaps
0 1
0.1 0.0 1.0
0.2 0.0 1.0
0.3 0.0 1.0
0.4 NaN NaN
1.0 0.0 1.0
1.1 0.0 1.0
1.2 0.0 1.0
1.3 NaN NaN
2.0 0.0 1.0
"""
sampling = remove_the_outliers(np.diff(df.index[:50]).reshape(-1, 1), threshold=1).mean()
sampling_threshold = sampling * 3
nons = []
memory = None
for i in df.index:
if memory and i - memory > sampling_threshold:
nons.append(
pd.DataFrame([[np.nan] * df.shape[1]], index=[memory + sampling], columns=df.columns,)
)
memory = i
try:
result = pd.concat([df, *nons]).sort_index()
return result
except NotImplementedError:
mylogging.traceback("If object dtype in DataFrame, it will fail. Use only numeric dtypes.")
raise
def edit_table_to_printable(
df: pd.DataFrame,
line_length_limit: int = 16,
round_decimals: int = 3,
number_length_limit: int | float = 10e8,
) -> pd.DataFrame:
"""Edit dataframe to be able to use in tabulate (or somewhere else).
Args:
df (pd.DataFrame): Input data with numeric or text columns.
line_length_limit (int, optional): Add line breaks if line too long. Defaults to 16.
round_decimals (int, optional): Round numeric columns to defined decimals. Defaults to 3.
number_length_limit (int | float, optional): If there is some very big or very small number,
convert format to scientific notation. Defaults to 10e8.
Returns:
pd.DataFrame: Dataframe with shorter and more readable to be printed (usually in table).
Note:
Dataframe column names can be changed ('\n' is added).
Example:
>>> df = pd.DataFrame([[151646516516, 1.5648646, "Lorem ipsum something else"]])
>>> for_table = edit_table_to_printable(df).values[0]
>>> for_table[0]
'1.516e+11'
>>> for_table[1]
1.565
>>> for_table[2]
'Lorem ipsum\\nsomething else'
"""
df.columns = [
(textwrap.fill(i, line_length_limit) if (isinstance(i, str) and len(i)) > line_length_limit else i)
for i in df.columns
]
for _, df_i in df.iteritems():
if pd.api.types.is_numeric_dtype(df_i):
# Replace very big numbers with scientific notation
if df_i.max() > number_length_limit or df_i.min() < -number_length_limit:
for k, l in df_i.iteritems():
if l > number_length_limit or l < -number_length_limit:
df_i[k] = f"{l:.3e}"
else:
for k, l in df_i.iteritems():
# Add line breaks to long strings
if isinstance(l, str) and len(l) > line_length_limit:
df_i[k] = textwrap.fill(df_i[k], line_length_limit)
# Convert dictionaries to formated strings
if isinstance(l, dict):
for i, j in df_i[k].items():
if isinstance(j, (int, float)):
if j > 10 ** -round_decimals:
df_i[k][i] = round(j, round_decimals)
if j > number_length_limit or j < -number_length_limit:
df_i[k][i] = f"{j:.3e}"
df_i[k] = json.dumps(l, indent=2)
df = df.round(round_decimals)
return df
| [
"pandas.DataFrame",
"textwrap.fill",
"json.dumps",
"numpy.lib.stride_tricks.as_strided",
"numpy.diff",
"pandas.api.types.is_numeric_dtype",
"mylogging.traceback",
"pandas.concat"
] | [((1118, 1185), 'numpy.lib.stride_tricks.as_strided', 'np.lib.stride_tricks.as_strided', (['data'], {'shape': 'shape', 'strides': 'strides'}), '(data, shape=shape, strides=strides)\n', (1149, 1185), True, 'import numpy as np\n'), ((5745, 5780), 'pandas.api.types.is_numeric_dtype', 'pd.api.types.is_numeric_dtype', (['df_i'], {}), '(df_i)\n', (5774, 5780), True, 'import pandas as pd\n'), ((4230, 4326), 'mylogging.traceback', 'mylogging.traceback', (['"""If object dtype in DataFrame, it will fail. Use only numeric dtypes."""'], {}), "(\n 'If object dtype in DataFrame, it will fail. Use only numeric dtypes.')\n", (4249, 4326), False, 'import mylogging\n'), ((5564, 5599), 'textwrap.fill', 'textwrap.fill', (['i', 'line_length_limit'], {}), '(i, line_length_limit)\n', (5577, 5599), False, 'import textwrap\n'), ((3985, 4075), 'pandas.DataFrame', 'pd.DataFrame', (['[[np.nan] * df.shape[1]]'], {'index': '[memory + sampling]', 'columns': 'df.columns'}), '([[np.nan] * df.shape[1]], index=[memory + sampling], columns=\n df.columns)\n', (3997, 4075), True, 'import pandas as pd\n'), ((4132, 4154), 'pandas.concat', 'pd.concat', (['[df, *nons]'], {}), '([df, *nons])\n', (4141, 4154), True, 'import pandas as pd\n'), ((6306, 6347), 'textwrap.fill', 'textwrap.fill', (['df_i[k]', 'line_length_limit'], {}), '(df_i[k], line_length_limit)\n', (6319, 6347), False, 'import textwrap\n'), ((6851, 6874), 'json.dumps', 'json.dumps', (['l'], {'indent': '(2)'}), '(l, indent=2)\n', (6861, 6874), False, 'import json\n'), ((3736, 3758), 'numpy.diff', 'np.diff', (['df.index[:50]'], {}), '(df.index[:50])\n', (3743, 3758), True, 'import numpy as np\n')] |
from pepnet import SequenceInput, Output, Predictor
import numpy as np
from collections import Counter
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold
import random
from helpers import to_ic50, from_ic50
from data import (
load_iedb_binding_data,
load_mass_spec,
generate_negatives_from_proteome,
load_pseudosequences)
N_EPOCHS = 10
TRAINING_DECOY_FACTOR = 0.5
DECOY_WEIGHT_FOR_QUANTITATIVE_ASSAYS = 0.01
TEST_DECOY_FACTOR = 9
MIN_ASSAY_COUNT = 10000
ONLY_HLA_DR = False
ASSAY = None # "half maximal inhibitory concentration (IC50):purified MHC/competitive/radioactivity"
def make_model(sufficiently_large_output_names):
mhc = SequenceInput(
length=34,
name="mhc",
encoding="index",
variable_length=True,
embedding_dim=20,
embedding_mask_zero=False,
dense_layer_sizes=[64],
dense_batch_normalization=True)
peptide = SequenceInput(
length=50,
name="peptide",
encoding="index",
embedding_dim=20,
embedding_mask_zero=True,
variable_length=True,
conv_filter_sizes=[1, 9, 10],
conv_activation="relu",
conv_output_dim=32,
n_conv_layers=2,
# conv_weight_source=mhc,
global_pooling=True,
global_pooling_batch_normalization=True)
outputs = []
for output_name in sufficiently_large_output_names:
if "IC50" in output_name or "EC50" in output_name:
transform = from_ic50
inverse = to_ic50
activation = "sigmoid"
elif "half life" in output_name:
transform = (lambda x: np.log10(x + 1))
inverse = (lambda x: (10.0 ** x) - 1)
activation = "relu"
else:
transform = None
inverse = None
activation = "sigmoid"
output = Output(
name=output_name,
transform=transform,
inverse_transform=inverse,
activation=activation)
print(output)
outputs.append(output)
return Predictor(
inputs=[mhc, peptide],
outputs=outputs,
merge_mode="concat",
dense_layer_sizes=[32],
dense_activation="tanh",
dense_batch_normalization=True)
def main():
mhc_pseudosequences_dict = load_pseudosequences()
hit_peptides, hit_mhc_seqs, decoy_peptides, decoy_mhc_sequences = \
load_mass_spec(mhc_pseudosequences_dict, decoy_factor=TEST_DECOY_FACTOR) # restrict_allele="HLA-DRA10101-DRB10101")
# Mass spec validation set
mass_spec_test_peptides = hit_peptides + decoy_peptides
mass_spec_test_mhc_sequences = hit_mhc_seqs + decoy_mhc_sequences
Y_mass_spec = np.zeros(len(mass_spec_test_peptides), dtype="int32")
Y_mass_spec[:len(hit_peptides)] = 1
assert Y_mass_spec.sum() == len(hit_peptides)
df = load_iedb_binding_data() # restrict_allele="HLA-DRA10101-DRB10101")
print("Allele names in binding data:\n%s" % (df.mhc.value_counts(),))
# Restrict binding data to alleles for which we have pseudosequences
valid_mhc_set = set(mhc_pseudosequences_dict.keys())
valid_mhc_mask = df.mhc.isin(valid_mhc_set)
print("Dropping %d rows without pseudosequences, invalid alleles:\n%s" % (
len(df) - valid_mhc_mask.sum(),
df[~valid_mhc_mask].mhc.value_counts()))
df = df[valid_mhc_mask]
if ONLY_HLA_DR:
dr_mask = df.mhc.str.contains("DR")
print("%d rows with HLA-DR" % dr_mask.sum())
df = df[dr_mask]
print("Kept %d rows" % (len(df)))
df["output_name"] = df["assay_group"] + ":" + df["assay_method"]
if ASSAY:
n_old = len(df)
df = df[df.output_name == ASSAY]
print("Kept %d/%d rows with assay %s" % (len(df), n_old, ASSAY))
output_counts = df.output_name.value_counts()
sufficiently_large_output_counts = output_counts[output_counts >= MIN_ASSAY_COUNT]
print("Keeping outputs: %s" % (sufficiently_large_output_counts,))
sufficiently_large_output_names = set(sufficiently_large_output_counts.index)
df_subset = df[df.output_name.isin(sufficiently_large_output_names)]
print(df_subset.head())
print("Number of measurements: %d" % len(df_subset))
predictor = make_model(sufficiently_large_output_names)
predictor.save_diagram()
unique_pmhcs = set(zip(df_subset["peptide"], df_subset["mhc"]))
print("Number of unique pMHCs: %d" % len(unique_pmhcs))
pmhc_list = sorted(unique_pmhcs)
random.shuffle(pmhc_list)
iedb_peptides = [p for (p, _) in pmhc_list]
iedb_mhc_names = [m for (_, m) in pmhc_list]
iedb_mhc_sequences = [
mhc_pseudosequences_dict[mhc_name]
for mhc_name in iedb_mhc_names
]
mhc_name_counts = Counter()
for name in iedb_mhc_names:
mhc_name_counts[name] += 1
print("Top MHC names:\n%s" % (mhc_name_counts,))
mhc_seq_counts = Counter()
for seq in iedb_mhc_sequences:
mhc_seq_counts[seq] += 1
print("Top MHC seqs:\n%s" % (mhc_seq_counts,))
n_unique_pmhc = len(pmhc_list)
pmhc_index_dict = {key: i for (i, key) in enumerate(pmhc_list)}
assert pmhc_index_dict[(iedb_peptides[100], iedb_mhc_names[100])] == 100
output_name_list = [o.name for o in predictor.outputs]
output_name_index_dict = {
output_name: i for i, output_name in enumerate(output_name_list)}
n_outputs = len(output_name_list)
output_is_quantitative_dict = {
output_name: any(
[(substr in output_name) for substr in ("IC50", "EC50", "half life")])
for output_name in output_name_list
}
print(output_is_quantitative_dict)
sums = np.zeros((n_unique_pmhc, n_outputs), dtype="float64")
counts = np.zeros_like(sums, dtype="float64")
for i, (output_name, peptide, mhc, qual, meas) in enumerate(zip(
df_subset.output_name, df_subset.peptide, df_subset.mhc,
df_subset.qual, df_subset.meas)):
row_idx = pmhc_index_dict[(peptide, mhc)]
col_idx = output_name_index_dict[output_name]
if output_is_quantitative_dict[output_name]:
if np.isnan(meas):
continue
counts[row_idx, col_idx] += 1
sums[row_idx, col_idx] += np.log10(1 + meas)
else:
counts[row_idx, col_idx] += 1
sums[row_idx, col_idx] += qual.startswith("Positive")
Y_iedb = sums / counts
for name, col_idx in output_name_index_dict.items():
if output_is_quantitative_dict[name]:
Y_iedb[:, col_idx] = 10.0 ** Y_iedb[:, col_idx] - 1
else:
Y_iedb[:, col_idx] = Y_iedb[:, col_idx] > 0.5
Y_iedb[counts == 0] = np.nan
cv_iterator = StratifiedKFold(3)
for train_idx, test_idx in cv_iterator.split(iedb_peptides, iedb_mhc_sequences):
train_peptides = [iedb_peptides[i] for i in train_idx]
test_peptides = [iedb_peptides[i] for i in test_idx]
Y_train_iedb = Y_iedb[train_idx, :]
train_mhc_seqs = [iedb_mhc_sequences[i] for i in train_idx]
test_mhc_seqs = [iedb_mhc_sequences[i] for i in test_idx]
Y_test_iedb = Y_iedb[test_idx, :]
assert len(train_mhc_seqs) == len(train_peptides) == len(Y_train_iedb)
assert len(test_mhc_seqs) == len(test_peptides) == len(Y_test_iedb)
for epoch in range(N_EPOCHS):
print("--- EPOCH %d/%d" % (epoch + 1, N_EPOCHS))
negative_training_peptides = generate_negatives_from_proteome(
peptides=train_peptides,
factor=TRAINING_DECOY_FACTOR)
# maintain the proportion of MHCs to not create a bias that rare MHCs are
# more likely to produce non-binders
negative_training_mhcs = list(np.random.choice(
train_mhc_seqs,
size=len(negative_training_peptides)))
Y_training_negative = np.zeros((len(negative_training_peptides), len(predictor.outputs)))
for i, output in enumerate(predictor.outputs):
if output.inverse_transform:
Y_training_negative[:, i] = output.inverse_transform(Y_training_negative[:, i])
combined_training_peptides = train_peptides + negative_training_peptides
combined_training_mhc_sequences = train_mhc_seqs + negative_training_mhcs
combined_training_output_values = np.vstack([Y_train_iedb, Y_training_negative])
assert len(combined_training_peptides) == len(combined_training_mhc_sequences)
assert len(combined_training_peptides) == len(combined_training_output_values)
real_to_decoy_ratio = (
len(Y_train_iedb) /
float(1 + len(negative_training_peptides)))
# print("Real sample to decoy ratio: %0.4f" % real_to_decoy_ratio)
training_weights_dict = {}
for o in predictor.outputs:
output_name = o.name
weights = np.ones(len(combined_training_peptides), dtype="float32")
if output_is_quantitative_dict[output_name]:
weights[len(train_peptides):] = (
DECOY_WEIGHT_FOR_QUANTITATIVE_ASSAYS * real_to_decoy_ratio)
else:
weights[len(train_peptides):] = real_to_decoy_ratio
training_weights_dict[output_name] = weights
predictor.fit({
"peptide": combined_training_peptides,
"mhc": combined_training_mhc_sequences},
combined_training_output_values,
epochs=1,
sample_weight=training_weights_dict)
Y_pred_mass_spec_dict = predictor.predict_scores({
"peptide": mass_spec_test_peptides,
"mhc": mass_spec_test_mhc_sequences})
Y_pred_train_dict = predictor.predict_scores({
"peptide": train_peptides,
"mhc": train_mhc_seqs})
Y_pred_test_dict = predictor.predict_scores({
"peptide": test_peptides,
"mhc": test_mhc_seqs})
for output_name, Y_pred_mass_spec in Y_pred_mass_spec_dict.items():
print("-- %s" % output_name)
col_idx = output_name_index_dict[output_name]
Y_train_iedb_curr_assay = Y_train_iedb[:, col_idx]
Y_test_iedb_curr_assay = Y_test_iedb[:, col_idx]
if "IC50" in output_name or "EC50" in output_name:
Y_train_label = Y_train_iedb_curr_assay <= 500
Y_test_label = Y_test_iedb_curr_assay <= 500
elif "half life" in output_name:
Y_train_label = Y_train_iedb_curr_assay >= 120
Y_test_label = Y_test_iedb_curr_assay >= 120
else:
assert not output_is_quantitative_dict[output_name], output_name
Y_train_label = Y_train_iedb_curr_assay > 0.5
Y_test_label = Y_test_iedb_curr_assay > 0.5
print("----> Training AUC=%0.4f" % (roc_auc_score(
y_true=Y_train_label,
y_score=Y_pred_train_dict[output_name]),))
print("----> Test Set AUC=%0.4f" % (roc_auc_score(
y_true=Y_test_label,
y_score=Y_pred_test_dict[output_name]),))
auc_mass_spec = roc_auc_score(
y_true=Y_mass_spec,
y_score=Y_pred_mass_spec)
descending_indices = np.argsort(-Y_pred_mass_spec)
n_hits = Y_mass_spec.sum()
ppv_mass_spec = Y_mass_spec[descending_indices[:n_hits]].mean()
print("----> Mass Spec %s AUC=%0.4f, PPV=%0.4f" % (
output_name,
auc_mass_spec,
ppv_mass_spec))
if __name__ == "__main__":
main()
| [
"pepnet.Output",
"numpy.zeros_like",
"random.shuffle",
"pepnet.SequenceInput",
"data.generate_negatives_from_proteome",
"numpy.zeros",
"numpy.isnan",
"data.load_iedb_binding_data",
"sklearn.metrics.roc_auc_score",
"numpy.argsort",
"data.load_pseudosequences",
"sklearn.model_selection.Stratifie... | [((700, 885), 'pepnet.SequenceInput', 'SequenceInput', ([], {'length': '(34)', 'name': '"""mhc"""', 'encoding': '"""index"""', 'variable_length': '(True)', 'embedding_dim': '(20)', 'embedding_mask_zero': '(False)', 'dense_layer_sizes': '[64]', 'dense_batch_normalization': '(True)'}), "(length=34, name='mhc', encoding='index', variable_length=True,\n embedding_dim=20, embedding_mask_zero=False, dense_layer_sizes=[64],\n dense_batch_normalization=True)\n", (713, 885), False, 'from pepnet import SequenceInput, Output, Predictor\n'), ((958, 1247), 'pepnet.SequenceInput', 'SequenceInput', ([], {'length': '(50)', 'name': '"""peptide"""', 'encoding': '"""index"""', 'embedding_dim': '(20)', 'embedding_mask_zero': '(True)', 'variable_length': '(True)', 'conv_filter_sizes': '[1, 9, 10]', 'conv_activation': '"""relu"""', 'conv_output_dim': '(32)', 'n_conv_layers': '(2)', 'global_pooling': '(True)', 'global_pooling_batch_normalization': '(True)'}), "(length=50, name='peptide', encoding='index', embedding_dim=20,\n embedding_mask_zero=True, variable_length=True, conv_filter_sizes=[1, 9,\n 10], conv_activation='relu', conv_output_dim=32, n_conv_layers=2,\n global_pooling=True, global_pooling_batch_normalization=True)\n", (971, 1247), False, 'from pepnet import SequenceInput, Output, Predictor\n'), ((2105, 2264), 'pepnet.Predictor', 'Predictor', ([], {'inputs': '[mhc, peptide]', 'outputs': 'outputs', 'merge_mode': '"""concat"""', 'dense_layer_sizes': '[32]', 'dense_activation': '"""tanh"""', 'dense_batch_normalization': '(True)'}), "(inputs=[mhc, peptide], outputs=outputs, merge_mode='concat',\n dense_layer_sizes=[32], dense_activation='tanh',\n dense_batch_normalization=True)\n", (2114, 2264), False, 'from pepnet import SequenceInput, Output, Predictor\n'), ((2350, 2372), 'data.load_pseudosequences', 'load_pseudosequences', ([], {}), '()\n', (2370, 2372), False, 'from data import load_iedb_binding_data, load_mass_spec, generate_negatives_from_proteome, load_pseudosequences\n'), ((2454, 2526), 'data.load_mass_spec', 'load_mass_spec', (['mhc_pseudosequences_dict'], {'decoy_factor': 'TEST_DECOY_FACTOR'}), '(mhc_pseudosequences_dict, decoy_factor=TEST_DECOY_FACTOR)\n', (2468, 2526), False, 'from data import load_iedb_binding_data, load_mass_spec, generate_negatives_from_proteome, load_pseudosequences\n'), ((2905, 2929), 'data.load_iedb_binding_data', 'load_iedb_binding_data', ([], {}), '()\n', (2927, 2929), False, 'from data import load_iedb_binding_data, load_mass_spec, generate_negatives_from_proteome, load_pseudosequences\n'), ((4542, 4567), 'random.shuffle', 'random.shuffle', (['pmhc_list'], {}), '(pmhc_list)\n', (4556, 4567), False, 'import random\n'), ((4804, 4813), 'collections.Counter', 'Counter', ([], {}), '()\n', (4811, 4813), False, 'from collections import Counter\n'), ((4956, 4965), 'collections.Counter', 'Counter', ([], {}), '()\n', (4963, 4965), False, 'from collections import Counter\n'), ((5718, 5771), 'numpy.zeros', 'np.zeros', (['(n_unique_pmhc, n_outputs)'], {'dtype': '"""float64"""'}), "((n_unique_pmhc, n_outputs), dtype='float64')\n", (5726, 5771), True, 'import numpy as np\n'), ((5785, 5821), 'numpy.zeros_like', 'np.zeros_like', (['sums'], {'dtype': '"""float64"""'}), "(sums, dtype='float64')\n", (5798, 5821), True, 'import numpy as np\n'), ((6763, 6781), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', (['(3)'], {}), '(3)\n', (6778, 6781), False, 'from sklearn.model_selection import StratifiedKFold\n'), ((1896, 1995), 'pepnet.Output', 'Output', ([], {'name': 'output_name', 'transform': 'transform', 'inverse_transform': 'inverse', 'activation': 'activation'}), '(name=output_name, transform=transform, inverse_transform=inverse,\n activation=activation)\n', (1902, 1995), False, 'from pepnet import SequenceInput, Output, Predictor\n'), ((6180, 6194), 'numpy.isnan', 'np.isnan', (['meas'], {}), '(meas)\n', (6188, 6194), True, 'import numpy as np\n'), ((6301, 6319), 'numpy.log10', 'np.log10', (['(1 + meas)'], {}), '(1 + meas)\n', (6309, 6319), True, 'import numpy as np\n'), ((7508, 7600), 'data.generate_negatives_from_proteome', 'generate_negatives_from_proteome', ([], {'peptides': 'train_peptides', 'factor': 'TRAINING_DECOY_FACTOR'}), '(peptides=train_peptides, factor=\n TRAINING_DECOY_FACTOR)\n', (7540, 7600), False, 'from data import load_iedb_binding_data, load_mass_spec, generate_negatives_from_proteome, load_pseudosequences\n'), ((8436, 8482), 'numpy.vstack', 'np.vstack', (['[Y_train_iedb, Y_training_negative]'], {}), '([Y_train_iedb, Y_training_negative])\n', (8445, 8482), True, 'import numpy as np\n'), ((11474, 11533), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', ([], {'y_true': 'Y_mass_spec', 'y_score': 'Y_pred_mass_spec'}), '(y_true=Y_mass_spec, y_score=Y_pred_mass_spec)\n', (11487, 11533), False, 'from sklearn.metrics import roc_auc_score\n'), ((11612, 11641), 'numpy.argsort', 'np.argsort', (['(-Y_pred_mass_spec)'], {}), '(-Y_pred_mass_spec)\n', (11622, 11641), True, 'import numpy as np\n'), ((1675, 1690), 'numpy.log10', 'np.log10', (['(x + 1)'], {}), '(x + 1)\n', (1683, 1690), True, 'import numpy as np\n'), ((11151, 11226), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', ([], {'y_true': 'Y_train_label', 'y_score': 'Y_pred_train_dict[output_name]'}), '(y_true=Y_train_label, y_score=Y_pred_train_dict[output_name])\n', (11164, 11226), False, 'from sklearn.metrics import roc_auc_score\n'), ((11323, 11396), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', ([], {'y_true': 'Y_test_label', 'y_score': 'Y_pred_test_dict[output_name]'}), '(y_true=Y_test_label, y_score=Y_pred_test_dict[output_name])\n', (11336, 11396), False, 'from sklearn.metrics import roc_auc_score\n')] |
__all__ = ['Evaluator']
from collections import defaultdict
from itertools import chain
import numpy as np
from typing import List, Union, Any
from continual_learning.datasets.base import DatasetSplits
from continual_learning.eval.metrics import Metric, ClassificationMetric, ContinualLearningMetric
def default_to_regular(d):
if isinstance(d, defaultdict):
d = {k: default_to_regular(v) for k, v in d.items()}
return d
class Evaluator:
# def __init__(self, classification_metrics: Union[List[ClassificationMetric], ClassificationMetric] = None,
# cl_metrics: Union[List[ContinualLearningMetric], ContinualLearningMetric] = None,
# other_metrics: Union[List[Metric], Metric] = None):
def __init__(self, classification_metrics: Union[List[Metric], Metric] = None):
self._classification_metrics = []
self._cl_metrics = []
self._others_metrics = []
self._custom_metrics = []
self._scores = {split: {} for split in DatasetSplits
if split != DatasetSplits.ALL}
self._labels = {}
self._r = {split: {} for split in DatasetSplits
if split != DatasetSplits.ALL}
self._custom_metrics = {split: {} for split in DatasetSplits
if split != DatasetSplits.ALL}
if isinstance(classification_metrics, Metric):
classification_metrics = [classification_metrics]
for metric in classification_metrics:
if isinstance(metric, ClassificationMetric):
self._classification_metrics.append((metric.__class__.__name__, metric))
elif isinstance(metric, ContinualLearningMetric):
self._cl_metrics.append((metric.__class__.__name__, metric))
elif isinstance(metric, Metric):
self._others_metrics.append((metric.__class__.__name__, metric))
# if classification_metrics is not None:
# if isinstance(classification_metrics, ClassificationMetric):
# classification_metrics = [classification_metrics]
#
# self._classification_metrics = [(i.__class__.__name__, i) for i in classification_metrics]
#
# if cl_metrics is not None:
# if isinstance(cl_metrics, ContinualLearningMetric):
# cl_metrics = [cl_metrics]
#
# self._cl_metrics = [(i.__class__.__name__, i) for i in cl_metrics]
#
# if other_metrics is not None:
# if isinstance(other_metrics, Metric):
# other_metrics = [other_metrics]
# self._others_metrics = [(i.__class__.__name__, i) for i in other_metrics]
@property
def task_matrix(self) -> dict:
return self._r
# r = {}
# for name, results in self._scores.items():
# k = sorted(results.keys(), reverse=False)
# _r = np.zeros((len(k), len(k)))
# for i in k:
# for j in range(i, len(k)):
# res = results[i][j]
# # res = res[1:] # remove the first score, which is calculated before the training
# # mx = np.argmax(res)
# # mx = len(res) - 1
# # print(i, j, k)
# _r[i, j] = res[-1]
# # for j in range(i + 1, len(k)):
# # ek = k[j]
# # res = results[ek][ck]
# # mx = len(res) - 1
# # _r[ck, ek] = res[-1]
#
# r[name] = _r
#
# return r
def classification_results(self) -> dict:
return default_to_regular(self._scores)
def cl_results(self) -> dict:
_r = self.task_matrix
res = {s: {} for s in _r}
for split in _r:
for name, m in self._classification_metrics:
res[split][name] = {n: m(_r[split][name])
for n, m in self._cl_metrics}
return res
def others_metrics_results(self) -> dict:
res = {}
for name, m in self._others_metrics:
res[name] = m()
return res
def custom_metrics_results(self) -> dict:
res = {}
for name, m in self._others_metrics:
res[name] = m()
return res
@property
def classification_metrics(self) -> List[str]:
return [name for name, _ in self._classification_metrics]
@property
def cl_metrics(self) -> List[str]:
return [name for name, _ in self._cl_metrics]
@property
def others_metrics(self) -> List[str]:
return [name for name, _ in self._others_metrics]
@property
def custom_metrics(self) -> List[str]:
return [name for name, _ in self._custom_metrics]
def evaluate(self,
y_true: Union[list, np.ndarray],
y_pred: Union[list, np.ndarray],
current_task: int,
evaluated_task: int,
evaluated_split: DatasetSplits):
if current_task not in self._labels:
self._labels[evaluated_task] = set(y_true)
mx = max(current_task, evaluated_task) + 1
scores = {}
for name, m in self._classification_metrics:
_m = m(y_true, y_pred, evaluator=self)
split_scores = self._scores.get(evaluated_split, {})
_s = split_scores.get(name, defaultdict(lambda: defaultdict(list)))
_s[evaluated_task][current_task].append(_m)
self._scores[evaluated_split][name] = _s
scores[name] = _m
r = self._r.get(evaluated_split, {})
r = r.get(name, None)
if r is None:
r = np.zeros((mx, mx), dtype=float)
elif r.shape[0] < mx:
com = np.zeros((mx, mx), dtype=r.dtype)
com[:r.shape[0], :r.shape[1]] = r
r = com
r[current_task, evaluated_task] = _m
self._r[evaluated_split][name] = r
return scores
def final_score(self, y_true: Union[list, np.ndarray], y_pred: Union[list, np.ndarray],
current_task: int, evaluated_task: int):
pass
def add_custom_metric(self,
name: str,
value: Any,
evaluated_split: DatasetSplits):
metrics = self._custom_metrics.get(evaluated_split, {})
def add_cl_metric(self, metric: ContinualLearningMetric):
self._cl_metrics.append((metric.__class__.__name__, metric))
def add_metric(self, metric: ClassificationMetric):
self._classification_metrics.append((metric.__class__.__name__, metric))
def on_epoch_starts(self, *args, **kwargs):
for n, m in chain(self._classification_metrics, self._cl_metrics, self._others_metrics):
m.on_epoch_starts(*args, **kwargs)
def on_epoch_ends(self, *args, **kwargs):
for n, m in chain(self._classification_metrics, self._cl_metrics, self._others_metrics):
m.on_epoch_ends(*args, **kwargs)
def on_task_starts(self, *args, **kwargs):
for n, m in chain(self._classification_metrics, self._cl_metrics, self._others_metrics):
m.on_task_starts(*args, **kwargs)
def on_task_ends(self, *args, **kwargs):
for n, m in chain(self._classification_metrics, self._cl_metrics, self._others_metrics):
m.on_task_ends(*args, **kwargs)
def on_batch_starts(self, *args, **kwargs):
for n, m in chain(self._classification_metrics, self._cl_metrics, self._others_metrics):
m.on_batch_starts(*args, **kwargs)
def on_batch_ends(self, *args, **kwargs):
for n, m in chain(self._classification_metrics, self._cl_metrics, self._others_metrics):
m.on_batch_ends(*args, **kwargs)
# def task_starts(self, t):
# if t not in self._task_times:
# self._task_times[t].append(time.time())
# else:
# self._task_times[t][0] = time.time()
#
# def task_ends(self, t):
# v = self._task_times[t]
# end = time.time()
# self._task_times[t].append(end - v[0])
#
# def times(self):
# d = {}
# for t, v in self._task_times.items():
# d[t] = np.sum(v[1:])
# return d
class ExperimentsContainer:
def __init__(self):
self._experiments_results = []
def add_evaluator(self, evaluator: Evaluator):
self._experiments_results.append(evaluator)
def get_mean_std(self):
n = len(self._experiments_results)
# cl_results = [i.cl_results for i in self._experiments_results]
task_results = [i.classification_results for i in self._experiments_results]
# task_r = [i.task_matrix for i in self._experiments_results]
tasks_scores = defaultdict(lambda: defaultdict(list))
for exp_n in range(len(task_results)):
_tasks = defaultdict(list)
for metric, results in task_results[exp_n].items():
for task, scores in results.items():
tasks_scores[metric][task].append(scores)
def matrix(self):
task_results = [i.task_matrix for i in self._experiments_results]
tasks_scores = defaultdict(list)
for exp_n in range(len(task_results)):
for metric, results in task_results[exp_n].items():
tasks_scores[metric].append(results)
scores = {}
for metric, v in tasks_scores.items():
# print(metric)
# for i, v in t.items():
scores[metric] = {'mean': np.asarray(v).mean(0), 'std': np.asarray(v).std(0)}
return scores
def task_scores(self):
task_results = [i.classification_results() for i in self._experiments_results]
tasks_scores = defaultdict(lambda: defaultdict(list))
for exp_n in range(len(task_results)):
for metric, results in task_results[exp_n].items():
for task, scores in results.items():
tasks_scores[metric][task].append(scores)
scores = defaultdict(dict)
for metric, t in tasks_scores.items():
for i, v in t.items():
scores[metric][i] = {'mean': np.asarray(v).mean(0), 'std': np.asarray(v).std(0)}
return scores
def cl_metrics(self):
cl_results = [i.cl_results() for i in self._experiments_results]
res = defaultdict(lambda: defaultdict(list))
for exp_n in range(len(cl_results)):
for metric, v in cl_results[exp_n].items():
for cl_metric, r in v.items():
res[metric][cl_metric].append(r)
metrics = defaultdict(dict)
for metric, t in res.items():
for i, v in t.items():
metrics[metric][i] = {'mean': np.asarray(v).mean(0), 'std': np.asarray(v).std(0)}
return metrics
def others_metrics(self):
cl_results = [i.others_metrics_results() for i in self._experiments_results]
res = defaultdict(list)
for exp_n in range(len(cl_results)):
for metric, v in cl_results[exp_n].items():
# for cl_metric, r in v.items():
res[metric].append(v)
metrics = dict()
for metric, v in res.items():
# for i, v in t.items():
metrics[metric] = {'mean': np.asarray(v).mean(0), 'std': np.asarray(v).std(0)}
return metrics
| [
"collections.defaultdict",
"numpy.asarray",
"numpy.zeros",
"itertools.chain"
] | [((6844, 6919), 'itertools.chain', 'chain', (['self._classification_metrics', 'self._cl_metrics', 'self._others_metrics'], {}), '(self._classification_metrics, self._cl_metrics, self._others_metrics)\n', (6849, 6919), False, 'from itertools import chain\n'), ((7035, 7110), 'itertools.chain', 'chain', (['self._classification_metrics', 'self._cl_metrics', 'self._others_metrics'], {}), '(self._classification_metrics, self._cl_metrics, self._others_metrics)\n', (7040, 7110), False, 'from itertools import chain\n'), ((7225, 7300), 'itertools.chain', 'chain', (['self._classification_metrics', 'self._cl_metrics', 'self._others_metrics'], {}), '(self._classification_metrics, self._cl_metrics, self._others_metrics)\n', (7230, 7300), False, 'from itertools import chain\n'), ((7414, 7489), 'itertools.chain', 'chain', (['self._classification_metrics', 'self._cl_metrics', 'self._others_metrics'], {}), '(self._classification_metrics, self._cl_metrics, self._others_metrics)\n', (7419, 7489), False, 'from itertools import chain\n'), ((7604, 7679), 'itertools.chain', 'chain', (['self._classification_metrics', 'self._cl_metrics', 'self._others_metrics'], {}), '(self._classification_metrics, self._cl_metrics, self._others_metrics)\n', (7609, 7679), False, 'from itertools import chain\n'), ((7795, 7870), 'itertools.chain', 'chain', (['self._classification_metrics', 'self._cl_metrics', 'self._others_metrics'], {}), '(self._classification_metrics, self._cl_metrics, self._others_metrics)\n', (7800, 7870), False, 'from itertools import chain\n'), ((9355, 9372), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (9366, 9372), False, 'from collections import defaultdict\n'), ((10207, 10224), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (10218, 10224), False, 'from collections import defaultdict\n'), ((10802, 10819), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (10813, 10819), False, 'from collections import defaultdict\n'), ((11146, 11163), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (11157, 11163), False, 'from collections import defaultdict\n'), ((9037, 9054), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (9048, 9054), False, 'from collections import defaultdict\n'), ((5792, 5823), 'numpy.zeros', 'np.zeros', (['(mx, mx)'], {'dtype': 'float'}), '((mx, mx), dtype=float)\n', (5800, 5823), True, 'import numpy as np\n'), ((8949, 8966), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (8960, 8966), False, 'from collections import defaultdict\n'), ((9943, 9960), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (9954, 9960), False, 'from collections import defaultdict\n'), ((10562, 10579), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (10573, 10579), False, 'from collections import defaultdict\n'), ((5880, 5913), 'numpy.zeros', 'np.zeros', (['(mx, mx)'], {'dtype': 'r.dtype'}), '((mx, mx), dtype=r.dtype)\n', (5888, 5913), True, 'import numpy as np\n'), ((5500, 5517), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (5511, 5517), False, 'from collections import defaultdict\n'), ((9709, 9722), 'numpy.asarray', 'np.asarray', (['v'], {}), '(v)\n', (9719, 9722), True, 'import numpy as np\n'), ((9739, 9752), 'numpy.asarray', 'np.asarray', (['v'], {}), '(v)\n', (9749, 9752), True, 'import numpy as np\n'), ((11493, 11506), 'numpy.asarray', 'np.asarray', (['v'], {}), '(v)\n', (11503, 11506), True, 'import numpy as np\n'), ((11523, 11536), 'numpy.asarray', 'np.asarray', (['v'], {}), '(v)\n', (11533, 11536), True, 'import numpy as np\n'), ((10352, 10365), 'numpy.asarray', 'np.asarray', (['v'], {}), '(v)\n', (10362, 10365), True, 'import numpy as np\n'), ((10382, 10395), 'numpy.asarray', 'np.asarray', (['v'], {}), '(v)\n', (10392, 10395), True, 'import numpy as np\n'), ((10939, 10952), 'numpy.asarray', 'np.asarray', (['v'], {}), '(v)\n', (10949, 10952), True, 'import numpy as np\n'), ((10969, 10982), 'numpy.asarray', 'np.asarray', (['v'], {}), '(v)\n', (10979, 10982), True, 'import numpy as np\n')] |
#################
## plotters.py ##
#################
import matplotlib.pyplot as plt
import numpy as np
from decimal import Decimal
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import learning_curve
###################################
## mnist_digit_pretty_printer() ##
###################################
def mnist_digit_pretty_printer(digit, white=" ", gray="+"):
"""
Parameters:
-----------
digit: a 2D array of floats
The pixels intensity of the digit
white: char
xxxx
gray: char
xxxx
"""
text = ""
for l in range(0, digit.shape[0]):
line = ""
for c in range(0, digit.shape[1]):
if digit[l][c] < (Decimal(10) ** -3):
line += white
else:
line += gray
text += line + "\n"
return text
###########################
## plot_2D_binary_data() ##
###########################
def plot_2D_binary_data(x1, y1, x2, y2, label1="class1", label2="class2"):
"""
Plot the 2 classes in the 2D feature subspace: 1 feature per dimension.
Useful to visually check that classes are lineary seperable.
Parameters
----------
TODO
Returns
-------
plt: A matplotlib.plt object
Usage
-----
ex. plot_binary_iris_data(X[:50, 0], X[:50, 1], X[50:100,0], X[50:100,1])
"""
plt.close()
plt.scatter(x1, y1, color='red', marker='o', label=label1)
plt.scatter(x2, y2, color='blue', marker='x', label=label2)
plt.xlabel('sepal length [cm]')
plt.ylabel('petal length [cm]')
plt.legend(loc='upper left')
return plt
############################
## plot_simple_sequence() ##
############################
def plot_simple_sequence(y_values, xlabel="xlabel", ylabel="ylabel", title="No title"):
"""
Plot a simple sequence of values: errors (e.g. y) vs epochs (e.g. x), costs vs epochs...
The x values is deduced from the size of the y values.
Parameters
----------
y_values: list like
The values of interest
Returns
-------
A plot object
"""
plt.close()
plt.plot(range(1, len(y_values) + 1), y_values, marker='o')
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(title)
return plt
####################################
# plot_learning_curves_cv_score() #
####################################
# tributes:
# + <NAME> / Hands-On Machine Learning With Scikit-Learn and Tensorflow
# + Scikit-learn https://scikit-learn.org/stable/auto_examples/model_selection/plot_learning_curve.html
def plot_learning_curves_cv_scores(estimator,
X, y,
title="Learning curves",
ylim=None,
cv=None,
n_jobs=4,
fit_times_vs_data=True,
scores_vs_fit_times=True,
logger=None):
"""
Plot the learning curves of a given estimator using the Scikit Learn accuracy_score metric.
Parameters:
-----------
estimator: xxxx
An estimator compliant to the Scikit Learn BaseEstimator interface (e.g. fit, transform...)
X, y: features matrix, labels vector
They must be compliant to Numpy array type.
cv: xxxxx
xxxxx
n_jobs: int or None, optional (default=None)
Number of jobs to run in parallel. 'None' means 1 unless in a :obj:`joblib.parallel_backend` context.
'-1' means using all processors. See :term:`Glossary <n_jobs>` for more details.
ylim : tuple, shape (ymin, ymax), optional
Defines minimum and maximum yvalues plotted.
fit_times_vs_data: bool = True,
Provide the fit_times = f(training data) curve.
scores_vs_fit_times: bool = True,
Provide the scores = f(fit_times) curve.
Returns:
plt: the plot object
"""
# using the Scikit-learn API
# train_sizes = [int(s) for s in np.linspace(1, X.shape[0], X.shape[0])] # absolute sizes
train_sizes = np.linspace(.1, 1.0, 10) # N = 10 relative sizes or ratios
train_sizes, train_scores, test_scores, fit_times, _ = \
learning_curve(estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes, return_times=True)
# metrics
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)
fit_times_mean = np.mean(fit_times, axis=1)
fit_times_std = np.std(fit_times, axis=1)
# 3 Plots:
# - lerning curves or scores = f(n_samples),
# - fit_times = f(n_samples)
# - score = f(fit_times)
if fit_times_vs_data is True:
if scores_vs_fit_times is True:
_, axes = plt.subplots(3, 1, figsize=(8, 20))
else:
_, axes = plt.subplots(2, 1, figsize=(8, 15))
else:
if scores_vs_fit_times is True:
_, axes = plt.subplots(2, 1, figsize=(8, 15))
else:
_, axes = plt.subplots(1, 1, figsize=(8, 8))
#
# Plot learning curve
#
if ylim is not None:
axes[0].set_ylim(*ylim)
axes[0].grid()
axes[0].fill_between(train_sizes, train_scores_mean - train_scores_std,
train_scores_mean + train_scores_std, alpha=0.1, color="r")
axes[0].fill_between(train_sizes, test_scores_mean - test_scores_std,
test_scores_mean + test_scores_std, alpha=0.1, color="g")
axes[0].plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training score")
axes[0].plot(train_sizes, test_scores_mean, 'o-', color="g", label="Cross-validation score")
axes[0].legend(loc="best")
axes[0].set_title(title)
axes[0].set_xlabel("Training examples")
axes[0].set_ylabel("Score")
#
# Plot n_samples vs fit_times = f(n_samples)
#
if fit_times_vs_data is True:
axes[1].grid()
axes[1].plot(train_sizes, fit_times_mean, 'o-')
axes[1].fill_between(train_sizes, fit_times_mean - fit_times_std, fit_times_mean + fit_times_std, alpha=0.1)
axes[1].set_xlabel("Training examples")
axes[1].set_ylabel("fit_times")
axes[1].set_title("Scalability of the model")
# index of the next plot: scores = f(fit_times)
if scores_vs_fit_times is True:
index = 2
else: # => N/A
index = -1
else:
index = 1
if index > 0:
axes[index].grid()
axes[index].plot(fit_times_mean, test_scores_mean, 'o-')
axes[index].fill_between(fit_times_mean, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std,
alpha=0.1)
axes[index].set_xlabel("fit_times")
axes[index].set_ylabel("Score")
axes[index].set_title("Performance of the model")
return plt
####################################
## plot_learning_curves_cv_rmse() ##
####################################
# Custom code
# X_train, X_val, y_train, y_val = train_test_split(X, y, test_size = val_ratio)
#
# if logger:
# msg = "[plot_learning_curves_acc_score()] X_train.shape = {}, y_train.shape = {}, X_val.shape = {}, y_val.shape = {}"
# logger.debug(msg.format(X_train.shape, y_train.shape, X_val.shape, y_val.shape))
#
# train_accs, val_accs = [], []
# for m in range(1, len(X_train)):
#
# estimator.fit(X_train[:m], y_train[:m])
# y_train_predict = estimator.predict(X_train[:m])
# y_val_predict = estimator.predict(X_val)
#
# # calculate the errors
# training_acc = accuracy_score(y_train_predict, y_train[:m])
# validation_acc = accuracy_score(y_val_predict, y_val)
#
# train_accs.append(training_acc)
# val_accs.append(validation_acc)
#
# plt.close()
# plt.plot(train_accs, "r-+", linewidth=2, label="train")
# plt.plot(val_accs, "b-", linewidth=3, label="val")
# plt.xlabel(xlabel)
# plt.ylabel(ylabel)
# plt.title(title)
# plt.legend(loc="best")
# return plt
| [
"matplotlib.pyplot.title",
"decimal.Decimal",
"numpy.std",
"matplotlib.pyplot.close",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.scatter",
"numpy.mean",
"numpy.linspace",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.subplots",
"sklearn.model_selection.learning... | [((1393, 1404), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (1402, 1404), True, 'import matplotlib.pyplot as plt\n'), ((1409, 1467), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x1', 'y1'], {'color': '"""red"""', 'marker': '"""o"""', 'label': 'label1'}), "(x1, y1, color='red', marker='o', label=label1)\n", (1420, 1467), True, 'import matplotlib.pyplot as plt\n'), ((1472, 1531), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x2', 'y2'], {'color': '"""blue"""', 'marker': '"""x"""', 'label': 'label2'}), "(x2, y2, color='blue', marker='x', label=label2)\n", (1483, 1531), True, 'import matplotlib.pyplot as plt\n'), ((1537, 1568), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""sepal length [cm]"""'], {}), "('sepal length [cm]')\n", (1547, 1568), True, 'import matplotlib.pyplot as plt\n'), ((1573, 1604), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""petal length [cm]"""'], {}), "('petal length [cm]')\n", (1583, 1604), True, 'import matplotlib.pyplot as plt\n'), ((1609, 1637), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""'}), "(loc='upper left')\n", (1619, 1637), True, 'import matplotlib.pyplot as plt\n'), ((2134, 2145), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2143, 2145), True, 'import matplotlib.pyplot as plt\n'), ((2214, 2232), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['xlabel'], {}), '(xlabel)\n', (2224, 2232), True, 'import matplotlib.pyplot as plt\n'), ((2237, 2255), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['ylabel'], {}), '(ylabel)\n', (2247, 2255), True, 'import matplotlib.pyplot as plt\n'), ((2260, 2276), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (2269, 2276), True, 'import matplotlib.pyplot as plt\n'), ((4217, 4242), 'numpy.linspace', 'np.linspace', (['(0.1)', '(1.0)', '(10)'], {}), '(0.1, 1.0, 10)\n', (4228, 4242), True, 'import numpy as np\n'), ((4346, 4448), 'sklearn.model_selection.learning_curve', 'learning_curve', (['estimator', 'X', 'y'], {'cv': 'cv', 'n_jobs': 'n_jobs', 'train_sizes': 'train_sizes', 'return_times': '(True)'}), '(estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=\n train_sizes, return_times=True)\n', (4360, 4448), False, 'from sklearn.model_selection import learning_curve\n'), ((4485, 4514), 'numpy.mean', 'np.mean', (['train_scores'], {'axis': '(1)'}), '(train_scores, axis=1)\n', (4492, 4514), True, 'import numpy as np\n'), ((4538, 4566), 'numpy.std', 'np.std', (['train_scores'], {'axis': '(1)'}), '(train_scores, axis=1)\n', (4544, 4566), True, 'import numpy as np\n'), ((4590, 4618), 'numpy.mean', 'np.mean', (['test_scores'], {'axis': '(1)'}), '(test_scores, axis=1)\n', (4597, 4618), True, 'import numpy as np\n'), ((4641, 4668), 'numpy.std', 'np.std', (['test_scores'], {'axis': '(1)'}), '(test_scores, axis=1)\n', (4647, 4668), True, 'import numpy as np\n'), ((4690, 4716), 'numpy.mean', 'np.mean', (['fit_times'], {'axis': '(1)'}), '(fit_times, axis=1)\n', (4697, 4716), True, 'import numpy as np\n'), ((4737, 4762), 'numpy.std', 'np.std', (['fit_times'], {'axis': '(1)'}), '(fit_times, axis=1)\n', (4743, 4762), True, 'import numpy as np\n'), ((4987, 5022), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)', '(1)'], {'figsize': '(8, 20)'}), '(3, 1, figsize=(8, 20))\n', (4999, 5022), True, 'import matplotlib.pyplot as plt\n'), ((5059, 5094), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'figsize': '(8, 15)'}), '(2, 1, figsize=(8, 15))\n', (5071, 5094), True, 'import matplotlib.pyplot as plt\n'), ((5167, 5202), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'figsize': '(8, 15)'}), '(2, 1, figsize=(8, 15))\n', (5179, 5202), True, 'import matplotlib.pyplot as plt\n'), ((5239, 5273), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(8, 8)'}), '(1, 1, figsize=(8, 8))\n', (5251, 5273), True, 'import matplotlib.pyplot as plt\n'), ((728, 739), 'decimal.Decimal', 'Decimal', (['(10)'], {}), '(10)\n', (735, 739), False, 'from decimal import Decimal\n')] |
import numpy as np
def load_mp4(vid_path):
import av
container = av.open(vid_path)
ims = [frame.to_image() for frame in container.decode(video=0)]
ims_c = np.array([np.array(im) for im in ims])
return ims_c
def load_mp4_ffmpeg(vid_path, grey=1, resolution=None):
import ffmpeg
probe = ffmpeg.probe(vid_path)
video_stream = next(
(stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
width = int(video_stream['width'])
height = int(video_stream['height'])
out, _ = (
ffmpeg
.input(vid_path)
.output('pipe:', format='rawvideo', pix_fmt='rgb24')
.global_args('-loglevel', 'error')
.run(capture_stdout=True)
)
ims = (
np
.frombuffer(out, np.uint8)
.reshape([-1, height, width, 3])
)
if resolution is not None or grey:
from PIL import Image
ims = [Image.fromarray(im) for im in ims]
if resolution:
ims = [im.resize(resolution) for im in ims]
if grey:
ims = [im.convert('L') for im in ims]
ims_c = np.array([np.array(im) for im in ims])
else:
ims_c = ims
if grey:
ims_c = np.expand_dims(ims_c, axis=3)
return ims_c
| [
"numpy.frombuffer",
"numpy.expand_dims",
"PIL.Image.fromarray",
"numpy.array",
"ffmpeg.probe",
"ffmpeg.input",
"av.open"
] | [((77, 94), 'av.open', 'av.open', (['vid_path'], {}), '(vid_path)\n', (84, 94), False, 'import av\n'), ((324, 346), 'ffmpeg.probe', 'ffmpeg.probe', (['vid_path'], {}), '(vid_path)\n', (336, 346), False, 'import ffmpeg\n'), ((1230, 1259), 'numpy.expand_dims', 'np.expand_dims', (['ims_c'], {'axis': '(3)'}), '(ims_c, axis=3)\n', (1244, 1259), True, 'import numpy as np\n'), ((187, 199), 'numpy.array', 'np.array', (['im'], {}), '(im)\n', (195, 199), True, 'import numpy as np\n'), ((761, 789), 'numpy.frombuffer', 'np.frombuffer', (['out', 'np.uint8'], {}), '(out, np.uint8)\n', (774, 789), True, 'import numpy as np\n'), ((931, 950), 'PIL.Image.fromarray', 'Image.fromarray', (['im'], {}), '(im)\n', (946, 950), False, 'from PIL import Image\n'), ((1141, 1153), 'numpy.array', 'np.array', (['im'], {}), '(im)\n', (1149, 1153), True, 'import numpy as np\n'), ((565, 587), 'ffmpeg.input', 'ffmpeg.input', (['vid_path'], {}), '(vid_path)\n', (577, 587), False, 'import ffmpeg\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 13 12:08:07 2021
@author: zihan
"""
import requests
from bs4 import BeautifulSoup as soup
import numpy as np
web = 'https://www.aeaweb.org'
base = 'https://www.aeaweb.org/journals/aer/issues'
root = requests.get(base)
leaf = soup(root.text,'lxml')
## scrape volume url
vol_list = []
for i in range(1,6):
classlink = "journal-preview last-col-" + str(i) # link to last i year journals
vol_element = leaf.find_all('article', class_ = classlink)
vol_element = str(vol_element)
vol_elementsp = soup(vol_element,'lxml')
vol_text = vol_elementsp.find_all('a')# find out the url for volumns
for vol in vol_text:
vol_list.append(vol['href'])
print('volumn link successful! year',i)
## scrape doi
doi_list = []
print('start scraping doi!')
for u in vol_list:
vol_link = web + u
doi_root = requests.get(vol_link)
doi_leaf = soup(doi_root.text,'lxml')
doi_element = doi_leaf.find_all('article')
for doi in doi_element:
try:
doi_list.append(doi['id'])
except KeyError:
print('Unable to find id!')
else:
print(doi['id'] + ' successful!')
## save doi_list
a = np.array(doi_list)
np.save('doi_list.npy', a) # npy file
filename = open('doi_list.txt', 'w')
for value in doi_list:
filename.write(str(value))
filename.close() # txt file
| [
"bs4.BeautifulSoup",
"numpy.save",
"numpy.array",
"requests.get"
] | [((273, 291), 'requests.get', 'requests.get', (['base'], {}), '(base)\n', (285, 291), False, 'import requests\n'), ((299, 322), 'bs4.BeautifulSoup', 'soup', (['root.text', '"""lxml"""'], {}), "(root.text, 'lxml')\n", (303, 322), True, 'from bs4 import BeautifulSoup as soup\n'), ((1281, 1299), 'numpy.array', 'np.array', (['doi_list'], {}), '(doi_list)\n', (1289, 1299), True, 'import numpy as np\n'), ((1300, 1326), 'numpy.save', 'np.save', (['"""doi_list.npy"""', 'a'], {}), "('doi_list.npy', a)\n", (1307, 1326), True, 'import numpy as np\n'), ((581, 606), 'bs4.BeautifulSoup', 'soup', (['vol_element', '"""lxml"""'], {}), "(vol_element, 'lxml')\n", (585, 606), True, 'from bs4 import BeautifulSoup as soup\n'), ((918, 940), 'requests.get', 'requests.get', (['vol_link'], {}), '(vol_link)\n', (930, 940), False, 'import requests\n'), ((956, 983), 'bs4.BeautifulSoup', 'soup', (['doi_root.text', '"""lxml"""'], {}), "(doi_root.text, 'lxml')\n", (960, 983), True, 'from bs4 import BeautifulSoup as soup\n')] |
# Copyright 2022 Google.
#
# 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.
"""Tests for training prompts."""
from unittest import mock
from absl.testing import absltest
from absl.testing import parameterized
import jax
import jax.numpy as jnp
import numpy as np
from prompt_tuning import prompts
from prompt_tuning.train import prompts as train_prompts
class PromptsTest(parameterized.TestCase):
def test_prefix_prompt(self):
embed_size = 20
prompt_length = 5
batch_size = 2
seq_len = 14
prompt = jnp.zeros((batch_size, prompt_length, embed_size))
embed = jnp.ones((batch_size, seq_len, embed_size))
with_prompt = jax.jit(train_prompts.prefix_prompt)(prompt, embed, None)
self.assertEqual(with_prompt.shape,
(batch_size, seq_len + prompt_length, embed_size))
for i, example in enumerate(with_prompt):
np.testing.assert_array_equal(example[:prompt_length], prompt[i])
np.testing.assert_array_equal(example[prompt_length:], embed[i])
def test_prefix_prompt_after_bos(self):
embed_size = 20
prompt_length = 5
batch_size = 2
seq_len = 14
prompt = jnp.ones((batch_size, prompt_length, embed_size))
embed = jnp.concatenate(
[jnp.zeros((batch_size, 1, embed_size)),
jnp.full((batch_size, seq_len - 1, embed_size), 2)],
axis=1)
with_prompt = jax.jit(train_prompts.prefix_prompt_after_bos)(prompt,
embed,
None)
self.assertEqual(with_prompt.shape,
(batch_size, seq_len + prompt_length, embed_size))
for i, example in enumerate(with_prompt):
np.testing.assert_array_equal(example[1:prompt_length + 1], prompt[i])
np.testing.assert_array_equal(example[prompt_length + 1:], embed[i, 1:])
np.testing.assert_equal(np.asarray(example[0]), 0)
@parameterized.product(
decoder_only=[True, False],
before_eos=[True, False]
)
def test_suffix_prompt(self, decoder_only, before_eos):
embed_size = 20
prompt_length = 5
lengths = [14, 7]
batch_size = 2
seq_len = 14
padding_embed_value = -1
eos_value = -2
prompt = jnp.reshape(jnp.arange(batch_size * prompt_length * embed_size),
(batch_size, prompt_length, embed_size))
embed = np.ones((batch_size, seq_len, embed_size))
inputs = np.ones((batch_size, seq_len))
for i, l in enumerate(lengths):
inputs[i, l:] = 0
embed[i, l:, :] = padding_embed_value
embed[i, l - 1, :] = eos_value
if decoder_only:
inputs[:, 0] = 0
inputs = jnp.asarray(inputs)
embed = jnp.asarray(embed)
with_prompt = jax.jit(train_prompts.suffix_prompt, static_argnums=(3, 4))(
prompt, embed, inputs, decoder_only=decoder_only, before_eos=before_eos)
self.assertEqual(with_prompt.shape,
(batch_size, seq_len + prompt_length, embed_size))
for i, (example, l) in enumerate(zip(with_prompt, lengths)):
if before_eos:
np.testing.assert_array_equal(example[:l - 1], embed[i, :l - 1])
np.testing.assert_array_equal(example[l + prompt_length], embed[i, l])
np.testing.assert_array_equal(example[l - 1:l - 1 + prompt_length],
prompt[i])
else:
np.testing.assert_array_equal(example[:l], embed[i, :l])
np.testing.assert_array_equal(example[l:l + prompt_length], prompt[i])
padding = example[l + prompt_length:]
np.testing.assert_array_equal(padding,
np.full_like(padding, padding_embed_value))
def test_prompt_does_concatenation(self):
embed_size = 20
prompt_length = 5
batch_size = 2
seq_len = 20
mock_prompt = mock.create_autospec(
prompts.Prompt, spec_set=True, instance=True)
prompt = jnp.zeros((prompt_length, embed_size))
mock_prompt.return_value = prompt
mock_combine = mock.create_autospec(
train_prompts.prefix_prompt, spec_set=True)
prompt_module = train_prompts.Prompt(
prompt=mock_prompt, combine=mock_combine)
input_tokens = jnp.ones((batch_size, seq_len))
embed = jnp.ones((batch_size, seq_len, embed_size))
prompt_module.apply({"params": {}}, input_tokens, embed)
# `.assert_called_once_with` doesn't work for instances returned from
# autospec, the error suggest it has something to do with `self` not being
# handled correctly, so just check the call itself.
self.assertEqual(mock_prompt.call_args_list[0],
mock.call(input_tokens, embed))
expanded_prompt = jnp.zeros((batch_size, prompt_length, embed_size))
# `.assert_called_once_with` doesn't handle comparing arrays that fail the
# `is` check (aren't the same object) so we manually check all call args.
np.testing.assert_allclose(mock_combine.call_args_list[0][0][0],
expanded_prompt)
np.testing.assert_allclose(mock_combine.call_args_list[0][0][1], embed)
if __name__ == "__main__":
absltest.main()
| [
"absl.testing.absltest.main",
"unittest.mock.create_autospec",
"numpy.full_like",
"jax.jit",
"numpy.testing.assert_array_equal",
"jax.numpy.arange",
"numpy.testing.assert_allclose",
"numpy.asarray",
"numpy.ones",
"prompt_tuning.train.prompts.Prompt",
"jax.numpy.asarray",
"absl.testing.paramete... | [((2435, 2510), 'absl.testing.parameterized.product', 'parameterized.product', ([], {'decoder_only': '[True, False]', 'before_eos': '[True, False]'}), '(decoder_only=[True, False], before_eos=[True, False])\n', (2456, 2510), False, 'from absl.testing import parameterized\n'), ((5613, 5628), 'absl.testing.absltest.main', 'absltest.main', ([], {}), '()\n', (5626, 5628), False, 'from absl.testing import absltest\n'), ((1020, 1070), 'jax.numpy.zeros', 'jnp.zeros', (['(batch_size, prompt_length, embed_size)'], {}), '((batch_size, prompt_length, embed_size))\n', (1029, 1070), True, 'import jax.numpy as jnp\n'), ((1083, 1126), 'jax.numpy.ones', 'jnp.ones', (['(batch_size, seq_len, embed_size)'], {}), '((batch_size, seq_len, embed_size))\n', (1091, 1126), True, 'import jax.numpy as jnp\n'), ((1638, 1687), 'jax.numpy.ones', 'jnp.ones', (['(batch_size, prompt_length, embed_size)'], {}), '((batch_size, prompt_length, embed_size))\n', (1646, 1687), True, 'import jax.numpy as jnp\n'), ((2889, 2931), 'numpy.ones', 'np.ones', (['(batch_size, seq_len, embed_size)'], {}), '((batch_size, seq_len, embed_size))\n', (2896, 2931), True, 'import numpy as np\n'), ((2945, 2975), 'numpy.ones', 'np.ones', (['(batch_size, seq_len)'], {}), '((batch_size, seq_len))\n', (2952, 2975), True, 'import numpy as np\n'), ((3174, 3193), 'jax.numpy.asarray', 'jnp.asarray', (['inputs'], {}), '(inputs)\n', (3185, 3193), True, 'import jax.numpy as jnp\n'), ((3206, 3224), 'jax.numpy.asarray', 'jnp.asarray', (['embed'], {}), '(embed)\n', (3217, 3224), True, 'import jax.numpy as jnp\n'), ((4326, 4392), 'unittest.mock.create_autospec', 'mock.create_autospec', (['prompts.Prompt'], {'spec_set': '(True)', 'instance': '(True)'}), '(prompts.Prompt, spec_set=True, instance=True)\n', (4346, 4392), False, 'from unittest import mock\n'), ((4415, 4453), 'jax.numpy.zeros', 'jnp.zeros', (['(prompt_length, embed_size)'], {}), '((prompt_length, embed_size))\n', (4424, 4453), True, 'import jax.numpy as jnp\n'), ((4511, 4575), 'unittest.mock.create_autospec', 'mock.create_autospec', (['train_prompts.prefix_prompt'], {'spec_set': '(True)'}), '(train_prompts.prefix_prompt, spec_set=True)\n', (4531, 4575), False, 'from unittest import mock\n'), ((4605, 4667), 'prompt_tuning.train.prompts.Prompt', 'train_prompts.Prompt', ([], {'prompt': 'mock_prompt', 'combine': 'mock_combine'}), '(prompt=mock_prompt, combine=mock_combine)\n', (4625, 4667), True, 'from prompt_tuning.train import prompts as train_prompts\n'), ((4696, 4727), 'jax.numpy.ones', 'jnp.ones', (['(batch_size, seq_len)'], {}), '((batch_size, seq_len))\n', (4704, 4727), True, 'import jax.numpy as jnp\n'), ((4740, 4783), 'jax.numpy.ones', 'jnp.ones', (['(batch_size, seq_len, embed_size)'], {}), '((batch_size, seq_len, embed_size))\n', (4748, 4783), True, 'import jax.numpy as jnp\n'), ((5181, 5231), 'jax.numpy.zeros', 'jnp.zeros', (['(batch_size, prompt_length, embed_size)'], {}), '((batch_size, prompt_length, embed_size))\n', (5190, 5231), True, 'import jax.numpy as jnp\n'), ((5393, 5478), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['mock_combine.call_args_list[0][0][0]', 'expanded_prompt'], {}), '(mock_combine.call_args_list[0][0][0],\n expanded_prompt)\n', (5419, 5478), True, 'import numpy as np\n'), ((5510, 5581), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['mock_combine.call_args_list[0][0][1]', 'embed'], {}), '(mock_combine.call_args_list[0][0][1], embed)\n', (5536, 5581), True, 'import numpy as np\n'), ((1145, 1181), 'jax.jit', 'jax.jit', (['train_prompts.prefix_prompt'], {}), '(train_prompts.prefix_prompt)\n', (1152, 1181), False, 'import jax\n'), ((1367, 1432), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['example[:prompt_length]', 'prompt[i]'], {}), '(example[:prompt_length], prompt[i])\n', (1396, 1432), True, 'import numpy as np\n'), ((1439, 1503), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['example[prompt_length:]', 'embed[i]'], {}), '(example[prompt_length:], embed[i])\n', (1468, 1503), True, 'import numpy as np\n'), ((1862, 1908), 'jax.jit', 'jax.jit', (['train_prompts.prefix_prompt_after_bos'], {}), '(train_prompts.prefix_prompt_after_bos)\n', (1869, 1908), False, 'import jax\n'), ((2224, 2294), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['example[1:prompt_length + 1]', 'prompt[i]'], {}), '(example[1:prompt_length + 1], prompt[i])\n', (2253, 2294), True, 'import numpy as np\n'), ((2301, 2373), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['example[prompt_length + 1:]', 'embed[i, 1:]'], {}), '(example[prompt_length + 1:], embed[i, 1:])\n', (2330, 2373), True, 'import numpy as np\n'), ((2758, 2809), 'jax.numpy.arange', 'jnp.arange', (['(batch_size * prompt_length * embed_size)'], {}), '(batch_size * prompt_length * embed_size)\n', (2768, 2809), True, 'import jax.numpy as jnp\n'), ((3243, 3302), 'jax.jit', 'jax.jit', (['train_prompts.suffix_prompt'], {'static_argnums': '(3, 4)'}), '(train_prompts.suffix_prompt, static_argnums=(3, 4))\n', (3250, 3302), False, 'import jax\n'), ((5127, 5157), 'unittest.mock.call', 'mock.call', (['input_tokens', 'embed'], {}), '(input_tokens, embed)\n', (5136, 5157), False, 'from unittest import mock\n'), ((1726, 1764), 'jax.numpy.zeros', 'jnp.zeros', (['(batch_size, 1, embed_size)'], {}), '((batch_size, 1, embed_size))\n', (1735, 1764), True, 'import jax.numpy as jnp\n'), ((1775, 1825), 'jax.numpy.full', 'jnp.full', (['(batch_size, seq_len - 1, embed_size)', '(2)'], {}), '((batch_size, seq_len - 1, embed_size), 2)\n', (1783, 1825), True, 'import jax.numpy as jnp\n'), ((2404, 2426), 'numpy.asarray', 'np.asarray', (['example[0]'], {}), '(example[0])\n', (2414, 2426), True, 'import numpy as np\n'), ((3591, 3655), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['example[:l - 1]', 'embed[i, :l - 1]'], {}), '(example[:l - 1], embed[i, :l - 1])\n', (3620, 3655), True, 'import numpy as np\n'), ((3664, 3734), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['example[l + prompt_length]', 'embed[i, l]'], {}), '(example[l + prompt_length], embed[i, l])\n', (3693, 3734), True, 'import numpy as np\n'), ((3743, 3821), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['example[l - 1:l - 1 + prompt_length]', 'prompt[i]'], {}), '(example[l - 1:l - 1 + prompt_length], prompt[i])\n', (3772, 3821), True, 'import numpy as np\n'), ((3880, 3936), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['example[:l]', 'embed[i, :l]'], {}), '(example[:l], embed[i, :l])\n', (3909, 3936), True, 'import numpy as np\n'), ((3945, 4015), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['example[l:l + prompt_length]', 'prompt[i]'], {}), '(example[l:l + prompt_length], prompt[i])\n', (3974, 4015), True, 'import numpy as np\n'), ((4141, 4183), 'numpy.full_like', 'np.full_like', (['padding', 'padding_embed_value'], {}), '(padding, padding_embed_value)\n', (4153, 4183), True, 'import numpy as np\n')] |
import folium
import numpy as np
def plot_circle(lat, lon, radii, map=None, **kwargs):
"""
Plot a circle on a map (creating a new folium map instance if necessary).
Parameters
----------
lat: float
latitude of circle to plot (degrees)
lon: float
longitude of circle to plot (degrees)
radii: list
radii of blast zones (we only need to plot the first for our example)
map: folium.Map
existing map object
Returns
-------
Folium map object
Examples
--------
>>> import folium
>>> armageddon.plot_circle(52.79, -2.95, 1e3, map=None)
"""
# lat = 51.5073219
# lon = -0.1276474
lat_c = 53.2744122
lon_c = -9.0490632
if not map:
# map = folium.Map(location=[lat, lon], control_scale=True)
# folium.Circle([lat, lon], radius, fill=True, fillOpacity=0.6, **kwargs).add_to(map)
map_UK = folium.Map(location=[lat_c, lon_c], zoom_start=5.5, control_scale=True)
folium.Circle(
[lat, lon],
radius = radii[0],
fill=True,
fillOpacity=0.1,
fill_color='blue',
color='blue',parse_html=False).add_to(map_UK)
map_UK.save('plot_data.html')
return map_UK
def plot_line(lat, lon, angle, distance, map_UK=None, **kwargs):
lat_c = 53.2744122
lon_c = -9.0490632
if not map_UK:
# map = folium.Map(location=[lat, lon], control_scale=True)
# folium.Circle([lat, lon], radius, fill=True, fillOpacity=0.6, **kwargs).add_to(map)
map_UK = folium.Map(location=[lat_c, lon_c], zoom_start=5.5, control_scale=True)
dx_lat = distance*np.sin(20)/11132
dx_lon = distance*np.cos(20)/10000
ls = folium.PolyLine(locations=[[lat,lon],[lat + dx_lat, lon - dx_lon]],
color='black')
ls.add_to(map_UK)
map_UK.save('plot_data.html')
return map_UK
def plot_outcome(lat, lon, radii, bearing, distance, map=None, **kwargs):
"""
Plot a circle on a map (creating a new folium map instance if necessary).
Parameters
----------
lat: float
latitude of circle to plot (degrees)
lon: float
longitude of circle to plot (degrees)
radii: list
radii of blast zones
bearing: float
bearing of trajectory
distance: float
distance traversed by meteor before bursting
map: folium.Map
existing map object
Returns
-------
Folium map object
Examples
--------
>>> import folium
>>> armageddon.plot_circle(52.79, -2.95, 1e3, map=None)
"""
# lat = 51.5073219
# lon = -0.1276474
lat_c = 53.2744122
lon_c = -9.0490632
if not map:
# map = folium.Map(location=[lat, lon], control_scale=True)
# folium.Circle([lat, lon], radius, fill=True, fillOpacity=0.6, **kwargs).add_to(map)
map_UK = folium.Map(location=[lat_c, lon_c], zoom_start=5.5, control_scale=True)
folium.Circle(
[lat, lon],
radius = radii[3],
fill=False,
fillOpacity=1.5,
weight = 2,
popup=folium.Popup(max_width=450),
fill_color='red',
color='red',parse_html=False).add_to(map_UK)
folium.Circle(
[lat, lon],
radius = radii[2],
fill=False,
fillOpacity=1,
weight = 2,
popup=folium.Popup(max_width=450),
fill_color='yellow',
color='yellow',parse_html=False).add_to(map_UK)
folium.Circle(
[lat, lon],
radius = radii[1],
fill=True,
fillOpacity=0.2,
fill_color='green',
color='green',parse_html=False).add_to(map_UK)
folium.Circle(
[lat, lon],
radius = radii[0],
fill=True,
fillOpacity=0.1,
fill_color='blue',
color='blue',parse_html=False).add_to(map_UK)
folium.Marker([lat, lon],
popup='Place',
clustered_marker = True,
color = 'yellow',
icon=folium.Icon(color = 'beige')).add_to(map_UK)
ls = folium.PolyLine(locations=[[lat,lon],[lat+2,lon-2]],
color='black')
ls.add_to(map_UK)
map_UK.save('plot_data.html')
return map_UK
def multiple_plots(latlon_array, map=None, **kwargs):
"""
Plot many circle on a map (creating a new folium map instance if necessary).
Parameters
----------
latlon_array: list
list of lists, each containing latitude, longitude and radius of our randomised blasts.
map: folium.Map
existing map object
Returns
-------
Folium map object
Examples
--------
>>> import folium
>>> armageddon.plot_circle([[52.79, -2.95, 10e3],[52.78, -2.94, 12e3],[52.785, -2.943, 11e3]], map=None)
"""
# lat = 51.5073219
# lon = -0.1276474
lat_c = 53.2744122
lon_c = -9.0490632
if not map:
# map = folium.Map(location=[lat, lon], control_scale=True)
# folium.Circle([lat, lon], radius, fill=True, fillOpacity=0.6, **kwargs).add_to(map)
map_UK = folium.Map(location=[lat_c, lon_c], zoom_start=5.5, control_scale=True)
length = len(latlon_array)
for lat, lon, radius in latlon_array:
folium.Circle(
[lat, lon],
radius = radius,
fill=True,
fillOpacity=0.1,
fill_color='blue',
color='blue',parse_html=False).add_to(map_UK)
# ls = folium.PolyLine(locations=[[lat,lon],[lat+2,lon-2]],
# color='black')
# ls.add_to(map_UK)
map_UK.save('plot_multiple.html')
return map_UK
| [
"folium.Popup",
"folium.Circle",
"numpy.sin",
"numpy.cos",
"folium.Map",
"folium.PolyLine",
"folium.Icon"
] | [((1718, 1807), 'folium.PolyLine', 'folium.PolyLine', ([], {'locations': '[[lat, lon], [lat + dx_lat, lon - dx_lon]]', 'color': '"""black"""'}), "(locations=[[lat, lon], [lat + dx_lat, lon - dx_lon]], color\n ='black')\n", (1733, 1807), False, 'import folium\n'), ((4076, 4150), 'folium.PolyLine', 'folium.PolyLine', ([], {'locations': '[[lat, lon], [lat + 2, lon - 2]]', 'color': '"""black"""'}), "(locations=[[lat, lon], [lat + 2, lon - 2]], color='black')\n", (4091, 4150), False, 'import folium\n'), ((923, 994), 'folium.Map', 'folium.Map', ([], {'location': '[lat_c, lon_c]', 'zoom_start': '(5.5)', 'control_scale': '(True)'}), '(location=[lat_c, lon_c], zoom_start=5.5, control_scale=True)\n', (933, 994), False, 'import folium\n'), ((1553, 1624), 'folium.Map', 'folium.Map', ([], {'location': '[lat_c, lon_c]', 'zoom_start': '(5.5)', 'control_scale': '(True)'}), '(location=[lat_c, lon_c], zoom_start=5.5, control_scale=True)\n', (1563, 1624), False, 'import folium\n'), ((2877, 2948), 'folium.Map', 'folium.Map', ([], {'location': '[lat_c, lon_c]', 'zoom_start': '(5.5)', 'control_scale': '(True)'}), '(location=[lat_c, lon_c], zoom_start=5.5, control_scale=True)\n', (2887, 2948), False, 'import folium\n'), ((5086, 5157), 'folium.Map', 'folium.Map', ([], {'location': '[lat_c, lon_c]', 'zoom_start': '(5.5)', 'control_scale': '(True)'}), '(location=[lat_c, lon_c], zoom_start=5.5, control_scale=True)\n', (5096, 5157), False, 'import folium\n'), ((1000, 1125), 'folium.Circle', 'folium.Circle', (['[lat, lon]'], {'radius': 'radii[0]', 'fill': '(True)', 'fillOpacity': '(0.1)', 'fill_color': '"""blue"""', 'color': '"""blue"""', 'parse_html': '(False)'}), "([lat, lon], radius=radii[0], fill=True, fillOpacity=0.1,\n fill_color='blue', color='blue', parse_html=False)\n", (1013, 1125), False, 'import folium\n'), ((1652, 1662), 'numpy.sin', 'np.sin', (['(20)'], {}), '(20)\n', (1658, 1662), True, 'import numpy as np\n'), ((1691, 1701), 'numpy.cos', 'np.cos', (['(20)'], {}), '(20)\n', (1697, 1701), True, 'import numpy as np\n'), ((3474, 3601), 'folium.Circle', 'folium.Circle', (['[lat, lon]'], {'radius': 'radii[1]', 'fill': '(True)', 'fillOpacity': '(0.2)', 'fill_color': '"""green"""', 'color': '"""green"""', 'parse_html': '(False)'}), "([lat, lon], radius=radii[1], fill=True, fillOpacity=0.2,\n fill_color='green', color='green', parse_html=False)\n", (3487, 3601), False, 'import folium\n'), ((3672, 3797), 'folium.Circle', 'folium.Circle', (['[lat, lon]'], {'radius': 'radii[0]', 'fill': '(True)', 'fillOpacity': '(0.1)', 'fill_color': '"""blue"""', 'color': '"""blue"""', 'parse_html': '(False)'}), "([lat, lon], radius=radii[0], fill=True, fillOpacity=0.1,\n fill_color='blue', color='blue', parse_html=False)\n", (3685, 3797), False, 'import folium\n'), ((5240, 5363), 'folium.Circle', 'folium.Circle', (['[lat, lon]'], {'radius': 'radius', 'fill': '(True)', 'fillOpacity': '(0.1)', 'fill_color': '"""blue"""', 'color': '"""blue"""', 'parse_html': '(False)'}), "([lat, lon], radius=radius, fill=True, fillOpacity=0.1,\n fill_color='blue', color='blue', parse_html=False)\n", (5253, 5363), False, 'import folium\n'), ((3099, 3126), 'folium.Popup', 'folium.Popup', ([], {'max_width': '(450)'}), '(max_width=450)\n', (3111, 3126), False, 'import folium\n'), ((3355, 3382), 'folium.Popup', 'folium.Popup', ([], {'max_width': '(450)'}), '(max_width=450)\n', (3367, 3382), False, 'import folium\n'), ((4017, 4043), 'folium.Icon', 'folium.Icon', ([], {'color': '"""beige"""'}), "(color='beige')\n", (4028, 4043), False, 'import folium\n')] |
import logging
import click
import numpy as np
from os.path import abspath, dirname, join
from gym.spaces import Tuple
from mae_envs.viewer.env_viewer import EnvViewer
from mae_envs.wrappers.multi_agent import JoinMultiAgentActions
from mujoco_worldgen.util.envs import examine_env, load_env
from mujoco_worldgen.util.types import extract_matching_arguments
from mujoco_worldgen.util.parse_arguments import parse_arguments
from mae_envs.envs.search_and_rescue import make_env
core_dir = abspath(join(dirname(__file__), ".."))
envs_dir = "mae_envs/envs"
xmls_dir = "xmls"
if __name__ == "__main__":
"""
Actions:
- action_movement: [n_agents, 3] (x, y, z forces)
- action_pull: [n_agents]
- action_glueall: [n_agents]
"""
agent_types = [
{
"is_rescuer": True,
"view_range": 5,
"has_lidar": True,
"lidar_range": 2,
"model_id": 0,
"type": "rescuer",
},
{
"is_rescuer": False,
"view_range": 10,
"has_lidar": True,
"lidar_range": 6,
"model_id": 1,
"type": "seeker",
},
{
"is_rescuer": False,
"view_range": 0,
"has_lidar": False,
"lidar_range": 0.1,
"model_id": -1,
"type": "hiker",
},
]
env = make_env(agent_types=agent_types, visualize_lidar=True, n_lidar_per_agent=30)
done = False
obs = env.reset()
# obs dim (n_agents, )
while not done:
action = np.random.randint(0, 11, size=(env.unwrapped.n_agents, 3))
action = {
"action_movement": action,
"action_pull": np.zeros(env.unwrapped.n_agents),
"action_glueall": np.zeros(env.unwrapped.n_agents),
}
obs, reward, done, info = env.step(action)
env.render()
print(action)
| [
"os.path.dirname",
"numpy.random.randint",
"numpy.zeros",
"mae_envs.envs.search_and_rescue.make_env"
] | [((1391, 1468), 'mae_envs.envs.search_and_rescue.make_env', 'make_env', ([], {'agent_types': 'agent_types', 'visualize_lidar': '(True)', 'n_lidar_per_agent': '(30)'}), '(agent_types=agent_types, visualize_lidar=True, n_lidar_per_agent=30)\n', (1399, 1468), False, 'from mae_envs.envs.search_and_rescue import make_env\n'), ((503, 520), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (510, 520), False, 'from os.path import abspath, dirname, join\n'), ((1572, 1630), 'numpy.random.randint', 'np.random.randint', (['(0)', '(11)'], {'size': '(env.unwrapped.n_agents, 3)'}), '(0, 11, size=(env.unwrapped.n_agents, 3))\n', (1589, 1630), True, 'import numpy as np\n'), ((1716, 1748), 'numpy.zeros', 'np.zeros', (['env.unwrapped.n_agents'], {}), '(env.unwrapped.n_agents)\n', (1724, 1748), True, 'import numpy as np\n'), ((1780, 1812), 'numpy.zeros', 'np.zeros', (['env.unwrapped.n_agents'], {}), '(env.unwrapped.n_agents)\n', (1788, 1812), True, 'import numpy as np\n')] |
import sys,traceback
import os
import math
import numpy as np
import logging
import collections
import time
import re
import random
from classes.highlighter import Highlighter
from classes.jogwidget import JogWidget
from classes.commandlineedit import CommandLineEdit
from classes.simulatordialog import SimulatorDialog
from gerbil.gerbil import Gerbil
from gcode_machine.gcode_machine import GcodeMachine
from gerbil.callbackloghandler import CallbackLogHandler
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import pyqtSignal, QPoint, QSize, Qt, QCoreApplication, QTimer, QSettings
from PyQt5.QtGui import QColor, QPalette, QKeySequence
from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMessageBox, QSlider, QLabel, QPushButton, QWidget, QDialog, QMainWindow, QFileDialog, QLineEdit, QSpacerItem, QListWidgetItem, QMenuBar, QMenu, QAction, QTableWidgetItem, QDialog, QShortcut
from lib.qt.gerbil_gui.ui_mainwindow import Ui_MainWindow
from lib import gcodetools
from lib import utility
from lib import compiler
from lib import pixel2laser
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, path, baud):
super(MainWindow, self).__init__()
self.logger = logging.getLogger('cnctoolbox.window')
_logbuffer_size = 200
self.devicepath = path
self.devicebaud = baud
self.setupUi(self)
self.modifyUi()
self.setupScripting()
# GENERIC SETUP BEGIN -----
self.setWindowTitle("gerbil_gui")
self.lcdNumber_feed_current.display("---")
# GENERIC SETUP END -----
self.state = None
self.state_hash = None
self.state_hash_dirty = False
self.state_cs_dirty = False
self.state_stage_dirty = False
self.state_heightmap_dirty = False
self.wpos = (0, 0, 0)
self.mpos = (0, 0, 0)
## LOGGING SETUP BEGIN ------
# setup ring buffer for logging
self.changed_loginput = False
self.logoutput_items = []
self.logoutput_current_index = -1
self.logbuffer = collections.deque(maxlen=_logbuffer_size)
for i in range(1, _logbuffer_size):
self.logbuffer.append("")
self.label_loginput = QLabel()
self.label_loginput.setTextFormat(Qt.RichText)
self.label_loginput.setTextInteractionFlags(Qt.TextSelectableByMouse)
self.scrollArea_loginput.setWidget(self.label_loginput)
self.label_loginput.setAlignment(Qt.AlignBottom | Qt.AlignLeft)
font = QtGui.QFont()
font.setFamily("DejaVu Sans Mono")
font.setPointSize(7)
#self.label_loginput.setStyleSheet("font: 8pt")
self.label_loginput.setFont(font)
font = QtGui.QFont()
font.setFamily("DejaVu Sans Mono")
font.setPointSize(7)
self.label_current_gcode.setFont(font)
## LOGGING SETUP END ------
# STATE VARIABLES BEGIN -----
self.changed_state = False
self._current_grbl_line_number = 0
self._rx_buffer_fill = 0
self._rx_buffer_fill_last = 0
self._progress_percent = 0
self._progress_percent_last = 0
# STATE VARIABLES END -----
## MENU BAR SETUP BEGIN ----------
self.menuBar = QMenuBar(self)
self.action_script_load = QAction("Open Script...", self)
self.action_script_load.triggered.connect(self._pick_script)
self.action_script_save = QAction("Save Script!", self)
self.action_script_save.triggered.connect(self._save_script)
self.action_script_save_as = QAction("Save Script As...", self)
self.action_script_save_as.triggered.connect(self._save_script_as)
self.action_file_set = QAction("Load G-Code...", self)
self.action_file_set.triggered.connect(self._pick_file)
self.action_file_quit = QAction("Quit!", self)
self.action_file_quit.triggered.connect(self._quit)
self.action_grbl_connect = QAction("Connect", self)
self.action_grbl_connect.triggered.connect(self.cnect)
self.action_grbl_disconnect = QAction("Disconnect", self)
self.action_grbl_disconnect.triggered.connect(self.disconnect)
self.menu_file = self.menuBar.addMenu("File")
self.menu_grbl = self.menuBar.addMenu("Grbl")
self.menu_file.addAction(self.action_script_load)
self.menu_file.addAction(self.action_script_save)
self.menu_file.addAction(self.action_script_save_as)
self.menu_file.addAction(self.action_file_set)
self.menu_file.addAction(self.action_file_quit)
self.menu_grbl.addAction(self.action_grbl_connect)
self.menu_grbl.addAction(self.action_grbl_disconnect)
self.action_grbl_disconnect.setEnabled(False)
self.action_grbl_connect.setEnabled(True)
## MENU BAR SETUP END ----------
## CS SETUP BEGIN ---------
self.cs_names = {
1: "G54",
2: "G55",
3: "G56",
4: "G57",
5: "G58",
6: "G59",
}
self.pushButton_current_cs_setzero.clicked.connect(self.current_cs_setzero)
for key, val in self.cs_names.items():
self.comboBox_coordinate_systems.insertItem(key, val)
self.comboBox_coordinate_systems.activated.connect(self._cs_selected)
## CS SETUP END ---------
refresh_rate = 20
self.sim_dialog = SimulatorDialog(self, refresh_rate)
self.sim_dialog.show()
# GRBL SETUP BEGIN -----
self.grbl = Gerbil(self.on_grbl_event)
self.grbl.setup_logging()
self.grbl.poll_interval = 0.15
#self.grbl.cnect()
## SIGNALS AND SLOTS BEGIN-------
self.comboBox_target.currentIndexChanged.connect(self._target_selected)
self.pushButton_homing.clicked.connect(self.homing)
self.pushButton_killalarm.clicked.connect(self.grbl.killalarm)
self.pushButton_job_run.clicked.connect(self.job_run)
self.pushButton_job_halt.clicked.connect(self.job_halt)
self.pushButton_job_new.clicked.connect(self.new_job)
self.pushButton_show_buffer.clicked.connect(self._show_buffer)
self.pushButton_hold.clicked.connect(self.hold)
self.pushButton_resume.clicked.connect(self.grbl.resume)
self.pushButton_abort.clicked.connect(self.abort)
self.pushButton_check.clicked.connect(self.check)
self.pushButton_g53z0.clicked.connect(self.g53z0)
self.pushButton_g53min.clicked.connect(self.g53min)
self.pushButton_g53x0y0.clicked.connect(self.g53x0y0)
self.pushButton_spindleon.clicked.connect(self.spindleon)
self.pushButton_spindleoff.clicked.connect(self.spindleoff)
self.pushButton_g0x0y0.clicked.connect(self.g0x0y0)
self.pushButton_xminus.clicked.connect(self.xminus)
self.pushButton_xplus.clicked.connect(self.xplus)
self.pushButton_yminus.clicked.connect(self.yminus)
self.pushButton_yplus.clicked.connect(self.yplus)
self.pushButton_zminus.clicked.connect(self.zminus)
self.pushButton_zplus.clicked.connect(self.zplus)
self.horizontalSlider_feed_override.valueChanged.connect(self._feedoverride_value_changed)
self.horizontalSlider_spindle_factor.valueChanged.connect(self._spindle_factor_value_changed)
self.checkBox_feed_override.stateChanged.connect(self._feedoverride_changed)
self.checkBox_incremental.stateChanged.connect(self._incremental_changed)
self.lineEdit_cmdline = CommandLineEdit(self, self._cmd_line_callback)
self.gridLayout_right.addWidget(self.lineEdit_cmdline, 7, 0, 1, 0)
self.listWidget_logoutput.itemDoubleClicked.connect(self._on_logoutput_item_double_clicked)
self.listWidget_logoutput.itemClicked.connect(self._on_logoutput_item_clicked)
self.listWidget_logoutput.currentItemChanged.connect(self._on_logoutput_current_item_changed)
self.spinBox_start_line.valueChanged.connect(self._start_line_changed)
self.pushButton_settings_download_grbl.clicked.connect(self.grbl.request_settings)
self.pushButton_settings_save_file.clicked.connect(self.settings_save_into_file)
self.pushButton_settings_load_file.clicked.connect(self.settings_load_from_file)
self.pushButton_settings_upload_grbl.clicked.connect(self.settings_upload_to_grbl)
self.pushButton_bbox.clicked.connect(self.bbox)
self.tableWidget_variables.cellChanged.connect(self._variables_edited)
## SIGNALS AND SLOTS END-------
self._startup_disable_inputs()
## TIMER SETUP BEGIN ----------
self.timer = QTimer()
self.timer.timeout.connect(self.on_timer)
self.timer.start(150)
self.timer_second = QTimer()
self.timer_second.timeout.connect(self.on_second_tick)
self.timer_second.start(1000)
## TIMER SETUP END ----------
## Keyboard shortcuts BEGIN ----------
self._shortcut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_S), self)
self._shortcut.activated.connect(self._save_script)
self._shortcut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_O), self)
self._shortcut.activated.connect(self._pick_script)
self._shortcut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_R), self)
self._shortcut.activated.connect(self.reset)
self._shortcut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_K), self)
self._shortcut.activated.connect(self.grbl.killalarm)
self._shortcut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_H), self)
self._shortcut.activated.connect(self.homing)
self._shortcut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_E), self)
self._shortcut.activated.connect(self.execute_script_clicked)
## Keyboard shortcuts END ----------
# initialize vars needed for heightmap/surface probing
self.heightmap_gldata = None
self.heightmap_dim = None
self.heightmap_llc = None
self.heightmap_urc = None
self.heightmap_ipolgrid = None
self.probe_z_first = None
self.probe_z_at_probestart = None
self.probe_z_expected_deviation = None
self.probe_feed = None
self.probe_points = None
self.probe_values = None
self.probe_points_count = None
self._add_to_logoutput("=calc_eta()")
self._add_to_logoutput("=bbox()")
self._add_to_logoutput("=remove_tracer()")
self._add_to_logoutput("=probe_start(100,100)")
self._add_to_logoutput("=probe_done()")
self._add_to_logoutput("=probe_load()")
self._add_to_logoutput("=goto_marker()")
self._add_to_logoutput("G38.2 Z-10 F50")
self._add_to_logoutput("G0 X0 Y0")
self.on_job_completed_callback = None
self.targets = ["firmware", "simulator", "file"]
self.comboBox_target.insertItem(0, self.targets[0])
self.comboBox_target.insertItem(1, self.targets[1])
self.comboBox_target.insertItem(2, self.targets[2])
self.set_target("simulator")
# GRBL SETUP END -----
# compiler SETUP BEGIN -----
compiler.receiver(self.grbl)
compiler.Settings['log_callback'] = lambda msg: print("<b>COMPILER:</b> {}".format(msg))
# compiler SETUP END -----
self.tableWidget_settings.setColumnWidth(2, 300)
for row in range(0, 32):
self.tableWidget_settings.setRowHeight(row, 15)
with open("examples/scripts/blank.py", 'r') as f: c = f.read()
self.plainTextEdit_script.setPlainText(c)
## JOG WIDGET SETUP BEGIN -------------
self.jogWidget = JogWidget(self, self.grbl.stream)
self.gridLayout_jog_container.addWidget(self.jogWidget)
## JOG WIDGET SETUP END -------------
self.statusBar.showMessage("Ready", 3000)
## SETTINGS SETUP BEGIN ---------------------
self.settings = QSettings("gerbil_gui.ini", QSettings.IniFormat)
self._open_script_location = self.settings.value("open_script_location")
if self._open_script_location == None:
self._open_script_location = os.getcwd() + "/examples/scripts"
self.settings.setValue("open_script_location", self._open_script_location)
self._open_gcode_location = self.settings.value("open_gcode_location")
if self._open_gcode_location == None:
self._open_gcode_location = os.getcwd() + "/examples/gcode"
self.settings.setValue("open_gcode_location", self._open_gcode_location)
self._last_cs = int(self.settings.value("last_cs"))
if self._last_cs == None:
self._last_cs = 1
self.settings.setValue("last_cs", self._last_cs)
## SETTINGS SETUP END ---------------------
self._put_buffer_marker_at_line_nr = None
self.job_run_timestamp = time.time()
self.job_current_eta = 0
self.current_script_filepath = None
def closeEvent(self, event):
"""
Overloaded Qt function
"""
print("Exiting normally...")
self.grbl.disconnect()
self.sim_dialog.close()
#event.ignore()
event.accept()
# =log(self.grbl.travel_dist_buffer)
def log(self, msg, color="black"):
self._add_to_loginput(msg, color)
#def conosole_log(self, msg):
def new_job(self):
self.job_run_timestamp = time.time()
self.grbl.job_new()
self.spinBox_start_line.setValue(0)
self.sim_dialog.simulator_widget.cleanup_stage()
# modify whatever was hardcoded in the Qt Form Editor
def modifyUi(self):
self.pushButton_homing.setStyleSheet("background-color: rgb(102,217,239);")
self.pushButton_resume.setStyleSheet("background-color: rgb(166,226,46);")
self.pushButton_killalarm.setStyleSheet("color: black;")
self.pushButton_abort.setStyleSheet("background-color: rgb(198,31,31);color: white;")
self.pushButton_hold.setStyleSheet("background-color: rgb(219,213,50);")
self.pushButton_check.setStyleSheet("background-color: rgb(235,122,9);")
self.pushButton_homing.setText("⌂ Homing")
self.pushButton_abort.setText("☠ ABRT/RST")
self.pushButton_killalarm.setText("⚐ Kill Alarm")
self.pushButton_job_new.setText("✧ New")
self.pushButton_job_halt.setText("⌛ Pause")
def setupScripting(self):
print("Setting up Scripting Tab")
p = self.plainTextEdit_script.palette();
self.plainTextEdit_script.setStyleSheet("QPlainTextEdit { background-color: rgb(51, 51, 51); color: rgb(255,255,255); }");
self.highlighter = Highlighter(self.plainTextEdit_script.document())
self.pushButton_script_run.clicked.connect(self.execute_script_clicked)
# to be used by scripting only
def set_target(self, targetname):
idx = self.targets.index(targetname)
self.comboBox_target.setCurrentIndex(idx)
def draw_probepoint(self, xy, z):
current_cs_offset = self.state_hash[self.cs_names[self.current_cs]]
z = z - self.probe_z_first
print("DRAWING PROBE POINT")
probepoint_origin = (xy[0], xy[1], z)
probepoint_origin = np.add(probepoint_origin, current_cs_offset)
self.sim_dialog.simulator_widget.item_create("Star", "probepoint_{}".format(len(self.probe_values)), "simple3d", probepoint_origin, 1, 4, (0.6, 0.6, 0.6, 1))
def probe_load(self):
with open("probedata.txt", 'r') as f:
lines = f.read().split("\n")
self.sim_dialog.simulator_widget.item_remove("probepoint_.+")
self.probe_points_count = 0
self.probe_points = []
self.probe_values = []
max_x = -999999
min_x = 999999
max_y = -999999
min_y = 999999
i = 0
for line in lines:
if (line.strip() == ""): continue
m = re.match('(........) (........) (........)', line)
x = float(m.group(1))
y = float(m.group(2))
z = float(m.group(3))
self.probe_points.append([x, y])
self.probe_values.append(z)
self.probe_points_count += 1
if (x > max_x): max_x = x
if (x < min_x): min_x = x
if (y > max_y): max_y = y
if (y < min_y): min_y = y
if (i == 0): self.probe_z_first = z
self.draw_probepoint(self.probe_points[-1], self.probe_values[-1])
i += 1
if (len(self.probe_values) == 0):
self.log("probedata.txt was empty!", "red")
return
print("LLC", self.heightmap_llc)
print("URC", self.heightmap_urc)
print("DIM", self.heightmap_dim)
print("POINTS", self.probe_points)
print("VALUES", self.probe_values)
self._init_heightmap(max_x, max_y)
self.state_heightmap_dirty = True
def probe_done(self):
with open("probedata.txt", 'w') as f:
for i in range(0, len(self.probe_points)):
f.write("{:8.03f} {:8.03f} {:8.03f}\n".format(self.probe_points[i][0], self.probe_points[i][1], self.probe_values[i]))
self.probe_points_count = None
self.log("<b>Probe data available in<br>self.probe_points and self.probe_values<br>and in probedata.txt.</b>", "orange")
def _init_heightmap(self, dimx, dimy):
self.sim_dialog.simulator_widget.remove_heightmap()
dimx = round(dimx) + 1
dimy = round(dimy) + 1
self.heightmap_dim = (dimx, dimy)
self.heightmap_llc = (0, 0)
self.heightmap_urc = (dimx, dimy)
self.heightmap_gldata = np.zeros(dimx * dimy, [("position", np.float32, 3), ("color", np.float32, 4)])
start_x = self.heightmap_llc[0]
end_x = self.heightmap_urc[0]
steps_x = (1 + dimx) * 1j
start_y = self.heightmap_llc[1]
end_y = self.heightmap_urc[1]
steps_y = (1 + dimy) * 1j
grid = np.mgrid[start_x:end_x:steps_x, start_y:end_y:steps_y]
self.heightmap_ipolgrid = (grid[0], grid[1]) # format required by interpolation
def probe_start(self, dimx, dimy, z_feed=50, z_expected_deviation=10):
"""
Probes area.
Probe must almost touch the surface. First movement is up.
Current X and Y pos will be Z=0 of resulting probe plane,
which can be used to offset Gcode.
@param dimx
Width of area to be probed, as measured into the X+ direction from the current pos
@param dimy
Height of area to be probed, as measured into the Y+ direction from the current pos
@param z_feed
The probe feed towards the workpiece.
@param z_expected_deviation
Approximate difference in mm between the lowest Z and highest Z of the warped workpiece surface
"""
if round(self.wpos[0]) != 0 or round(self.wpos[1]) != 0:
self.log("<b>Probe cycle must start at X0 Y0</b>", "red")
return
if z_expected_deviation < 5 or z_expected_deviation > 10:
self.log("<b>For safety reasons, z_expected_deviation shouldn't be smaller than 5 or larger than 10 mm.</b>", "red")
return
self._init_heightmap(dimx, dimy)
self.probe_points = []
self.probe_values = []
self.probe_points_count = 0
self.probe_z_expected_deviation = z_expected_deviation
self.probe_feed = z_feed
self.probe_points_planned = [ # all corners of area are pre-planned
(0, 0),
(dimx, 0),
(dimx, dimy),
(0, dimy)
]
self.probe_z_at_probestart = self.wpos[2]
self.grbl.send_immediately("G90") # absolute mode
self.do_probe_point(self.probe_points_planned[0])
def do_probe_point(self, pos):
"""
Lift, go to new point, then probe
@param pos
tuple or list of xy coordinates relative to the current CS
"""
new_x = pos[0]
new_y = pos[1]
# fast lift by z_clear from last probe trigger point
lift_security_margin = 2
lift_z = self.probe_z_at_probestart + self.probe_z_expected_deviation + lift_security_margin
self.grbl.send_immediately("G0 Z{:0.3f}".format(lift_z))
# probe is now clear of any obstacles. do fast move to new probe coord.
self.grbl.send_immediately("G0 X{} Y{}".format(new_x, new_y))
# the actual probing
probe_goto_z = self.probe_z_at_probestart - self.probe_z_expected_deviation
self.grbl.send_immediately("G38.2 Z{:0.3f} F{}".format(probe_goto_z, self.probe_feed))
def handle_probe_point(self, mpos):
"""
@param pos
3-tuple of machine coordinates
"""
if self.probe_points_count == None:
# set to None by self.probe_done(). Stop the infinite probing cycle.
return
current_cs_offset = self.state_hash[self.cs_names[self.current_cs]]
# transform from machine coords into current CS
probed_pos = np.subtract(mpos, current_cs_offset)
# record probe points for interpolation
self.probe_points.append([round(probed_pos[0]), round(probed_pos[1])])
self.probe_values.append(round(probed_pos[2], 2))
if self.probe_points_count == 0:
self.probe_z_first = round(probed_pos[2], 2)
# probe next point
self.probe_points_count += 1
planned_points = len(self.probe_points_planned)
if self.probe_points_count < planned_points:
# still planned points available
nextpoint = self.probe_points_planned[self.probe_points_count]
else:
nx = random.randint(self.heightmap_llc[0], self.heightmap_urc[0])
ny = random.randint(self.heightmap_llc[1], self.heightmap_urc[1])
nextpoint = [nx, ny]
self.state_heightmap_dirty = True
self.do_probe_point(nextpoint)
def draw_heightmap(self):
current_cs_offset = self.state_hash[self.cs_names[self.current_cs]]
if len(self.probe_values) < 4: return # at least 4 for suitable interpol
# I put this here to not make it a hard requirement
# it is difficult to install on Windows
from scipy.interpolate import griddata
# see http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html
interpolated_z = griddata(
self.probe_points,
self.probe_values,
self.heightmap_ipolgrid,
method='cubic',
fill_value=-100)
# construct the vertex attributes in the format needed for pyglpainter
for y in range(0, self.heightmap_dim[1]):
for x in range(0, self.heightmap_dim[0]):
idx = y * self.heightmap_dim[0] + x
self.heightmap_gldata["position"][idx] = (x, y, interpolated_z[x][y])
self.heightmap_gldata["color"][idx] = (1, 1, 1, 1)
origin = (current_cs_offset[0] + self.heightmap_llc[0],
current_cs_offset[1] + self.heightmap_llc[1],
current_cs_offset[2] - self.probe_z_first
)
print("DRAWING HEIGHTMAP", origin, self.probe_points, self.probe_values)
self.sim_dialog.simulator_widget.draw_heightmap(self.heightmap_gldata, self.heightmap_dim, origin)
# CALLBACKS
def on_grbl_event(self, event, *data):
if event == "on_stateupdate":
self.state = data[0]
self.mpos = data[1]
self.wpos = data[2]
if self.grbl.connected:
self.changed_state = True
elif event == "on_hash_stateupdate":
self.state_hash = data[0]
self.sim_dialog.simulator_widget.cs_offsets = self.state_hash
self.state_hash_dirty = True
elif event == "on_probe":
pos = data[0]
self.log("Probe: <b>{}</b>".format(pos[2]))
self.handle_probe_point(pos)
elif event == "on_gcode_parser_stateupdate":
gps = data[0]
mm_string = "G" + gps[0]
self.label_motionmode.setText(mm_string)
# current coordinate system
cs_string = "G" + gps[1]
ivd = {v: k for k, v in self.cs_names.items()}
cs_nr = ivd[cs_string]
self.set_cs(cs_nr)
pm_string = "G" + gps[2]
self.label_planemode.setText(pm_string)
um_string = "G" + gps[3]
self.label_unitmode.setText(um_string)
dm_string = "G" + gps[4]
self.label_distmode.setText(dm_string)
fm_string = "G" + gps[5]
self.label_feedmode.setText(fm_string)
pm_string = "M" + gps[6]
self.label_programmode.setText(pm_string)
ss_string = "M" + gps[7]
self.label_spindle_state.setText(ss_string)
cr_string = gps[11]
self.label_current_rpm.setText(cr_string)
elif event == "on_processed_command":
txt = "✓ Line {}: {}".format(data[0], data[1])
self._add_to_loginput(txt, "green")
self._current_grbl_line_number = int(data[0])
elif event == "on_line_number_change":
self._current_grbl_line_number = int(data[0])
elif event == "on_error":
self._add_to_loginput("<b>◀ {}</b>".format(data[0]), "red")
if data[2] > -1:
self._add_to_loginput("<b>✗ Error was in line {}: {}</b>".format(data[2], data[1]), "red")
self.reset()
elif event == "on_alarm":
self._add_to_loginput("☹ " + data[0], "orange")
elif event == "on_read":
self._add_to_loginput("◀ {}".format(data[0]), "#000099")
elif event == "on_write":
self._add_to_loginput("▶ {}".format(data[0]), "#990099")
elif event == "on_log":
colors = {
0: "black", # notset
10: "#999999", # debug
20: "#555555", # info
30: "orange", # warning
40: "red", # error
50: "red", # critical
}
lr = data[0] # LogRecord instance
message = lr.msg % lr.args
level = lr.levelno
levelname = lr.levelname
filename = lr.filename
funcname = lr.funcName
lineno = lr.lineno
color = colors[level]
if level >= 40:
txt = "{}: {} ({}:{}:{})".format(levelname, message, filename, funcname, lineno)
else:
txt = message
self._add_to_loginput("✎ " + message, color)
elif event == "on_bufsize_change":
#what = data[0]
msg = "{:d} Lines".format(data[0])
self._current_grbl_buffer_size = int(data[0])
self.label_bufsize.setText(msg)
#enabled = self._current_grbl_buffer_size == 0
#self.lineEdit_cmdline.setEnabled(enabled)
#self.listWidget_logoutput.setEnabled(enabled)
elif event == "on_rx_buffer_percent":
self._rx_buffer_fill = data[0]
elif event == "on_progress_percent":
self._progress_percent = data[0]
elif event == "on_feed_change":
feed = data[0]
if feed == None:
self.lcdNumber_feed_current.display("---")
else:
self.lcdNumber_feed_current.display("{:d}".format(int(feed)))
elif event == "on_streaming_complete":
self.grbl.incremental_streaming = True
elif event == "on_boot":
self.grbl.poll_start()
self.comboBox_target.setEnabled(True)
self.pushButton_homing.setEnabled(True)
self.pushButton_killalarm.setEnabled(True)
self.pushButton_job_halt.setEnabled(True)
self.pushButton_job_new.setEnabled(True)
self.pushButton_hold.setEnabled(True)
self.pushButton_resume.setEnabled(True)
self.pushButton_abort.setEnabled(True)
self.pushButton_check.setEnabled(True)
self.pushButton_g0x0y0.setEnabled(True)
self.pushButton_xminus.setEnabled(True)
self.pushButton_xplus.setEnabled(True)
self.pushButton_yminus.setEnabled(True)
self.pushButton_yplus.setEnabled(True)
self.pushButton_zminus.setEnabled(True)
self.pushButton_zplus.setEnabled(True)
self.horizontalSlider_feed_override.setEnabled(True)
self.horizontalSlider_spindle_factor.setEnabled(True)
self.checkBox_feed_override.setEnabled(True)
self.checkBox_incremental.setEnabled(True)
self.comboBox_coordinate_systems.setEnabled(True)
self.pushButton_current_cs_setzero.setEnabled(True)
self.pushButton_g53z0.setEnabled(True)
self.pushButton_g53min.setEnabled(True)
self.pushButton_g53x0y0.setEnabled(True)
self.pushButton_spindleon.setEnabled(True)
self.pushButton_spindleoff.setEnabled(True)
self.spinBox_start_line.setEnabled(True)
self.action_grbl_disconnect.setEnabled(True)
self.action_grbl_connect.setEnabled(False)
self.lcdNumber_feed_current.display("---")
self.horizontalSlider_feed_override.setValue(30)
self._feedoverride_value_changed()
self.horizontalSlider_spindle_factor.setValue(100)
self._spindle_factor_value_changed()
self.spinBox_start_line.setValue(0)
self._start_line_changed(0)
elif event == "on_disconnected":
self.action_grbl_disconnect.setEnabled(False)
self.action_grbl_connect.setEnabled(True)
self.lcdNumber_mx.display("{:0.3f}".format(8888.888))
self.lcdNumber_my.display("{:0.3f}".format(8888.888))
self.lcdNumber_mz.display("{:0.3f}".format(8888.888))
self.lcdNumber_wx.display("{:0.3f}".format(8888.888))
self.lcdNumber_wy.display("{:0.3f}".format(8888.888))
self.lcdNumber_wz.display("{:0.3f}".format(8888.888))
self.label_state.setText("disconnected")
self.label_state.setStyleSheet("background-color: 'transparent'; color: 'black';")
self._add_to_loginput("<i>Successfully disconnected!</i>")
self._add_to_loginput("")
self.state = None
self._startup_disable_inputs()
elif event == "on_settings_downloaded":
settings = data[0] #self.grbl.get_settings()
self.dict_into_settings_table(settings)
self.state_stage_dirty = True
elif event == "on_job_completed":
self._add_to_loginput("JOB COMPLETED")
self.grbl.current_line_number = 0
if self.on_job_completed_callback:
self.on_job_completed_callback()
elif event == "on_vars_change":
keys = data[0]
self.var_keys_into_var_table(keys)
elif event == "on_simulation_finished":
gcode = data[0]
ccs = self.cs_names[self.current_cs]
self.sim_dialog.simulator_widget.cs_offsets = self.state_hash
self.sim_dialog.simulator_widget.draw_gcode(gcode, self.mpos, ccs)
self._current_grbl_line_number = self.grbl._current_line_nr
self.spinBox_start_line.setValue(self._current_grbl_line_number)
elif event == "on_line_sent":
line_number = data[0]
line_str = data[1]
self.sim_dialog.simulator_widget.highlight_gcode_line(line_number)
self._put_buffer_marker_at_line_nr = line_number
elif event == "on_standstill":
self.log("Machine is standing still")
if (self.grbl.gps[7] == "3" and
self.grbl.preprocessor.current_spindle_speed > 1):
self.log("Laser Watchdog: Machine standstill but laser on. Turning off...", "red")
self.grbl.abort()
if self.state == "Idle":
# restore previous CS
self.comboBox_coordinate_systems.setCurrentIndex(self._last_cs - 1)
self._cs_selected(self._last_cs - 1)
elif event == "on_movement":
pass
else:
self._add_to_loginput("Grbl event {} not yet implemented".format(event))
def remove_tracer(self):
self.sim_dialog.simulator_widget.remove_item("tracer")
def goto_marker(self):
pos = self.sim_dialog.simulator_widget.get_buffer_marker_pos()
self._add_to_logoutput("G1 G53 X{:0.3f} Y{:0.3f} Z{:0.3f}".format(pos[0], pos[1], pos[2]))
def on_second_tick(self):
if self.grbl.job_finished == False:
self.label_runningtime.setText(self._secs_to_timestring(time.time() - self.job_run_timestamp))
self.label_eta.setText(self._secs_to_timestring(self.job_current_eta - time.time()))
else:
self.label_runningtime.setText("---")
self.label_eta.setText("---")
def on_timer(self):
self.label_current_line_number.setText(str(self._current_grbl_line_number))
if self._put_buffer_marker_at_line_nr != None:
self.sim_dialog.simulator_widget.put_buffer_marker_at_line(self._put_buffer_marker_at_line_nr)
self._put_buffer_marker_at_line_nr = None
if self.state_hash_dirty == True:
# used to draw/update origins of coordinate systems (after $# command)
for key, tpl in self.state_hash.items():
if re.match("G5[4-9].*", key):
self.sim_dialog.simulator_widget.draw_coordinate_system(key, tpl)
self.state_hash_dirty = False
if self.state_stage_dirty == True:
# used to draw/update the workarea (stage) (after $$ command)
workarea_x = int(float(self.grbl.settings[130]["val"]))
workarea_y = int(float(self.grbl.settings[131]["val"]))
self.sim_dialog.simulator_widget.draw_stage(workarea_x, workarea_y)
self.state_stage_dirty = False
if self.state_heightmap_dirty == True:
self.draw_probepoint(self.probe_points[-1], self.probe_values[-1])
self.draw_heightmap()
self.state_heightmap_dirty = False
if self.state_cs_dirty == True:
# used to highlight coordinate systems (after $G command)
for idx, val in self.cs_names.items():
do_highlight = val == self.cs_names[self.current_cs]
cs_item = self.sim_dialog.simulator_widget.programs["simple3d"].items["cs" + val]
cs_item.highlight(do_highlight)
#self.sim_dialog.simulator_widget.cleanup_stage()
self.sim_dialog.simulator_widget.dirty = True
self.state_cs_dirty = False
if self.changed_state:
# used to update the opengl tool, and UI displays
mx = self.mpos[0]
my = self.mpos[1]
mz = self.mpos[2]
wx = self.wpos[0]
wy = self.wpos[1]
wz = self.wpos[2]
self.lcdNumber_mx.display("{:0.3f}".format(mx))
self.lcdNumber_my.display("{:0.3f}".format(my))
self.lcdNumber_mz.display("{:0.3f}".format(mz))
self.lcdNumber_wx.display("{:0.3f}".format(wx))
self.lcdNumber_wy.display("{:0.3f}".format(wy))
self.lcdNumber_wz.display("{:0.3f}".format(wz))
self.jogWidget.wx_current = wx
self.jogWidget.wy_current = wy
self.jogWidget.wz_current = wz
# simulator update
self.sim_dialog.simulator_widget.draw_tool(self.mpos)
bgcolor = "transparent"
color = "black"
if self.state == "Idle":
bgcolor = "green"
color = "white"
self.jogWidget.onIdle()
if self.probe_points_count == None and self.grbl.streaming_complete == True:
# we are currently not probing, or dwell command is active
print("on idle: requesting hash ")
self.grbl.hash_state_requested = True
if self._rx_buffer_fill == 0:
self.listWidget_logoutput.setEnabled(True)
self.lineEdit_cmdline.setEnabled(True)
self.spinBox_start_line.setValue(self._current_grbl_line_number)
self.spinBox_start_line.setEnabled(True)
elif self.state == "Run":
bgcolor = "blue"
color = "white"
self.spinBox_start_line.setEnabled(False)
elif self.state == "Check":
bgcolor = "orange"
color = "white"
elif self.state == "Hold":
bgcolor = "yellow"
color = "black"
elif self.state == "Alarm":
bgcolor = "red"
color = "white"
self.label_state.setText(self.state)
self.label_state.setStyleSheet("background-color: '{}'; color: '{}';".format(bgcolor, color))
self.changed_state = False
if self.changed_loginput == True:
self._render_logbuffer()
self.changed_loginput = False
if self._rx_buffer_fill_last != self._rx_buffer_fill:
self.progressBar_buffer.setValue(self._rx_buffer_fill)
self._rx_buffer_fill_last = self._rx_buffer_fill
if self._progress_percent_last != self._progress_percent:
self.progressBar_job.setValue(self._progress_percent)
self._progress_percent_last = self._progress_percent
def _startup_disable_inputs(self):
self.comboBox_target.setEnabled(False)
self.pushButton_homing.setEnabled(False)
self.pushButton_killalarm.setEnabled(False)
self.pushButton_job_halt.setEnabled(False)
self.pushButton_job_new.setEnabled(False)
self.pushButton_hold.setEnabled(False)
self.pushButton_resume.setEnabled(False)
self.pushButton_abort.setEnabled(False)
self.pushButton_check.setEnabled(False)
self.pushButton_g0x0y0.setEnabled(False)
self.pushButton_xminus.setEnabled(False)
self.pushButton_xplus.setEnabled(False)
self.pushButton_yminus.setEnabled(False)
self.pushButton_yplus.setEnabled(False)
self.pushButton_zminus.setEnabled(False)
self.pushButton_zplus.setEnabled(False)
self.horizontalSlider_feed_override.setEnabled(False)
self.horizontalSlider_spindle_factor.setEnabled(False)
self.checkBox_feed_override.setEnabled(False)
self.checkBox_incremental.setEnabled(False)
self.comboBox_coordinate_systems.setEnabled(False)
self.pushButton_current_cs_setzero.setEnabled(False)
self.pushButton_g53z0.setEnabled(False)
self.pushButton_g53min.setEnabled(False)
self.pushButton_g53x0y0.setEnabled(False)
self.pushButton_spindleon.setEnabled(False)
self.pushButton_spindleoff.setEnabled(False)
def _cmd_line_callback(self, data):
if data == "Enter":
cmd = self.lineEdit_cmdline.text()
self._exec_cmd(cmd)
elif data == "UP":
if self.logoutput_at_end:
itemcount = len(self.logoutput_items) - 1
row = itemcount
self.logoutput_at_end = False
else:
row = self.listWidget_logoutput.currentRow()
row -= 1
row = 0 if row < 0 else row
item = self.logoutput_items[row]
self.listWidget_logoutput.setCurrentItem(item)
self.lineEdit_cmdline.setText(item.text())
elif data == "DOWN":
row = self.listWidget_logoutput.currentRow()
itemcount = len(self.logoutput_items) - 1
row += 1
row = itemcount if row > itemcount else row
item = self.logoutput_items[row]
self.listWidget_logoutput.setCurrentItem(item)
self.lineEdit_cmdline.setText(item.text())
# UI SLOTS
def settings_save_into_file(self):
filename_tuple = QFileDialog.getSaveFileName(self, "Save File", os.getcwd(), "")
filepath = filename_tuple[0]
if filepath == "": return
settings_string = self.settings_table_to_str()
with open(filepath, 'w') as f:
f.write(settings_string)
def settings_load_from_file(self):
filename_tuple = QFileDialog.getOpenFileName(self, "Open File", os.getcwd(), "")
filepath = filename_tuple[0]
if filepath == "": return
settings = {}
with open(filepath, 'r') as f:
for line in f:
m = re.match("\$(.*)=(.*) \((.*)\)", line)
if m:
key = int(m.group(1))
val = m.group(2)
comment = m.group(3)
settings[key] = {
"val" : val,
"cmt" : comment
}
self.dict_into_settings_table(settings)
def settings_upload_to_grbl(self):
settings_string = self.settings_table_to_str()
was_incremental = self.checkBox_incremental.isChecked()
self._add_to_loginput("<i>Stashing current buffer</i>")
self.grbl.do_buffer_stash()
self.grbl.incremental_streaming = True
self.checkBox_incremental.setChecked(True)
def settings_upload_complete():
self.checkBox_incremental.setChecked(was_incremental)
self._add_to_loginput("<i>Successfully uploaded settings!</i>")
self.on_job_completed_callback = None
self._add_to_loginput("<i>Unstashing previous buffer</i>")
self.grbl.do_buffer_unstash()
self.on_job_completed_callback = settings_upload_complete
self._add_to_loginput("<i>Sending settings...</i>")
self.grbl.current_line_number = 0
self.set_target("firmware")
self.grbl.stream(settings_string)
def _start_line_changed(self, nr):
line_number = int(nr)
if line_number < self.grbl.buffer_size:
self.grbl.current_line_number = line_number
self.sim_dialog.simulator_widget.put_buffer_marker_at_line(line_number)
self.label_current_gcode.setText(self.grbl.buffer[line_number])
def execute_script_clicked(self):
self.grbl.update_preprocessor_position()
code = self.plainTextEdit_script.toPlainText()
self.statusBar.showMessage("Executing script. Please wait...")
try:
exec(code, globals(), locals())
except:
txt = traceback.format_exc()
txt = re.sub(r"\n", "<br/>", txt)
self._add_to_loginput(txt)
self.statusBar.showMessage("Executing script done!", 3000)
def _on_logoutput_item_double_clicked(self, item):
self._exec_cmd(item.text())
def _on_logoutput_item_clicked(self, item):
self.lineEdit_cmdline.setText(item.text())
self.lineEdit_cmdline.setFocus()
def _on_logoutput_current_item_changed(self, item_current, item_previous):
self.lineEdit_cmdline.setText(item_current.text())
self.logoutput_at_end = False
def _quit(self):
self.grbl.disconnect()
QApplication.quit()
def _pick_file(self):
filename_tuple = QFileDialog.getOpenFileName(self, "Open File",self._open_gcode_location, "GCode Files (*.ngc *.gcode *.nc)")
fpath = filename_tuple[0]
if fpath == "": return
self.grbl.load_file(fpath)
self._open_gcode_location = os.path.dirname(fpath)
self.settings.setValue("open_gcode_location", self._open_gcode_location)
def _pick_script(self):
filename_tuple = QFileDialog.getOpenFileName(self, "Open Script", self._open_script_location, "Python3 Files (*.py)")
fpath = filename_tuple[0]
if fpath == "": return
with open(fpath, 'r') as content_file: content = content_file.read()
self.plainTextEdit_script.setPlainText(content)
self.label_script_filename.setText(os.path.basename(fpath))
self.current_script_filepath = fpath
self._open_script_location = os.path.dirname(fpath)
self.settings.setValue("open_script_location", self._open_script_location)
def _save_script(self):
fname = self.current_script_filepath
if fname == None:
self._save_script_as()
return
with open(fname, 'w') as content_file:
content_file.write(self.plainTextEdit_script.toPlainText())
self._add_to_loginput("File {} written.".format(fname))
def _save_script_as(self):
filename_tuple = QFileDialog.getSaveFileName(self, "Save Script", self._open_script_location)
fname = filename_tuple[0]
if fname == "": return
with open(fname, 'w') as content_file:
content_file.write(self.plainTextEdit_script.toPlainText())
self._add_to_loginput("File {} written.".format(fname))
self.label_script_filename.setText(os.path.basename(fpath))
def xminus(self):
step = - self.doubleSpinBox_jogstep.value()
self.grbl.send_immediately("G91")
self.grbl.send_immediately("G0 X" + str(step))
self.grbl.send_immediately("G90")
def xplus(self):
step = self.doubleSpinBox_jogstep.value()
self.grbl.send_immediately("G91")
self.grbl.send_immediately("G0 X" + str(step))
self.grbl.send_immediately("G90")
def yminus(self):
step = - self.doubleSpinBox_jogstep.value()
self.grbl.send_immediately("G91")
self.grbl.send_immediately("G0 Y" + str(step))
self.grbl.send_immediately("G90")
def yplus(self):
step = self.doubleSpinBox_jogstep.value()
self.grbl.send_immediately("G91")
self.grbl.send_immediately("G0 Y" + str(step))
self.grbl.send_immediately("G90")
def zminus(self):
step = - self.doubleSpinBox_jogstep.value()
self.grbl.send_immediately("G91")
self.grbl.send_immediately("G0 Z" + str(step))
self.grbl.send_immediately("G90")
def zplus(self):
step = self.doubleSpinBox_jogstep.value()
self.grbl.send_immediately("G91")
self.grbl.send_immediately("G0 Z" + str(step))
self.grbl.send_immediately("G90")
def _feedoverride_value_changed(self):
val = self.horizontalSlider_feed_override.value() # 0..100
val = int(math.exp((val+100)/23)-50) # nice exponential growth between 20 and 6000
self.lcdNumber_feed_override.display(val)
self.grbl.request_feed(val)
if self.state == "Idle":
self.grbl.send_immediately("F{:d}".format(val))
def _spindle_factor_value_changed(self):
val = self.horizontalSlider_spindle_factor.value() # 0..100
self.grbl.preprocessor.spindle_factor = val / 100
def _feedoverride_changed(self, val):
val = False if val == 0 else True
# first write feed to Grbl
self._feedoverride_value_changed()
# next set the boolean flag
self.grbl.set_feed_override(val)
def _incremental_changed(self, val):
val = False if val == 0 else True
self.grbl.incremental_streaming = val
def abort(self):
self.reset()
def hold(self):
self.grbl.hold()
def reset(self):
self.probe_points_count = None
self.grbl.abort()
def job_run(self):
self.job_run_timestamp = time.time()
line_nr = self.spinBox_start_line.value()
self.grbl.job_run(line_nr)
def job_halt(self):
self.grbl.job_halt()
self.grbl.gcode_parser_state_requested = True
def stream_play(self):
self.grbl.job_run()
def check(self):
self.grbl.send_immediately("$C")
def g0x0y0(self):
motion_mode = self.grbl.gps[4] # remember previous
self.grbl.send_immediately("G90") # absolute mode
self.grbl.send_immediately("G0 X0 Y0")
self.grbl.send_immediately("G" + motion_mode) # restore
def g53z0(self):
# one millimeter below the limit switch
self.grbl.send_immediately("G53 G0 Z-1")
def g53min(self):
workarea_x = int(float(self.grbl.settings[130]["val"]))
workarea_y = int(float(self.grbl.settings[131]["val"]))
self.grbl.send_immediately("G53 G0 X{:0.3f} Y{:0.3f}".format(-workarea_x, -workarea_y))
def g53x0y0(self):
self.grbl.send_immediately("G53 G0 X0 Y0")
def spindleon(self):
self.grbl.send_immediately("M3")
self.grbl.send_immediately("S255")
self.grbl.gcode_parser_state_requested = True
def spindleoff(self):
self.grbl.send_immediately("S0")
self.grbl.send_immediately("M5")
self.grbl.gcode_parser_state_requested = True
def cnect(self):
self.action_grbl_connect.setEnabled(False)
self.grbl.cnect(self.devicepath, self.devicebaud)
def disconnect(self):
self.action_grbl_disconnect.setEnabled(False)
self.grbl.disconnect()
def draw_gcode(self, gcode, do_fractionize_arcs=True):
ccs = self.cs_names[self.current_cs]
self.sim_dialog.simulator_widget.cs_offsets = self.state_hash
self.sim_dialog.simulator_widget.draw_gcode(gcode, self.mpos, ccs, do_fractionize_arcs)
def _show_buffer(self):
buf = self.grbl.buffer
output = ""
for i in range(0, len(buf)):
output += "L{:06d} {}\n".format(i, buf[i])
self.plainTextEdit_job.setPlainText(output)
def _secs_to_timestring(self, secs):
if secs < 0: return ""
secs = int(secs)
hours = math.floor(secs / 3600)
secs = secs - hours * 3600
mins = math.floor(secs / 60)
secs = secs - mins * 60
result = "{:02d}:{:02d}:{:02d}".format(hours, mins, secs)
return result
def _cs_selected(self, idx):
self.current_cs = idx + 1
self._last_cs = self.current_cs
self.settings.setValue("last_cs", self._last_cs)
self.grbl.send_immediately(self.cs_names[self.current_cs])
self.grbl.hash_state_requested = True
# callback for the drop-down
def _target_selected(self, idx):
self.current_target = self.targets[idx]
self.grbl.target = self.current_target
self.pushButton_job_run.setText("➾ {}".format(self.current_target))
self.spinBox_start_line.setValue(0)
self._start_line_changed(0)
if self.current_target == "firmware":
self.pushButton_job_run.setText("⚒ RUN MACHINE ⚠")
self.pushButton_job_run.setStyleSheet("background-color: rgb(198,31,31); color: white;")
else:
self.pushButton_job_run.setStyleSheet("background-color: none; color: black;")
def current_cs_setzero(self):
self.grbl.send_immediately("G10 L2 P{:d} X{:f} Y{:f} Z{:f}".format(self.current_cs, self.mpos[0], self.mpos[1], self.mpos[2]))
self.grbl.hash_state_requested = True
def _variables_edited(self, row, col):
print("_variables_edited", row, col)
d = self._var_table_to_dict()
self.grbl.preprocessor.vars = d
## UTILITY FUNCTIONS
def _var_table_to_dict(self):
row_count = self.tableWidget_variables.rowCount()
vars = {}
for row in range(0, row_count):
cell_a = self.tableWidget_variables.item(row, 0)
if cell_a == None:
continue
key = cell_a.text().strip()
key = key.replace("#", "")
cell_b = self.tableWidget_variables.item(row, 1)
if cell_b:
val = cell_b.text().strip()
if val == "":
val = None
else:
val = None
vars[key] = val
return vars
def var_keys_into_var_table(self, d):
self.tableWidget_variables.clear()
row = 0
for key, val in d.items():
cell_a = QTableWidgetItem("#" + key)
cell_b = QTableWidgetItem(val)
self.tableWidget_variables.setItem(row, 0, cell_a)
self.tableWidget_variables.setItem(row, 1, cell_b)
row += 1
def dict_into_settings_table(self, d):
self.tableWidget_settings.clear()
row = 0
for key, val in sorted(d.items()):
cell_a = QTableWidgetItem("$" + str(key))
cell_b = QTableWidgetItem(val["val"])
cell_c = QTableWidgetItem(val["cmt"])
self.tableWidget_settings.setItem(row, 0, cell_a)
self.tableWidget_settings.setItem(row, 1, cell_b)
self.tableWidget_settings.setItem(row, 2, cell_c)
self.tableWidget_settings.setRowHeight(row, 20)
row += 1
def settings_table_to_str(self):
row_count = self.tableWidget_settings.rowCount()
settings_string = ""
for row in range(0, row_count):
key = self.tableWidget_settings.item(row, 0).text()
key = "$" + key.replace("$", "").strip()
val = self.tableWidget_settings.item(row, 1).text().strip()
cmt = self.tableWidget_settings.item(row, 2).text().strip()
settings_string += key + "=" + val + " (" + cmt + ")\n"
return settings_string
def _exec_cmd(self, cmd):
cmd = cmd.strip()
if len(cmd) == 0:
return
self._add_to_logoutput(cmd)
self.lineEdit_cmdline.setText("")
if cmd[0] == "=":
# dynamically executed python code must begin with an equal sign
# "self." is prepended for convenience
kls = "self"
cmd = cmd[1:]
cmd = "%s.%s" % (kls,cmd)
try:
exec(cmd)
except:
self._add_to_loginput("Error during dynamic python execution:<br />{}".format(sys.exc_info()))
print("Exception in user code:")
traceback.print_exc(file=sys.stdout)
else:
self.grbl.send_immediately(cmd)
self.grbl.gcode_parser_state_requested = True
def set_cs(self, nr):
"""
A convenience function update the UI for CS
"""
self.current_cs = nr
current_cs_text = self.cs_names[self.current_cs]
#self.label_current_cs.setText(current_cs_text)
self.comboBox_coordinate_systems.setCurrentIndex(nr - 1)
self.state_cs_dirty = True
def calc_eta(self):
proc = GcodeMachine()
proc.cs_offsets = self.grbl.settings_hash
proc.position_m = [0, 0, 0]
dists_by_feed = {}
g0_feed = float(self.grbl.settings[110]["val"])
feed_is_overridden = self.checkBox_feed_override.isChecked()
for line in self.grbl.buffer[self.grbl.current_line_number:]:
proc.set_line(line)
proc.parse_state()
proc.override_feed()
cf = proc.current_feed
cmm = proc.current_motion_mode
if cmm == None:
continue
elif cmm == 0:
cf = g0_feed
else:
# G1, G2, G3
if feed_is_overridden:
cf = self.grbl.preprocessor.request_feed
if cf in dists_by_feed:
dists_by_feed[cf] += proc.dist
else:
dists_by_feed[cf] = proc.dist
proc.done()
mins = 0
for feed, dist in dists_by_feed.items():
mins += dist / feed
self.job_current_eta = time.time() + mins * 60
self.label_jobtime.setText(self._secs_to_timestring(mins * 60))
def bbox(self, move_z=False):
lines = gcodetools.bbox_draw(self.grbl.buffer, move_z).split("\n")
for line in lines:
self.grbl.send_immediately(line)
def _render_logbuffer(self):
self.label_loginput.setText("<br />".join(self.logbuffer))
self.scrollArea_loginput.verticalScrollBar().setValue(self.scrollArea_loginput.verticalScrollBar().maximum())
def _add_to_loginput(self, msg, color="black"):
html = "<span style='color: {}'>{}</span>".format(color, msg)
#print(html)
self.logbuffer.append(html)
self.changed_loginput = True
def _add_to_logoutput(self, line):
item = QListWidgetItem(line, self.listWidget_logoutput)
self.logoutput_items.append(item)
self.listWidget_logoutput.setCurrentItem(item)
self.listWidget_logoutput.scrollToBottom()
self.logoutput_at_end = True
def homing(self):
self.grbl.homing() | [
"PyQt5.QtGui.QKeySequence",
"PyQt5.QtWidgets.QFileDialog.getOpenFileName",
"gcode_machine.gcode_machine.GcodeMachine",
"sys.exc_info",
"lib.compiler.receiver",
"PyQt5.QtWidgets.QAction",
"PyQt5.QtWidgets.QMenuBar",
"collections.deque",
"PyQt5.QtWidgets.QLabel",
"traceback.print_exc",
"PyQt5.QtWi... | [((1212, 1250), 'logging.getLogger', 'logging.getLogger', (['"""cnctoolbox.window"""'], {}), "('cnctoolbox.window')\n", (1229, 1250), False, 'import logging\n'), ((2158, 2199), 'collections.deque', 'collections.deque', ([], {'maxlen': '_logbuffer_size'}), '(maxlen=_logbuffer_size)\n', (2175, 2199), False, 'import collections\n'), ((2334, 2342), 'PyQt5.QtWidgets.QLabel', 'QLabel', ([], {}), '()\n', (2340, 2342), False, 'from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMessageBox, QSlider, QLabel, QPushButton, QWidget, QDialog, QMainWindow, QFileDialog, QLineEdit, QSpacerItem, QListWidgetItem, QMenuBar, QMenu, QAction, QTableWidgetItem, QDialog, QShortcut\n'), ((2627, 2640), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (2638, 2640), False, 'from PyQt5 import QtCore, QtGui\n'), ((2835, 2848), 'PyQt5.QtGui.QFont', 'QtGui.QFont', ([], {}), '()\n', (2846, 2848), False, 'from PyQt5 import QtCore, QtGui\n'), ((3414, 3428), 'PyQt5.QtWidgets.QMenuBar', 'QMenuBar', (['self'], {}), '(self)\n', (3422, 3428), False, 'from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMessageBox, QSlider, QLabel, QPushButton, QWidget, QDialog, QMainWindow, QFileDialog, QLineEdit, QSpacerItem, QListWidgetItem, QMenuBar, QMenu, QAction, QTableWidgetItem, QDialog, QShortcut\n'), ((3472, 3503), 'PyQt5.QtWidgets.QAction', 'QAction', (['"""Open Script..."""', 'self'], {}), "('Open Script...', self)\n", (3479, 3503), False, 'from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMessageBox, QSlider, QLabel, QPushButton, QWidget, QDialog, QMainWindow, QFileDialog, QLineEdit, QSpacerItem, QListWidgetItem, QMenuBar, QMenu, QAction, QTableWidgetItem, QDialog, QShortcut\n'), ((3616, 3645), 'PyQt5.QtWidgets.QAction', 'QAction', (['"""Save Script!"""', 'self'], {}), "('Save Script!', self)\n", (3623, 3645), False, 'from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMessageBox, QSlider, QLabel, QPushButton, QWidget, QDialog, QMainWindow, QFileDialog, QLineEdit, QSpacerItem, QListWidgetItem, QMenuBar, QMenu, QAction, QTableWidgetItem, QDialog, QShortcut\n'), ((3761, 3795), 'PyQt5.QtWidgets.QAction', 'QAction', (['"""Save Script As..."""', 'self'], {}), "('Save Script As...', self)\n", (3768, 3795), False, 'from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMessageBox, QSlider, QLabel, QPushButton, QWidget, QDialog, QMainWindow, QFileDialog, QLineEdit, QSpacerItem, QListWidgetItem, QMenuBar, QMenu, QAction, QTableWidgetItem, QDialog, QShortcut\n'), ((3911, 3942), 'PyQt5.QtWidgets.QAction', 'QAction', (['"""Load G-Code..."""', 'self'], {}), "('Load G-Code...', self)\n", (3918, 3942), False, 'from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMessageBox, QSlider, QLabel, QPushButton, QWidget, QDialog, QMainWindow, QFileDialog, QLineEdit, QSpacerItem, QListWidgetItem, QMenuBar, QMenu, QAction, QTableWidgetItem, QDialog, QShortcut\n'), ((4048, 4070), 'PyQt5.QtWidgets.QAction', 'QAction', (['"""Quit!"""', 'self'], {}), "('Quit!', self)\n", (4055, 4070), False, 'from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMessageBox, QSlider, QLabel, QPushButton, QWidget, QDialog, QMainWindow, QFileDialog, QLineEdit, QSpacerItem, QListWidgetItem, QMenuBar, QMenu, QAction, QTableWidgetItem, QDialog, QShortcut\n'), ((4175, 4199), 'PyQt5.QtWidgets.QAction', 'QAction', (['"""Connect"""', 'self'], {}), "('Connect', self)\n", (4182, 4199), False, 'from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMessageBox, QSlider, QLabel, QPushButton, QWidget, QDialog, QMainWindow, QFileDialog, QLineEdit, QSpacerItem, QListWidgetItem, QMenuBar, QMenu, QAction, QTableWidgetItem, QDialog, QShortcut\n'), ((4301, 4328), 'PyQt5.QtWidgets.QAction', 'QAction', (['"""Disconnect"""', 'self'], {}), "('Disconnect', self)\n", (4308, 4328), False, 'from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMessageBox, QSlider, QLabel, QPushButton, QWidget, QDialog, QMainWindow, QFileDialog, QLineEdit, QSpacerItem, QListWidgetItem, QMenuBar, QMenu, QAction, QTableWidgetItem, QDialog, QShortcut\n'), ((5689, 5724), 'classes.simulatordialog.SimulatorDialog', 'SimulatorDialog', (['self', 'refresh_rate'], {}), '(self, refresh_rate)\n', (5704, 5724), False, 'from classes.simulatordialog import SimulatorDialog\n'), ((5826, 5852), 'gerbil.gerbil.Gerbil', 'Gerbil', (['self.on_grbl_event'], {}), '(self.on_grbl_event)\n', (5832, 5852), False, 'from gerbil.gerbil import Gerbil\n'), ((7848, 7894), 'classes.commandlineedit.CommandLineEdit', 'CommandLineEdit', (['self', 'self._cmd_line_callback'], {}), '(self, self._cmd_line_callback)\n', (7863, 7894), False, 'from classes.commandlineedit import CommandLineEdit\n'), ((9001, 9009), 'PyQt5.QtCore.QTimer', 'QTimer', ([], {}), '()\n', (9007, 9009), False, 'from PyQt5.QtCore import pyqtSignal, QPoint, QSize, Qt, QCoreApplication, QTimer, QSettings\n'), ((9127, 9135), 'PyQt5.QtCore.QTimer', 'QTimer', ([], {}), '()\n', (9133, 9135), False, 'from PyQt5.QtCore import pyqtSignal, QPoint, QSize, Qt, QCoreApplication, QTimer, QSettings\n'), ((11652, 11680), 'lib.compiler.receiver', 'compiler.receiver', (['self.grbl'], {}), '(self.grbl)\n', (11669, 11680), False, 'from lib import compiler\n'), ((12188, 12221), 'classes.jogwidget.JogWidget', 'JogWidget', (['self', 'self.grbl.stream'], {}), '(self, self.grbl.stream)\n', (12197, 12221), False, 'from classes.jogwidget import JogWidget\n'), ((12487, 12535), 'PyQt5.QtCore.QSettings', 'QSettings', (['"""gerbil_gui.ini"""', 'QSettings.IniFormat'], {}), "('gerbil_gui.ini', QSettings.IniFormat)\n", (12496, 12535), False, 'from PyQt5.QtCore import pyqtSignal, QPoint, QSize, Qt, QCoreApplication, QTimer, QSettings\n'), ((13452, 13463), 'time.time', 'time.time', ([], {}), '()\n', (13461, 13463), False, 'import time\n'), ((14050, 14061), 'time.time', 'time.time', ([], {}), '()\n', (14059, 14061), False, 'import time\n'), ((15950, 15994), 'numpy.add', 'np.add', (['probepoint_origin', 'current_cs_offset'], {}), '(probepoint_origin, current_cs_offset)\n', (15956, 15994), True, 'import numpy as np\n'), ((18597, 18675), 'numpy.zeros', 'np.zeros', (['(dimx * dimy)', "[('position', np.float32, 3), ('color', np.float32, 4)]"], {}), "(dimx * dimy, [('position', np.float32, 3), ('color', np.float32, 4)])\n", (18605, 18675), True, 'import numpy as np\n'), ((22256, 22292), 'numpy.subtract', 'np.subtract', (['mpos', 'current_cs_offset'], {}), '(mpos, current_cs_offset)\n', (22267, 22292), True, 'import numpy as np\n'), ((23671, 23779), 'scipy.interpolate.griddata', 'griddata', (['self.probe_points', 'self.probe_values', 'self.heightmap_ipolgrid'], {'method': '"""cubic"""', 'fill_value': '(-100)'}), "(self.probe_points, self.probe_values, self.heightmap_ipolgrid,\n method='cubic', fill_value=-100)\n", (23679, 23779), False, 'from scipy.interpolate import griddata\n'), ((46105, 46124), 'PyQt5.QtWidgets.QApplication.quit', 'QApplication.quit', ([], {}), '()\n', (46122, 46124), False, 'from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMessageBox, QSlider, QLabel, QPushButton, QWidget, QDialog, QMainWindow, QFileDialog, QLineEdit, QSpacerItem, QListWidgetItem, QMenuBar, QMenu, QAction, QTableWidgetItem, QDialog, QShortcut\n'), ((46178, 46291), 'PyQt5.QtWidgets.QFileDialog.getOpenFileName', 'QFileDialog.getOpenFileName', (['self', '"""Open File"""', 'self._open_gcode_location', '"""GCode Files (*.ngc *.gcode *.nc)"""'], {}), "(self, 'Open File', self._open_gcode_location,\n 'GCode Files (*.ngc *.gcode *.nc)')\n", (46205, 46291), False, 'from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMessageBox, QSlider, QLabel, QPushButton, QWidget, QDialog, QMainWindow, QFileDialog, QLineEdit, QSpacerItem, QListWidgetItem, QMenuBar, QMenu, QAction, QTableWidgetItem, QDialog, QShortcut\n'), ((46423, 46445), 'os.path.dirname', 'os.path.dirname', (['fpath'], {}), '(fpath)\n', (46438, 46445), False, 'import os\n'), ((46589, 46693), 'PyQt5.QtWidgets.QFileDialog.getOpenFileName', 'QFileDialog.getOpenFileName', (['self', '"""Open Script"""', 'self._open_script_location', '"""Python3 Files (*.py)"""'], {}), "(self, 'Open Script', self._open_script_location,\n 'Python3 Files (*.py)')\n", (46616, 46693), False, 'from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMessageBox, QSlider, QLabel, QPushButton, QWidget, QDialog, QMainWindow, QFileDialog, QLineEdit, QSpacerItem, QListWidgetItem, QMenuBar, QMenu, QAction, QTableWidgetItem, QDialog, QShortcut\n'), ((47056, 47078), 'os.path.dirname', 'os.path.dirname', (['fpath'], {}), '(fpath)\n', (47071, 47078), False, 'import os\n'), ((47599, 47675), 'PyQt5.QtWidgets.QFileDialog.getSaveFileName', 'QFileDialog.getSaveFileName', (['self', '"""Save Script"""', 'self._open_script_location'], {}), "(self, 'Save Script', self._open_script_location)\n", (47626, 47675), False, 'from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMessageBox, QSlider, QLabel, QPushButton, QWidget, QDialog, QMainWindow, QFileDialog, QLineEdit, QSpacerItem, QListWidgetItem, QMenuBar, QMenu, QAction, QTableWidgetItem, QDialog, QShortcut\n'), ((50612, 50623), 'time.time', 'time.time', ([], {}), '()\n', (50621, 50623), False, 'import time\n'), ((52968, 52991), 'math.floor', 'math.floor', (['(secs / 3600)'], {}), '(secs / 3600)\n', (52978, 52991), False, 'import math\n'), ((53042, 53063), 'math.floor', 'math.floor', (['(secs / 60)'], {}), '(secs / 60)\n', (53052, 53063), False, 'import math\n'), ((58014, 58028), 'gcode_machine.gcode_machine.GcodeMachine', 'GcodeMachine', ([], {}), '()\n', (58026, 58028), False, 'from gcode_machine.gcode_machine import GcodeMachine\n'), ((59937, 59985), 'PyQt5.QtWidgets.QListWidgetItem', 'QListWidgetItem', (['line', 'self.listWidget_logoutput'], {}), '(line, self.listWidget_logoutput)\n', (59952, 59985), False, 'from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMessageBox, QSlider, QLabel, QPushButton, QWidget, QDialog, QMainWindow, QFileDialog, QLineEdit, QSpacerItem, QListWidgetItem, QMenuBar, QMenu, QAction, QTableWidgetItem, QDialog, QShortcut\n'), ((9375, 9407), 'PyQt5.QtGui.QKeySequence', 'QKeySequence', (['(Qt.CTRL + Qt.Key_S)'], {}), '(Qt.CTRL + Qt.Key_S)\n', (9387, 9407), False, 'from PyQt5.QtGui import QColor, QPalette, QKeySequence\n'), ((9519, 9551), 'PyQt5.QtGui.QKeySequence', 'QKeySequence', (['(Qt.CTRL + Qt.Key_O)'], {}), '(Qt.CTRL + Qt.Key_O)\n', (9531, 9551), False, 'from PyQt5.QtGui import QColor, QPalette, QKeySequence\n'), ((9663, 9695), 'PyQt5.QtGui.QKeySequence', 'QKeySequence', (['(Qt.CTRL + Qt.Key_R)'], {}), '(Qt.CTRL + Qt.Key_R)\n', (9675, 9695), False, 'from PyQt5.QtGui import QColor, QPalette, QKeySequence\n'), ((9800, 9832), 'PyQt5.QtGui.QKeySequence', 'QKeySequence', (['(Qt.CTRL + Qt.Key_K)'], {}), '(Qt.CTRL + Qt.Key_K)\n', (9812, 9832), False, 'from PyQt5.QtGui import QColor, QPalette, QKeySequence\n'), ((9946, 9978), 'PyQt5.QtGui.QKeySequence', 'QKeySequence', (['(Qt.CTRL + Qt.Key_H)'], {}), '(Qt.CTRL + Qt.Key_H)\n', (9958, 9978), False, 'from PyQt5.QtGui import QColor, QPalette, QKeySequence\n'), ((10084, 10116), 'PyQt5.QtGui.QKeySequence', 'QKeySequence', (['(Qt.CTRL + Qt.Key_E)'], {}), '(Qt.CTRL + Qt.Key_E)\n', (10096, 10116), False, 'from PyQt5.QtGui import QColor, QPalette, QKeySequence\n'), ((16684, 16734), 're.match', 're.match', (['"""(........) (........) (........)"""', 'line'], {}), "('(........) (........) (........)', line)\n", (16692, 16734), False, 'import re\n'), ((22919, 22979), 'random.randint', 'random.randint', (['self.heightmap_llc[0]', 'self.heightmap_urc[0]'], {}), '(self.heightmap_llc[0], self.heightmap_urc[0])\n', (22933, 22979), False, 'import random\n'), ((22997, 23057), 'random.randint', 'random.randint', (['self.heightmap_llc[1]', 'self.heightmap_urc[1]'], {}), '(self.heightmap_llc[1], self.heightmap_urc[1])\n', (23011, 23057), False, 'import random\n'), ((42777, 42788), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (42786, 42788), False, 'import os\n'), ((43141, 43152), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (43150, 43152), False, 'import os\n'), ((46940, 46963), 'os.path.basename', 'os.path.basename', (['fpath'], {}), '(fpath)\n', (46956, 46963), False, 'import os\n'), ((47967, 47990), 'os.path.basename', 'os.path.basename', (['fpath'], {}), '(fpath)\n', (47983, 47990), False, 'import os\n'), ((55444, 55471), 'PyQt5.QtWidgets.QTableWidgetItem', 'QTableWidgetItem', (["('#' + key)"], {}), "('#' + key)\n", (55460, 55471), False, 'from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMessageBox, QSlider, QLabel, QPushButton, QWidget, QDialog, QMainWindow, QFileDialog, QLineEdit, QSpacerItem, QListWidgetItem, QMenuBar, QMenu, QAction, QTableWidgetItem, QDialog, QShortcut\n'), ((55493, 55514), 'PyQt5.QtWidgets.QTableWidgetItem', 'QTableWidgetItem', (['val'], {}), '(val)\n', (55509, 55514), False, 'from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMessageBox, QSlider, QLabel, QPushButton, QWidget, QDialog, QMainWindow, QFileDialog, QLineEdit, QSpacerItem, QListWidgetItem, QMenuBar, QMenu, QAction, QTableWidgetItem, QDialog, QShortcut\n'), ((55891, 55919), 'PyQt5.QtWidgets.QTableWidgetItem', 'QTableWidgetItem', (["val['val']"], {}), "(val['val'])\n", (55907, 55919), False, 'from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMessageBox, QSlider, QLabel, QPushButton, QWidget, QDialog, QMainWindow, QFileDialog, QLineEdit, QSpacerItem, QListWidgetItem, QMenuBar, QMenu, QAction, QTableWidgetItem, QDialog, QShortcut\n'), ((55941, 55969), 'PyQt5.QtWidgets.QTableWidgetItem', 'QTableWidgetItem', (["val['cmt']"], {}), "(val['cmt'])\n", (55957, 55969), False, 'from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMessageBox, QSlider, QLabel, QPushButton, QWidget, QDialog, QMainWindow, QFileDialog, QLineEdit, QSpacerItem, QListWidgetItem, QMenuBar, QMenu, QAction, QTableWidgetItem, QDialog, QShortcut\n'), ((59143, 59154), 'time.time', 'time.time', ([], {}), '()\n', (59152, 59154), False, 'import time\n'), ((12706, 12717), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (12715, 12717), False, 'import os\n'), ((13005, 13016), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (13014, 13016), False, 'import os\n'), ((35718, 35744), 're.match', 're.match', (['"""G5[4-9].*"""', 'key'], {}), "('G5[4-9].*', key)\n", (35726, 35744), False, 'import re\n'), ((43342, 43383), 're.match', 're.match', (['"""\\\\$(.*)=(.*) \\\\((.*)\\\\)"""', 'line'], {}), "('\\\\$(.*)=(.*) \\\\((.*)\\\\)', line)\n", (43350, 43383), False, 'import re\n'), ((45391, 45413), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (45411, 45413), False, 'import sys, traceback\n'), ((45432, 45459), 're.sub', 're.sub', (['"""\\\\n"""', '"""<br/>"""', 'txt'], {}), "('\\\\n', '<br/>', txt)\n", (45438, 45459), False, 'import re\n'), ((49504, 49530), 'math.exp', 'math.exp', (['((val + 100) / 23)'], {}), '((val + 100) / 23)\n', (49512, 49530), False, 'import math\n'), ((59299, 59345), 'lib.gcodetools.bbox_draw', 'gcodetools.bbox_draw', (['self.grbl.buffer', 'move_z'], {}), '(self.grbl.buffer, move_z)\n', (59319, 59345), False, 'from lib import gcodetools\n'), ((57450, 57486), 'traceback.print_exc', 'traceback.print_exc', ([], {'file': 'sys.stdout'}), '(file=sys.stdout)\n', (57469, 57486), False, 'import sys, traceback\n'), ((34919, 34930), 'time.time', 'time.time', ([], {}), '()\n', (34928, 34930), False, 'import time\n'), ((35041, 35052), 'time.time', 'time.time', ([], {}), '()\n', (35050, 35052), False, 'import time\n'), ((57368, 57382), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (57380, 57382), False, 'import sys, traceback\n')] |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 11 22:31:03 2017
@author: Mihailo
"""
import cv2
import numpy as np
import math
def thresholdImage(img):
grayImg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# retval, threshImg = cv2.threshold(grayImg,0,255,cv2.THRESH_OTSU)
threshImg = cv2.adaptiveThreshold(grayImg,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,99,10)
numWhite = cv2.countNonZero(threshImg)
numBlack = threshImg.size - numWhite
if (numWhite < numBlack): # invert the image if the background is mostly white
return threshImg
else:
return 255-threshImg
def rotate90_counter_clockwise(img):
timg = cv2.transpose(img)
timg = cv2.flip(timg,0)
return timg
def distancePts(x1,y1,x2,y2):
return math.sqrt((x2-x1)**2+(y2-y1)**2)
def extractWord(img):
# Rotate counter clockwise by 90 degrees
img = rotate90_counter_clockwise(img)
# Apply adaptive threshold
threshImg = thresholdImage(img)
# Apply dilation to join the gaps
# http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_morphological_ops/py_morphological_ops.html
# http://docs.opencv.org/master/d1/dee/tutorial_moprh_lines_detection.html
binaryImg = (threshImg==255).astype(np.uint8)
kernel = np.zeros([5,5]) #horizontal structuring element
kernel[2,:] = np.ones([1,5])
kernel = kernel.astype(np.uint8)
#kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
dilateImg = cv2.dilate(binaryImg,kernel,iterations=4)
dilateImg = dilateImg*255
# Find the contours to get blocks that correspond to words
# https://opencvpython.blogspot.com/2012/06/hi-this-article-is-tutorial-which-try.html
# http://docs.opencv.org/master/d4/d73/tutorial_py_contours_begin.html
dilateImg_copy = dilateImg.copy()
im2, contours, hierarchy = cv2.findContours(dilateImg_copy,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
imgContours = img.copy()
imgContours = cv2.drawContours(imgContours,contours,-1,(0,255,0),3)
# For each contour, find the bounding rectangle and draw it
# http://docs.opencv.org/3.1.0/dd/d49/tutorial_py_contour_features.html
fixedPt_x = 670
fixedPt_y = 575
minDistance = img.shape[0]
for contour in contours:
center,dimensions,theta = cv2.minAreaRect(contour)
if (dimensions[0]>10) and (dimensions[1]>20): # filter out small boxes created from noise
distanceFromFixed = distancePts(fixedPt_x,fixedPt_y,center[0],center[1])
if (distanceFromFixed < minDistance):
minDistance = distanceFromFixed
minContour = contour
center,dimensions,theta = cv2.minAreaRect(minContour)
if(dimensions[0] < dimensions[1]):
w = dimensions[1]
h = dimensions[0]
theta = theta+90
else:
w = dimensions[0]
h = dimensions[1]
box = cv2.boxPoints((center,(w,h),theta))
box = np.int0(box)
cv2.drawContours(img,[box],0,(0,0,255),2)
cv2.namedWindow('image', cv2.WINDOW_NORMAL)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite(r'/home/pi/Documents/RPi_Translator/images/wordSegmented.jpg',img)
rotateImg = threshImg.copy()
rotateMatrix = cv2.getRotationMatrix2D(center,theta,1.0)
rotateImg = cv2.warpAffine(threshImg, rotateMatrix, (rotateImg.shape[0], rotateImg.shape[0]))
wordSegmented = cv2.getRectSubPix(rotateImg, (np.int0(w),np.int0(h)), center)
wordSegmented = cv2.copyMakeBorder(wordSegmented,10,10,10,10,cv2.BORDER_CONSTANT,0)
wordSegmented = 255-wordSegmented
return wordSegmented
| [
"numpy.ones",
"cv2.transpose",
"cv2.adaptiveThreshold",
"cv2.warpAffine",
"cv2.boxPoints",
"cv2.minAreaRect",
"cv2.imshow",
"cv2.getRotationMatrix2D",
"cv2.dilate",
"cv2.cvtColor",
"cv2.imwrite",
"cv2.copyMakeBorder",
"cv2.drawContours",
"cv2.destroyAllWindows",
"numpy.int0",
"math.sqr... | [((179, 216), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (191, 216), False, 'import cv2\n'), ((305, 404), 'cv2.adaptiveThreshold', 'cv2.adaptiveThreshold', (['grayImg', '(255)', 'cv2.ADAPTIVE_THRESH_GAUSSIAN_C', 'cv2.THRESH_BINARY', '(99)', '(10)'], {}), '(grayImg, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.\n THRESH_BINARY, 99, 10)\n', (326, 404), False, 'import cv2\n'), ((411, 438), 'cv2.countNonZero', 'cv2.countNonZero', (['threshImg'], {}), '(threshImg)\n', (427, 438), False, 'import cv2\n'), ((692, 710), 'cv2.transpose', 'cv2.transpose', (['img'], {}), '(img)\n', (705, 710), False, 'import cv2\n'), ((723, 740), 'cv2.flip', 'cv2.flip', (['timg', '(0)'], {}), '(timg, 0)\n', (731, 740), False, 'import cv2\n'), ((807, 849), 'math.sqrt', 'math.sqrt', (['((x2 - x1) ** 2 + (y2 - y1) ** 2)'], {}), '((x2 - x1) ** 2 + (y2 - y1) ** 2)\n', (816, 849), False, 'import math\n'), ((1334, 1350), 'numpy.zeros', 'np.zeros', (['[5, 5]'], {}), '([5, 5])\n', (1342, 1350), True, 'import numpy as np\n'), ((1401, 1416), 'numpy.ones', 'np.ones', (['[1, 5]'], {}), '([1, 5])\n', (1408, 1416), True, 'import numpy as np\n'), ((1534, 1577), 'cv2.dilate', 'cv2.dilate', (['binaryImg', 'kernel'], {'iterations': '(4)'}), '(binaryImg, kernel, iterations=4)\n', (1544, 1577), False, 'import cv2\n'), ((1916, 1992), 'cv2.findContours', 'cv2.findContours', (['dilateImg_copy', 'cv2.RETR_EXTERNAL', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(dilateImg_copy, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n', (1932, 1992), False, 'import cv2\n'), ((2040, 2099), 'cv2.drawContours', 'cv2.drawContours', (['imgContours', 'contours', '(-1)', '(0, 255, 0)', '(3)'], {}), '(imgContours, contours, -1, (0, 255, 0), 3)\n', (2056, 2099), False, 'import cv2\n'), ((2766, 2793), 'cv2.minAreaRect', 'cv2.minAreaRect', (['minContour'], {}), '(minContour)\n', (2781, 2793), False, 'import cv2\n'), ((2990, 3028), 'cv2.boxPoints', 'cv2.boxPoints', (['(center, (w, h), theta)'], {}), '((center, (w, h), theta))\n', (3003, 3028), False, 'import cv2\n'), ((3037, 3049), 'numpy.int0', 'np.int0', (['box'], {}), '(box)\n', (3044, 3049), True, 'import numpy as np\n'), ((3055, 3102), 'cv2.drawContours', 'cv2.drawContours', (['img', '[box]', '(0)', '(0, 0, 255)', '(2)'], {}), '(img, [box], 0, (0, 0, 255), 2)\n', (3071, 3102), False, 'import cv2\n'), ((3108, 3151), 'cv2.namedWindow', 'cv2.namedWindow', (['"""image"""', 'cv2.WINDOW_NORMAL'], {}), "('image', cv2.WINDOW_NORMAL)\n", (3123, 3151), False, 'import cv2\n'), ((3157, 3181), 'cv2.imshow', 'cv2.imshow', (['"""image"""', 'img'], {}), "('image', img)\n", (3167, 3181), False, 'import cv2\n'), ((3186, 3200), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (3197, 3200), False, 'import cv2\n'), ((3206, 3229), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (3227, 3229), False, 'import cv2\n'), ((3235, 3313), 'cv2.imwrite', 'cv2.imwrite', (['"""/home/pi/Documents/RPi_Translator/images/wordSegmented.jpg"""', 'img'], {}), "('/home/pi/Documents/RPi_Translator/images/wordSegmented.jpg', img)\n", (3246, 3313), False, 'import cv2\n'), ((3378, 3421), 'cv2.getRotationMatrix2D', 'cv2.getRotationMatrix2D', (['center', 'theta', '(1.0)'], {}), '(center, theta, 1.0)\n', (3401, 3421), False, 'import cv2\n'), ((3437, 3523), 'cv2.warpAffine', 'cv2.warpAffine', (['threshImg', 'rotateMatrix', '(rotateImg.shape[0], rotateImg.shape[0])'], {}), '(threshImg, rotateMatrix, (rotateImg.shape[0], rotateImg.\n shape[0]))\n', (3451, 3523), False, 'import cv2\n'), ((3629, 3702), 'cv2.copyMakeBorder', 'cv2.copyMakeBorder', (['wordSegmented', '(10)', '(10)', '(10)', '(10)', 'cv2.BORDER_CONSTANT', '(0)'], {}), '(wordSegmented, 10, 10, 10, 10, cv2.BORDER_CONSTANT, 0)\n', (3647, 3702), False, 'import cv2\n'), ((2381, 2405), 'cv2.minAreaRect', 'cv2.minAreaRect', (['contour'], {}), '(contour)\n', (2396, 2405), False, 'import cv2\n'), ((3576, 3586), 'numpy.int0', 'np.int0', (['w'], {}), '(w)\n', (3583, 3586), True, 'import numpy as np\n'), ((3587, 3597), 'numpy.int0', 'np.int0', (['h'], {}), '(h)\n', (3594, 3597), True, 'import numpy as np\n')] |
""" Household ref person microsynthesis """
import numpy as np
import pandas as pd
import ukcensusapi.Nomisweb as Api
import humanleague
import household_microsynth.utils as Utils
class ReferencePerson:
""" Household ref person microsynthesis """
# Placeholders for unknown or non-applicable category values
UNKNOWN = -1
NOTAPPLICABLE = -2
# initialise, supplying geographical area and resolution , plus (optionally) a location to cache downloads
def __init__(self, region, resolution, cache_dir="./cache"):
self.api = Api.Nomisweb(cache_dir)
self.region = region
# convert input string to enum
self.resolution = resolution
# (down)load the census tables
self.__get_census_data()
# initialise table and index
categories = ["Area", "LC4605_C_NSSEC", "LC4605_C_TENHUK11", "LC4201_C_AGE", "LC4201_C_ETHPUK11",
"QS111_C_HHLSHUK11", "LC1102_C_LARPUK11"]
# LC4605_C_NSSEC LC4605_C_TENHUK11
# LC4201_C_AGE LC4201_C_ETHPUK11 [C_TENHUK11]
# QS111_C_HHLSHUK11
# [C_AGE] LC1102_C_LARPUK11
self.num_hrps = sum(self.lc4605.OBS_VALUE)
self.hrps = pd.DataFrame(columns=categories)
self.index = 0
# # generate indices
self.nssec_index = self.lc4605.C_NSSEC.unique()
self.tenure_index = self.lc4605.C_TENHUK11.unique()
self.age_index = self.lc4201.C_AGE.unique()
self.eth_index = self.lc4201.C_ETHPUK11.unique() # how come not C_ETHHUK11?
self.lifestage_index = self.qs111.C_HHLSHUK11.unique()
self.livarr_index = self.lc1102.C_LARPUK11.unique()
def run(self):
""" run the microsynthesis """
# print(self.nssec_index)
# print(self.tenure_index)
# print(self.age_index)
# print(self.eth_index)
# print(self.lifestage_index)
# print(self.livarr_index)
area_map = self.lc4605.GEOGRAPHY_CODE.unique()
# construct seed disallowing states where lifestage doesn match age
# N T A E L V (V=living arrangements)
# use microdata here if possible
constraints = np.ones([9, 4, 4, 7, 12, 7])
# seed from microdata...
for area in area_map:
print('.', end='', flush=True)
self.__add_ref_persons(area, constraints)
# end area loop
def __add_ref_persons(self, area, constraints):
nssec_tenure = self.lc4605.loc[self.lc4605.GEOGRAPHY_CODE == area].copy()
# unmap indices
# TODO might be quicker to unmap the entire table upfront?
Utils.unmap(nssec_tenure.C_NSSEC, self.nssec_index)
Utils.unmap(nssec_tenure.C_TENHUK11, self.tenure_index)
m4605 = Utils.unlistify(nssec_tenure,
["C_NSSEC", "C_TENHUK11"],
[len(self.nssec_index), len(self.tenure_index)],
"OBS_VALUE")
#print(m4605)
age_eth_tenure = self.lc4201.loc[self.lc4201.GEOGRAPHY_CODE == area].copy()
# unmap indices
# TODO might be quicker to unmap the entire table upfront?
#Utils.unmap(age_eth_tenure.C_AGE, self.age_index)
Utils.unmap(age_eth_tenure.C_ETHPUK11, self.eth_index)
Utils.unmap(age_eth_tenure.C_TENHUK11, self.tenure_index)
m4201 = Utils.unlistify(age_eth_tenure,
["C_AGE", "C_ETHPUK11", "C_TENHUK11"],
[len(self.age_index), len(self.eth_index), len(self.tenure_index)],
"OBS_VALUE")
# collapse age
m4201 = np.sum(m4201, axis=0)
# now check LC4605 total matches LC4201 and adjust as necessary (ensuring partial sum in tenure dimension is preserved)
m4605_sum = np.sum(m4605)
m4201_sum = np.sum(m4201)
if m4605_sum != m4201_sum:
print("LC4605:"+str(m4605_sum)+"->"+str(m4201_sum), end="")
tenure_4201 = np.sum(m4201, axis=0)
nssec_4605_adj = humanleague.prob2IntFreq(np.sum(m4605, axis=1) / m4605_sum, m4201_sum)["freq"]
#print(m4605)
m4605_adj = humanleague.qisi(m4605.astype(float), [np.array([0]), np.array([1])], [nssec_4605_adj, tenure_4201])
if isinstance(m4605_adj, str):
print(m4605_adj)
assert m4605_adj["conv"]
m4605 = m4605_adj["result"]
#print(m4605)
lifestage = self.qs111.loc[self.qs111.GEOGRAPHY_CODE == area].copy()
# unmap indices
# TODO might be quicker to unmap the entire table upfront?
Utils.unmap(lifestage.C_HHLSHUK11, self.lifestage_index)
mq111 = Utils.unlistify(lifestage,
["C_HHLSHUK11"],
[len(self.lifestage_index)],
"OBS_VALUE")
#mq111 = lifestage.OBS_VALUE
#print(mq111)
age_livarr = self.lc1102.loc[self.lc1102.GEOGRAPHY_CODE == area].copy()
# unmap indices
# TODO might be quicker to unmap the entire table upfront?
Utils.unmap(age_livarr.C_AGE, self.age_index)
Utils.unmap(age_livarr.C_LARPUK11, self.livarr_index)
# # TODO resolve age band incompatibility issues
# m1102 = Utils.unlistify(age_livarr,
# ["C_AGE", "C_LARPUK11"],
# [len(self.age_index) + 1, len(self.livarr_index)],
# "OBS_VALUE")
# m1102 = age_livarr.groupby("C_LARPUK11")["OBS_VALUE"].sum().as_matrix()
m1102 = Utils.unlistify(age_livarr,
["C_LARPUK11"],
[len(self.livarr_index)],
"OBS_VALUE")
#print(m1102)
pop = humanleague.qis([np.array([0, 1]), np.array([2, 1]), np.array([3]), np.array([4])], [m4605, m4201, mq111, m1102])
if isinstance(pop, str):
print(pop)
assert pop["conv"]
table = humanleague.flatten(pop["result"])
chunk = pd.DataFrame(columns=self.hrps.columns.values)
chunk.Area = np.repeat(area, len(table[0]))
chunk.LC4605_C_NSSEC = Utils.remap(table[0], self.nssec_index)
chunk.LC4605_C_TENHUK11 = Utils.remap(table[1], self.tenure_index)
chunk.LC4201_C_ETHPUK11 = Utils.remap(table[2], self.eth_index)
chunk.QS111_C_HHLSHUK11 = Utils.remap(table[3], self.lifestage_index)
chunk.LC1102_C_LARPUK11 = Utils.remap(table[4], self.livarr_index)
#print(chunk.head())
self.hrps = self.hrps.append(chunk)
def __get_census_data(self):
"""
Retrieves census tables for the specified geography
checks for locally cached data or calls nomisweb API
"""
# convert input string to enum
resolution = self.api.GeoCodeLookup[self.resolution]
if self.region in self.api.GeoCodeLookup.keys():
region_codes = self.api.GeoCodeLookup[self.region]
else:
region_codes = self.api.get_lad_codes(self.region)
if not region_codes:
raise ValueError("no regions match the input: \"" + self.region + "\"")
area_codes = self.api.get_geo_codes(region_codes, resolution)
# assignment does shallow copy, need to use .copy() to avoid this getting query_params fields
common_params = {"MEASURES": "20100",
"date": "latest",
"geography": area_codes}
# tables:
# LC4605EW Tenure by NS-SeC - Household Reference Persons
query_params = common_params.copy()
query_params["C_TENHUK11"] = "2,3,5,6"
query_params["C_NSSEC"] = "1...9"
query_params["select"] = "GEOGRAPHY_CODE,C_NSSEC,C_TENHUK11,OBS_VALUE"
self.lc4605 = self.api.get_data("LC4605EW", query_params)
#self.lc4605.to_csv("LC4605.csv")
# LC4201EW Tenure by ethnic group by age - Household Reference Persons
# "C_AGE": {
# "0": "All categories: Age",
# "1": "Age 24 and under",
# "2": "Age 25 to 49",
# "3": "Age 50 to 64",
# "4": "Age 65 and over"
# },
query_params = common_params.copy()
query_params["C_TENHUK11"] = "2,3,5,6"
query_params["C_AGE"] = "1...4"
query_params["C_ETHPUK11"] = "2...8"
query_params["select"] = "GEOGRAPHY_CODE,C_AGE,C_ETHPUK11,C_TENHUK11,OBS_VALUE"
self.lc4201 = self.api.get_data("LC4201EW", query_params)
# QS111EW - Household lifestage
# Stages correspond to:
# LIFESTAGE LC4201 LC1102
# <35 1,2* 1,2
# 35-54 2*,3* 3,4*
# 55-64 3* 4*
# >=65 4 5
# * overlaps two categories
query_params = common_params.copy()
query_params["C_HHLSHUK11"] = "2,3,4,6,7,8,10,11,12,14,15,16"
query_params["RURAL_URBAN"] = "0"
query_params["select"] = "GEOGRAPHY_CODE,C_HHLSHUK11,OBS_VALUE"
self.qs111 = self.api.get_data("QS111EW", query_params)
# LC1102EW - Living arrangements by age - Household Reference Persons
# NOTE DIFFERENT AGE CATEGORIES
# "0": "All categories: Age",
# "1": "Age 24 and under",
# "2": "Age 25 to 34",
# "3": "Age 35 to 49",
# "4": "Age 50 to 64",
# "5": "Age 65 and over"
# },
query_params = common_params.copy()
query_params["C_AGE"] = "1...5"
query_params["C_LARPUK11"] = "2,3,5,6,7,8,9"
query_params["select"] = "GEOGRAPHY_CODE,C_AGE,C_LARPUK11,OBS_VALUE"
self.lc1102 = self.api.get_data("LC1102EW", query_params)
# LC6115 HRP: composition by NSSEC?
| [
"pandas.DataFrame",
"numpy.sum",
"humanleague.flatten",
"numpy.ones",
"household_microsynth.utils.remap",
"ukcensusapi.Nomisweb.Nomisweb",
"numpy.array",
"household_microsynth.utils.unmap"
] | [((540, 563), 'ukcensusapi.Nomisweb.Nomisweb', 'Api.Nomisweb', (['cache_dir'], {}), '(cache_dir)\n', (552, 563), True, 'import ukcensusapi.Nomisweb as Api\n'), ((1132, 1164), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'categories'}), '(columns=categories)\n', (1144, 1164), True, 'import pandas as pd\n'), ((2048, 2076), 'numpy.ones', 'np.ones', (['[9, 4, 4, 7, 12, 7]'], {}), '([9, 4, 4, 7, 12, 7])\n', (2055, 2076), True, 'import numpy as np\n'), ((2459, 2510), 'household_microsynth.utils.unmap', 'Utils.unmap', (['nssec_tenure.C_NSSEC', 'self.nssec_index'], {}), '(nssec_tenure.C_NSSEC, self.nssec_index)\n', (2470, 2510), True, 'import household_microsynth.utils as Utils\n'), ((2515, 2570), 'household_microsynth.utils.unmap', 'Utils.unmap', (['nssec_tenure.C_TENHUK11', 'self.tenure_index'], {}), '(nssec_tenure.C_TENHUK11, self.tenure_index)\n', (2526, 2570), True, 'import household_microsynth.utils as Utils\n'), ((3028, 3082), 'household_microsynth.utils.unmap', 'Utils.unmap', (['age_eth_tenure.C_ETHPUK11', 'self.eth_index'], {}), '(age_eth_tenure.C_ETHPUK11, self.eth_index)\n', (3039, 3082), True, 'import household_microsynth.utils as Utils\n'), ((3087, 3144), 'household_microsynth.utils.unmap', 'Utils.unmap', (['age_eth_tenure.C_TENHUK11', 'self.tenure_index'], {}), '(age_eth_tenure.C_TENHUK11, self.tenure_index)\n', (3098, 3144), True, 'import household_microsynth.utils as Utils\n'), ((3425, 3446), 'numpy.sum', 'np.sum', (['m4201'], {'axis': '(0)'}), '(m4201, axis=0)\n', (3431, 3446), True, 'import numpy as np\n'), ((3588, 3601), 'numpy.sum', 'np.sum', (['m4605'], {}), '(m4605)\n', (3594, 3601), True, 'import numpy as np\n'), ((3618, 3631), 'numpy.sum', 'np.sum', (['m4201'], {}), '(m4201)\n', (3624, 3631), True, 'import numpy as np\n'), ((4320, 4376), 'household_microsynth.utils.unmap', 'Utils.unmap', (['lifestage.C_HHLSHUK11', 'self.lifestage_index'], {}), '(lifestage.C_HHLSHUK11, self.lifestage_index)\n', (4331, 4376), True, 'import household_microsynth.utils as Utils\n'), ((4776, 4821), 'household_microsynth.utils.unmap', 'Utils.unmap', (['age_livarr.C_AGE', 'self.age_index'], {}), '(age_livarr.C_AGE, self.age_index)\n', (4787, 4821), True, 'import household_microsynth.utils as Utils\n'), ((4826, 4879), 'household_microsynth.utils.unmap', 'Utils.unmap', (['age_livarr.C_LARPUK11', 'self.livarr_index'], {}), '(age_livarr.C_LARPUK11, self.livarr_index)\n', (4837, 4879), True, 'import household_microsynth.utils as Utils\n'), ((5637, 5671), 'humanleague.flatten', 'humanleague.flatten', (["pop['result']"], {}), "(pop['result'])\n", (5656, 5671), False, 'import humanleague\n'), ((5685, 5731), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'self.hrps.columns.values'}), '(columns=self.hrps.columns.values)\n', (5697, 5731), True, 'import pandas as pd\n'), ((5807, 5846), 'household_microsynth.utils.remap', 'Utils.remap', (['table[0]', 'self.nssec_index'], {}), '(table[0], self.nssec_index)\n', (5818, 5846), True, 'import household_microsynth.utils as Utils\n'), ((5877, 5917), 'household_microsynth.utils.remap', 'Utils.remap', (['table[1]', 'self.tenure_index'], {}), '(table[1], self.tenure_index)\n', (5888, 5917), True, 'import household_microsynth.utils as Utils\n'), ((5948, 5985), 'household_microsynth.utils.remap', 'Utils.remap', (['table[2]', 'self.eth_index'], {}), '(table[2], self.eth_index)\n', (5959, 5985), True, 'import household_microsynth.utils as Utils\n'), ((6016, 6059), 'household_microsynth.utils.remap', 'Utils.remap', (['table[3]', 'self.lifestage_index'], {}), '(table[3], self.lifestage_index)\n', (6027, 6059), True, 'import household_microsynth.utils as Utils\n'), ((6090, 6130), 'household_microsynth.utils.remap', 'Utils.remap', (['table[4]', 'self.livarr_index'], {}), '(table[4], self.livarr_index)\n', (6101, 6130), True, 'import household_microsynth.utils as Utils\n'), ((3749, 3770), 'numpy.sum', 'np.sum', (['m4201'], {'axis': '(0)'}), '(m4201, axis=0)\n', (3755, 3770), True, 'import numpy as np\n'), ((5458, 5474), 'numpy.array', 'np.array', (['[0, 1]'], {}), '([0, 1])\n', (5466, 5474), True, 'import numpy as np\n'), ((5476, 5492), 'numpy.array', 'np.array', (['[2, 1]'], {}), '([2, 1])\n', (5484, 5492), True, 'import numpy as np\n'), ((5494, 5507), 'numpy.array', 'np.array', (['[3]'], {}), '([3])\n', (5502, 5507), True, 'import numpy as np\n'), ((5509, 5522), 'numpy.array', 'np.array', (['[4]'], {}), '([4])\n', (5517, 5522), True, 'import numpy as np\n'), ((3950, 3963), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (3958, 3963), True, 'import numpy as np\n'), ((3965, 3978), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (3973, 3978), True, 'import numpy as np\n'), ((3819, 3840), 'numpy.sum', 'np.sum', (['m4605'], {'axis': '(1)'}), '(m4605, axis=1)\n', (3825, 3840), True, 'import numpy as np\n')] |
#! /usr/bin/env python2
from __future__ import print_function, division
import numpy as np, cv2, sys, os, math, random, time, torch, torch.nn as nn, collections, tensorboardX, gym, termcolor, datetime, colored_traceback.always
sys.dont_write_bytecode = True
from agent import Experience
#==============================================================================
# BASIC SESSION
class Session(object):
def __init__(self, experience, writer, agent, env, task, run_tag, params, live):
self.update = 0
self.episodes = 0
self.experience = experience
self.writer = writer
self.agent = agent
self.env = env
self.task = task
self.run_tag = run_tag
self.params = params
self.live = live
#------------------------------------------------------------------------------
def episode(self, train=True):
metrics = {"episode/length": 0, "episode/reward_env": 0, "episode/reward_task": 0}
metrics_reset_agent = self.agent.reset()
metrics_reset_task = self.task .reset()
self._metrics("reset_agent", metrics_reset_agent, metrics)
self._metrics("reset_task", metrics_reset_task, metrics)
done = False
obs = self.env.reset()
while not done:
act = self.agent.act(self.task.obs(obs))
nobs, rew, done, info = self.env.step(self._scale(act))
step = self.task.online(Experience(obs, act, rew, nobs, done))
if self.live: self.experience.append(step)
metrics_train = self.agent.train(self.experience) if train else {}
metrics_task = self.task .train(self.experience) if train else {}
self._metrics("actions", {str(k):v for k,v in enumerate(act)}, metrics)
self._metrics("observations", {str(k):v for k,v in enumerate(obs)}, metrics)
self._metrics("train", metrics_train, metrics)
self._metrics("task", metrics_task, metrics)
metrics["episode/reward_env" ] += rew
metrics["episode/reward_task"] += step.rew
metrics["episode/length"] += 1
metrics["episode/buffer"] = len(self.experience)
obs = nobs
done = step.done
return metrics
#------------------------------------------------------------------------------
def run(self):
while self.update < self.params.UPDATES:
metrics = self.episode()
self.update += metrics['episode/length']
self.episodes += 1
self.writer.add_scalar("episode/number", self.episodes, self.update)
self.report(metrics)
raw_experience = [self.task.decode(step) for step in self.experience]
return raw_experience
#------------------------------------------------------------------------------
def report(self, metrics, step=None):
if step is None: step = self.update
for k,v in metrics.items():
self.writer.add_scalar(str(k), np.mean(v), step)
if sum(np.array(v).shape) > 1: # if we have more than just a scalar
self.writer.add_scalar("{}_std".format(k), np.std(v), step)
#------------------------------------------------------------------------------
def _scale(self, act): return ((np.clip(act.astype(np.float32),-1,1)/2.0+0.5)*(self.env.action_space.high-self.env.action_space.low)+self.env.action_space.low).astype(np.float32)
#------------------------------------------------------------------------------
def _metrics(self, prefix, new, metrics):
for k,v in new.items():
if isinstance(v,torch.Tensor): v = v.detach().cpu().numpy()
tag = "{}/{}".format(prefix, k)
if tag not in metrics: metrics[tag] = []
metrics[tag].append(v)
#----------------------------------------------------------------------------
def ckpt(self):
if not os.path.exists(".ckpt"): os.mkdir(".ckpt")
agent_state = self.agent.state_dict()
task_state = self.task .state_dict()
torch.save(agent_state, ".ckpt/{}_{}_step{:07d}_agent.ckpt".format(self.params.COMMENT, self.params.DATA_IN.replace("/","_"), self.update))
torch.save( task_state, ".ckpt/{}_{}_step{:07d}_task.ckpt" .format(self.params.COMMENT, self.params.DATA_IN.replace("/","_"), self.update))
#----------------------------------------------------------------------------
def load_ckpt(self):
self.agent.load_state_dict(torch.load(self.params.CKPT_AGENT))
self.task .load_state_dict(torch.load(self.params.CKPT_TASK))
#==============================================================================
# EVALUATION SESSION
class EvaluationSession(Session):
def __init__(self, experience, writer, agent, env, task, run_tag, params, live):
super(EvaluationSession, self).__init__(experience, writer, agent, env, task, run_tag, params, live)
self.load_ckpt()
self.episodes = 0
#----------------------------------------------------------------------------
def run(self):
while self.episodes < self.params.EVAL_EPISODES:
metrics = self.episode(train=False)
self.episodes += 1
self.report(metrics, step=self.episodes)
return self.experience # because run assumes this
#==============================================================================
# OFFLINE SESSION
class OfflineSession(Session):
def run(self):
metrics = {}
while self.update < self.params.UPDATES:
metrics_train = self.agent.train(self.experience)
metrics_task = self.task .train(self.experience)
self._metrics("train", metrics_train, metrics)
self._metrics("task", metrics_task, metrics)
if self.update % 1000 == 0: self.report(metrics); metrics = {}
if self.update % 100000 == 0: self.ckpt()
self.update += 1
self.report(metrics)
self.ckpt()
return self.experience # because run assumes this
| [
"os.mkdir",
"numpy.std",
"torch.load",
"os.path.exists",
"agent.Experience",
"numpy.mean",
"numpy.array"
] | [((3726, 3749), 'os.path.exists', 'os.path.exists', (['""".ckpt"""'], {}), "('.ckpt')\n", (3740, 3749), False, 'import numpy as np, cv2, sys, os, math, random, time, torch, torch.nn as nn, collections, tensorboardX, gym, termcolor, datetime, colored_traceback.always\n'), ((3751, 3768), 'os.mkdir', 'os.mkdir', (['""".ckpt"""'], {}), "('.ckpt')\n", (3759, 3768), False, 'import numpy as np, cv2, sys, os, math, random, time, torch, torch.nn as nn, collections, tensorboardX, gym, termcolor, datetime, colored_traceback.always\n'), ((4277, 4311), 'torch.load', 'torch.load', (['self.params.CKPT_AGENT'], {}), '(self.params.CKPT_AGENT)\n', (4287, 4311), False, 'import numpy as np, cv2, sys, os, math, random, time, torch, torch.nn as nn, collections, tensorboardX, gym, termcolor, datetime, colored_traceback.always\n'), ((4344, 4377), 'torch.load', 'torch.load', (['self.params.CKPT_TASK'], {}), '(self.params.CKPT_TASK)\n', (4354, 4377), False, 'import numpy as np, cv2, sys, os, math, random, time, torch, torch.nn as nn, collections, tensorboardX, gym, termcolor, datetime, colored_traceback.always\n'), ((1395, 1432), 'agent.Experience', 'Experience', (['obs', 'act', 'rew', 'nobs', 'done'], {}), '(obs, act, rew, nobs, done)\n', (1405, 1432), False, 'from agent import Experience\n'), ((2854, 2864), 'numpy.mean', 'np.mean', (['v'], {}), '(v)\n', (2861, 2864), True, 'import numpy as np, cv2, sys, os, math, random, time, torch, torch.nn as nn, collections, tensorboardX, gym, termcolor, datetime, colored_traceback.always\n'), ((2997, 3006), 'numpy.std', 'np.std', (['v'], {}), '(v)\n', (3003, 3006), True, 'import numpy as np, cv2, sys, os, math, random, time, torch, torch.nn as nn, collections, tensorboardX, gym, termcolor, datetime, colored_traceback.always\n'), ((2885, 2896), 'numpy.array', 'np.array', (['v'], {}), '(v)\n', (2893, 2896), True, 'import numpy as np, cv2, sys, os, math, random, time, torch, torch.nn as nn, collections, tensorboardX, gym, termcolor, datetime, colored_traceback.always\n')] |
"""
This module implements the search-based refactoring with various search strategy
using pymoo framework.
Gene, RefactoringOperation: One refactoring with params
Individual: A list of RefactoringOperation
SudoRandomInitialization: Population, list of Individual
## References
[1] https://pymoo.org/customization/custom.html
[2] https://pymoo.org/misc/reference_directions.html
"""
__version__ = '0.1.0'
__author__ = '<NAME>, <NAME>'
import random
from typing import List
import numpy as np
from pymoo.algorithms.moo.nsga2 import NSGA2
from pymoo.algorithms.moo.nsga3 import NSGA3
from pymoo.algorithms.soo.nonconvex.ga import GA
from pymoo.factory import get_reference_directions, get_crossover
from pymoo.core.crossover import Crossover
from pymoo.core.duplicate import ElementwiseDuplicateElimination
from pymoo.core.mutation import Mutation
from pymoo.core.problem import ElementwiseProblem
from pymoo.core.sampling import Sampling
from pymoo.optimize import minimize
from sbse import config
from sbse.config import logger
from sbse.initialize import RandomInitialization
from sbse.objectives import Objectives
from metrics.testability_prediction import main as testability_main
from metrics.modularity import main as modularity_main
from utilization.directory_utils import update_understand_database, git_restore
# TODO: Parallelism, Double Check Befor Run on Server
class Gene:
"""
The base class for the Gene in genetic algorithms
"""
def __init__(self, **kwargs):
self.name = kwargs.get('name')
self.params = kwargs.get('params')
self.main = kwargs.get('main')
def __str__(self):
return self.name
class RefactoringOperation(Gene):
"""
The class define a data structure (dictionary) to hold a refactoring operation
"""
def __init__(self, **kwargs):
"""
Each refactoring operation hold as a dictionary contains the required parameters.
Example:
make_field_static refactoring is marshaled as the following dict:
params = {
'refactoring_name': 'make_field_static'
'api': 'main_function'
'source_class': 'name_of_source_class'
'field_name': 'name_of_the_field_to_be_static'
}
"""
super(RefactoringOperation, self).__init__(**kwargs)
def do_refactoring(self):
logger.info(f"Running {self.name}")
logger.info(f"Parameters {self.params}")
try:
self.main(**self.params)
except Exception as e:
logger.error(f"Error in executing refactoring:\n {e}")
@classmethod
def generate_randomly(cls):
initializer = RandomInitialization(udb_path=config.UDB_PATH)
item = initializer.select_random()
return cls(
name=item[2],
params=item[1],
main=item[0]
)
def __str__(self):
return f"\n{self.name}\n{self.params}\n"
def __repr__(self):
return self.__str__()
class Individual(List):
"""
The class define a data structure (list) to hold an individual during the search process.
Each individual (also called, chromosome or solution in the context of genetic programming)
is an array of refactoring operations
where the order of their execution is accorded by their positions in the array.
"""
def __init__(self):
super(Individual, self).__init__()
self.refactoring_operations = []
def __iter__(self):
for ref in self.refactoring_operations:
yield ref
def __len__(self):
return len(self.refactoring_operations)
def __getitem__(self, item):
return self.refactoring_operations[item]
def __delitem__(self, key):
del self.refactoring_operations[key]
def __setitem__(self, key, value):
self.refactoring_operations[key] = value
def __str__(self):
return str(self.refactoring_operations)
def insert(self, __index: int, __object: RefactoringOperation) -> None:
self.refactoring_operations.insert(__index, __object)
def append(self, __object: RefactoringOperation) -> None:
self.insert(len(self.refactoring_operations), __object)
class ProblemSingleObjective(ElementwiseProblem):
"""
The CodART single-objective optimization work with only one objective, testability:
"""
def __init__(self, n_refactorings_lowerbound=50, n_refactorings_upperbound=75):
super(ProblemSingleObjective, self).__init__(n_var=1,
n_obj=1,
n_constr=0)
self.n_refactorings_lowerbound = n_refactorings_lowerbound
self.n_refactorings_upperbound = n_refactorings_upperbound
def _evaluate(self,
x, #
out,
*args,
**kwargs):
"""
This method iterate over an Individual, execute the refactoring operation sequentially,
and compute quality attributes for the refactored version of the program, as objectives of the search
params:
x[0] (Individual): x[0] is an instance of Individual (i.e., a list of refactoring operations)
"""
# Stage 0: Git restore
logger.debug("Executing git restore.")
git_restore(config.PROJECT_PATH)
update_understand_database(config.UDB_PATH)
# Stage 1: Execute all refactoring operations in the sequence x
logger.debug(f"Reached Individual with Size {len(x[0])}")
for refactoring_operation in x[0]:
refactoring_operation.do_refactoring()
# Update Understand DB
update_understand_database(config.UDB_PATH)
# Stage 2: Computing quality attributes
score = testability_main(config.UDB_PATH)
logger.info(f"Testability Score: {score}")
# Stage 3: Marshal objectives into vector
out["F"] = np.array([-1 * score], dtype=float)
class ProblemMultiObjective(ElementwiseProblem):
"""
The CodART multi-objective optimization work with three objective:
Objective 1: Mean value of QMOOD metrics
Objective 2: Testability
Objective 3: Modularity
"""
def __init__(self, n_refactorings_lowerbound=50, n_refactorings_upperbound=75):
super(ProblemMultiObjective, self).__init__(n_var=1,
n_obj=3,
n_constr=0)
self.n_refactorings_lowerbound = n_refactorings_lowerbound
self.n_refactorings_upperbound = n_refactorings_upperbound
def _evaluate(self,
x, #
out,
*args,
**kwargs):
"""
This method iterate over an Individual, execute the refactoring operation sequentially,
and compute quality attributes for the refactored version of the program, as objectives of the search
params:
x (Individual): x is an instance of Individual (i.e., a list of refactoring operations)
"""
# Stage 0: Git restore
logger.debug("Executing git restore.")
git_restore(config.PROJECT_PATH)
update_understand_database(config.UDB_PATH)
# Stage 1: Execute all refactoring operations in the sequence x
logger.debug(f"Reached Individual with Size {len(x[0])}")
for refactoring_operation in x[0]:
refactoring_operation.do_refactoring()
# Update Understand DB
update_understand_database(config.UDB_PATH)
# Stage 2: Computing quality attributes
obj = Objectives(udb_path=config.UDB_PATH)
o1 = obj.average
del obj
o2 = testability_main(config.UDB_PATH)
o3 = modularity_main(config.UDB_PATH)
logger.info(f"QMOOD AVG Score: {o1}")
logger.info(f"Testability Score: {o2}")
logger.info(f"Modularity Score: {o3}")
# Stage 3: Marshal objectives into vector
out["F"] = np.array([-1 * o1, -1 * o2, -1 * o3], dtype=float)
class ProblemManyObjective(ElementwiseProblem):
"""
The CodART many-objective optimization work with eight objective:
Objective 1 to 6: QMOOD metrics
Objective 7: Testability
Objective 8: Modularity
"""
def __init__(self, n_refactorings_lowerbound=50, n_refactorings_upperbound=75):
super(ProblemManyObjective, self).__init__(n_var=1,
n_obj=8,
n_constr=0)
self.n_refactorings_lowerbound = n_refactorings_lowerbound
self.n_refactorings_upperbound = n_refactorings_upperbound
def _evaluate(self,
x, #
out,
*args,
**kwargs):
"""
This method iterate over an Individual, execute the refactoring operation sequentially,
and compute quality attributes for the refactored version of the program, as objectives of the search
params:
x (Individual): x is an instance of Individual (i.e., a list of refactoring operations)
"""
# Git restore`
logger.debug("Executing git restore.")
git_restore(config.PROJECT_PATH)
update_understand_database(config.UDB_PATH)
# Stage 1: Execute all refactoring operations in the sequence x
logger.debug(f"Reached Individual with Size {len(x[0])}")
for refactoring_operation in x[0]:
refactoring_operation.do_refactoring()
# Update Understand DB
update_understand_database(config.UDB_PATH)
# Stage 2: Computing quality attributes
qmood = Objectives(udb_path=config.UDB_PATH)
o1 = qmood.reusability
o2 = qmood.understandability
o3 = qmood.flexibility
o4 = qmood.functionality
o5 = qmood.effectiveness
o6 = qmood.extendability
del qmood
o7 = testability_main(config.UDB_PATH)
o8 = modularity_main(config.UDB_PATH)
logger.info(f"Reusability Score: {o1}")
logger.info(f"Understandability Score: {o2}")
logger.info(f"Flexibility Score: {o3}")
logger.info(f"Functionality Score: {o4}")
logger.info(f"Effectiveness Score: {o5}")
logger.info(f"Extendability Score: {o6}")
logger.info(f"Testability Score: {o7}")
logger.info(f"Modularity Score: {o8}")
# Stage 3: Marshal objectives into vector
out["F"] = np.array([-1 * o1, -1 * o2, -1 * o3, -1 * o4, -1 * o5, -1 * o6, -1 * o7, -1 * o8, ], dtype=float)
class SudoRandomInitialization(Sampling):
"""
This class create the initial population, X, consists of n_samples, pop_size.
For each refactoring operation, a set of controlling parameters (e.g., actors and roles) is picked based on
existing code smells in the program to be refactored.
The selected refactoring operations are randomly arranged in each individual.
Assigning randomly a sequence of refactorings to certain code fragments generates the initial population
"""
def _do(self, problem, n_samples, **kwargs):
"""
Since the problem having only one variable, we return a matrix with the shape (n,1)
Params:
n_samples (int): the same population size, pop_size
"""
X = np.full((n_samples, 1), None, dtype=Individual)
population = RandomInitialization(
udb_path=config.UDB_PATH,
population_size=n_samples,
lower_band=problem.n_refactorings_lowerbound,
upper_band=problem.n_refactorings_upperbound
).generate_population()
for i in range(n_samples):
individual_object = [] # list of refactoring operations
for ref in population[i]:
individual_object.append(
RefactoringOperation(
name=ref[2],
params=ref[1],
main=ref[0]
)
)
X[i, 0] = individual_object
return X
class AdaptiveSinglePointCrossover(Crossover):
"""
This class implements solution variation, the adaptive one-point or single-point crossover operator.
The crossover operator combines parents to create offsprings.
It starts by selecting and splitting at random two parent solutions or individuals.
Then, this operator creates two child solutions by putting, for the first child,
the first part of the first parent with the second part of the second parent,
and vice versa for the second child.
Note 1: In the pymoo framework, the crossover operator retrieves the input already with predefined matings.
The default parent selection algorithm is TournamentSelection.
Note 2: It is better to create children that are close to their parents to have a more efficient search process,
a so-called __adaptive crossover__, specifically in many-objective optimization.
Therefore, the cutting point of the one-point crossover operator are controlled by restricting its position
to be either belonging to the first tier of the refactoring sequence or belonging to the last tier.
Params:
prob (float): crossover probability
"""
def __init__(self, prob=0.9):
# Define the crossover: number of parents, number of offsprings, and cross-over probability
super().__init__(n_parents=2, n_offsprings=2, prob=prob)
def _do(self, problem, X, **kwargs):
"""
Todo: Implementing adaptive single-point-cross-over
"""
print("Running crossover")
# The input of has the following shape (n_parents, n_matings, n_var)
# print(X.shape)
# print(X)
# print('='*50)
_, n_matings, n_var = X.shape
# The output will be with the shape (n_offsprings, n_matings, n_var)
# Because there the number of parents and offsprings are equal it keeps the shape of X
Y = np.full_like(X, None, dtype=np.object)
# for each mating provided
for k in range(n_matings):
# get the first and the second parent
a, b = X[0, k, 0], X[1, k, 0]
# prepare the offsprings
off_a = ["_"] * problem.n_characters
off_b = ["_"] * problem.n_characters
for i in range(problem.n_characters):
if np.random.random() < 0.5:
off_a[i] = a[i]
off_b[i] = b[i]
else:
off_a[i] = b[i]
off_b[i] = a[i]
# join the character list and set the output
Y[0, k, 0], Y[1, k, 0] = "".join(off_a), "".join(off_b)
return Y
class BitStringMutation(Mutation):
"""
This class implements solution variation, a bit-string mutation operator.
The bit-string mutation operator that picks probabilistically one or more refactoring operations from its
or their associated sequence and replaces them by other ones from the initial list of possible refactorings.
Each chromosome dimension would be changed according to the mutation probability.
For example, for a mutation probability of 0.2, for each dimension, we generate randomly a number x between 0 and 1,
if x<0.2 we change the refactoring operation in that dimension, otherwise no change is took into account.
"""
def __init__(self, prob=0.2):
super().__init__()
self.mutation_probability = prob
def _do(self, problem, X, **kwargs):
for i, individual in enumerate(X):
r = np.random.random()
# with a probability of `mutation_probability` replace the refactoring operation with new one
if r < self.mutation_probability:
# j is a random index in individual
j = random.randint(0, len(individual[0]) - 1)
random_refactoring_operation = RefactoringOperation.generate_randomly()
X[i][0][j] = random_refactoring_operation
return X
class RefactoringSequenceDuplicateElimination(ElementwiseDuplicateElimination):
"""
This class implement is_equal method which should return True if two instances of Individual are equal.
Otherwise it return False.
The duplicate instances are removed from population at each generation.
Only one instance is held to speed up the search algorithm
"""
def is_equal(self, a, b):
"""
# Calling the equal method of individual class
"""
return a.X[0] == b.X[0]
def main():
# Define search algorithms
algorithms = list()
# 1: GA
algorithm = GA(
pop_size=config.POPULATION_SIZE,
sampling=SudoRandomInitialization(),
# crossover=AdaptiveSinglePointCrossover(prob=0.8),
crossover=get_crossover("real_k_point", n_points=2),
mutation=BitStringMutation(),
eliminate_duplicates=RefactoringSequenceDuplicateElimination()
)
algorithms.append(algorithm)
# 2: NSGA II
algorithm = NSGA2(pop_size=config.POPULATION_SIZE,
sampling=SudoRandomInitialization(),
# crossover=AdaptiveSinglePointCrossover(prob=0.8),
crossover=get_crossover("real_k_point", n_points=2),
mutation=BitStringMutation(),
eliminate_duplicates=RefactoringSequenceDuplicateElimination()
)
algorithms.append(algorithm)
# 3: NSGA III
# Todo: Ask for best practices in determining ref_dirs
ref_dirs = get_reference_directions("energy", 8, 90, seed=1)
algorithm = NSGA3(ref_dirs=ref_dirs,
pop_size=config.POPULATION_SIZE,
sampling=SudoRandomInitialization(),
# crossover=AdaptiveSinglePointCrossover(prob=0.8),
crossover=get_crossover("real_k_point", n_points=2),
mutation=BitStringMutation(),
eliminate_duplicates=RefactoringSequenceDuplicateElimination()
)
algorithms.append(algorithm)
# Define problems
problems = list()
problems.append(
ProblemSingleObjective(n_refactorings_lowerbound=config.LOWER_BAND, n_refactorings_upperbound=config.UPPER_BAND)
)
problems.append(
ProblemMultiObjective(n_refactorings_lowerbound=config.LOWER_BAND, n_refactorings_upperbound=config.UPPER_BAND)
)
problems.append(
ProblemManyObjective(n_refactorings_lowerbound=config.LOWER_BAND, n_refactorings_upperbound=config.UPPER_BAND)
)
# Do optimization for various problems with various algorithms
res = minimize(problem=problems[2],
algorithm=algorithms[2],
termination=('n_gen', config.MAX_ITERATIONS),
seed=1,
verbose=True)
logger.info("** FINISHED **")
logger.info("Best Individual:")
logger.info(res.X)
logger.info("Objective Values:")
logger.info(res.F)
logger.info("==================")
logger.info("Other Solutions:")
for ind in res.opt:
logger.info(ind.X)
logger.info(ind.F)
logger.info("==================")
logger.info(f"Start Time: {res.start_time}")
logger.info(f"End Time: {res.end_time}")
logger.info(f"Execution Time in Seconds: {res.exec_time}")
if __name__ == '__main__':
config.log_project_info()
main()
| [
"numpy.full",
"sbse.config.logger.info",
"pymoo.factory.get_reference_directions",
"numpy.full_like",
"pymoo.optimize.minimize",
"pymoo.factory.get_crossover",
"metrics.testability_prediction.main",
"sbse.config.logger.debug",
"utilization.directory_utils.git_restore",
"numpy.random.random",
"nu... | [((17789, 17838), 'pymoo.factory.get_reference_directions', 'get_reference_directions', (['"""energy"""', '(8)', '(90)'], {'seed': '(1)'}), "('energy', 8, 90, seed=1)\n", (17813, 17838), False, 'from pymoo.factory import get_reference_directions, get_crossover\n'), ((18901, 19027), 'pymoo.optimize.minimize', 'minimize', ([], {'problem': 'problems[2]', 'algorithm': 'algorithms[2]', 'termination': "('n_gen', config.MAX_ITERATIONS)", 'seed': '(1)', 'verbose': '(True)'}), "(problem=problems[2], algorithm=algorithms[2], termination=('n_gen',\n config.MAX_ITERATIONS), seed=1, verbose=True)\n", (18909, 19027), False, 'from pymoo.optimize import minimize\n'), ((19104, 19133), 'sbse.config.logger.info', 'logger.info', (['"""** FINISHED **"""'], {}), "('** FINISHED **')\n", (19115, 19133), False, 'from sbse.config import logger\n'), ((19139, 19170), 'sbse.config.logger.info', 'logger.info', (['"""Best Individual:"""'], {}), "('Best Individual:')\n", (19150, 19170), False, 'from sbse.config import logger\n'), ((19175, 19193), 'sbse.config.logger.info', 'logger.info', (['res.X'], {}), '(res.X)\n', (19186, 19193), False, 'from sbse.config import logger\n'), ((19198, 19230), 'sbse.config.logger.info', 'logger.info', (['"""Objective Values:"""'], {}), "('Objective Values:')\n", (19209, 19230), False, 'from sbse.config import logger\n'), ((19235, 19253), 'sbse.config.logger.info', 'logger.info', (['res.F'], {}), '(res.F)\n', (19246, 19253), False, 'from sbse.config import logger\n'), ((19259, 19292), 'sbse.config.logger.info', 'logger.info', (['"""=================="""'], {}), "('==================')\n", (19270, 19292), False, 'from sbse.config import logger\n'), ((19297, 19328), 'sbse.config.logger.info', 'logger.info', (['"""Other Solutions:"""'], {}), "('Other Solutions:')\n", (19308, 19328), False, 'from sbse.config import logger\n'), ((19454, 19498), 'sbse.config.logger.info', 'logger.info', (['f"""Start Time: {res.start_time}"""'], {}), "(f'Start Time: {res.start_time}')\n", (19465, 19498), False, 'from sbse.config import logger\n'), ((19503, 19543), 'sbse.config.logger.info', 'logger.info', (['f"""End Time: {res.end_time}"""'], {}), "(f'End Time: {res.end_time}')\n", (19514, 19543), False, 'from sbse.config import logger\n'), ((19548, 19606), 'sbse.config.logger.info', 'logger.info', (['f"""Execution Time in Seconds: {res.exec_time}"""'], {}), "(f'Execution Time in Seconds: {res.exec_time}')\n", (19559, 19606), False, 'from sbse.config import logger\n'), ((19640, 19665), 'sbse.config.log_project_info', 'config.log_project_info', ([], {}), '()\n', (19663, 19665), False, 'from sbse import config\n'), ((2401, 2436), 'sbse.config.logger.info', 'logger.info', (['f"""Running {self.name}"""'], {}), "(f'Running {self.name}')\n", (2412, 2436), False, 'from sbse.config import logger\n'), ((2445, 2485), 'sbse.config.logger.info', 'logger.info', (['f"""Parameters {self.params}"""'], {}), "(f'Parameters {self.params}')\n", (2456, 2485), False, 'from sbse.config import logger\n'), ((2706, 2752), 'sbse.initialize.RandomInitialization', 'RandomInitialization', ([], {'udb_path': 'config.UDB_PATH'}), '(udb_path=config.UDB_PATH)\n', (2726, 2752), False, 'from sbse.initialize import RandomInitialization\n'), ((5342, 5380), 'sbse.config.logger.debug', 'logger.debug', (['"""Executing git restore."""'], {}), "('Executing git restore.')\n", (5354, 5380), False, 'from sbse.config import logger\n'), ((5389, 5421), 'utilization.directory_utils.git_restore', 'git_restore', (['config.PROJECT_PATH'], {}), '(config.PROJECT_PATH)\n', (5400, 5421), False, 'from utilization.directory_utils import update_understand_database, git_restore\n'), ((5430, 5473), 'utilization.directory_utils.update_understand_database', 'update_understand_database', (['config.UDB_PATH'], {}), '(config.UDB_PATH)\n', (5456, 5473), False, 'from utilization.directory_utils import update_understand_database, git_restore\n'), ((5861, 5894), 'metrics.testability_prediction.main', 'testability_main', (['config.UDB_PATH'], {}), '(config.UDB_PATH)\n', (5877, 5894), True, 'from metrics.testability_prediction import main as testability_main\n'), ((5903, 5945), 'sbse.config.logger.info', 'logger.info', (['f"""Testability Score: {score}"""'], {}), "(f'Testability Score: {score}')\n", (5914, 5945), False, 'from sbse.config import logger\n'), ((6015, 6050), 'numpy.array', 'np.array', (['[-1 * score]'], {'dtype': 'float'}), '([-1 * score], dtype=float)\n', (6023, 6050), True, 'import numpy as np\n'), ((7217, 7255), 'sbse.config.logger.debug', 'logger.debug', (['"""Executing git restore."""'], {}), "('Executing git restore.')\n", (7229, 7255), False, 'from sbse.config import logger\n'), ((7264, 7296), 'utilization.directory_utils.git_restore', 'git_restore', (['config.PROJECT_PATH'], {}), '(config.PROJECT_PATH)\n', (7275, 7296), False, 'from utilization.directory_utils import update_understand_database, git_restore\n'), ((7305, 7348), 'utilization.directory_utils.update_understand_database', 'update_understand_database', (['config.UDB_PATH'], {}), '(config.UDB_PATH)\n', (7331, 7348), False, 'from utilization.directory_utils import update_understand_database, git_restore\n'), ((7735, 7771), 'sbse.objectives.Objectives', 'Objectives', ([], {'udb_path': 'config.UDB_PATH'}), '(udb_path=config.UDB_PATH)\n', (7745, 7771), False, 'from sbse.objectives import Objectives\n'), ((7826, 7859), 'metrics.testability_prediction.main', 'testability_main', (['config.UDB_PATH'], {}), '(config.UDB_PATH)\n', (7842, 7859), True, 'from metrics.testability_prediction import main as testability_main\n'), ((7873, 7905), 'metrics.modularity.main', 'modularity_main', (['config.UDB_PATH'], {}), '(config.UDB_PATH)\n', (7888, 7905), True, 'from metrics.modularity import main as modularity_main\n'), ((7914, 7951), 'sbse.config.logger.info', 'logger.info', (['f"""QMOOD AVG Score: {o1}"""'], {}), "(f'QMOOD AVG Score: {o1}')\n", (7925, 7951), False, 'from sbse.config import logger\n'), ((7960, 7999), 'sbse.config.logger.info', 'logger.info', (['f"""Testability Score: {o2}"""'], {}), "(f'Testability Score: {o2}')\n", (7971, 7999), False, 'from sbse.config import logger\n'), ((8008, 8046), 'sbse.config.logger.info', 'logger.info', (['f"""Modularity Score: {o3}"""'], {}), "(f'Modularity Score: {o3}')\n", (8019, 8046), False, 'from sbse.config import logger\n'), ((8116, 8166), 'numpy.array', 'np.array', (['[-1 * o1, -1 * o2, -1 * o3]'], {'dtype': 'float'}), '([-1 * o1, -1 * o2, -1 * o3], dtype=float)\n', (8124, 8166), True, 'import numpy as np\n'), ((9311, 9349), 'sbse.config.logger.debug', 'logger.debug', (['"""Executing git restore."""'], {}), "('Executing git restore.')\n", (9323, 9349), False, 'from sbse.config import logger\n'), ((9358, 9390), 'utilization.directory_utils.git_restore', 'git_restore', (['config.PROJECT_PATH'], {}), '(config.PROJECT_PATH)\n', (9369, 9390), False, 'from utilization.directory_utils import update_understand_database, git_restore\n'), ((9399, 9442), 'utilization.directory_utils.update_understand_database', 'update_understand_database', (['config.UDB_PATH'], {}), '(config.UDB_PATH)\n', (9425, 9442), False, 'from utilization.directory_utils import update_understand_database, git_restore\n'), ((9831, 9867), 'sbse.objectives.Objectives', 'Objectives', ([], {'udb_path': 'config.UDB_PATH'}), '(udb_path=config.UDB_PATH)\n', (9841, 9867), False, 'from sbse.objectives import Objectives\n'), ((10097, 10130), 'metrics.testability_prediction.main', 'testability_main', (['config.UDB_PATH'], {}), '(config.UDB_PATH)\n', (10113, 10130), True, 'from metrics.testability_prediction import main as testability_main\n'), ((10144, 10176), 'metrics.modularity.main', 'modularity_main', (['config.UDB_PATH'], {}), '(config.UDB_PATH)\n', (10159, 10176), True, 'from metrics.modularity import main as modularity_main\n'), ((10186, 10225), 'sbse.config.logger.info', 'logger.info', (['f"""Reusability Score: {o1}"""'], {}), "(f'Reusability Score: {o1}')\n", (10197, 10225), False, 'from sbse.config import logger\n'), ((10234, 10279), 'sbse.config.logger.info', 'logger.info', (['f"""Understandability Score: {o2}"""'], {}), "(f'Understandability Score: {o2}')\n", (10245, 10279), False, 'from sbse.config import logger\n'), ((10288, 10327), 'sbse.config.logger.info', 'logger.info', (['f"""Flexibility Score: {o3}"""'], {}), "(f'Flexibility Score: {o3}')\n", (10299, 10327), False, 'from sbse.config import logger\n'), ((10336, 10377), 'sbse.config.logger.info', 'logger.info', (['f"""Functionality Score: {o4}"""'], {}), "(f'Functionality Score: {o4}')\n", (10347, 10377), False, 'from sbse.config import logger\n'), ((10386, 10427), 'sbse.config.logger.info', 'logger.info', (['f"""Effectiveness Score: {o5}"""'], {}), "(f'Effectiveness Score: {o5}')\n", (10397, 10427), False, 'from sbse.config import logger\n'), ((10436, 10477), 'sbse.config.logger.info', 'logger.info', (['f"""Extendability Score: {o6}"""'], {}), "(f'Extendability Score: {o6}')\n", (10447, 10477), False, 'from sbse.config import logger\n'), ((10486, 10525), 'sbse.config.logger.info', 'logger.info', (['f"""Testability Score: {o7}"""'], {}), "(f'Testability Score: {o7}')\n", (10497, 10525), False, 'from sbse.config import logger\n'), ((10534, 10572), 'sbse.config.logger.info', 'logger.info', (['f"""Modularity Score: {o8}"""'], {}), "(f'Modularity Score: {o8}')\n", (10545, 10572), False, 'from sbse.config import logger\n'), ((10643, 10742), 'numpy.array', 'np.array', (['[-1 * o1, -1 * o2, -1 * o3, -1 * o4, -1 * o5, -1 * o6, -1 * o7, -1 * o8]'], {'dtype': 'float'}), '([-1 * o1, -1 * o2, -1 * o3, -1 * o4, -1 * o5, -1 * o6, -1 * o7, -1 *\n o8], dtype=float)\n', (10651, 10742), True, 'import numpy as np\n'), ((11505, 11552), 'numpy.full', 'np.full', (['(n_samples, 1)', 'None'], {'dtype': 'Individual'}), '((n_samples, 1), None, dtype=Individual)\n', (11512, 11552), True, 'import numpy as np\n'), ((14174, 14212), 'numpy.full_like', 'np.full_like', (['X', 'None'], {'dtype': 'np.object'}), '(X, None, dtype=np.object)\n', (14186, 14212), True, 'import numpy as np\n'), ((19361, 19379), 'sbse.config.logger.info', 'logger.info', (['ind.X'], {}), '(ind.X)\n', (19372, 19379), False, 'from sbse.config import logger\n'), ((19388, 19406), 'sbse.config.logger.info', 'logger.info', (['ind.F'], {}), '(ind.F)\n', (19399, 19406), False, 'from sbse.config import logger\n'), ((19415, 19448), 'sbse.config.logger.info', 'logger.info', (['"""=================="""'], {}), "('==================')\n", (19426, 19448), False, 'from sbse.config import logger\n'), ((5753, 5796), 'utilization.directory_utils.update_understand_database', 'update_understand_database', (['config.UDB_PATH'], {}), '(config.UDB_PATH)\n', (5779, 5796), False, 'from utilization.directory_utils import update_understand_database, git_restore\n'), ((7628, 7671), 'utilization.directory_utils.update_understand_database', 'update_understand_database', (['config.UDB_PATH'], {}), '(config.UDB_PATH)\n', (7654, 7671), False, 'from utilization.directory_utils import update_understand_database, git_restore\n'), ((9722, 9765), 'utilization.directory_utils.update_understand_database', 'update_understand_database', (['config.UDB_PATH'], {}), '(config.UDB_PATH)\n', (9748, 9765), False, 'from utilization.directory_utils import update_understand_database, git_restore\n'), ((15796, 15814), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (15812, 15814), True, 'import numpy as np\n'), ((17030, 17071), 'pymoo.factory.get_crossover', 'get_crossover', (['"""real_k_point"""'], {'n_points': '(2)'}), "('real_k_point', n_points=2)\n", (17043, 17071), False, 'from pymoo.factory import get_reference_directions, get_crossover\n'), ((17459, 17500), 'pymoo.factory.get_crossover', 'get_crossover', (['"""real_k_point"""'], {'n_points': '(2)'}), "('real_k_point', n_points=2)\n", (17472, 17500), False, 'from pymoo.factory import get_reference_directions, get_crossover\n'), ((18100, 18141), 'pymoo.factory.get_crossover', 'get_crossover', (['"""real_k_point"""'], {'n_points': '(2)'}), "('real_k_point', n_points=2)\n", (18113, 18141), False, 'from pymoo.factory import get_reference_directions, get_crossover\n'), ((2579, 2636), 'sbse.config.logger.error', 'logger.error', (['f"""Error in executing refactoring:\n {e}"""'], {}), '(f"""Error in executing refactoring:\n {e}""")\n', (2591, 2636), False, 'from sbse.config import logger\n'), ((11574, 11748), 'sbse.initialize.RandomInitialization', 'RandomInitialization', ([], {'udb_path': 'config.UDB_PATH', 'population_size': 'n_samples', 'lower_band': 'problem.n_refactorings_lowerbound', 'upper_band': 'problem.n_refactorings_upperbound'}), '(udb_path=config.UDB_PATH, population_size=n_samples,\n lower_band=problem.n_refactorings_lowerbound, upper_band=problem.\n n_refactorings_upperbound)\n', (11594, 11748), False, 'from sbse.initialize import RandomInitialization\n'), ((14583, 14601), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (14599, 14601), True, 'import numpy as np\n')] |
#!/usr/bin/env python
#
# test_fnirt.py -
#
# Author: <NAME> <<EMAIL>>
#
import os.path as op
import itertools as it
import numpy as np
import nibabel as nib
import pytest
import fsl.data.image as fslimage
import fsl.utils.tempdir as tempdir
import fsl.data.constants as constants
import fsl.transform.affine as affine
import fsl.transform.nonlinear as nonlinear
import fsl.transform.fnirt as fnirt
from .test_nonlinear import _random_affine_field
datadir = op.join(op.dirname(__file__), 'testdata', 'nonlinear')
def test_readFnirt():
src = op.join(datadir, 'src')
ref = op.join(datadir, 'ref')
coef = op.join(datadir, 'coefficientfield')
disp = op.join(datadir, 'displacementfield')
src = fslimage.Image(src)
ref = fslimage.Image(ref)
coef = fnirt.readFnirt(coef, src, ref)
disp = fnirt.readFnirt(disp, src, ref)
with pytest.raises(ValueError):
fnirt.readFnirt(src, src, ref)
assert isinstance(coef, nonlinear.CoefficientField)
assert isinstance(disp, nonlinear.DeformationField)
assert coef.src.sameSpace(src)
assert coef.ref.sameSpace(ref)
assert disp.src.sameSpace(src)
assert disp.ref.sameSpace(ref)
assert coef.srcSpace == 'fsl'
assert coef.refSpace == 'fsl'
assert disp.srcSpace == 'fsl'
assert disp.refSpace == 'fsl'
def test_readFnirt_defType_intent():
src = op.join(datadir, 'src.nii.gz')
ref = op.join(datadir, 'ref.nii.gz')
coef = op.join(datadir, 'coefficientfield.nii.gz')
disp = op.join(datadir, 'displacementfield.nii.gz')
src = fslimage.Image(src)
ref = fslimage.Image(ref)
field = fnirt.readFnirt(disp, src, ref, defType='absolute')
assert field.deformationType == 'absolute'
field = fnirt.readFnirt(disp, src, ref, defType='relative')
assert field.deformationType == 'relative'
img = nib.load(coef)
img.header['intent_code'] = 0
with tempdir.tempdir():
img.to_filename('field.nii.gz')
with pytest.raises(ValueError):
fnirt.readFnirt('field', src, ref)
field = fnirt.readFnirt(
'field', src, ref,
intent=constants.FSL_CUBIC_SPLINE_COEFFICIENTS)
assert isinstance(field, nonlinear.CoefficientField)
field = fnirt.readFnirt(
'field', src, ref,
intent=constants.FSL_FNIRT_DISPLACEMENT_FIELD)
assert isinstance(field, nonlinear.DeformationField)
def test_toFnirt():
def check(got, exp):
tol = dict(atol=1e-5, rtol=1e-5)
assert np.all(np.isclose(got.data, exp.data, **tol))
assert got.src.sameSpace(exp.src)
assert got.ref.sameSpace(exp.ref)
assert got.srcSpace == 'fsl'
assert got.refSpace == 'fsl'
basefield, xform = _random_affine_field()
src = basefield.src
ref = basefield.ref
spaces = it.permutations(('voxel', 'fsl', 'world'), 2)
for from_, to in spaces:
field = nonlinear.convertDeformationSpace(basefield, from_, to)
got = fnirt.toFnirt(field)
check(got, basefield)
src = fslimage.Image(op.join(datadir, 'src'))
ref = fslimage.Image(op.join(datadir, 'ref'))
coef = fnirt.readFnirt(op.join(datadir, 'coefficientfield'), src, ref)
got = fnirt.toFnirt(coef)
check(got, coef)
def test_fromFnirt():
basefield, basexform = _random_affine_field()
src = basefield.src
ref = basefield.ref
spaces = list(it.permutations(('voxel', 'fsl', 'world'), 2))
for from_, to in spaces:
got = fnirt.fromFnirt(basefield, from_, to)
assert got.srcSpace == to
assert got.refSpace == from_
coords = [np.random.randint(0, basefield.shape[0], 5),
np.random.randint(0, basefield.shape[1], 5),
np.random.randint(0, basefield.shape[2], 5)]
coords = np.array(coords).T
coords = affine.transform(coords, ref.getAffine('voxel', from_))
aff = affine.concat(src.getAffine('fsl', to),
basexform,
ref.getAffine(from_, 'fsl'))
got = got.transform(coords)
exp = affine.transform(coords, aff)
enan = np.isnan(exp)
gnan = np.isnan(got)
assert np.all(np.isclose(enan, gnan))
assert np.all(np.isclose(exp[~enan], got[~gnan]))
# Converting from a FNIRT coefficient field
src = fslimage.Image(op.join(datadir, 'src'))
ref = fslimage.Image(op.join(datadir, 'ref'))
coef = fnirt.readFnirt(op.join(datadir, 'coefficientfield'), src, ref)
disp = fnirt.readFnirt(op.join(datadir, 'displacementfield'), src, ref)
for from_, to in spaces:
cnv = fnirt.fromFnirt(coef, from_, to)
exp = nonlinear.convertDeformationSpace(disp, from_, to)
tol = dict(atol=1e-5, rtol=1e-5)
assert np.all(np.isclose(cnv.data, exp.data, **tol))
| [
"nibabel.load",
"fsl.transform.nonlinear.convertDeformationSpace",
"os.path.dirname",
"itertools.permutations",
"numpy.isnan",
"fsl.transform.fnirt.toFnirt",
"fsl.data.image.Image",
"pytest.raises",
"numpy.isclose",
"numpy.random.randint",
"fsl.transform.affine.transform",
"numpy.array",
"fs... | [((500, 520), 'os.path.dirname', 'op.dirname', (['__file__'], {}), '(__file__)\n', (510, 520), True, 'import os.path as op\n'), ((583, 606), 'os.path.join', 'op.join', (['datadir', '"""src"""'], {}), "(datadir, 'src')\n", (590, 606), True, 'import os.path as op\n'), ((618, 641), 'os.path.join', 'op.join', (['datadir', '"""ref"""'], {}), "(datadir, 'ref')\n", (625, 641), True, 'import os.path as op\n'), ((653, 689), 'os.path.join', 'op.join', (['datadir', '"""coefficientfield"""'], {}), "(datadir, 'coefficientfield')\n", (660, 689), True, 'import os.path as op\n'), ((701, 738), 'os.path.join', 'op.join', (['datadir', '"""displacementfield"""'], {}), "(datadir, 'displacementfield')\n", (708, 738), True, 'import os.path as op\n'), ((751, 770), 'fsl.data.image.Image', 'fslimage.Image', (['src'], {}), '(src)\n', (765, 770), True, 'import fsl.data.image as fslimage\n'), ((782, 801), 'fsl.data.image.Image', 'fslimage.Image', (['ref'], {}), '(ref)\n', (796, 801), True, 'import fsl.data.image as fslimage\n'), ((813, 844), 'fsl.transform.fnirt.readFnirt', 'fnirt.readFnirt', (['coef', 'src', 'ref'], {}), '(coef, src, ref)\n', (828, 844), True, 'import fsl.transform.fnirt as fnirt\n'), ((856, 887), 'fsl.transform.fnirt.readFnirt', 'fnirt.readFnirt', (['disp', 'src', 'ref'], {}), '(disp, src, ref)\n', (871, 887), True, 'import fsl.transform.fnirt as fnirt\n'), ((1404, 1434), 'os.path.join', 'op.join', (['datadir', '"""src.nii.gz"""'], {}), "(datadir, 'src.nii.gz')\n", (1411, 1434), True, 'import os.path as op\n'), ((1446, 1476), 'os.path.join', 'op.join', (['datadir', '"""ref.nii.gz"""'], {}), "(datadir, 'ref.nii.gz')\n", (1453, 1476), True, 'import os.path as op\n'), ((1488, 1531), 'os.path.join', 'op.join', (['datadir', '"""coefficientfield.nii.gz"""'], {}), "(datadir, 'coefficientfield.nii.gz')\n", (1495, 1531), True, 'import os.path as op\n'), ((1543, 1587), 'os.path.join', 'op.join', (['datadir', '"""displacementfield.nii.gz"""'], {}), "(datadir, 'displacementfield.nii.gz')\n", (1550, 1587), True, 'import os.path as op\n'), ((1600, 1619), 'fsl.data.image.Image', 'fslimage.Image', (['src'], {}), '(src)\n', (1614, 1619), True, 'import fsl.data.image as fslimage\n'), ((1631, 1650), 'fsl.data.image.Image', 'fslimage.Image', (['ref'], {}), '(ref)\n', (1645, 1650), True, 'import fsl.data.image as fslimage\n'), ((1664, 1715), 'fsl.transform.fnirt.readFnirt', 'fnirt.readFnirt', (['disp', 'src', 'ref'], {'defType': '"""absolute"""'}), "(disp, src, ref, defType='absolute')\n", (1679, 1715), True, 'import fsl.transform.fnirt as fnirt\n'), ((1775, 1826), 'fsl.transform.fnirt.readFnirt', 'fnirt.readFnirt', (['disp', 'src', 'ref'], {'defType': '"""relative"""'}), "(disp, src, ref, defType='relative')\n", (1790, 1826), True, 'import fsl.transform.fnirt as fnirt\n'), ((1885, 1899), 'nibabel.load', 'nib.load', (['coef'], {}), '(coef)\n', (1893, 1899), True, 'import nibabel as nib\n'), ((2878, 2923), 'itertools.permutations', 'it.permutations', (["('voxel', 'fsl', 'world')", '(2)'], {}), "(('voxel', 'fsl', 'world'), 2)\n", (2893, 2923), True, 'import itertools as it\n'), ((3281, 3300), 'fsl.transform.fnirt.toFnirt', 'fnirt.toFnirt', (['coef'], {}), '(coef)\n', (3294, 3300), True, 'import fsl.transform.fnirt as fnirt\n'), ((898, 923), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (911, 923), False, 'import pytest\n'), ((933, 963), 'fsl.transform.fnirt.readFnirt', 'fnirt.readFnirt', (['src', 'src', 'ref'], {}), '(src, src, ref)\n', (948, 963), True, 'import fsl.transform.fnirt as fnirt\n'), ((1943, 1960), 'fsl.utils.tempdir.tempdir', 'tempdir.tempdir', ([], {}), '()\n', (1958, 1960), True, 'import fsl.utils.tempdir as tempdir\n'), ((2107, 2194), 'fsl.transform.fnirt.readFnirt', 'fnirt.readFnirt', (['"""field"""', 'src', 'ref'], {'intent': 'constants.FSL_CUBIC_SPLINE_COEFFICIENTS'}), "('field', src, ref, intent=constants.\n FSL_CUBIC_SPLINE_COEFFICIENTS)\n", (2122, 2194), True, 'import fsl.transform.fnirt as fnirt\n'), ((2293, 2379), 'fsl.transform.fnirt.readFnirt', 'fnirt.readFnirt', (['"""field"""', 'src', 'ref'], {'intent': 'constants.FSL_FNIRT_DISPLACEMENT_FIELD'}), "('field', src, ref, intent=constants.\n FSL_FNIRT_DISPLACEMENT_FIELD)\n", (2308, 2379), True, 'import fsl.transform.fnirt as fnirt\n'), ((2970, 3025), 'fsl.transform.nonlinear.convertDeformationSpace', 'nonlinear.convertDeformationSpace', (['basefield', 'from_', 'to'], {}), '(basefield, from_, to)\n', (3003, 3025), True, 'import fsl.transform.nonlinear as nonlinear\n'), ((3040, 3060), 'fsl.transform.fnirt.toFnirt', 'fnirt.toFnirt', (['field'], {}), '(field)\n', (3053, 3060), True, 'import fsl.transform.fnirt as fnirt\n'), ((3118, 3141), 'os.path.join', 'op.join', (['datadir', '"""src"""'], {}), "(datadir, 'src')\n", (3125, 3141), True, 'import os.path as op\n'), ((3169, 3192), 'os.path.join', 'op.join', (['datadir', '"""ref"""'], {}), "(datadir, 'ref')\n", (3176, 3192), True, 'import os.path as op\n'), ((3221, 3257), 'os.path.join', 'op.join', (['datadir', '"""coefficientfield"""'], {}), "(datadir, 'coefficientfield')\n", (3228, 3257), True, 'import os.path as op\n'), ((3463, 3508), 'itertools.permutations', 'it.permutations', (["('voxel', 'fsl', 'world')", '(2)'], {}), "(('voxel', 'fsl', 'world'), 2)\n", (3478, 3508), True, 'import itertools as it\n'), ((3555, 3592), 'fsl.transform.fnirt.fromFnirt', 'fnirt.fromFnirt', (['basefield', 'from_', 'to'], {}), '(basefield, from_, to)\n', (3570, 3592), True, 'import fsl.transform.fnirt as fnirt\n'), ((4167, 4196), 'fsl.transform.affine.transform', 'affine.transform', (['coords', 'aff'], {}), '(coords, aff)\n', (4183, 4196), True, 'import fsl.transform.affine as affine\n'), ((4213, 4226), 'numpy.isnan', 'np.isnan', (['exp'], {}), '(exp)\n', (4221, 4226), True, 'import numpy as np\n'), ((4242, 4255), 'numpy.isnan', 'np.isnan', (['got'], {}), '(got)\n', (4250, 4255), True, 'import numpy as np\n'), ((4436, 4459), 'os.path.join', 'op.join', (['datadir', '"""src"""'], {}), "(datadir, 'src')\n", (4443, 4459), True, 'import os.path as op\n'), ((4487, 4510), 'os.path.join', 'op.join', (['datadir', '"""ref"""'], {}), "(datadir, 'ref')\n", (4494, 4510), True, 'import os.path as op\n'), ((4539, 4575), 'os.path.join', 'op.join', (['datadir', '"""coefficientfield"""'], {}), "(datadir, 'coefficientfield')\n", (4546, 4575), True, 'import os.path as op\n'), ((4615, 4652), 'os.path.join', 'op.join', (['datadir', '"""displacementfield"""'], {}), "(datadir, 'displacementfield')\n", (4622, 4652), True, 'import os.path as op\n'), ((4709, 4741), 'fsl.transform.fnirt.fromFnirt', 'fnirt.fromFnirt', (['coef', 'from_', 'to'], {}), '(coef, from_, to)\n', (4724, 4741), True, 'import fsl.transform.fnirt as fnirt\n'), ((4756, 4806), 'fsl.transform.nonlinear.convertDeformationSpace', 'nonlinear.convertDeformationSpace', (['disp', 'from_', 'to'], {}), '(disp, from_, to)\n', (4789, 4806), True, 'import fsl.transform.nonlinear as nonlinear\n'), ((2016, 2041), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2029, 2041), False, 'import pytest\n'), ((2055, 2089), 'fsl.transform.fnirt.readFnirt', 'fnirt.readFnirt', (['"""field"""', 'src', 'ref'], {}), "('field', src, ref)\n", (2070, 2089), True, 'import fsl.transform.fnirt as fnirt\n'), ((2572, 2609), 'numpy.isclose', 'np.isclose', (['got.data', 'exp.data'], {}), '(got.data, exp.data, **tol)\n', (2582, 2609), True, 'import numpy as np\n'), ((3684, 3727), 'numpy.random.randint', 'np.random.randint', (['(0)', 'basefield.shape[0]', '(5)'], {}), '(0, basefield.shape[0], 5)\n', (3701, 3727), True, 'import numpy as np\n'), ((3747, 3790), 'numpy.random.randint', 'np.random.randint', (['(0)', 'basefield.shape[1]', '(5)'], {}), '(0, basefield.shape[1], 5)\n', (3764, 3790), True, 'import numpy as np\n'), ((3810, 3853), 'numpy.random.randint', 'np.random.randint', (['(0)', 'basefield.shape[2]', '(5)'], {}), '(0, basefield.shape[2], 5)\n', (3827, 3853), True, 'import numpy as np\n'), ((3872, 3888), 'numpy.array', 'np.array', (['coords'], {}), '(coords)\n', (3880, 3888), True, 'import numpy as np\n'), ((4279, 4301), 'numpy.isclose', 'np.isclose', (['enan', 'gnan'], {}), '(enan, gnan)\n', (4289, 4301), True, 'import numpy as np\n'), ((4325, 4359), 'numpy.isclose', 'np.isclose', (['exp[~enan]', 'got[~gnan]'], {}), '(exp[~enan], got[~gnan])\n', (4335, 4359), True, 'import numpy as np\n'), ((4870, 4907), 'numpy.isclose', 'np.isclose', (['cnv.data', 'exp.data'], {}), '(cnv.data, exp.data, **tol)\n', (4880, 4907), True, 'import numpy as np\n')] |
import pickle
import numpy as np
class Glove:
def __init__(self, fname):
self.fname = fname
self.embeddings_dim = 300
self._read_data()
self._build_embeddings()
def __getitem__(self, value):
try:
return self.embeddings[value]
except KeyError:
self.embeddings[value] = np.random.uniform(-0.25, 0.25, size=self.embeddings_dim)
return self.embeddings[value]
def _read_data(self):
with open(self.fname, 'r') as file:
self._raw_data = [
line for line in file.readlines()
]
file.close()
def _build_embeddings(self):
"""
This function will spend a lot of time on building (depends on your computer spec. and embeddings model size.)
"""
self.embeddings = {}
for line in self._raw_data:
splitted_line = line.split()
concatenated_word = ' '.join(splitted_line[:-self.embeddings_dim])
self.embeddings[concatenated_word] = np.array(splitted_line[-self.embeddings_dim:], dtype=np.float32)
self.embeddings[''] = np.random.uniform(-0.25, 0.25, size=self.embeddings_dim)
# memory recycle
del self._raw_data
| [
"numpy.random.uniform",
"numpy.array"
] | [((1151, 1207), 'numpy.random.uniform', 'np.random.uniform', (['(-0.25)', '(0.25)'], {'size': 'self.embeddings_dim'}), '(-0.25, 0.25, size=self.embeddings_dim)\n', (1168, 1207), True, 'import numpy as np\n'), ((1055, 1119), 'numpy.array', 'np.array', (['splitted_line[-self.embeddings_dim:]'], {'dtype': 'np.float32'}), '(splitted_line[-self.embeddings_dim:], dtype=np.float32)\n', (1063, 1119), True, 'import numpy as np\n'), ((353, 409), 'numpy.random.uniform', 'np.random.uniform', (['(-0.25)', '(0.25)'], {'size': 'self.embeddings_dim'}), '(-0.25, 0.25, size=self.embeddings_dim)\n', (370, 409), True, 'import numpy as np\n')] |
# type: ignore
import math
import matplotlib.pyplot as plt
import numpy as np
from common import Fitness
def print_summary(history, algorithm):
max, average_fitness, entropy, baseline, _ = history.keys()
print(algorithm, 'summary statistics')
print(f'Max: {history[max][-1]:>10.3f}')
print(f'Average fitness: {history[average_fitness][-1]:>10.3f}')
print(f'Entropy: {history[entropy][-1]:>10.3f}')
print(f'Baseline: {history[baseline]:>10.3f}')
print('---------------------------')
def plot_history(history, filename):
fig, ax1 = plt.subplots()
ax1.set_title(filename.upper())
baseline = history['baseline']
color = 'tab:blue'
ax1.set_xlabel('generation')
ax1.set_ylabel('Average fitness', color=color)
ax1.plot(history['average_fitness'], color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax1.plot(np.full(len(history['average_fitness']), baseline), linestyle='--', color='black', label='Baseline')
ax2 = ax1.twinx()
color = 'tab:orange'
ax2.set_ylabel('entropy', color=color)
ax2.plot(history['entropy'], color=color)
ax2.tick_params(axis='y', labelcolor=color)
fig.tight_layout()
ax1.legend()
fig.savefig(f'src/results/{filename}.png')
plt.close()
def plot_sine(generations, filename):
plt.title(f'Population plot ({filename.upper()})')
plt.xlabel('x')
plt.ylabel('sin(x)')
x = np.linspace(0, 128, 1000, endpoint=True)
plt.plot(x, np.sin(x), label='sin(x)')
upper_bound = 128
scaling_factor = 2 ** -(len(generations[0][0]) - math.log2(upper_bound))
population = [chromosome for population in generations for chromosome in population] # flatten generation
chromosomes = [int(chromosome, 2) * scaling_factor for chromosome in population]
fitnesses = [Fitness.sine_fitness(chromosome) for chromosome in population]
plt.scatter(chromosomes, fitnesses, color='tab:orange')
plt.tight_layout()
plt.savefig(f'src/results/{filename}_sine.png')
plt.close()
def plot_diversity(sga, crowding, filename):
plt.title('Diveristy')
plt.xlabel('generations')
plt.ylabel('entropy')
plt.plot(crowding['entropy'], label='Crowding', color='tab:blue')
plt.plot(sga['entropy'], label='Simple Genetic Algorithm', color='tab:orange')
plt.legend()
plt.tight_layout()
plt.savefig(f'src/results/{filename}.png')
plt.close()
| [
"matplotlib.pyplot.title",
"matplotlib.pyplot.tight_layout",
"math.log2",
"matplotlib.pyplot.plot",
"common.Fitness.sine_fitness",
"matplotlib.pyplot.close",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.legend",
"numpy.sin",
"numpy.linspace",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.x... | [((595, 609), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (607, 609), True, 'import matplotlib.pyplot as plt\n'), ((1283, 1294), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (1292, 1294), True, 'import matplotlib.pyplot as plt\n'), ((1394, 1409), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""x"""'], {}), "('x')\n", (1404, 1409), True, 'import matplotlib.pyplot as plt\n'), ((1414, 1434), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""sin(x)"""'], {}), "('sin(x)')\n", (1424, 1434), True, 'import matplotlib.pyplot as plt\n'), ((1444, 1484), 'numpy.linspace', 'np.linspace', (['(0)', '(128)', '(1000)'], {'endpoint': '(True)'}), '(0, 128, 1000, endpoint=True)\n', (1455, 1484), True, 'import numpy as np\n'), ((1909, 1964), 'matplotlib.pyplot.scatter', 'plt.scatter', (['chromosomes', 'fitnesses'], {'color': '"""tab:orange"""'}), "(chromosomes, fitnesses, color='tab:orange')\n", (1920, 1964), True, 'import matplotlib.pyplot as plt\n'), ((1970, 1988), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1986, 1988), True, 'import matplotlib.pyplot as plt\n'), ((1993, 2040), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""src/results/{filename}_sine.png"""'], {}), "(f'src/results/{filename}_sine.png')\n", (2004, 2040), True, 'import matplotlib.pyplot as plt\n'), ((2045, 2056), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2054, 2056), True, 'import matplotlib.pyplot as plt\n'), ((2108, 2130), 'matplotlib.pyplot.title', 'plt.title', (['"""Diveristy"""'], {}), "('Diveristy')\n", (2117, 2130), True, 'import matplotlib.pyplot as plt\n'), ((2135, 2160), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""generations"""'], {}), "('generations')\n", (2145, 2160), True, 'import matplotlib.pyplot as plt\n'), ((2165, 2186), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""entropy"""'], {}), "('entropy')\n", (2175, 2186), True, 'import matplotlib.pyplot as plt\n'), ((2192, 2257), 'matplotlib.pyplot.plot', 'plt.plot', (["crowding['entropy']"], {'label': '"""Crowding"""', 'color': '"""tab:blue"""'}), "(crowding['entropy'], label='Crowding', color='tab:blue')\n", (2200, 2257), True, 'import matplotlib.pyplot as plt\n'), ((2262, 2340), 'matplotlib.pyplot.plot', 'plt.plot', (["sga['entropy']"], {'label': '"""Simple Genetic Algorithm"""', 'color': '"""tab:orange"""'}), "(sga['entropy'], label='Simple Genetic Algorithm', color='tab:orange')\n", (2270, 2340), True, 'import matplotlib.pyplot as plt\n'), ((2346, 2358), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2356, 2358), True, 'import matplotlib.pyplot as plt\n'), ((2363, 2381), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2379, 2381), True, 'import matplotlib.pyplot as plt\n'), ((2386, 2428), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""src/results/{filename}.png"""'], {}), "(f'src/results/{filename}.png')\n", (2397, 2428), True, 'import matplotlib.pyplot as plt\n'), ((2433, 2444), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2442, 2444), True, 'import matplotlib.pyplot as plt\n'), ((1501, 1510), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (1507, 1510), True, 'import numpy as np\n'), ((1842, 1874), 'common.Fitness.sine_fitness', 'Fitness.sine_fitness', (['chromosome'], {}), '(chromosome)\n', (1862, 1874), False, 'from common import Fitness\n'), ((1604, 1626), 'math.log2', 'math.log2', (['upper_bound'], {}), '(upper_bound)\n', (1613, 1626), False, 'import math\n')] |
# Copyright (c) <NAME> (<EMAIL>). All Rights Reserved.
#
# Please cite "4D Spatio-Temporal ConvNets: Minkowski Convolutional Neural
# Networks", CVPR'19 (https://arxiv.org/abs/1904.08755) if you use any part of
# the code.
import logging
import warnings
import os
import numpy as np
import torch
import torch.nn as nn
from sklearn.metrics import average_precision_score
from sklearn.preprocessing import label_binarize
from lib.utils import Timer, AverageMeter, precision_at_one, fast_hist, per_class_iu, \
get_prediction, get_torch_device, save_map
import MinkowskiEngine as ME
def print_info(iteration,
max_iteration,
data_time,
iter_time,
has_gt=False,
losses=None,
scores=None,
ious=None,
hist=None,
ap_class=None,
class_names=None):
debug_str = "{}/{}: ".format(iteration + 1, max_iteration)
debug_str += "Data time: {:.4f}, Iter time: {:.4f}".format(data_time, iter_time)
if has_gt:
acc = hist.diagonal() / hist.sum(1) * 100
debug_str += "\tLoss {loss.val:.3f} (AVG: {loss.avg:.3f})\t" \
"Score {top1.val:.3f} (AVG: {top1.avg:.3f})\t" \
"mIOU {mIOU:.3f} mAP {mAP:.3f} mAcc {mAcc:.3f}\n".format(
loss=losses, top1=scores, mIOU=np.nanmean(ious),
mAP=np.nanmean(ap_class), mAcc=np.nanmean(acc))
if class_names is not None:
debug_str += "\nClasses: " + " ".join(class_names) + '\n'
debug_str += 'IOU: ' + ' '.join('{:.03f}'.format(i) for i in ious) + '\n'
debug_str += 'mAP: ' + ' '.join('{:.03f}'.format(i) for i in ap_class) + '\n'
debug_str += 'mAcc: ' + ' '.join('{:.03f}'.format(i) for i in acc) + '\n'
logging.info(debug_str)
def average_precision(prob_np, target_np):
num_class = prob_np.shape[1]
label = label_binarize(target_np, classes=list(range(num_class)))
with np.errstate(divide='ignore', invalid='ignore'):
# return average_precision_score(label, prob_np)
return average_precision_score(label, prob_np, None)
def test(model, data_loader, config, transform_data_fn=None, has_gt=True, save_pred=False, split=None):
device = get_torch_device(config.is_cuda)
dataset = data_loader.dataset
num_labels = dataset.NUM_LABELS
global_timer, data_timer, iter_timer = Timer(), Timer(), Timer()
criterion = nn.CrossEntropyLoss(ignore_index=config.ignore_label)
losses, scores, ious = AverageMeter(), AverageMeter(), 0
aps = np.zeros((0, num_labels))
hist = np.zeros((num_labels, num_labels))
# some cfgs concerning the usage of instance-level information
config.save_pred = save_pred
if split is not None:
assert save_pred
if config.save_pred:
save_dict = {}
save_dict['pred'] = []
save_dict['coord'] = []
logging.info('===> Start testing')
global_timer.tic()
data_iter = data_loader.__iter__()
max_iter = len(data_loader)
max_iter_unique = max_iter
# Fix batch normalization running mean and std
model.eval()
# Clear cache (when run in val mode, cleanup training cache)
torch.cuda.empty_cache()
with torch.no_grad():
# Calc of the iou
total_correct = np.zeros(num_labels)
total_seen = np.zeros(num_labels)
total_positive = np.zeros(num_labels)
for iteration in range(max_iter):
data_timer.tic()
if config.return_transformation:
coords, input, target, unique_map_list, inverse_map_list, pointcloud, transformation = data_iter.next()
else:
coords, input, target, unique_map_list, inverse_map_list = data_iter.next()
data_time = data_timer.toc(False)
if config.use_aux:
assert target.shape[1] == 2
aux = target[:,1]
target = target[:,0]
else:
aux = None
# Preprocess input
iter_timer.tic()
if config.normalize_color:
input[:, :3] = input[:, :3] / input[:,:3].max() - 0.5
coords_norm = coords[:,1:] / coords[:,1:].max() - 0.5
XYZ_INPUT = config.xyz_input
# cat xyz into the rgb feature
if XYZ_INPUT:
input = torch.cat([coords_norm, input], dim=1)
sinput = ME.SparseTensor(input, coords, device=device)
# Feed forward
if aux is not None:
soutput = model(sinput)
else:
soutput = model(sinput, iter_ = iteration / max_iter, enable_point_branch=config.enable_point_branch)
output = soutput.F
if torch.isnan(output).sum() > 0:
import ipdb; ipdb.set_trace()
pred = get_prediction(dataset, output, target).int()
assert sum([int(t.shape[0]) for t in unique_map_list]) == len(pred), "number of points in unique_map doesn't match predition, do not enable preprocessing"
iter_time = iter_timer.toc(False)
if config.save_pred:
# troublesome processing for splitting each batch's data, and export
batch_ids = sinput.C[:,0]
splits_at = torch.stack([torch.where(batch_ids == i)[0][-1] for i in torch.unique(batch_ids)]).int()
splits_at = splits_at + 1
splits_at_leftshift_one = splits_at.roll(shifts=1)
splits_at_leftshift_one[0] = 0
# len_per_batch = splits_at - splits_at_leftshift_one
len_sum = 0
batch_id = 0
for start, end in zip(splits_at_leftshift_one, splits_at):
len_sum += len(pred[int(start):int(end)])
pred_this_batch = pred[int(start):int(end)]
coord_this_batch = pred[int(start):int(end)]
save_dict['pred'].append(pred_this_batch[inverse_map_list[batch_id]])
# save_dict['coord'].append(coord_this_batch[inverse_map_list[batch_id]])
batch_id += 1
assert len_sum == len(pred)
# Unpack it to original length
REVERT_WHOLE_POINTCLOUD = True
print('{}/{}'.format(iteration, max_iter))
if REVERT_WHOLE_POINTCLOUD:
whole_pred = []
whole_target = []
for batch_ in range(config.batch_size):
batch_mask_ = (soutput.C[:,0] == batch_).cpu().numpy()
if batch_mask_.sum() == 0: # for empty batch, skip em
continue
try:
whole_pred_ = soutput.F[batch_mask_][inverse_map_list[batch_]]
except:
import ipdb; ipdb.set_trace()
whole_target_ = target[batch_mask_][inverse_map_list[batch_]]
whole_pred.append(whole_pred_)
whole_target.append(whole_target_)
whole_pred = torch.cat(whole_pred, dim=0)
whole_target = torch.cat(whole_target, dim=0)
pred = get_prediction(dataset, whole_pred, whole_target).int()
output = whole_pred
target = whole_target
if has_gt:
target_np = target.numpy()
num_sample = target_np.shape[0]
target = target.to(device)
output = output.to(device)
cross_ent = criterion(output, target.long())
losses.update(float(cross_ent), num_sample)
scores.update(precision_at_one(pred, target), num_sample)
hist += fast_hist(pred.cpu().numpy().flatten(), target_np.flatten(), num_labels) # within fast hist, mark label should >=0 & < num_label to filter out 255 / -1
ious = per_class_iu(hist) * 100
prob = torch.nn.functional.softmax(output, dim=-1)
pred = pred[target != -1]
target = target[target != -1]
# for _ in range(num_labels): # debug for SemKITTI: spvnas way of calc miou
# total_seen[_] += torch.sum(target == _)
# total_correct[_] += torch.sum((pred == target) & (target == _))
# total_positive[_] += torch.sum(pred == _)
# ious_ = []
# for _ in range(num_labels):
# if total_seen[_] == 0:
# ious_.append(1)
# else:
# ious_.append(total_correct[_]/(total_seen[_] + total_positive[_] - total_correct[_]))
# ious_ = torch.stack(ious_, dim=-1).cpu().numpy()*100
# print(np.nanmean(per_class_iu(hist)), np.nanmean(ious_))
# ious = np.array(ious_)*100
# skip calculating aps
ap = average_precision(prob.cpu().detach().numpy(), target_np)
aps = np.vstack((aps, ap))
# Due to heavy bias in class, there exists class with no test label at all
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
ap_class = np.nanmean(aps, 0) * 100.
if iteration % config.test_stat_freq == 0 and iteration > 0:
reordered_ious = dataset.reorder_result(ious)
reordered_ap_class = dataset.reorder_result(ap_class)
# dirty fix for semnaticcKITTI has no getclassnames
if hasattr(dataset, "class_names"):
class_names = dataset.get_classnames()
else: # semnantic KITTI
class_names = None
print_info(
iteration,
max_iter_unique,
data_time,
iter_time,
has_gt,
losses,
scores,
reordered_ious,
hist,
reordered_ap_class,
class_names=class_names)
if iteration % 5 == 0:
# Clear cache
torch.cuda.empty_cache()
if config.save_pred:
# torch.save(save_dict, os.path.join(config.log_dir, 'preds_{}_with_coord.pth'.format(split)))
torch.save(save_dict, os.path.join(config.log_dir, 'preds_{}.pth'.format(split)))
print("===> saved prediction result")
global_time = global_timer.toc(False)
save_map(model, config)
reordered_ious = dataset.reorder_result(ious)
reordered_ap_class = dataset.reorder_result(ap_class)
if hasattr(dataset, "class_names"):
class_names = dataset.get_classnames()
else:
class_names = None
print_info(
iteration,
max_iter_unique,
data_time,
iter_time,
has_gt,
losses,
scores,
reordered_ious,
hist,
reordered_ap_class,
class_names=class_names)
logging.info("Finished test. Elapsed time: {:.4f}".format(global_time))
# Explicit memory cleanup
if hasattr(data_iter, 'cleanup'):
data_iter.cleanup()
return losses.avg, scores.avg, np.nanmean(ap_class), np.nanmean(per_class_iu(hist)) * 100
# ===============================================================================================
def load_checkpoint(model, filename):
if os.path.isfile(filename):
logging.info("==> Loading from checkpoint %s" % filename)
checkpoint = torch.load(filename)
epoch = checkpoint['epoch']
model.load_state_dict(checkpoint['model_state'])
logging.info("==> Done")
else:
logging.info(filename)
raise FileNotFoundError
return epoch
def vote(predict, vote_num, pred, points_idx):
''' numpy array
:param predict: (pn,21) float
:param vote_num: (pn,1) int
:param pred: (bs,np,21) float
:param points_idx: (bs,np) int
'''
bs, np = points_idx.shape
for i in range(bs):
for j in range(np):
pred_ = pred[i, j, :] # 21
pidx_ = points_idx[i, j] # int
predict[pidx_, :] += pred_
vote_num[pidx_, 0] += 1
return predict, vote_num
# def test_points(model,
# data_loader,
# config,
# with_aux=False,
# save_dir=None,
# split='eval',
# use_voxel=True):
# '''
# :param pn_list: sn (list => int), the number of points in a scene
# :param scene_list: sn (list => str), scene id
# '''
# pn_list = data_loader.dataset.point_num
# scene_list = data_loader.dataset.scene_list
# SEM_LABELS = data_loader.dataset.semantic_labels_list
# model.eval()
# total_seen = 0
# total_correct = 0
# total_seen_class = [0] * NUM_CLASSES
# total_correct_class = [0] * NUM_CLASSES
# total_iou_deno_class = [0] * NUM_CLASSES
# if save_dir is not None:
# save_dict = {}
# save_dict['pred'] = []
# use_voxel = not config.pure_point
# scene_num = len(scene_list)
# for scene_index in range(scene_num):
# logging.info(' ======= {}/{} ======= '.format(scene_index, scene_num))
# # scene_index = 0
# scene_id = scene_list[scene_index]
# point_num = pn_list[scene_index]
# predict = np.zeros((point_num, NUM_CLASSES), dtype=np.float32) # pn,21
# vote_num = np.zeros((point_num, 1), dtype=np.int) # pn,1
# for idx, batch_data in enumerate(data_loader):
# # logging.info('batch {}'.format(idx))
# if with_aux:
# pc, seg, aux, smpw, pidx= batch_data
# aux = aux.cuda()
# seg = seg.cuda()
# else:
# pc, seg, smpw, pidx= batch_data
# if pidx.max() > point_num:
# import ipdb; ipdb.set_trace()
# pc = pc.cuda().float()
# '''
# use voxel-forward for testing the scannet
# '''
# if use_voxel:
# coords = torch.unbind(pc[:,:,:3]/config.voxel_size, dim=0)
# # Normalize the xyz after the coord is set
# # pc[:,:,:3] = pc[:,:,:3] / pc[:,:,:3].mean()
# feats = torch.unbind(pc[:,:,:], dim=0) # use all 6 chs for eval
# coords, feats= ME.utils.sparse_collate(coords, feats) # the returned coords adds a batch-dimw
# pc = ME.TensorField(features=feats.float(),coordinates=coords.cuda()) # [xyz, norm_xyz, rgb]
# voxels = pc.sparse()
# seg = seg.view(-1)
# inputs = voxels
# else:
# # DEBUG: discrete input xyz for point-based method
# feats = torch.unbind(pc[:,:,:], dim=0)
# coords = torch.unbind(pc[:,:,:3]/config.voxel_size, dim=0)
# coords, feats= ME.utils.sparse_collate(coords, feats) # the returned coords adds a batch-dim
# pc = ME.TensorField(features=feats.float(),coordinates=coords.cuda()) # [xyz, norm_xyz, rgb]
# voxels = pc.sparse()
# pc_ = voxels.slice(pc)
# # pc = torch.cat([pc_.C[:,1:],pc_.F[:,:3:]],dim=1).reshape([-1, config.num_points, 6])
# pc = pc_.F.reshape([-1, config.num_points, 6])
# # discrete_coords = coords.reshape([-1, config.num_points, 4])[:,:,1:] # the batch does not have drop-last
# # pc[:,:,:3] = discrete_coords
# pc = pc.transpose(1,2)
# inputs = pc
# if with_aux:
# # DEBUG: Use target as instance for now
# pred = model(inputs, instance=aux) # B,N,C
# else:
# pred = model(inputs) # B,N,C
# if use_voxel:
# assert isinstance(pred, ME.SparseTensor)
# pred = pred.slice(pc).F
# try:
# pred = pred.reshape([-1, config.num_points, NUM_CLASSES]) # leave the 1st dim, since no droplast
# except RuntimeError:
# import ipdb; ipdb.set_trace()
# pred = torch.nn.functional.softmax(pred, dim=2)
# pred = pred.cpu().detach().numpy()
# pidx = pidx.numpy() # B,N
# predict, vote_num = vote(predict, vote_num, pred, pidx)
# predict = predict / vote_num
# if save_dir is not None:
# if np.isnan(predict).any():
# print("found nan in scene{}".format(scene_id))
# import ipdb; ipdb.set_trace()
# save_dict['pred'].append(np.argmax(predict, axis=-1))
# # predict = np.argmax(predict[:, 1:], axis=-1) # pn # debug WHY?
# predict = np.argmax(predict, axis=-1) # pn
# labels = SEM_LABELS[scene_index]
# '''
# additional logic for handling 20 class output
# '''
# labels = labels - 1
# correct = predict == labels
# correct = correct[labels != -1]
# total_seen += np.sum(labels.size) # point_num
# # total_correct += np.sum((predict == labels) & (labels > 0))
# total_correct += np.sum(correct)
# logging.info('accuracy:{} '.format(total_correct / total_seen))
# for l in range(NUM_CLASSES):
# total_seen_class[l] += np.sum((labels == l) & (labels >= 0))
# total_correct_class[l] += np.sum((predict == l) & (labels == l))
# total_iou_deno_class[l] += np.sum(((predict == l) & (labels >= 0)) | (labels == l))
# '''Uncomment this to save the map, this could take about 500M sapce'''
# # save_map(model, config)
# # import ipdb; ipdb.set_trace()
# # final save
# if save_dir is not None:
# torch.save(save_dict, os.path.join(save_dir,'{}_pred.pth'.format(split)))
# IoU = np.array(total_correct_class)/(np.array(total_iou_deno_class,dtype=np.float)+1e-6)
# logging.info('eval point avg class IoU: %f' % (np.mean(IoU)))
# IoU_Class = 'Each Class IoU:::\n'
# for i in range(IoU.shape[0]):
# logging.info('Class %d : %.4f'%(i+1, IoU[i]))
# logging.info('eval accuracy: %f'% (total_correct / float(total_seen)))
# logging.info('eval avg class acc: %f' % (np.mean(np.array(total_correct_class)/(np.array(total_seen_class,dtype=np.float)+1e-6))))
| [
"ipdb.set_trace",
"torch.cat",
"os.path.isfile",
"lib.utils.get_torch_device",
"torch.no_grad",
"torch.isnan",
"numpy.nanmean",
"lib.utils.per_class_iu",
"warnings.simplefilter",
"torch.load",
"warnings.catch_warnings",
"sklearn.metrics.average_precision_score",
"MinkowskiEngine.SparseTensor... | [((1971, 1994), 'logging.info', 'logging.info', (['debug_str'], {}), '(debug_str)\n', (1983, 1994), False, 'import logging\n'), ((2437, 2469), 'lib.utils.get_torch_device', 'get_torch_device', (['config.is_cuda'], {}), '(config.is_cuda)\n', (2453, 2469), False, 'from lib.utils import Timer, AverageMeter, precision_at_one, fast_hist, per_class_iu, get_prediction, get_torch_device, save_map\n'), ((2625, 2678), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {'ignore_index': 'config.ignore_label'}), '(ignore_index=config.ignore_label)\n', (2644, 2678), True, 'import torch.nn as nn\n'), ((2750, 2775), 'numpy.zeros', 'np.zeros', (['(0, num_labels)'], {}), '((0, num_labels))\n', (2758, 2775), True, 'import numpy as np\n'), ((2787, 2821), 'numpy.zeros', 'np.zeros', (['(num_labels, num_labels)'], {}), '((num_labels, num_labels))\n', (2795, 2821), True, 'import numpy as np\n'), ((3090, 3124), 'logging.info', 'logging.info', (['"""===> Start testing"""'], {}), "('===> Start testing')\n", (3102, 3124), False, 'import logging\n'), ((3390, 3414), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (3412, 3414), False, 'import torch\n'), ((10869, 10892), 'lib.utils.save_map', 'save_map', (['model', 'config'], {}), '(model, config)\n', (10877, 10892), False, 'from lib.utils import Timer, AverageMeter, precision_at_one, fast_hist, per_class_iu, get_prediction, get_torch_device, save_map\n'), ((11833, 11857), 'os.path.isfile', 'os.path.isfile', (['filename'], {}), '(filename)\n', (11847, 11857), False, 'import os\n'), ((2152, 2198), 'numpy.errstate', 'np.errstate', ([], {'divide': '"""ignore"""', 'invalid': '"""ignore"""'}), "(divide='ignore', invalid='ignore')\n", (2163, 2198), True, 'import numpy as np\n'), ((2272, 2317), 'sklearn.metrics.average_precision_score', 'average_precision_score', (['label', 'prob_np', 'None'], {}), '(label, prob_np, None)\n', (2295, 2317), False, 'from sklearn.metrics import average_precision_score\n'), ((2583, 2590), 'lib.utils.Timer', 'Timer', ([], {}), '()\n', (2588, 2590), False, 'from lib.utils import Timer, AverageMeter, precision_at_one, fast_hist, per_class_iu, get_prediction, get_torch_device, save_map\n'), ((2592, 2599), 'lib.utils.Timer', 'Timer', ([], {}), '()\n', (2597, 2599), False, 'from lib.utils import Timer, AverageMeter, precision_at_one, fast_hist, per_class_iu, get_prediction, get_torch_device, save_map\n'), ((2601, 2608), 'lib.utils.Timer', 'Timer', ([], {}), '()\n', (2606, 2608), False, 'from lib.utils import Timer, AverageMeter, precision_at_one, fast_hist, per_class_iu, get_prediction, get_torch_device, save_map\n'), ((2706, 2720), 'lib.utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (2718, 2720), False, 'from lib.utils import Timer, AverageMeter, precision_at_one, fast_hist, per_class_iu, get_prediction, get_torch_device, save_map\n'), ((2722, 2736), 'lib.utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (2734, 2736), False, 'from lib.utils import Timer, AverageMeter, precision_at_one, fast_hist, per_class_iu, get_prediction, get_torch_device, save_map\n'), ((3425, 3440), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3438, 3440), False, 'import torch\n'), ((3493, 3513), 'numpy.zeros', 'np.zeros', (['num_labels'], {}), '(num_labels)\n', (3501, 3513), True, 'import numpy as np\n'), ((3535, 3555), 'numpy.zeros', 'np.zeros', (['num_labels'], {}), '(num_labels)\n', (3543, 3555), True, 'import numpy as np\n'), ((3581, 3601), 'numpy.zeros', 'np.zeros', (['num_labels'], {}), '(num_labels)\n', (3589, 3601), True, 'import numpy as np\n'), ((11625, 11645), 'numpy.nanmean', 'np.nanmean', (['ap_class'], {}), '(ap_class)\n', (11635, 11645), True, 'import numpy as np\n'), ((11875, 11932), 'logging.info', 'logging.info', (["('==> Loading from checkpoint %s' % filename)"], {}), "('==> Loading from checkpoint %s' % filename)\n", (11887, 11932), False, 'import logging\n'), ((11962, 11982), 'torch.load', 'torch.load', (['filename'], {}), '(filename)\n', (11972, 11982), False, 'import torch\n'), ((12108, 12132), 'logging.info', 'logging.info', (['"""==> Done"""'], {}), "('==> Done')\n", (12120, 12132), False, 'import logging\n'), ((12163, 12185), 'logging.info', 'logging.info', (['filename'], {}), '(filename)\n', (12175, 12185), False, 'import logging\n'), ((4624, 4669), 'MinkowskiEngine.SparseTensor', 'ME.SparseTensor', (['input', 'coords'], {'device': 'device'}), '(input, coords, device=device)\n', (4639, 4669), True, 'import MinkowskiEngine as ME\n'), ((1520, 1536), 'numpy.nanmean', 'np.nanmean', (['ious'], {}), '(ious)\n', (1530, 1536), True, 'import numpy as np\n'), ((1566, 1586), 'numpy.nanmean', 'np.nanmean', (['ap_class'], {}), '(ap_class)\n', (1576, 1586), True, 'import numpy as np\n'), ((1593, 1608), 'numpy.nanmean', 'np.nanmean', (['acc'], {}), '(acc)\n', (1603, 1608), True, 'import numpy as np\n'), ((4563, 4601), 'torch.cat', 'torch.cat', (['[coords_norm, input]'], {'dim': '(1)'}), '([coords_norm, input], dim=1)\n', (4572, 4601), False, 'import torch\n'), ((5012, 5028), 'ipdb.set_trace', 'ipdb.set_trace', ([], {}), '()\n', (5026, 5028), False, 'import ipdb\n'), ((7296, 7324), 'torch.cat', 'torch.cat', (['whole_pred'], {'dim': '(0)'}), '(whole_pred, dim=0)\n', (7305, 7324), False, 'import torch\n'), ((7356, 7386), 'torch.cat', 'torch.cat', (['whole_target'], {'dim': '(0)'}), '(whole_target, dim=0)\n', (7365, 7386), False, 'import torch\n'), ((8185, 8228), 'torch.nn.functional.softmax', 'torch.nn.functional.softmax', (['output'], {'dim': '(-1)'}), '(output, dim=-1)\n', (8212, 8228), False, 'import torch\n'), ((9258, 9278), 'numpy.vstack', 'np.vstack', (['(aps, ap)'], {}), '((aps, ap))\n', (9267, 9278), True, 'import numpy as np\n'), ((10531, 10555), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (10553, 10555), False, 'import torch\n'), ((11658, 11676), 'lib.utils.per_class_iu', 'per_class_iu', (['hist'], {}), '(hist)\n', (11670, 11676), False, 'from lib.utils import Timer, AverageMeter, precision_at_one, fast_hist, per_class_iu, get_prediction, get_torch_device, save_map\n'), ((5049, 5088), 'lib.utils.get_prediction', 'get_prediction', (['dataset', 'output', 'target'], {}), '(dataset, output, target)\n', (5063, 5088), False, 'from lib.utils import Timer, AverageMeter, precision_at_one, fast_hist, per_class_iu, get_prediction, get_torch_device, save_map\n'), ((7894, 7924), 'lib.utils.precision_at_one', 'precision_at_one', (['pred', 'target'], {}), '(pred, target)\n', (7910, 7924), False, 'from lib.utils import Timer, AverageMeter, precision_at_one, fast_hist, per_class_iu, get_prediction, get_torch_device, save_map\n'), ((8137, 8155), 'lib.utils.per_class_iu', 'per_class_iu', (['hist'], {}), '(hist)\n', (8149, 8155), False, 'from lib.utils import Timer, AverageMeter, precision_at_one, fast_hist, per_class_iu, get_prediction, get_torch_device, save_map\n'), ((9391, 9416), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (9414, 9416), False, 'import warnings\n'), ((9438, 9494), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {'category': 'RuntimeWarning'}), "('ignore', category=RuntimeWarning)\n", (9459, 9494), False, 'import warnings\n'), ((4952, 4971), 'torch.isnan', 'torch.isnan', (['output'], {}), '(output)\n', (4963, 4971), False, 'import torch\n'), ((7411, 7460), 'lib.utils.get_prediction', 'get_prediction', (['dataset', 'whole_pred', 'whole_target'], {}), '(dataset, whole_pred, whole_target)\n', (7425, 7460), False, 'from lib.utils import Timer, AverageMeter, precision_at_one, fast_hist, per_class_iu, get_prediction, get_torch_device, save_map\n'), ((9526, 9544), 'numpy.nanmean', 'np.nanmean', (['aps', '(0)'], {}), '(aps, 0)\n', (9536, 9544), True, 'import numpy as np\n'), ((7062, 7078), 'ipdb.set_trace', 'ipdb.set_trace', ([], {}), '()\n', (7076, 7078), False, 'import ipdb\n'), ((5554, 5577), 'torch.unique', 'torch.unique', (['batch_ids'], {}), '(batch_ids)\n', (5566, 5577), False, 'import torch\n'), ((5510, 5537), 'torch.where', 'torch.where', (['(batch_ids == i)'], {}), '(batch_ids == i)\n', (5521, 5537), False, 'import torch\n')] |
import argparse
import logging
import numpy as np
import random
import torch
logger = logging.getLogger("SemEval")
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def bool_flag(v):
if v.lower() in {"on", "true", "yes", "t", "y", "1"}:
return True
elif v.lower() in {"off", "false", "no", "f", "n", "0"}:
return False
else:
raise argparse.ArgumentTypeError("Invalid value for a boolean flag!")
def set_args(parser, additional=False, **kwargs):
path_config(parser)
run_config(parser)
### add by func
add_func = kwargs.get("add_func", None)
if add_func is not None:
for each in add_func:
logger.info(f'Args add: [{each}]')
eval(each)(parser)
args = parser.parse_args()
return args
def path_config(parser):
path_group = parser.add_argument_group("Path information and required dirs")
path_group.add_argument("--data_dir",
default=None,
type=str,
required=True,
help="The input data dir. Should contain the .csv files (or other data files) for the task.")
path_group.add_argument("--train_file", default=None, type=str)
path_group.add_argument("--trail_file", default=None, type=str)
path_group.add_argument("--dev_file", default=None, type=str)
path_group.add_argument("--test_file", default=None, type=str)
path_group.add_argument("--use_newd", default=False, type=bool_flag)
path_group.add_argument("--split_dev", default=False, type=bool_flag)
path_group.add_argument("--output_dir",
default=None,
type=str,
required=True,
help="The output directory where the model checkpoints will be written.")
path_group.add_argument("--log_file", default="log.out", type=str)
path_group.add_argument("--tfboard_log_dir", default="event.out", type=str)
path_group.add_argument("--result_eval_file", default="result.eval.txt", type=str)
path_group.add_argument("--result_test_file", default="result.test.txt", type=str)
path_group.add_argument("--result_trial_file", default="result.trial.txt", type=str)
path_group.add_argument("--model_type", default="bert", type=str)
path_group.add_argument("--model_name_or_path",
default=None,
type=str,
required=True,
help="Bert pre-trained model selected in the list: bert-base-uncased, "
"bert-large-uncased, bert-base-cased, bert-large-cased, bert-base-multilingual-uncased, "
"bert-base-multilingual-cased, bert-base-chinese.")
path_group.add_argument("--tokenizer_name_or_path",
default=None,
type=str,
required=True,
help="Bert pre-trained model selected in the list: bert-base-uncased, "
"bert-large-uncased, bert-base-cased, bert-large-cased, bert-base-multilingual-uncased, "
"bert-base-multilingual-cased, bert-base-chinese.")
path_group.add_argument("--config_name",
default=None,
type=str,
help="Pretrained config name or path if not the same as model_name")
path_group.add_argument('--overwrite_output_dir', action='store_true',
help="Overwrite the content of the output directory")
path_group.add_argument('--overwrite_cache', action='store_true',
help="Overwrite the cached input feature sets.")
def run_config(parser):
run_group = parser.add_argument_group("Run configs")
run_group.add_argument("--task_name", default='wic_pair',
type=str,
required=True)
run_group.add_argument("--network_name", default=None,
type=str)
### Run parameters
run_group.add_argument("--max_seq_length", default=128,
type=int,
help="The maximum total input sequence length after WordPiece tokenization. \n"
"Sequences longer than this will be truncated, and sequences shorter \n"
"than this will be padded.")
run_group.add_argument("--do_lower_case",
action='store_true',
help="Set this flag if you are using an uncased model.")
run_group.add_argument("--cls_segment_id", default=0,
type=int)
run_group.add_argument("--from_tf", action='store_true')
### Run Mode
run_group.add_argument("--do_train",
action='store_true',
help="Whether to run training.")
run_group.add_argument("--do_eval",
action='store_true',
help="Whether to run eval on the dev set.")
run_group.add_argument("--do_test",
action='store_true',
help="Whether to run test on the test set.")
run_group.add_argument("--do_trial",
action='store_true',
help="Whether to run test on the unofficial dev set.")
run_group.add_argument("--have_test_label",
action='store_true',
help="Used when testing")
### Train parameters
run_group.add_argument("--train_batch_size",
default=32,
type=int,
help="Total batch size for training.\n"
"Discarded.")
run_group.add_argument("--per_gpu_train_batch_size",
default=8,
type=int,
help="Batch size per GPU/CPU for training.")
run_group.add_argument("--eval_batch_size",
default=8,
type=int,
help="Total batch size for eval. \n"
"Discarded.")
run_group.add_argument("--per_gpu_eval_batch_size",
default=8,
type=int,
help="Batch size per GPU/CPU for evaluation.")
run_group.add_argument("--learning_rate",
default=5e-5,
type=float,
help="The initial learning rate for Adam.")
run_group.add_argument("--adam_epsilon",
# default=1e-8,
default=1e-6,
type=float,
help="Epsilon for Adam optimizer.")
run_group.add_argument("--num_train_epochs",
default=3.0,
type=float,
help="Total number of training epochs to perform.")
run_group.add_argument("--max_steps",
default=-1,
type=int,
help="If > 0: set total number of training steps to perform. Override num_train_epochs.")
run_group.add_argument("--warmup_proportion",
default=0.1,
type=float,
help="Proportion of training to perform linear learning rate warmup for. "
"E.g., 0.1 = 10%% of training.")
run_group.add_argument("--warmup_steps",
default=0, type=int,
help="Linear warmup over warmup_steps.")
run_group.add_argument("--weight_decay",
# default=0.0,
default=0.01,
type=float,
help="Weight deay if we apply some.")
run_group.add_argument('--gradient_accumulation_steps',
type=int,
default=1,
help="Number of updates steps to accumulate before performing a backward/update pass.")
run_group.add_argument("--max_grad_norm",
default=1.0, # default is 1.0
type=float,
help="Max gradient norm.")
run_group.add_argument('--loss_scale',
type=float, default=0,
help="Loss scaling to improve fp16 numeric stability. Only used when fp16 set to True.\n"
"0 (default value): dynamic loss scaling.\n"
"Positive power of 2: static loss scaling value.\n")
run_group.add_argument('--lm_coef', type=float, default=0.9,
help="parameter to balance lm loss and task loss for GPT/GPT2")
run_group.add_argument('--add_loss_coef', type=float, default=1.0,
help="parameter to balance main loss and additional loss for Task")
### Environment
run_group.add_argument("--no_cuda",
action='store_true',
help="Whether not to use CUDA when available")
run_group.add_argument("--local_rank",
default=-1,
type=int,
help="local_rank for distributed training on gpus")
run_group.add_argument('--seed',
default=42,
type=int,
help="random seed for initialization")
run_group.add_argument('--fp16',
action='store_true',
help="Whether to use 16-bit float precision instead of 32-bit")
run_group.add_argument('--fp16_opt_level',
type=str, default='O1',
help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']."
"See details at https://nvidia.github.io/apex/amp.html")
### Others
run_group.add_argument('--logging_steps', type=int, default=100,
help="Log every X updates steps.")
run_group.add_argument('--save_steps', type=int, default=0,
help="Save checkpoint every X updates steps.")
run_group.add_argument("--eval_all_checkpoints", action='store_true',
help="Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number")
run_group.add_argument("--evaluate_during_training", action='store_true',
help="Rul evaluation during training at each logging step.")
run_group.add_argument("--evaluate_epoch", action='store_true',
help="Rul evaluation during training at each logging step.")
### Task specific
run_group.add_argument("--output_mode",
default="classification",
type=str)
run_group.add_argument("--num_choices", default=2,
type=int)
run_group.add_argument("--have_passage",
action='store_true',
help="if example have context passage")
run_group.add_argument("--label_smooth",
default=0.0,
type=float,
help="label smoothing, if set to 0.0 = close label smoothing. "
"Smoothed probability for each class = (label_smooth / (num_of_class - 1))"
"True class probability = 1 - label_smooth")
def add_args(now_args, additional_args):
now_args, additional_args = vars(now_args), vars(additional_args)
for k,v in additional_args.items():
if k not in now_args:
now_args[k] = v
logger.info("Update additional config {}: {}".format(k,v))
else:
if v != now_args[k]:
logger.info("Warn: additional config {}: {}/{} exist.".format(k, now_args[k], v))
return argparse.Namespace(**now_args)
def check_args_version(load_args, now_args):
load_args, now_args = vars(load_args), vars(now_args)
for k, v in now_args.items():
if k not in load_args:
load_args[k] = v
logger.info("Update load checkpoint config {}: {}".format(k,v))
return argparse.Namespace(**load_args)
def override_args(old_args, new_args):
KEEP_CONFIG = {}
old_args, new_args = vars(old_args), vars(new_args)
for k in old_args.keys():
if k in new_args and old_args[k] != new_args[k]:
if k in KEEP_CONFIG:
logger.info("Overriding saved {}: {} --> {}".format(k, old_args[k], new_args[k]))
old_args[k] = new_args[k]
else:
logger.info("Keeping saved {}: {}".format(k, old_args[k]))
return argparse.Namespace(**old_args)
def task_lm_finetune(parser):
lm_task_group = parser.add_argument_group('Task configs: lm fine-tune')
### for lm finetuning
lm_task_group.add_argument("--mlm",
action='store_true',
help="Train with masked-language modeling loss instead of language modeling.")
lm_task_group.add_argument("--mlm_probability",
type=float,
default=0.15,
help="Ratio of tokens to mask for masked language modeling loss")
lm_task_group.add_argument("--block_size",
default=-1,
type=int,
help="Optional input sequence length after tokenization."
"The training dataset will be truncated in block of this size for training."
"Default to the model max input length for single sentence inputs "
"(take into account special tokens).")
lm_task_group.add_argument('--save_total_limit',
type=int,
default=None,
help='Limit the total amount of checkpoints, delete the older checkpoints in the output_dir, '
'does not delete by default')
lm_task_group.add_argument("--cache_dir", default="", type=str,
help="Optional directory to store the pre-trained models downloaded from s3 "
"(instread of the default one)") | [
"argparse.Namespace",
"numpy.random.seed",
"torch.manual_seed",
"torch.cuda.manual_seed_all",
"random.seed",
"logging.getLogger",
"argparse.ArgumentTypeError"
] | [((88, 116), 'logging.getLogger', 'logging.getLogger', (['"""SemEval"""'], {}), "('SemEval')\n", (105, 116), False, 'import logging\n'), ((143, 165), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (154, 165), False, 'import random\n'), ((170, 195), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (184, 195), True, 'import numpy as np\n'), ((200, 228), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (217, 228), False, 'import torch\n'), ((12536, 12566), 'argparse.Namespace', 'argparse.Namespace', ([], {}), '(**now_args)\n', (12554, 12566), False, 'import argparse\n'), ((12853, 12884), 'argparse.Namespace', 'argparse.Namespace', ([], {}), '(**load_args)\n', (12871, 12884), False, 'import argparse\n'), ((13368, 13398), 'argparse.Namespace', 'argparse.Namespace', ([], {}), '(**old_args)\n', (13386, 13398), False, 'import argparse\n'), ((260, 297), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['args.seed'], {}), '(args.seed)\n', (286, 297), False, 'import torch\n'), ((502, 565), 'argparse.ArgumentTypeError', 'argparse.ArgumentTypeError', (['"""Invalid value for a boolean flag!"""'], {}), "('Invalid value for a boolean flag!')\n", (528, 565), False, 'import argparse\n')] |
"""
Undersaturated (Volatile and Non-volatile) Oil Material Balance
@author: <NAME>
@email: <EMAIL>
"""
import numpy as np
import matplotlib.pyplot as plt
class mbplot():
"""
Undersaturated Oil Material Balance Plot
Ideal Data
"""
def plot1(self, p, Bg, Bo, Np, Gp, Gi, cf, cw, swi, Rs, Rv, output=None):
"""
Plot 1: F vs Eo+(Bti* Efw)
"""
# initial conditions
pi = p[0]
Boi = Bo[0]
Rsi = Rs[0]
Bto = []
F = []
for i in range(len(p)):
if Rv[i] == 0:
# reservoir is non-volatile undersaturated
Bto_ = Bo[i] + Bg[i] * (Rsi - Rs[i])
F_ = Np[i](Bo[i] - Rs[i] * Bg[i]) + ((Gp[i] - Gi[i]) * Bg[i])
Bto.append(Bto_)
F.append(F_)
if Rv[i] != 0:
# reservoir is volatile undersaturated
Bto_ = ((Bo[i] * (1 - (Rv[i] * Rsi))) + (Bg[i] * (Rsi - Rs[i]))) / (1 - (Rv[i] * Rs[i]))
F_ = (Np * ((Bo - (Rs * Bg)) / (1 - (Rv * Rs)))) + ((Gp[i] - Gi[i]) * ((Bg - (Rv * Bo)) / (1 - (Rv * Rs))))
Bto.append(Bto_)
F.append(F_)
Bto = np.array(Bto)
F = np.array(F)
# calculate Eo+(Boi*Efw)
Efw = ((cf + (cw * swi)) / (1 - swi)) * (pi - p)
Eo = Bto - Boi
Eo_Boi_Efw = Eo + Boi * Efw
if output == 'allparams':
return(Bto, Efw, Eo, F)
if output == None:
# plot
plt.plot(Eo_Boi_Efw, F, '.')
plt.title('Plot 1: F vs Eo+(Bti* Efw)')
plt.xlim(xmin=0);
plt.ylim(ymin=0)
plt.xlabel('Eo+(Bti*Efw) (RB/STB)')
plt.ylabel('F (res bbl)')
plt.show()
return(Eo_Boi_Efw, F)
def plot2(self, p, Bg, Bo, Np, Gp, cf, cw, swi, Rs, Rv, output=None):
"""
Plot 2: F/Eo+(Bti* Efw) vs Np
"""
# initial conditions
pi = p[0]
Boi = Bo[0]
Rsi = Rs[0]
Bto = []
F = []
for i in range(len(p)):
if Rv[i] == 0:
# reservoir is non-volatile undersaturated
Bto_ = Bo[i] + Bg[i] * (Rsi - Rs[i])
F_ = Np[i](Bo[i] - Rs[i] * Bg[i]) + ((Gp[i] - Gi[i]) * Bg[i])
Bto.append(Bto_)
F.append(F_)
if Rv[i] != 0:
# reservoir is volatile undersaturated
Bto_ = ((Bo[i] * (1 - (Rv[i] * Rsi))) + (Bg[i] * (Rsi - Rs[i]))) / (1 - (Rv[i] * Rs[i]))
F_ = (Np * ((Bo - (Rs * Bg)) / (1 - (Rv * Rs)))) + ((Gp[i] - Gi[i]) * ((Bg - (Rv * Bo)) / (1 - (Rv * Rs))))
Bto.append(Bto_)
F.append(F_)
Bto = np.array(Bto)
F = np.array(F)
# calculate Eo+(Boi*Efw)
Efw = ((cf + (cw * swi)) / (1 - swi)) * (pi - p)
Eo = Bto - Boi
Eo_Boi_Efw = Eo + Boi * Efw
N = F / Eo_Boi_Efw
if output == 'allparams':
return(Bto, Efw, Eo, F)
if output == None:
# plot
plt.plot(Np, N, '.')
plt.title('Plot 2: F/Eo+(Bti* Efw) vs Np')
plt.xlim(xmin=0);
plt.ylim(ymin=0)
plt.xlabel('Np (STB)')
plt.ylabel('F/Eo+(Bti* Efw) (STB)')
plt.show()
return(Np, N)
| [
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"numpy.array",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] | [((1192, 1205), 'numpy.array', 'np.array', (['Bto'], {}), '(Bto)\n', (1200, 1205), True, 'import numpy as np\n'), ((1218, 1229), 'numpy.array', 'np.array', (['F'], {}), '(F)\n', (1226, 1229), True, 'import numpy as np\n'), ((2735, 2748), 'numpy.array', 'np.array', (['Bto'], {}), '(Bto)\n', (2743, 2748), True, 'import numpy as np\n'), ((2761, 2772), 'numpy.array', 'np.array', (['F'], {}), '(F)\n', (2769, 2772), True, 'import numpy as np\n'), ((1510, 1538), 'matplotlib.pyplot.plot', 'plt.plot', (['Eo_Boi_Efw', 'F', '"""."""'], {}), "(Eo_Boi_Efw, F, '.')\n", (1518, 1538), True, 'import matplotlib.pyplot as plt\n'), ((1551, 1590), 'matplotlib.pyplot.title', 'plt.title', (['"""Plot 1: F vs Eo+(Bti* Efw)"""'], {}), "('Plot 1: F vs Eo+(Bti* Efw)')\n", (1560, 1590), True, 'import matplotlib.pyplot as plt\n'), ((1603, 1619), 'matplotlib.pyplot.xlim', 'plt.xlim', ([], {'xmin': '(0)'}), '(xmin=0)\n', (1611, 1619), True, 'import matplotlib.pyplot as plt\n'), ((1633, 1649), 'matplotlib.pyplot.ylim', 'plt.ylim', ([], {'ymin': '(0)'}), '(ymin=0)\n', (1641, 1649), True, 'import matplotlib.pyplot as plt\n'), ((1662, 1697), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Eo+(Bti*Efw) (RB/STB)"""'], {}), "('Eo+(Bti*Efw) (RB/STB)')\n", (1672, 1697), True, 'import matplotlib.pyplot as plt\n'), ((1710, 1735), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""F (res bbl)"""'], {}), "('F (res bbl)')\n", (1720, 1735), True, 'import matplotlib.pyplot as plt\n'), ((1748, 1758), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1756, 1758), True, 'import matplotlib.pyplot as plt\n'), ((3081, 3101), 'matplotlib.pyplot.plot', 'plt.plot', (['Np', 'N', '"""."""'], {}), "(Np, N, '.')\n", (3089, 3101), True, 'import matplotlib.pyplot as plt\n'), ((3114, 3156), 'matplotlib.pyplot.title', 'plt.title', (['"""Plot 2: F/Eo+(Bti* Efw) vs Np"""'], {}), "('Plot 2: F/Eo+(Bti* Efw) vs Np')\n", (3123, 3156), True, 'import matplotlib.pyplot as plt\n'), ((3169, 3185), 'matplotlib.pyplot.xlim', 'plt.xlim', ([], {'xmin': '(0)'}), '(xmin=0)\n', (3177, 3185), True, 'import matplotlib.pyplot as plt\n'), ((3199, 3215), 'matplotlib.pyplot.ylim', 'plt.ylim', ([], {'ymin': '(0)'}), '(ymin=0)\n', (3207, 3215), True, 'import matplotlib.pyplot as plt\n'), ((3228, 3250), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Np (STB)"""'], {}), "('Np (STB)')\n", (3238, 3250), True, 'import matplotlib.pyplot as plt\n'), ((3263, 3298), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""F/Eo+(Bti* Efw) (STB)"""'], {}), "('F/Eo+(Bti* Efw) (STB)')\n", (3273, 3298), True, 'import matplotlib.pyplot as plt\n'), ((3311, 3321), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3319, 3321), True, 'import matplotlib.pyplot as plt\n')] |
# -*- coding: utf-8 -*-
import sys
sys.path.append('/Users/SeongHwanKim/tensorflow3/caffe-master/python')
from caffe.proto import caffe_pb2
import numpy as np
import json
import copy
global mdlnet
global inlayername
# calculate output dimension size for all layer
def layerDim(mdlnet, inname, indim, sizelist):
tempdim = copy.deepcopy(indim)
for layer in mdlnet["layers"]:
if "name" in layer and "input" in layer["inputs"]:
if layer["inputs"]["input"][0].split(".")[0] == inname: #inname레이어의 다음 레이어의 경우
if layer["type"] == "conv": #conv의 경우
# get stride value
if "stride" in layer["attributes"]:
temp_stride = int(layer["attributes"]["stride"])
else:
temp_stride = 1
# get kernel size value
temp_ksize = [layer["attributes"]["filter"][0], layer["attributes"]["filter"][1]]
# calculate dimension w.r.t padding type
if "padding" in layer["attributes"]:
if layer["attributes"]["padding"].upper() == "SAME":
tempdim[0] = np.ceil(float(tempdim[0]) / float(temp_stride))
tempdim[1] = np.ceil(float(tempdim[1]) / float(temp_stride))
elif layer["attributes"]["padding"].upper() == "VALID":
tempdim[0] = np.ceil(float(tempdim[0] - temp_ksize[0] + 1) / float(temp_stride))
tempdim[1] = np.ceil(float(tempdim[1] - temp_ksize[1] + 1) / float(temp_stride))
else:
tempdim[0] = np.ceil(float(tempdim[0]) / float(temp_stride))
tempdim[1] = np.ceil(float(tempdim[1]) / float(temp_stride))
# recursive
sizelist.append([layer["name"], copy.deepcopy(tempdim)])
layerDim(mdlnet, layer["name"], copy.deepcopy(tempdim), sizelist)
elif layer["type"] == "max_pool" or layer["type"] == "avg_pool": #max_pool, avg_pool의 경우
# get stride value
if "stride" in layer["attributes"]:
temp_stride = int(layer["attributes"]["stride"])
else:
temp_stride = 2
# get kernel size value
if "ksize" in layer["attributes"]:
temp_ksize = int(layer["attributes"]["ksize"])
else:
temp_ksize = 2
# calculate dimension w.r.t padding type
if "padding" in layer["attributes"]:
if layer["attributes"]["padding"].upper() == "SAME":
tempdim[0] = np.ceil(float(tempdim[0]) / float(temp_stride))
tempdim[1] = np.ceil(float(tempdim[1]) / float(temp_stride))
elif layer["attributes"]["padding"].upper() == "VALID":
tempdim[0] = np.ceil(float(tempdim[0] - temp_ksize + 1) / float(temp_stride))
tempdim[1] = np.ceil(float(tempdim[1] - temp_ksize + 1) / float(temp_stride))
else:
tempdim[0] = np.ceil(float(tempdim[0]) / float(temp_stride))
tempdim[1] = np.ceil(float(tempdim[1]) / float(temp_stride))
# recursive
sizelist.append([layer["name"], copy.deepcopy(tempdim)])
layerDim(mdlnet, layer["name"], copy.deepcopy(tempdim), sizelist)
# read the dl-mdl model
def readDLMDL(path):
json_data=open(path).read()
mdlnet = json.loads(json_data)
return mdlnet
# convert dropout attr
def dropoutConvert(net, alayer, lname, ratio):
aalayer = net.layer.add()
aalayer.name = lname + "_dropout" # name
aalayer.type = "Dropout" # type
aalayer.bottom.extend([lname]) # bottom # TODO:Error?
aalayer.top.extend([lname]) # top # TODO:Error?
aalayer.dropout_param.dropout_ratio = ratio # dropout ratio
# convert activation attr
def activationConvert(net, alayer, lname, actmode):
if actmode == "relu":
aalayer = net.layer.add()
aalayer.name = lname + "_relu" # name
aalayer.type = "ReLU" # type
aalayer.bottom.extend([lname]) # bottom # TODO:Error?
aalayer.top.extend([lname]) # top # TODO:Error?
# else activation?????????????????????
# convert bias attr
def biasConvert(alayer, initmode, ltype):
# check layer type
if ltype == "conv":
tempo = alayer.convolution_param
elif ltype == "fc":
tempo = alayer.inner_product_param
# set weight filler w.r.t selected mode
if initmode == "random_normal":
tempo.weight_filler.type = "gaussian"
tempo.weight_filler.mean = 0
tempo.weight_filler.std = 1
elif initmode == "zeroes":
tempo.weight_filler.type = "constant"
# convert weight attr
def weightConvert(alayer, initmode, ltype):
# check layer type
if ltype == "conv":
tempo = alayer.convolution_param
elif ltype == "fc":
tempo = alayer.inner_product_param
# set bias filler w.r.t selected mode
if initmode == "random_normal":
tempo.bias_filler.type = "gaussian"
tempo.bias_filler.mean = 0
tempo.bias_filler.std = 1
elif initmode == "zeroes":
tempo.bias_filler.type = "constant"
# convert padding attr
def paddingConvert(layer, alayer, temp_stride, indim):
# get kernel size
tempksize = [0,0]
if layer["type"] == "conv":
tempksize[0] = layer["attributes"]["filter"][0]
tempksize[1] = layer["attributes"]["filter"][1]
elif layer["type"] == "max_pool" or layer["type"] == "avg_pool":
tempksize[0] = int(layer["attributes"]["ksize"])
tempksize[1] = int(layer["attributes"]["ksize"])
# calculate padding
if "padding" in layer["attributes"]:
if layer["attributes"]["padding"].upper() == "VALID":
pad_h = 0
pad_w = 0
elif layer["attributes"]["padding"].upper() == "SAME":
# calculate padding value for SAME
out_height = np.ceil(indim[0] / temp_stride)
out_width = np.ceil(indim[1] / temp_stride)
pad_along_height = ((out_height - 1) * temp_stride + tempksize[0] - indim[0])
pad_along_width = ((out_width - 1) * temp_stride + tempksize[1] - indim[1])
pad_top = pad_along_height / 2
pad_left = pad_along_width / 2
pad_h = int(pad_top)
pad_w = int(pad_left)
else: # default to SAME
# calculate padding value for SAME
out_height = np.ceil(indim[0] / temp_stride);
out_width = np.ceil(indim[1] / temp_stride);
pad_along_height = ((out_height - 1) * temp_stride + tempksize[0] - indim[0]);
pad_along_width = ((out_width - 1) * temp_stride + tempksize[1] - indim[1]);
pad_top = pad_along_height / 2;
pad_left = pad_along_width / 2;
pad_h = int(pad_top)
pad_w = int(pad_left)
return [pad_h, pad_w]
# convert input layer
def inputConvert(layer, net, sol):
# add layer to caffe net
alayer = net.layer.add()
# layer checkpoint setting
alayer.name = layer["name"] # name
alayer.type = "Data" # type
alayer.top.extend(["data"]) # top # need to be considered????????????
alayer.top.extend(["label"]) # top # need to be considered????????????
# include{ phase }
if "option" in layer["attributes"]:
temp = caffe_pb2.NetStateRule()
if layer["attributes"]["option"].lower() == "datasets":
temp.phase = 0
elif layer["attributes"]["option"].lower() == "test":
temp.phase = 1
alayer.include.extend([temp])
# data_param{}
# source
if "train_data" in layer["attributes"]:
alayer.data_param.source = layer["attributes"]["train_data"]
# batch_size
if "batch_size" in layer["attributes"]:
alayer.data_param.batch_size = layer["attributes"]["batch_size"]
# solver checkpoint setting
# solver_mode
if "mode" in layer["attributes"]:
if layer["attributes"]["mode"].lower() == "cpu":
sol.solver_mode = 0
elif layer["attributes"]["mode"].lower() == "gpu":
sol.solver_mode = 1
else:
sol.solver_mode = 1
# max_iter
if "iteration" in layer["attributes"]:
sol.max_iter = layer["attributes"]["iteration"]
# default value!!!!!!!!
alayer.data_param.backend = 0
## image_size ???????????????????
## test_data?????
# convert conv layer
def convConvert(layer, net, sizelist):
# add layer to caffe net
alayer = net.layer.add()
# get input dimension
for item in sizelist:
print(item)
print(layer["inputs"]["input"][0].split(".")[0])
if item[0] == layer["inputs"]["input"][0].split(".")[0]:
indim = item[1] # [height, width]
# layer checkpoint setting
alayer.name = layer["name"] # name
alayer.type = "Convolution" # type
# bottom, top, kernel_h/w, num_output
if layer["inputs"]["input"][0].split(".")[0] == inlayername:
alayer.bottom.extend(["data"]) # need custom handling???????????????????
else:
alayer.bottom.extend([layer["inputs"]["input"][0].split(".")[0]])
alayer.top.extend([layer["name"]])
alayer.convolution_param.kernel_h = layer["attributes"]["filter"][0]
alayer.convolution_param.kernel_w = layer["attributes"]["filter"][1]
alayer.convolution_param.num_output = layer["attributes"]["filter"][3]
# stride
if "stride" in layer["attributes"]:
alayer.convolution_param.stride.extend([int(layer["attributes"]["stride"])])
temp_stride = int(layer["attributes"]["stride"])
else:
temp_stride = 1
# pad_h/w
temp_pad = paddingConvert(layer, alayer, temp_stride, indim)
alayer.convolution_param.pad_h = temp_pad[0]
alayer.convolution_param.pad_w = temp_pad[1]
# weight_filler
if "weight" in layer["attributes"]:
weightConvert(alayer, layer["attributes"]["weight"].lower(), "conv")
else:
weightConvert(alayer, "random_normal", "conv")
# bias_filler
if "bias" in layer["attributes"]:
biasConvert(alayer, layer["attributes"]["bias"].lower(), "conv")
else:
biasConvert(alayer, "zeroes", "conv")
# activation
if "activation" in layer["attributes"]:
activationConvert(net, alayer, layer["name"], layer["attributes"]["activation"])
# dropout
if "dropout" in layer["attributes"]:
activationConvert(net, alayer, layer["name"], float(layer["attributes"]["dropout"]))
# convert pooling layer
def poolConvert(layer, net, sizelist):
# add layer to caffe net
alayer = net.layer.add()
# get input dimension
for item in sizelist:
print(item)
print(layer["inputs"]["input"][0].split(".")[0])
if item[0] == layer["inputs"]["input"][0].split(".")[0]:
indim = item[1] # [height, width]
# layer checkpoint setting
alayer.name = layer["name"] # name
alayer.type = "Pooling" # type
# bottom
if layer["inputs"]["input"][0].split(".")[0] == inlayername:
alayer.bottom.extend(["data"]) # need custom handling???????????????????
else:
alayer.bottom.extend([layer["inputs"]["input"][0].split(".")[0]])
# top
alayer.top.extend([layer["name"]])
# pool type
if layer["type"] == "max_pool":
alayer.pooling_param.pool = 0
elif layer["type"] == "avg_pool":
alayer.pooling_param.pool = 1
# stride
if "stride" in layer["attributes"]:
alayer.pooling_param.stride = int(layer["attributes"]["stride"])
temp_stride = int(layer["attributes"]["stride"])
else:
alayer.pooling_param.stride = 2
temp_stride = 2
# kernel_size
if "ksize" in layer["attributes"]:
alayer.pooling_param.kernel_size = int(layer["attributes"]["ksize"])
else:
alayer.pooling_param.kernel_size = 2
# pad_h/w
temp_pad = paddingConvert(layer, alayer, temp_stride, indim)
alayer.pooling_param.pad_h = temp_pad[0]
alayer.pooling_param.pad_w = temp_pad[1]
# activation
if "activation" in layer["attributes"]:
activationConvert(net, alayer, layer["name"], layer["attributes"]["activation"])
# dropout
if "dropout" in layer["attributes"]:
activationConvert(net, alayer, layer["name"], float(layer["attributes"]["dropout"])) # TODO:Error?
# convert fc layer
def fcConvert(layer, net):
# add layer to caffe net
alayer = net.layer.add()
# layer checkpoint setting
alayer.name = layer["name"] # name
alayer.type = "InnerProduct" # type
# bottom
if layer["inputs"]["input"][0].split(".")[0] == inlayername:
alayer.bottom.extend(["data"]) # need custom handling???????????????????
else:
alayer.bottom.extend([layer["inputs"]["input"][0].split(".")[0]])
# top
alayer.top.extend([layer["name"]])
# num_output
if "output_shape" in layer["attributes"]:
alayer.inner_product_param.num_output = int(layer["attributes"]["output_shape"])
# weight_filler
if "weight" in layer["attributes"]:
weightConvert(alayer, layer["attributes"]["weight"].lower(), "fc")
else:
weightConvert(alayer, "random_normal", "fc")
# bias_filler
if "bias" in layer["attributes"]:
biasConvert(alayer, layer["attributes"]["bias"].lower(), "fc")
else:
biasConvert(alayer, "zeroes", "fc")
# activation
if "activation" in layer["attributes"]:
activationConvert(net, alayer, layer["name"], layer["attributes"]["activation"])
# convert xentropy loss layer
def xentropylossConvert(layer, net):
# add layer to caffe net
alayer = net.layer.add()
# layer checkpoint setting
alayer.name = layer["name"]
alayer.type = "SoftmaxWithLoss"
alayer.bottom.extend([layer["inputs"]["logits"][0].split(".")[0]])
alayer.bottom.extend(["label"]) # need custom handling????????????????
alayer.top.extend([layer["name"]])
# convert accuracy layer
def accuracyConvert(layer, net):
# add layer to caffe net
alayer = net.layer.add()
# layer checkpoint setting
alayer.name = layer["name"]
alayer.type = "Accuracy"
alayer.bottom.extend([layer["inputs"]["logits"][0].split(".")[0]])
alayer.bottom.extend(["label"]) # need custom handling????????????????
alayer.top.extend([layer["name"]])
# convert optimizer checkpoint
def optimizerConvert(layer, sol):
# default values
sol.net = "/home/ncl/caffe/examples/msjeon/dlmdl2caffe/dlmdl2caffe.prototxt"
sol.lr_policy = "fixed"
sol.display = 50
# specified values
sol.base_lr = float(layer["attributes"]["learning_rate"])
if "beta1" in layer["attributes"]:
sol.momentum = float(layer["attributes"]["beta1"])
if "beta2" in layer["attributes"]:
sol.momentum2 = float(layer["attributes"]["beta2"])
### epsilon, train_iteration(input layer), test_iteration, test_interval????????????
# convert dl-mdl => caffe for each layer
def netConvertMdl2caffe(mdlnet, net, sol, sizelist):
for layer in mdlnet["layers"]:
# print layer
# convert in each type of layer
if layer["type"] == "input":
inputConvert(layer, net, sol)
elif layer["type"] == "conv":
convConvert(layer, net, sizelist)
elif layer["type"] == "max_pool":
poolConvert(layer, net, sizelist)
elif layer["type"] == "avg_pool":
poolConvert(layer, net, sizelist)
elif layer["type"] == "fc":
fcConvert(layer, net)
elif layer["type"] == "loss":
xentropylossConvert(layer, net)
elif layer["type"] == "accuracy":
accuracyConvert(layer, net)
elif layer["type"] == "adamoptimizer":
optimizerConvert(layer, sol)
"""
main
"""
# create caffe pb2 net, solver
net = caffe_pb2.NetParameter()
net.name = 'dlmdl2caffe'
sol = caffe_pb2.SolverParameter()
# read dl-mdl file
mdlnet = readDLMDL("../data/VGG.dlmdl")
# get dimension of all layer
sizelist = []
for layer in mdlnet["layers"]:
if layer["type"] == "input":
inlayername = copy.deepcopy(layer["name"])
sizelist.append([layer["name"], layer["attributes"]["image_size"]])
layerDim(mdlnet, layer["name"], layer["attributes"]["image_size"], sizelist)
# convert dl-mdl => caffe
netConvertMdl2caffe(mdlnet, net, sol, sizelist)
print(str(net))
print(str(sol))
# print str(mdlnet)
# print sizelist
# write to file
outFn = '../output/dlmdl2caffe.prototxt'
print('writing', outFn)
with open(outFn, 'w') as f:
f.write(str(net))
outFn2 = '../output/sol.prototxt'
print('writing', outFn2)
with open(outFn2, 'w') as f2:
f2.write(str(sol))
| [
"sys.path.append",
"copy.deepcopy",
"json.loads",
"numpy.ceil",
"caffe.proto.caffe_pb2.SolverParameter",
"caffe.proto.caffe_pb2.NetStateRule",
"caffe.proto.caffe_pb2.NetParameter"
] | [((36, 106), 'sys.path.append', 'sys.path.append', (['"""/Users/SeongHwanKim/tensorflow3/caffe-master/python"""'], {}), "('/Users/SeongHwanKim/tensorflow3/caffe-master/python')\n", (51, 106), False, 'import sys\n'), ((16246, 16270), 'caffe.proto.caffe_pb2.NetParameter', 'caffe_pb2.NetParameter', ([], {}), '()\n', (16268, 16270), False, 'from caffe.proto import caffe_pb2\n'), ((16302, 16329), 'caffe.proto.caffe_pb2.SolverParameter', 'caffe_pb2.SolverParameter', ([], {}), '()\n', (16327, 16329), False, 'from caffe.proto import caffe_pb2\n'), ((328, 348), 'copy.deepcopy', 'copy.deepcopy', (['indim'], {}), '(indim)\n', (341, 348), False, 'import copy\n'), ((3763, 3784), 'json.loads', 'json.loads', (['json_data'], {}), '(json_data)\n', (3773, 3784), False, 'import json\n'), ((6825, 6856), 'numpy.ceil', 'np.ceil', (['(indim[0] / temp_stride)'], {}), '(indim[0] / temp_stride)\n', (6832, 6856), True, 'import numpy as np\n'), ((6879, 6910), 'numpy.ceil', 'np.ceil', (['(indim[1] / temp_stride)'], {}), '(indim[1] / temp_stride)\n', (6886, 6910), True, 'import numpy as np\n'), ((7703, 7727), 'caffe.proto.caffe_pb2.NetStateRule', 'caffe_pb2.NetStateRule', ([], {}), '()\n', (7725, 7727), False, 'from caffe.proto import caffe_pb2\n'), ((16520, 16548), 'copy.deepcopy', 'copy.deepcopy', (["layer['name']"], {}), "(layer['name'])\n", (16533, 16548), False, 'import copy\n'), ((6310, 6341), 'numpy.ceil', 'np.ceil', (['(indim[0] / temp_stride)'], {}), '(indim[0] / temp_stride)\n', (6317, 6341), True, 'import numpy as np\n'), ((6367, 6398), 'numpy.ceil', 'np.ceil', (['(indim[1] / temp_stride)'], {}), '(indim[1] / temp_stride)\n', (6374, 6398), True, 'import numpy as np\n'), ((2001, 2023), 'copy.deepcopy', 'copy.deepcopy', (['tempdim'], {}), '(tempdim)\n', (2014, 2023), False, 'import copy\n'), ((1924, 1946), 'copy.deepcopy', 'copy.deepcopy', (['tempdim'], {}), '(tempdim)\n', (1937, 1946), False, 'import copy\n'), ((3637, 3659), 'copy.deepcopy', 'copy.deepcopy', (['tempdim'], {}), '(tempdim)\n', (3650, 3659), False, 'import copy\n'), ((3560, 3582), 'copy.deepcopy', 'copy.deepcopy', (['tempdim'], {}), '(tempdim)\n', (3573, 3582), False, 'import copy\n')] |
from config import *
from data import *
from utils import *
from constant import *
from nn import *
from torch.autograd import Variable
from tqdm import tqdm
import numpy as np
import os
from datetime import datetime
import pytz
model_name = 'nn_xnn_time_diff_v2'
torch.backends.cudnn.deterministic = True
seed_everything(42)
configuration = NNConfiguration()
os.environ["CUDA_VISIBLE_DEVICES"] = str(configuration.device_id)
print("CUDA_VISIBLE_DEVICES: ", os.environ["CUDA_VISIBLE_DEVICES"])
if configuration.sub_sample:
model_name += '_140k'
else:
model_name += '_all'
if configuration.use_test:
model_name += '_ut'
if configuration.debug:
model_name += '_db'
model_name += f'_{configuration.device_id}'
weight_path = f"../weights/{model_name}.model"
print(configuration.get_attributes())
data_gen = NNDataGenerator(configuration)
print(configuration.get_attributes())
valid_data = data_gen.val_data
train_data= data_gen.train_data
if configuration.use_cuda:
net = Net(configuration).cuda()
else:
net = Net(configuration)
optim = use_optimizer(net, configuration)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optim, 'min',min_lr=0.0005, factor=0.7, verbose=True)
print(net)
def get_prediction(loader, net):
net.eval()
all_scores = []
validation_loss = []
for batch_id, data in enumerate(loader):
with torch.no_grad():
item_ids = Variable(data[0]).to(device=device_type)
targets = Variable(data[1]).to(device=device_type)
past_interactions = Variable(data[2]).to(device=device_type)
past_interaction_masks = (data[3])
price_rank = Variable(data[4]).to(device=device_type)
city = Variable(data[5]).to(device=device_type)
last_item = Variable(data[6]).to(device=device_type)
impression_index = Variable(data[7]).to(device=device_type)
continuous_features = Variable(data[8]).to(device=device_type)
star = Variable(data[9]).to(device=device_type)
past_interactions_sess = Variable(data[10]).to(device=device_type)
past_actions_sess = Variable(data[11]).to(device=device_type)
last_click_item = Variable(data[12]).to(device=device_type)
last_click_impression = Variable(data[13]).to(device=device_type)
last_interact_index = Variable(data[14]).to(device=device_type)
neighbor_prices = Variable(data[15]).to(device=device_type)
other_item_ids = Variable(data[16]).to(device=device_type)
city_platform = Variable(data[17]).to(device=device_type)
prediction = net(item_ids, past_interactions, past_interaction_masks, price_rank, city, last_item, impression_index, continuous_features, star, past_interactions_sess, past_actions_sess, last_click_item, last_click_impression, last_interact_index, neighbor_prices, other_item_ids, city_platform)
loss = crit(prediction,targets).item()
prediction = prediction.detach().cpu().numpy().tolist()
all_scores += prediction
validation_loss.append(loss)
validation_loss = np.mean(validation_loss)
return all_scores, validation_loss
def evaluate_valid(val_loader, val_df, net ):
val_df['score'], val_loss = get_prediction(val_loader, net)
grouped_val = val_df.groupby('session_id')
rss = []
rss_group = {i:[] for i in range(1,26)}
incorrect_session = {}
for session_id, group in grouped_val:
scores = group['score']
sorted_arg = np.flip(np.argsort(scores))
if group['label'].values[sorted_arg][0] != 1:
incorrect_session[session_id] = (sorted_arg.values, group['label'].values[sorted_arg])
rss.append( group['label'].values[sorted_arg])
rss_group[len(group)].append(group['label'].values[sorted_arg])
mrr = compute_mean_reciprocal_rank(rss)
mrr_group = {i:(len(rss_group[i]), compute_mean_reciprocal_rank(rss_group[i])) for i in range(1,26)}
# print(mrr_group)
pickle.dump( incorrect_session, open(f'../output/{model_name}_val_incorrect_order.p','wb'))
return mrr, mrr_group, val_loss
device_type='cuda'
crit = configuration.loss()
best_mrr = 0
early_stopping = configuration.early_stopping
not_improve_round = 0
val_loader = data_gen.evaluate_data_valid()
test_loader =data_gen.instance_a_test_loader()
train_loader = data_gen.instance_a_train_loader()
n_iter = 0
stopped = False
for i in range(configuration.num_epochs):
net.train()
for batch_id, data in enumerate(tqdm(train_loader)):
optim.zero_grad()
n_iter += 1
item_ids = Variable(data[0]).to(device=device_type)
targets = Variable(data[1]).to(device=device_type)
past_interactions = Variable(data[2]).to(device=device_type)
past_interaction_masks = (data[3])
price_rank = Variable(data[4]).to(device=device_type)
city = Variable(data[5]).to(device=device_type)
last_item = Variable(data[6]).to(device=device_type)
impression_index = Variable(data[7]).to(device=device_type)
continuous_features = Variable(data[8]).to(device=device_type)
star = Variable(data[9]).to(device=device_type)
past_interactions_sess = Variable(data[10]).to(device=device_type)
past_actions_sess = Variable(data[11]).to(device=device_type)
# other_item_impressions = Variable(data[13]).to(device=device_type)
last_click_item = Variable(data[12]).to(device=device_type)
last_click_impression = Variable(data[13]).to(device=device_type)
last_interact_index = Variable(data[14]).to(device=device_type)
neighbor_prices = Variable(data[15]).to(device=device_type)
other_item_ids = Variable(data[16]).to(device=device_type)
city_platform = Variable(data[17]).to(device=device_type)
prediction = net(item_ids, past_interactions, past_interaction_masks, price_rank, city, last_item, impression_index, continuous_features, star, past_interactions_sess, past_actions_sess, last_click_item, last_click_impression, last_interact_index, neighbor_prices, other_item_ids, city_platform)
loss = crit(prediction,targets)
loss.backward()
optim.step()
mrr, mrr_group, val_loss = evaluate_valid(val_loader, valid_data, net)
if mrr > best_mrr:
print(f"improve from {best_mrr} to {mrr}")
best_mrr = mrr
not_improve_round = 0
torch.save(net.state_dict(), weight_path)
else:
print(f"didn't improve from {best_mrr} to {mrr}")
not_improve_round += 1
if not_improve_round >= early_stopping:
break
net.load_state_dict(torch.load(weight_path))
print("BEST mrr", best_mrr)
if configuration.debug:
exit(0)
test_df = data_gen.test_data
test_df['score'], _ = get_prediction(test_loader, net)
with open(f'../output/{model_name}_test_score.p', 'wb') as f:
pickle.dump( test_df.loc[:,['score', 'session_id', 'step']],f, protocol=4)
grouped_test = test_df.groupby('session_id')
predictions = []
session_ids = []
for session_id, group in grouped_test:
scores = group['score']
sorted_arg = np.flip(np.argsort(scores))
sorted_item_ids = group['item_id'].values[sorted_arg]
sorted_item_ids = data_gen.cat_encoders['item_id'].reverse_transform(sorted_item_ids)
sorted_item_string = ' '.join([str(i) for i in sorted_item_ids])
predictions.append(sorted_item_string)
session_ids.append(session_id)
prediction_df = pd.DataFrame()
prediction_df['session_id'] = session_ids
prediction_df['item_recommendations'] = predictions
print("pred df shape", prediction_df.shape)
sub_df = pd.read_csv('../input/submission_popular.csv')
sub_df.drop('item_recommendations', axis=1, inplace=True)
sub_df = sub_df.merge(prediction_df, on="session_id")
# sub_df['item_recommendations'] = predictions
sub_df.to_csv(f'../output/{model_name}.csv', index=None) | [
"numpy.argsort",
"torch.autograd.Variable",
"tqdm.tqdm",
"numpy.mean"
] | [((3210, 3234), 'numpy.mean', 'np.mean', (['validation_loss'], {}), '(validation_loss)\n', (3217, 3234), True, 'import numpy as np\n'), ((4668, 4686), 'tqdm.tqdm', 'tqdm', (['train_loader'], {}), '(train_loader)\n', (4672, 4686), False, 'from tqdm import tqdm\n'), ((7371, 7389), 'numpy.argsort', 'np.argsort', (['scores'], {}), '(scores)\n', (7381, 7389), True, 'import numpy as np\n'), ((3652, 3670), 'numpy.argsort', 'np.argsort', (['scores'], {}), '(scores)\n', (3662, 3670), True, 'import numpy as np\n'), ((4755, 4772), 'torch.autograd.Variable', 'Variable', (['data[0]'], {}), '(data[0])\n', (4763, 4772), False, 'from torch.autograd import Variable\n'), ((4814, 4831), 'torch.autograd.Variable', 'Variable', (['data[1]'], {}), '(data[1])\n', (4822, 4831), False, 'from torch.autograd import Variable\n'), ((4883, 4900), 'torch.autograd.Variable', 'Variable', (['data[2]'], {}), '(data[2])\n', (4891, 4900), False, 'from torch.autograd import Variable\n'), ((5006, 5023), 'torch.autograd.Variable', 'Variable', (['data[4]'], {}), '(data[4])\n', (5014, 5023), False, 'from torch.autograd import Variable\n'), ((5062, 5079), 'torch.autograd.Variable', 'Variable', (['data[5]'], {}), '(data[5])\n', (5070, 5079), False, 'from torch.autograd import Variable\n'), ((5123, 5140), 'torch.autograd.Variable', 'Variable', (['data[6]'], {}), '(data[6])\n', (5131, 5140), False, 'from torch.autograd import Variable\n'), ((5191, 5208), 'torch.autograd.Variable', 'Variable', (['data[7]'], {}), '(data[7])\n', (5199, 5208), False, 'from torch.autograd import Variable\n'), ((5262, 5279), 'torch.autograd.Variable', 'Variable', (['data[8]'], {}), '(data[8])\n', (5270, 5279), False, 'from torch.autograd import Variable\n'), ((5318, 5335), 'torch.autograd.Variable', 'Variable', (['data[9]'], {}), '(data[9])\n', (5326, 5335), False, 'from torch.autograd import Variable\n'), ((5401, 5419), 'torch.autograd.Variable', 'Variable', (['data[10]'], {}), '(data[10])\n', (5409, 5419), False, 'from torch.autograd import Variable\n'), ((5471, 5489), 'torch.autograd.Variable', 'Variable', (['data[11]'], {}), '(data[11])\n', (5479, 5489), False, 'from torch.autograd import Variable\n'), ((5625, 5643), 'torch.autograd.Variable', 'Variable', (['data[12]'], {}), '(data[12])\n', (5633, 5643), False, 'from torch.autograd import Variable\n'), ((5699, 5717), 'torch.autograd.Variable', 'Variable', (['data[13]'], {}), '(data[13])\n', (5707, 5717), False, 'from torch.autograd import Variable\n'), ((5771, 5789), 'torch.autograd.Variable', 'Variable', (['data[14]'], {}), '(data[14])\n', (5779, 5789), False, 'from torch.autograd import Variable\n'), ((5839, 5857), 'torch.autograd.Variable', 'Variable', (['data[15]'], {}), '(data[15])\n', (5847, 5857), False, 'from torch.autograd import Variable\n'), ((5906, 5924), 'torch.autograd.Variable', 'Variable', (['data[16]'], {}), '(data[16])\n', (5914, 5924), False, 'from torch.autograd import Variable\n'), ((5972, 5990), 'torch.autograd.Variable', 'Variable', (['data[17]'], {}), '(data[17])\n', (5980, 5990), False, 'from torch.autograd import Variable\n'), ((1437, 1454), 'torch.autograd.Variable', 'Variable', (['data[0]'], {}), '(data[0])\n', (1445, 1454), False, 'from torch.autograd import Variable\n'), ((1500, 1517), 'torch.autograd.Variable', 'Variable', (['data[1]'], {}), '(data[1])\n', (1508, 1517), False, 'from torch.autograd import Variable\n'), ((1573, 1590), 'torch.autograd.Variable', 'Variable', (['data[2]'], {}), '(data[2])\n', (1581, 1590), False, 'from torch.autograd import Variable\n'), ((1688, 1705), 'torch.autograd.Variable', 'Variable', (['data[4]'], {}), '(data[4])\n', (1696, 1705), False, 'from torch.autograd import Variable\n'), ((1748, 1765), 'torch.autograd.Variable', 'Variable', (['data[5]'], {}), '(data[5])\n', (1756, 1765), False, 'from torch.autograd import Variable\n'), ((1814, 1831), 'torch.autograd.Variable', 'Variable', (['data[6]'], {}), '(data[6])\n', (1822, 1831), False, 'from torch.autograd import Variable\n'), ((1886, 1903), 'torch.autograd.Variable', 'Variable', (['data[7]'], {}), '(data[7])\n', (1894, 1903), False, 'from torch.autograd import Variable\n'), ((1961, 1978), 'torch.autograd.Variable', 'Variable', (['data[8]'], {}), '(data[8])\n', (1969, 1978), False, 'from torch.autograd import Variable\n'), ((2022, 2039), 'torch.autograd.Variable', 'Variable', (['data[9]'], {}), '(data[9])\n', (2030, 2039), False, 'from torch.autograd import Variable\n'), ((2113, 2131), 'torch.autograd.Variable', 'Variable', (['data[10]'], {}), '(data[10])\n', (2121, 2131), False, 'from torch.autograd import Variable\n'), ((2187, 2205), 'torch.autograd.Variable', 'Variable', (['data[11]'], {}), '(data[11])\n', (2195, 2205), False, 'from torch.autograd import Variable\n'), ((2273, 2291), 'torch.autograd.Variable', 'Variable', (['data[12]'], {}), '(data[12])\n', (2281, 2291), False, 'from torch.autograd import Variable\n'), ((2351, 2369), 'torch.autograd.Variable', 'Variable', (['data[13]'], {}), '(data[13])\n', (2359, 2369), False, 'from torch.autograd import Variable\n'), ((2427, 2445), 'torch.autograd.Variable', 'Variable', (['data[14]'], {}), '(data[14])\n', (2435, 2445), False, 'from torch.autograd import Variable\n'), ((2499, 2517), 'torch.autograd.Variable', 'Variable', (['data[15]'], {}), '(data[15])\n', (2507, 2517), False, 'from torch.autograd import Variable\n'), ((2570, 2588), 'torch.autograd.Variable', 'Variable', (['data[16]'], {}), '(data[16])\n', (2578, 2588), False, 'from torch.autograd import Variable\n'), ((2640, 2658), 'torch.autograd.Variable', 'Variable', (['data[17]'], {}), '(data[17])\n', (2648, 2658), False, 'from torch.autograd import Variable\n')] |
# Copyright (c) 2018 PaddlePaddle 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.
"""
CIFAR-10 dataset.
This module will download dataset from
https://www.cs.toronto.edu/~kriz/cifar.html and parse train/test set into
paddle reader creators.
The CIFAR-10 dataset consists of 60000 32x32 colour images in 10 classes,
with 6000 images per class. There are 50000 training images and 10000 test images.
"""
from PIL import Image
from PIL import ImageOps
import numpy as np
import cPickle
import itertools
import paddle.dataset.common
import tarfile
from absl import flags
FLAGS = flags.FLAGS
flags.DEFINE_boolean("random_flip_left_right", True,
"random flip left and right")
flags.DEFINE_boolean("random_flip_up_down", False, "random flip up and down")
flags.DEFINE_boolean("cutout", True, "cutout")
flags.DEFINE_boolean("standardize_image", True, "standardize input images")
flags.DEFINE_boolean("pad_and_cut_image", True, "pad and cut input images")
__all__ = ['train10', 'test10', 'convert']
URL_PREFIX = 'https://www.cs.toronto.edu/~kriz/'
CIFAR10_URL = URL_PREFIX + 'cifar-10-python.tar.gz'
CIFAR10_MD5 = 'c58f30108f718f92721af3b95e74349a'
paddle.dataset.common.DATA_HOME = "dataset/"
image_size = 32
image_depth = 3
half_length = 8
def preprocess(sample, is_training):
image_array = sample.reshape(3, image_size, image_size)
rgb_array = np.transpose(image_array, (1, 2, 0))
img = Image.fromarray(rgb_array, 'RGB')
if is_training:
if FLAGS.pad_and_cut_image:
# pad and ramdom crop
img = ImageOps.expand(
img, (2, 2, 2, 2), fill=0) # pad to 36 * 36 * 3
left_top = np.random.randint(5, size=2) # rand 0 - 4
img = img.crop((left_top[0], left_top[1], left_top[0] + image_size,
left_top[1] + image_size))
if FLAGS.random_flip_left_right and np.random.randint(2):
img = img.transpose(Image.FLIP_LEFT_RIGHT)
if FLAGS.random_flip_up_down and np.random.randint(2):
img = img.transpose(Image.FLIP_TOP_BOTTOM)
img = np.array(img).astype(np.float32)
if FLAGS.standardize_image:
# per_image_standardization
img_float = img / 255.0
mean = np.mean(img_float)
std = max(np.std(img_float), 1.0 / np.sqrt(3 * image_size * image_size))
img = (img_float - mean) / std
if is_training and FLAGS.cutout:
center = np.random.randint(image_size, size=2)
offset_width = max(0, center[0] - half_length)
offset_height = max(0, center[1] - half_length)
target_width = min(center[0] + half_length, image_size)
target_height = min(center[1] + half_length, image_size)
for i in range(offset_height, target_height):
for j in range(offset_width, target_width):
img[i][j][:] = 0.0
img = np.transpose(img, (2, 0, 1))
return img.reshape(3 * image_size * image_size)
def reader_creator(filename, sub_name, is_training):
def read_batch(batch):
data = batch['data']
labels = batch.get('labels', batch.get('fine_labels', None))
assert labels is not None
for sample, label in itertools.izip(data, labels):
yield preprocess(sample, is_training), int(label)
def reader():
with tarfile.open(filename, mode='r') as f:
names = [
each_item.name for each_item in f if sub_name in each_item.name
]
names.sort()
for name in names:
print("Reading file " + name)
batch = cPickle.load(f.extractfile(name))
for item in read_batch(batch):
yield item
return reader
def train10():
"""
CIFAR-10 training set creator.
It returns a reader creator, each sample in the reader is image pixels in
[0, 1] and label in [0, 9].
:return: Training reader creator
:rtype: callable
"""
return reader_creator(
paddle.dataset.common.download(CIFAR10_URL, 'cifar', CIFAR10_MD5),
'data_batch', True)
def test10():
"""
CIFAR-10 test set creator.
It returns a reader creator, each sample in the reader is image pixels in
[0, 1] and label in [0, 9].
:return: Test reader creator.
:rtype: callable
"""
return reader_creator(
paddle.dataset.common.download(CIFAR10_URL, 'cifar', CIFAR10_MD5),
'test_batch', False)
def fetch():
paddle.dataset.common.download(CIFAR10_URL, 'cifar', CIFAR10_MD5)
def convert(path):
"""
Converts dataset to recordio format
"""
paddle.dataset.common.convert(path, train10(), 1000, "cifar_train10")
paddle.dataset.common.convert(path, test10(), 1000, "cifar_test10")
| [
"tarfile.open",
"numpy.std",
"numpy.transpose",
"PIL.ImageOps.expand",
"numpy.random.randint",
"numpy.mean",
"absl.flags.DEFINE_boolean",
"itertools.izip",
"numpy.array",
"PIL.Image.fromarray",
"numpy.sqrt"
] | [((1118, 1204), 'absl.flags.DEFINE_boolean', 'flags.DEFINE_boolean', (['"""random_flip_left_right"""', '(True)', '"""random flip left and right"""'], {}), "('random_flip_left_right', True,\n 'random flip left and right')\n", (1138, 1204), False, 'from absl import flags\n'), ((1222, 1299), 'absl.flags.DEFINE_boolean', 'flags.DEFINE_boolean', (['"""random_flip_up_down"""', '(False)', '"""random flip up and down"""'], {}), "('random_flip_up_down', False, 'random flip up and down')\n", (1242, 1299), False, 'from absl import flags\n'), ((1300, 1346), 'absl.flags.DEFINE_boolean', 'flags.DEFINE_boolean', (['"""cutout"""', '(True)', '"""cutout"""'], {}), "('cutout', True, 'cutout')\n", (1320, 1346), False, 'from absl import flags\n'), ((1347, 1422), 'absl.flags.DEFINE_boolean', 'flags.DEFINE_boolean', (['"""standardize_image"""', '(True)', '"""standardize input images"""'], {}), "('standardize_image', True, 'standardize input images')\n", (1367, 1422), False, 'from absl import flags\n'), ((1423, 1498), 'absl.flags.DEFINE_boolean', 'flags.DEFINE_boolean', (['"""pad_and_cut_image"""', '(True)', '"""pad and cut input images"""'], {}), "('pad_and_cut_image', True, 'pad and cut input images')\n", (1443, 1498), False, 'from absl import flags\n'), ((1904, 1940), 'numpy.transpose', 'np.transpose', (['image_array', '(1, 2, 0)'], {}), '(image_array, (1, 2, 0))\n', (1916, 1940), True, 'import numpy as np\n'), ((1951, 1984), 'PIL.Image.fromarray', 'Image.fromarray', (['rgb_array', '"""RGB"""'], {}), "(rgb_array, 'RGB')\n", (1966, 1984), False, 'from PIL import Image\n'), ((3406, 3434), 'numpy.transpose', 'np.transpose', (['img', '(2, 0, 1)'], {}), '(img, (2, 0, 1))\n', (3418, 3434), True, 'import numpy as np\n'), ((2777, 2795), 'numpy.mean', 'np.mean', (['img_float'], {}), '(img_float)\n', (2784, 2795), True, 'import numpy as np\n'), ((2971, 3008), 'numpy.random.randint', 'np.random.randint', (['image_size'], {'size': '(2)'}), '(image_size, size=2)\n', (2988, 3008), True, 'import numpy as np\n'), ((3730, 3758), 'itertools.izip', 'itertools.izip', (['data', 'labels'], {}), '(data, labels)\n', (3744, 3758), False, 'import itertools\n'), ((2094, 2136), 'PIL.ImageOps.expand', 'ImageOps.expand', (['img', '(2, 2, 2, 2)'], {'fill': '(0)'}), '(img, (2, 2, 2, 2), fill=0)\n', (2109, 2136), False, 'from PIL import ImageOps\n'), ((2199, 2227), 'numpy.random.randint', 'np.random.randint', (['(5)'], {'size': '(2)'}), '(5, size=2)\n', (2216, 2227), True, 'import numpy as np\n'), ((2422, 2442), 'numpy.random.randint', 'np.random.randint', (['(2)'], {}), '(2)\n', (2439, 2442), True, 'import numpy as np\n'), ((2540, 2560), 'numpy.random.randint', 'np.random.randint', (['(2)'], {}), '(2)\n', (2557, 2560), True, 'import numpy as np\n'), ((2628, 2641), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (2636, 2641), True, 'import numpy as np\n'), ((2814, 2831), 'numpy.std', 'np.std', (['img_float'], {}), '(img_float)\n', (2820, 2831), True, 'import numpy as np\n'), ((3854, 3886), 'tarfile.open', 'tarfile.open', (['filename'], {'mode': '"""r"""'}), "(filename, mode='r')\n", (3866, 3886), False, 'import tarfile\n'), ((2839, 2875), 'numpy.sqrt', 'np.sqrt', (['(3 * image_size * image_size)'], {}), '(3 * image_size * image_size)\n', (2846, 2875), True, 'import numpy as np\n')] |
#**************************************************
#Python
import numpy as np
import pandas as pd
import os.path
import subprocess
import math
import datetime
import matplotlib
import os.path
from copy import copy, deepcopy
from matplotlib import pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from datetime import datetime, timedelta
#settings
start_date=datetime(2014,12,1)
start_date_scen=start_date+timedelta(days=20)
num_days=20
num_days_scen=7
dtdz=-0.006 # temperature gradient (deg C km-1)
hstat=1709 # elevation of weather station
topo=[0.78,1768,44,0.0172] # area, elevation, max depth, volume
elev_lake=topo[1] # elevation of lake
# ---- scenario - INPUT / ADJUSTMENT / CALIBRATION
scenprec_corrfact=1.0 # Factor to correct precipitation in second week of scenario - normally strongly overestimated...
ice_thickness_scen=13 # (cm) Ice thickness (measured) at start of scenario period (default: -9999)
snow_thickness_scen=0 # (cm w.==!) snow thickness (measured) at start of scenario period (default: -9999)
snow_dens_scen=600 # (kg m-3) snow density (measured/estimated) at start of scenario period (default: -9999)
slushice_thickness_scen=0 # (cm) thickness of refrozen ice ("Sandwich") at start of scenario period (default: -9999)
# ------------------
format_csv='y' # raw climate file in csv format
# prepare climate data file
prepare='n'
twater_ini=[4,4,20] # [Tmin,Tmax,break(m)]
int_slush=[[18,1],[20,1]] # dates to insert slush
vol_slush=[0.02,0.02] # volumes of inserted slush in m w.e. (same length as int_slush)
dtdz=-0.006 # temperature gradient (deg C km-1)
hstat=1709 # elevation of weather station
alpha_ice=0.3 # albedo of ice
alpha_water=0.12 # albedo of water
alpha_snow0=0.92 # albedo of fresh snow
alpha_snow1=0.5 # albedo of very old snow
turbulent_fact=1.5 # 5 # factor to increase transfer of water heat to base of ice (to be calibrated)
corrprec=1 # Korrektur des Niederschlags
lakedepth=25 # depth of lake m
first_freezeparam=1.0 # [-] Parameter to accelerate or decelerate the first freezing of the lake
# temperature of river entering the lake and lake geometry
topo=[0.78,1768,44,0.0172] # area, elevation, max depth, volume
flow=1 #5.8 # [m3/s] river charactersitic inflow
flow_tcorr=-5 # [deg C] correct temperature of stream flow for elevation / snow melt relative to air temperature
flow_tmin=0 # [deg C] minimum temperature of stream
wwin=[1.2,1,0.8] # weighting of lake water layering in different depths
elev_lake=topo[1] # elevation of lake
# number of iterations for heat conduction (per hour)
iterations_si=150 # snow / ice
iterations_w=150 # water
# number of iterations for snow surface temperature
dt_snoit=120 # s
freq_plots=6 # (hours) frequency of output plots
language_plots='e' # language of plots (d: deutsch, e: english)
# -----------------------------
# parameters / constants
kice=2.33 # conductivity ice [J s-1 K-1 m-1]
kwater=0.56 # conductivity water
kair=0.001
cice=1890000 # heat capacity of ice
cair=1297
cwater=4217700 # [J m-3 K-1]
emissivity_atm=0.95
emissivity_ice=0.966
emissivity_water=0.957
emissivity_snow=0.97
attenuation_water=1 # m-1
attenuation_ice0=1.0 # m-1
attenuation_snow=10 # m-1 ??? 10
at_rho=250
fact_at=0.1 # increase in ice attenuation per day (ageing)
rho=917 # ice density
rho_water=1000
rho_snow0=70 # density of fresh snow
rho_max=400
compression='y'
rho_compression=450 # kg m-3
L=334000*rho # [J m-3] latent heat of fusion
Lhe=2260000 # [J kg-1] latent heat of evapoation
Lhs=2594000 # [J kg-1] latent heat of sublimation
bulk_exchange_s=0.3*pow(10,-3) # bulk exchange coefficients for sensible heat flux (to be calibrated)
bulk_exchange_l=0.8*pow(10,-3) # bulk exchange coefficients for latent heat flux (to be calibrated)
bulk_exchange_s=1.5*pow(10,-3) # bulk exchange coefficients for sensible heat flux (to be calibrated)
bulk_exchange_l=1.5*pow(10,-3) # bulk exchange coefficients for latent heat flux (to be calibrated)
# -----------------------
# settings
dz=0.005 # nodespacing (ice)
dzs=0.0025 # snow
dzw=0.2 # water
nodes=[lakedepth/dzw,200,200] # water, ice, snow
dt=3600 # [s] timestep
s_b=5.67*pow(10,-8) # <NAME>
t_wmin=4 # minimum temperature of water (density)
meltlast=0
# *************************************************
# read files
df=pd.read_csv('../data/raw/samedan_2014_2015.dat',header=None,encoding='latin-1',skiprows=14, sep='\s+',names=['STA','Year','Mo','Day','HH','MM','Tair','RH','Wind','Rad','Pressure','Prec'])
df=df.replace(32767, np.NaN) #Assign missing data as null
df=df.drop('STA',axis=1)
error=df.isnull() # Grab DataFrame rows where column has errors
right=error[error['Tair']].index.tolist()
a=np.array(right)
b=a-1
b[0]=0
columns=['Tair','RH','Wind','Rad','Pressure','Prec']
df['Year']=df['Year'].astype(int)
df['Mo']=df['Mo'].astype(int)
df['Day']=df['Day'].astype(int)
for i in range(0, a.size):
df.loc[a[i],columns]=df.loc[b[i],columns] #Use previous data to fill #Error last column not filled
df.loc[0,columns]=df.loc[1,columns]
for i in range(0, df.shape[0]):
t = datetime(df['Year'][i], df['Mo'][i], df['Day'][i],df['HH'][i], 0)
df.loc[i,'When']=t
df.loc[i,'DoY']=t.timetuple().tm_yday
df['DoY']=df['DoY'].astype(int)
df['When'] = pd.to_datetime(df['When'])
df.to_csv('../data/interim/2015_SAM.csv', sep='\t')
# Cloudiness
clmax=np.zeros(shape=(365,24),dtype=float)
for i in range(0,365):
for j in range(0,24):
l=np.where(np.logical_and(np.logical_and(df['HH']==j, i-5<=df['DoY']), df['DoY']<=i+5))
a=np.array([])
a=np.append(0,l)
a=np.delete(a,0)
if a.size:
clmax[i,j]=df.loc[a,'Rad'].max()/0.98
cl=np.empty(shape=df.shape[0],dtype=float)
for row in df.iterrows():
a=clmax[df.loc[row[0],'DoY']-1,df.loc[row[0],'HH']]
if a!=0:
cl[row[0]]=(1-df.loc[row[0],'Rad']/a)
# cloudiness at nighttime - use average of day before
if df.loc[row[0],'Rad']<10:
l=np.where(np.logical_and(np.logical_and(df['DoY']==df.loc[row[0],'DoY'], 10<=df['HH']), df['HH']<=15))
b=np.array([])
b=np.append(0,l)
b=np.delete(b,0)
if b.size:
cl[row[0]]=np.mean(cl[b])
else:
cl[row[0]]=cl[row[0]-1]
df['Cl']=cl
#Select Data
mask = (df['When'] >= start_date) & (df['When'] < start_date_scen+ timedelta(days=num_days_scen))
df=df.loc[mask]
df=df.reset_index()
df['Tair']+=(elev_lake-hstat)*dtdz
df['Pressure']*=100
df['Prec']/=1000
df['rho_air']=df['Pressure']/(287.058*(df['Tair']+273.15))
df['ew']=6.1094*np.exp((17.625 * df['Tair'])/(df['Tair']+243.04))*(df['RH']/100)*100
df['huma']=0.622*df['ew']/abs(df['Pressure']-df['ew']) # specific air humidity
df = df[['When','Rad', 'Tair', 'RH', 'Wind','Pressure','Prec','Cl','ew','rho_air','huma','DoY']]
df=df.round(7)
#output csv
df.to_csv('../data/interim/cloud.csv')
dfs=pd.read_csv('../data/raw/forecast2016.csv',encoding='latin-1',skiprows=1, sep=';')
#Clean file
df['When'] = pd.to_datetime(df['When'])
df['Year']=df['When'].apply(lambda x:x.year)
df['Mo']=df['When'].apply(lambda x:x.month)
df['Day']=df['When'].apply(lambda x:x.day)
mask =(df['When'] < start_date+ timedelta(days=num_days))
df=df.loc[mask]
df=df.reset_index()
#Clean Scenario file
dfs1=dfs[0:14] #WEEK1
dfs1=dfs1.drop('Unnamed: 11', axis=1)
i=1
dfp=pd.DataFrame({'A' : []})
while i<=dfs1.shape[0]:
dfp=dfp.append(dfs1.loc[dfs1.index[i]])
dfs1=dfs1.drop(dfs1.index[i],axis=0)
i=i+1
dfp=dfp.drop('A',axis=1)
dfp=dfp[['day','2','5','8','11','14','17','20','23']]
dfs2=dfs[15:22] #WEEK2
dfs2=dfs2.drop({'Unnamed: 11','14','17','20','23'}, axis=1)
dfs2.columns = ['year', 'month','day','Tmax','Tmin','Prec','Prec-percent']
dfs2=dfs2.reset_index()
#Daily Temperature Ranges
dfs1= dfs1.apply(pd.to_numeric, errors='coerce')
for index,row in dfs1.iterrows():
dfs1.loc[index,'Trange']=dfs1.loc[index,['2','5','8','11','14','17','20','23']].max()-dfs1.loc[index,['2','5','8','11','14','17','20','23']].min()
dfs2= dfs2.apply(pd.to_numeric, errors='coerce')
dfs2['Trange']=dfs2['Tmax']-dfs2['Tmin']
k=0
l=[]
dft=pd.DataFrame({'A' : []})
dff=pd.DataFrame({'A' : []})
c=0
for i in range(0,num_days):
run=True
k=0
while run:
l.append(df.loc[int(24*i+k),'Tair'])
k=k+1
if k==24:
run=False
l=np.array(l)
dft.loc[i,'Tr']=l.max()-l.min()
dft.loc[i,'When']=df.loc[int(24*i),'When']
l=[]
#Select Climate variables using daily temperature range matches
j=0
for index,row in dfs1.iterrows():
b=0
l=np.array([])
run=True
l=abs(dfs1.loc[index,'Trange']-dft['Tr'])
c=l.min()
h=np.where(l==c)
h=h[0]
dff=dff.append(dft.loc[h[h.size-1]])
j=j+1
dff=dff.drop('A',axis=1)
dff=dff.reset_index()
dft=dft.reset_index()
dfs1=dfs1.reset_index()
for index,row in dfs2.iterrows():
b=0
l=np.array([])
l=abs(dfs2.loc[index,'Trange']-dft['Tr'])
c=l.min()
h=np.where(l==c)
h=h[0]
dff=dff.append(dft.loc[h[h.size-1]])
j=j+1
dff=dff.drop('A',axis=1)
dff=dff.reset_index()
dft=dft.reset_index()
dfs2=dfs2.reset_index()
dft['When'] = pd.to_datetime(dft['When'])
dft['Date']= dft['When'].apply(lambda x:x.date())
dff['When'] = pd.to_datetime(dff['When'])
dff['Day']= dff['When'].apply(lambda x:x.day)
#Create scenario files
dfg=pd.DataFrame({'A' : []})
c=0
for index,row in dff.iterrows():
l=np.where(df['Day']==dff['Day'][index])
l=l[0]
j=0
while j<24:
dfg=dfg.append(df.loc[l[0]+j],ignore_index=True)
dfg.loc[c,'Date']=start_date_scen+timedelta(days=int(index),hours=j)
j=j+1
c=c+1
dfg=dfg.drop('A',axis=1)
dfg=dfg.reset_index()
dfp=dfp.reset_index()
#Use forecast2016
j=0
for i in range(0,7):
l=np.where(dfs1['day']==dfg.loc[j,'Date'].day)
k=0
c=0
if len(l[0])>0:
while c!=24:
dfg.loc[j+c,'Tair']=dfs1.iloc[l[0][0],4+k]
dfg.loc[j+c,'Prec']=dfp.iloc[l[0][0],2+k]
if dfg.loc[j+c,'Prec']=='-':
dfg.loc[j+c,'Prec']=0
c=c+1
if c%3==0:
k=k+1
j=j+24
#WEEK2
temp_dist=[0.2,0,0.1,0.4,0.8,1,0.7,0.4,0.3]
for i in range(0,7):
dtt=dfs2.loc[i,'Tmax']-dfs2.loc[i,'Tmin']
dfs2.loc[i,'Tair']=dfs2.loc[i,'Tmax']+dtt
dfs2.loc[i,'Prec']=dfs2.loc[i,'Prec']*dfs2.loc[i,'Prec-percent']/100/8
c=dfg.shape[0]
for i in range(c,c+7*24):
dfg.loc[i,'Date']=dfg.loc[i-1,'Date']+ timedelta(hours=1)
dfg.loc[i,'Tair']=dfs2.loc[math.floor((i-c)/24),'Tmax']+dtt*temp_dist[math.floor((i-c)/24)]
dfg.loc[i,'Prec']=dfs2.loc[math.floor((i-c)/24),'Prec']
dfg['Prec']=dfg['Prec'].astype(float)
dfg['Prec']=(dfg['Prec'])/3000
dfg=dfg.round(5)
dfg['Prec']=dfg['Prec'].astype(float)
dfg['Prec']=(dfg['Prec'])/3000
dfg=dfg.round(5)
dfg['Date'] = pd.to_datetime(dfg['Date'])
#Add Original Weather Data
df['Time'],df['Date']= df['When'].apply(lambda x:x.time()), df['When'].apply(lambda x:x.date())
mask =(dfg['Date'] < start_date_scen+ timedelta(days=num_days_scen))
dfg=dfg.loc[mask]
dfg['Time'],dfg['Date']= dfg['Date'].apply(lambda x:x.time()), dfg['Date'].apply(lambda x:x.date())
df=pd.concat([pd.DataFrame(df), dfg], ignore_index=True)
df=pd.concat([pd.DataFrame(df), dfg], ignore_index=True)
#output csv
df = df[['When','Date','Time','Rad', 'Tair', 'RH', 'Wind','Pressure','Prec','Cl','huma','rho_air']]
df=df.round(7)
df.to_csv('../data/interim/scenario.csv')
#variables
ice=np.full(nodes[1],np.inf)
snow=np.full((3,nodes[2]),np.inf)
df['Date'] = pd.to_datetime(df['Date'])
nodes=list(map(int, nodes))
fr=0
sn=0
im=0
c=0
i_slush=0
Qbmelt=0
Qswi_i=0.0
ci_icest=0
water=np.zeros(shape=nodes[0])
water+=twater_ini[0]
for i in range(nodes[0]-1,-1,-1):
d=i*dzw
if d< twater_ini[2]:
water[i]=water[i]+((((twater_ini[2]/dzw)-i)*(twater_ini[1]-twater_ini[0]))/(twater_ini[2]/dzw))
slush=np.full((3,nodes[2]),0.0)
icethick=np.full(df.shape[0],0.0)
load=np.full((2,df.shape[0]),0.0)
mtemp=np.full((3,df.shape[0]),0.0)
stype=np.full(df.shape[0],0.0)
snowthick=deepcopy(stype)
icet=deepcopy(stype)
snow_albedo=deepcopy(stype)
slush_thick=deepcopy(icethick)
i_age=np.full(df.shape[0],np.inf)
dfo=pd.DataFrame({'Type' : []})
dfo['Temp']=np.inf
dfo['Date']=df['Date'].dt.date
dfo['Time']=df['Time']
dfo['Icethick']=0
dfo['Snowthick']=0
with PdfPages('../data/processed/figures.pdf') as pdf:
for index in range(0,df.shape[0]):
l=np.where(snow[0,]!=np.inf)
l=l[0]
ci=l.size
jj=np.where(ice!=np.inf)
cj=jj[0].size
l3=np.where(water!=np.inf)
ch=l3[0].size
if ci>0:
tt=snow[0,ci-1]
print(index,'Snow')
print(snow[0,0:ci])
dfo.loc[index,'Type']='Snow'
if ci==0 and cj>1:
tt=ice[0]
print(index,'Ice')
print(ice[0:5])
dfo.loc[index,'Type']='Ice'
if cj==0:
tt=water[0]
print(index,'Water')
print(water[0:5])
dfo.loc[index,'Type']='Water'
dfo.loc[index,'Temp']=tt
if np.isnan(tt) or tt==np.inf:
print(snow[0,])
exit()
ew=6.1094*np.exp((17.625 * tt)/(tt+243.04))*100
hum0=0.622*ew/abs(df.loc[index,'Pressure']-ew)
# *************************************************
# *************************************************
# SNOW
tes=deepcopy(snow[0,])
tls=deepcopy(tes)
# accumulation
t_threshold=1.25
ptt=df.loc[index,'Prec']
if df.loc[index,'Tair']>t_threshold+1:
df.loc[index,'Prec']=0
if df.loc[index,'Tair']<t_threshold+1 and df.loc[index,'Tair']>t_threshold-1:
df.loc[index,'Prec']=df.loc[index,'Prec']*(1-(df.loc[index,'Tair']-(t_threshold-1))/2)
df.loc[index,'p_liq']=ptt-df.loc[index,'Prec']
if ice[0]==np.inf:
df.loc[index,'Prec']=0
sn=sn+df.loc[index,'Prec']
if sn>=dzs:
if snow[0,0]==np.inf:
snow[0,0]=ice[0]
sn=sn-dzs
l=np.where(snow[0,]==np.inf)
l=l[0]
snow[0,l[0]]=min([df.loc[index,'Tair'],0])
snow[1,l[0]]=rho_snow0/1000
#artificial compression of snow
if compression=='y':
snow[1,l[0]]=rho_compression/1000
snow[2,l[0]]=1/24
#update snow density and albedo
ts_snow=21.9
l=np.where(snow[0,]!=np.inf)
l=l[0]
if l.size!=0:
for i in range(0,l.size):
if snow[1,i]<rho_max/1000 or snow[1,i]==np.inf:
snow[1,i]=(rho_max-(rho_max-rho_snow0)*math.exp(-0.03*pow((0.01*rho_max),0.5)*snow[2,i]))/1000
snow[1,0]=0.2
if snow[2,i]!=np.inf:
alpha_snow=alpha_snow1+(alpha_snow0-alpha_snow1)*math.exp((-1)*snow[2,i]/ts_snow)
if snow[2,i]!=np.inf:
snow[2,i]=snow[2,i]+1/24
else:
alpha_snow=0.85
# arrays for capacity and conductivity depending on density for snow
csnow=np.full(nodes[2],0.0)
ksnow=deepcopy(csnow)
for i in range(0,nodes[2]):
if snow[0,i] != np.inf:
csnow[i]=(1-snow[1,i])*cair+snow[1,i]*cice
if snow[0,i] != np.inf:
ksnow[i]=(2.93*pow(snow[1,i],2))+0.01 # according to Mellor (1977)
# update capacity and conductivity if slush is present
if slush[0,i]!= 0:
c=slush[1,i]*cwater+(1-slush[1,i])*cice
k=slush[1,i]*kwater+(1-slush[1,i])*kice
if slush[2,i]!=0:
ff=(slush[0,i]/slush[2,i])*(1-snow[1,i])
csnow[i]=(1-snow[1,i]-ff)*cair+snow[1,i]*cice+ff*c
ksnow[i]=(1-snow[1,i]-ff)*kair+snow[1,i]*kice+ff*k
# ------- energy balance snow
Qswi=(1-alpha_snow)*df.loc[index,'Rad']
Qswo=(-1)*alpha_snow*df.loc[index,'Rad'] # outgoing short wave
Qlwi=(0.68+0.0036*pow(df.loc[index,'huma'],0.5))*(1+0.18*pow(df.loc[index,'Cl'],2))*emissivity_atm*s_b*pow((df.loc[index,'Tair']+273.15),4)
Qe=df.loc[index,'rho_air']*Lhs*bulk_exchange_l*(df.loc[index,'huma']-hum0)*df.loc[index,'Wind']
if df.loc[index,'Tair']> 1 :
Qp=df.loc[index,'p_liq']*(df.loc[index,'Tair']-1)*cwater/dt
else:
Qp=0
gamma=math.exp(-attenuation_snow*dzs/(at_rho/1000.))
# iterate for snow surface temperature
if snow[0,0]== np.inf :
dt_snoit_tt=1
else:
dt_snoit_tt=dt_snoit
snit=dt/dt_snoit_tt
l=np.where(snow[0,] != np.inf)
l=l[0]
ci=l.size
snit=int(snit)
for it in range(0,snit):
if snow[0,0]==np.inf :
tsno=0
else:
if it==0:
tsno=snow[0,l[ci-1]]
else:
tsno=tt_ts
tt_ts=tsno
Qlwo=(-1)*emissivity_snow*s_b*pow((tsno+273.15),4)
Qc=df.loc[index,'rho_air']*cair*bulk_exchange_s*(df.loc[index,'Tair']-tsno)*df.loc[index,'Wind']
Q0snow=(1-gamma)*Qswi+Qlwi+Qlwo+Qc+Qe+Qp
# calculate temperature of uppermost layer with energy balance
if ci > 1 :
tt_ts=tt_ts+Q0snow*dt_snoit_tt/(csnow[l[ci-1]]*(dzs/snow[1,l[ci-1]]))
# done iteration for snow surface temperature
l=np.where(snow[0,] != np.inf)
l=l[0]
ci=l.size
if ci > 1 :
# attribute surface temperature
tls[l[ci-1]]=tt_ts
tls[0]=ice[0]
for i in range(ci-2,0,-1):
tls[l[ci-2]]=tls[l[ci-1]]+(math.exp(-attenuation_snow*(i+1)*dzs/(at_rho/1000))-math.exp(-attenuation_snow*i*dzs/(at_rho/1000)))*Qswi*dt/(csnow[l[ci-1]]*(dzs/snow[1,l[ci-1]]))
Qswi_s=Qswi*math.exp(-attenuation_snow*(ci-1)*dzs/(at_rho/1000))
# ----- snow evaporation
if Qe < 0 :
sn=sn+Qe*dt/(Lhs*1000)
# ----- snow melt
if Q0snow > 0 and 0<=tls[l[ci-1]] :
Qmelt=Q0snow+(tls[l[ci-1]]*csnow[l[ci-1]]*(dzs/snow[1,l[ci-1]])/dt)
melt=Qmelt/L*dt
if slush[1,l[ci-1]]!=0:
m=melt*(dzs/(dzs+slush[0,l[ci-1]]*(slush[1,l[ci-1]])))
else:
m=melt
sn=sn-m
tls[l[ci-1]]=0
else:
melt=meltlast
# reduce snow
if sn <= -dzs :
sn=sn+dzs
tls[l[ci-1]]=np.inf
l=np.where(tls != np.inf)
l=l[0]
ci=l.size
# add liquid precipitation to melt water
melt=melt+df.loc[index,'p_liq']
# ----- refreezing of melt water
if melt > 0 and ci>2:
for j in range(ci-2,0,-1) :
re=(-1)*snow[0,j]*csnow[j]*(dzs/snow[1,j])/L
if melt > re :
tls[j]=0
elif re > 0 :
tls[j]=(1-melt/re)*snow[0,j]
if melt > re :
melt=melt-re
elif re > 0:
melt=0
# ----- slush formation (melt water in snow pore space)
if melt > 0 :
for j in range(1,ci):
sp=dzs/snow[1,j]*(1-snow[1,j])
a=sp-slush[0,j]
slush[2,j]=sp
if melt < a and melt != 0 :
slush[0,j]=slush[0,j]+melt
melt=0
slush[1,j]=1
if melt > a :
melt=melt-a
slush[0,j]=sp
if melt < 0 :
melt=0
if slush[0,j] < 0 :
slush[0,j]=0
jj=np.where(snow[0,] == np.inf)
jj=jj[0]
slush[0,jj]=0
if jj.size>0:
if jj[0]<= 1 :
slush[0,0:2]=dzs
# ----- manual slush injection (melt water in snow pore space) - injection at 12.00
if vol_slush[0] != np.inf :
jj=np.where(df['Date'][index].day == int_slush[0] and df['Date'][index].month == int_slush[1])
cj=jj[0].size
if cj > 0 and df.loc[index,'Date'](3,index) == 12 :
ij=vol_slush[l[0]]
for j in range(1,ci) :
sp=dzs/snow[1,j]*[1-snow[1,j]]
a=sp-slush[0,j]
if ij > 0 :
if ij < a :
slush[0,j]=slush[0,j]+ij
ij=0
slush[1,j]=1
slush[2,j]=sp
else:
slush[0,j]=slush[0,j]+a
ij=ij-a
slush[1,j]=1
slush[2,j]=sp
# ----- refreezing of slush
for j in range(1,ci) :
if slush[0,j] != 0 and slush[1,j] > 0 and tls[j] < 0 :
re=(-1)*tls[j]*csnow[j]*(dzs/snow[1,j])/L
if (slush[0,j]*slush[1,j]) > re :
tls[j]=0
slush[1,j]=slush[1,j]-(re/(slush[0,j]*slush[1,j]))*slush[1,j]
else:
if re > 0 :
tls[j]=(1+(slush[0,j]*slush[1,j])/re)*tls[j]
slush[1,j]=0
l=np.where(tls != np.inf)
l=l[0]
ci=l.size
tes=deepcopy(tls)
# -----------------------
# heat conduction
if ci>0:
tll=deepcopy(tls)
tel=deepcopy(tes)
for it in range(0,iterations_si) :
for j in range(0,ci-1) :
if j == 0 :
tel[j]=tll[j]-(dt/iterations_si*ksnow[j]/(csnow[j])*(tll[j]-tll[j+1])/pow((dzs/snow[1,j]),2))/2
else:
tel[j]=tll[j]+((dt/iterations_si*ksnow[j]/(csnow[j])*(tll[j-1]-tll[j])/pow((dzs/snow[1,j]),2))-(dt/iterations_si*ksnow[j]/(csnow[j])*(tll[j]-tll[j+1])/pow((dzs/snow[1,j]),2)))/2
tll=deepcopy(tel)
tes=deepcopy(tel)
ice[0]=tes[0] # setting ice surface temperature to value of lowermost snow layer!
snow[0,]=deepcopy(tes)
snow[0,0]=tls[0]
if l.size > 0 :
snow[0,l[ci-1]]=tls[l[ci-1]]
meltlast=melt
# correct and reset
if snow[0,1] == np.inf :
snow.T[0,]=np.inf
l=np.where(np.logical_and(snow[0,]!=np.inf,snow[0,]<-40))
l=l[0]
if l.size > 0 :
snow[0,l]=-40
l=np.where(np.logical_and(snow[0,]!=np.inf,snow[0,]>0))
l=l[0]
if l.size > 0 :
snow[0,l]=0
# ---- forcing layers to measured thicknesses at begin of scenario period
# if str(df.loc[index,'Date'].date())==str(start_date_scen):
# *************************************************
# ICE
l=np.where(ice != np.inf)
l=l[0]
ci=l.size
# age of ice sheet
ii=np.where(ice != np.inf)
ii=ii[0]
jj=np.where(ice == np.inf)
jj=jj[0]
i_age[jj]=np.inf
for i in range(0,ci):
if i_age[i] == np.inf:
i_age[i]=1/24
else:
i_age[i]=i_age[i]+1/24
if ci > 0 :
attenuation_ice=attenuation_ice0+np.mean(i_age[ii])*fact_at
else:
attenuation_ice=attenuation_ice0
# energy balance ice
Qswi=(1-alpha_ice)*df.loc[index,'Rad']
Qswo=(-1)*alpha_ice*df.loc[index,'Rad'] #
Qlwi=(0.68+0.0036*pow(df.loc[index,'huma'],0.5))*(1+0.18*pow(df.loc[index,'Cl'],2))*emissivity_atm*s_b*pow((df.loc[index,'Tair']+273.15),4)
Qe=df.loc[index,'rho_air']*Lhs*bulk_exchange_l*(df.loc[index,'huma']-hum0)*df.loc[index,'Wind'] #huma==hum0???
Qp=0
gamma=math.exp(-attenuation_ice*dz)
# iterate for ice surface temperature
if snow[0,1] == np.inf :
dt_iceit=dt_snoit
else:
dt_iceit=dt
snit=(dt/dt_iceit)
for it in range(0,int(snit)) :
if ice[0] == np.inf :
tice=0
else:
tice=ice[0]
if it > 1 :
tice=tt_ts
else:
tt_ts=tice
Qlwo=(-1)*emissivity_ice*s_b*pow((tice+273.15),4) # long-wave outgoing
Qc=df.loc[index,'rho_air']*cair*bulk_exchange_s*(df.loc[index,'Tair']-tice)*df.loc[index,'Wind'] # sensible heat flux
Q0ice=(1-gamma)*(Qswi)+Qlwi+Qlwo+Qc+Qe+Qp # energy balance of top layer
tt_ts=tt_ts+Q0ice*dt_iceit/(cice*dz)
l=np.where(ice != np.inf)
l=l[0]
ci=l.size
if ci > 0 :
te=deepcopy(ice)
tl=deepcopy(te)
# calculate temperature of uppermost layer with energy balance
if snow[0,1] == np.inf :
tl[0]=tt_ts# apply surface temperature from iteration
# adapting ice temperature based on direct radiation absorbed within ice sheet
for i in range(1,ci-1):
tl[i]=tl[i]+(math.exp(-attenuation_ice*(i-1)*dz)-math.exp(-attenuation_ice*i*dz))*Qswi*dt/(cice*dz)
Qswi_i=Qswi*math.exp(-attenuation_ice*(ci-2)*dz) # radiation below ice sheet
# below snow coverage - temperature change calculated with heat fluxes from above and below
if snow[0,1] != np.inf :
for i in range(0,ci-1):
tl[i]=tl[i]+(math.exp(-attenuation_ice*(i-1)*dz)-math.exp(-attenuation_ice*i*dz))*Qswi_s*dt/(cice*dz)
Qswi_i=Qswi_s*math.exp(-attenuation_ice*(ci-2)*dz) # radiation below ice sheet
snow[0,0]=tl[0] # equalizing ice surface and bottom snow temperature
# ----- ice evaporation
if Qe < 0 and snow[0,1] == np.inf :
if 0<= i_slush :
im=im+Qe*dt/(Lhs*917)
else:
i_slush=i_slush+Qe*dt/(Lhw*1000)
if i_slush < 0 :
i_slush=0
# ----- ice melt
if Q0ice > 0 and tl[0] >= 0 :
Qmelt=Q0ice+(tl[0]*cice*dz/dt)
if Qmelt > 0 :
imelt=Qmelt/L*dt
else:
imelt=0
im=im-imelt
tl[0]=0
i_slush=i_slush+imelt
else:
melt=0
# reduce ice cover
if im <= -dz :
im=im+dz
for i in range(0,ci-1):
ice[i]=ice[i+1]
ice[ci-1]=np.inf
l=np.where(ice != np.inf)
l=l[0]
ci=l.size
tl=deepcopy(ice)
# ---- freezing of slush at ice surface
if slush[0,1] > 0 and tl[0] < 0 :
re=(-1)*tl[0]*cice*dz/L
if slush[0,1]*slush[1,1] > re :
tl[0]=0
slush[1,1]=slush[1,1]*(re/(slush[0,1]*slush[1,1]))
else:
if re > 0 :
tl[0]=tl[0]+tl[0]*((slush[0,1]*slush[1,1])/re)
slush[1,1]=0
# ---- freezing liquid water on bare ice surface or within ice sheet!
if i_slush > 0 :
re=0
for j in range(0,ci) :
if tl[j] < 0 :
re=(-1)*tl[j]*cice*dz/L
if i_slush > re :
tl[j]=0
i_slush=i_slush-re
else:
if re > 0 :
tl[j]=tl[j]+tl[j]*(i_slush/re)
i_slush=0
# ------- heat conduction
l=np.where(ice != np.inf)
l=l[0]
ci=l.size
tll=deepcopy(tl)
tel=deepcopy(te)
for it in range(0,iterations_si) :
for j in range(1,ci-1) :
tel[j]=tll[j]+((dt/iterations_si*kice/(cice)*(tll[j-1]-tll[j+1])*pow(dz,-2)))/2
tll=deepcopy(tel)
te=deepcopy(tel)
jj=np.where(tl == np.inf)
jj=jj[0]
cj=jj.size
if cj > 0 :
te[jj]=np.inf
# --- check for positive ice temperatures
jj=np.where(np.logical_and(te>0,te!=np.inf))
jj=jj[0]
cj=jj.size
if cj>0:
te[jj]=np.inf
hh=np.where(te<0)
hh=hh[0]
ch=hh.size
if cj > 0 and ch == 0 :
fr=fr-np.sum(te[jj])*cice*dz/L
te[jj]=0
if cj > 0 and ch > 0 :
p=np.sum(te[jj])/ch
kk=np.where(np.logical_and(te < -p, te != np.inf) )
kk=kk[0]
ck=kk.size
if ck > 0 :
te[kk]=te[kk]+np.sum(te[jj])/ck
else:
fr=fr-np.sum(te[jj])*cice*dz/L
te[jj]=0
# --- freezing / thawing at base!
if ci > 1 :
ice_flux=(-1)*min(te[l])*cice*dz/dt
else:
ice_flux=0.
if ice_flux < 0 :
ice_flux=0
if ci > 1 :
fr=fr+(ice_flux+(turbulent_fact*kwater*(water[0]-water[1])/(dzw))-Qbmelt)*dt/L
else:
tl[0]=np.inf
if fr > dz :
fr=fr-dz
te[ci-1]=0
if fr < (-1)*dz :
fr=fr+dz
te[ci-1]=np.inf
if ci > 1 :
te[ci-2]=0
ice=deepcopy(te)
ice[0]=tl[0] # ice loop
if ice[0] == np.inf :
ice[1]=np.inf
if snow[0,0] == np.inf : #Correction
snow[0,1]=np.inf
# Break up of ice cover if it is completely temperate and reasonably thin
l=np.where(ice != np.inf)
l=l[0]
ci=l.size
if ci > 0 and ci < 4 :
if min(ice[l]) == 0 :
ice[l]=np.inf
ii=np.where(np.logical_and(ice != np.inf, ice<-30))
ii=ii[0]
ci=l.size
if ci>0:
ice[ii]=-30
# *************************************************
# *************************************************
# WATER
# iterate for snow surface temperature
ts_water=water[0]
# energy balance water
Qswi=(1-alpha_water)*df.loc[index,'Rad']
Qswo=(-1)*alpha_water*df.loc[index,'Rad'] #
Qlwo=(-1)*emissivity_water*s_b*pow((ts_water+273.15),4)
Qlwi=(0.68+0.0036*pow(df.loc[index,'huma'],0.5))*(1+0.18*pow(df.loc[index,'Cl'],2))*emissivity_atm*s_b*(pow(df.loc[index,'Tair']+273.15,4))
Qc=df.loc[index,'rho_air']*cair*bulk_exchange_s*(df.loc[index,'Tair']-ts_water)*df.loc[index,'Wind']
Qe=df.loc[index,'rho_air']*Lhe*bulk_exchange_l*(df.loc[index,'huma']-hum0)*df.loc[index,'Wind']
Qp=0
gamma=math.exp(-attenuation_water*dz)
Q0water=Qswi+Qlwi+Qlwo+Qc+Qe+Qp
l=np.where(water != np.inf)
l=l[0]
ci=l.size
tew=deepcopy(water)
tlw=deepcopy(tew)
# mixing of water during summer - include layering of water!
if ice[0] == np.inf :
ww=np.full(ci,1.0)
ww[0:11]=wwin[0]
ww[10:21]=wwin[1]
ww[ci-10:ci]=wwin[2]
ww=ww/np.mean(ww)
cj=ci
if water[0] < t_wmin :
ww=np.full(ci,0.0)
ww[0]=1
cj=1
if Q0water < 0 :
jj=np.where(water > t_wmin)
jj=jj[0]
cj=jj.size
ww=np.full(ci,0.0)
if cj > 0 :
ww[jj]=1
else:
ww[0]=1
if cj == 0 :
cj=1
for j in range(0,cj):
tlw[j]=tlw[j]+Q0water*dt/(cwater*cj*dzw)*ww[j]
# !!! heat input by rivers and rain !!!
tr=(df.loc[index,'Tair']+flow_tcorr)
if tr < flow_tmin :
tr=flow_tmin
di_temp=tr-np.mean(water)
hrain=(df.loc[index,'Prec']*corrprec)*1000000.*topo[0]*di_temp # cwater gekuerzt!
tlw=tlw+hrain/(topo[3]*pow(10,9))
ran_riv=168
tt=min([ran_riv,index])
triv=np.mean(df.loc[index-tt:index+1,'Tair'])+flow_tcorr
if triv < flow_tmin :
triv=flow_tmin
di_temp=triv-np.mean(water)
hriv=flow*dt*di_temp # cwater gekuerzt!
tlw=tlw+hriv/(topo[3]*pow(10,9))
if ice[0] != np.inf :
tlw[0]=0
Qbmelt=Qswi_i*(1-gamma)
for i in range(1,ci):
tlw[i]=tlw[i]+(math.exp(-attenuation_water*(i-1)*dz)-math.exp(-attenuation_water*i*dz))*Qswi_i*dt/(cwater*dzw)
tll=deepcopy(tlw)
tel=deepcopy(tew)
for j in range(1,ci-1) :
tel[j]=tll[j]+((dt/iterations_w*kwater/(cwater)*(tll[j-1]-tll[j])/pow(dzw,2))-(dt/iterations_w*kwater/(cwater)*(tll[j]-tll[j+1])/pow(dzw,2)))/2
tll=deepcopy(tel)
tew=deepcopy(tel)
tew[0]=tlw[0]
# try to eliminate values < t_wmin
for j in range(0,ci) :
if tew[j] < t_wmin and max(tew) > t_wmin :
tp=t_wmin-tew[j]
tew[j]=t_wmin
for h in range(j+1,ci) :
if tew[h] > t_wmin :
if tp > tew[h]-t_wmin :
tp=tp-(tew[h]-t_wmin)
tew[h]=t_wmin
else:
tew[h]=tew[h]-tp
tp=0
water=deepcopy(tew)
water[0]=tlw[0]
# first ice formation
tfreeze=(-1)*dz*L/(dzw*cwater)*first_freezeparam
if np.mean(water[0:2]) < tfreeze and ice[0] == np.inf :
ice[0:3]=0
water[0]=0
# *******************************
# compile results
snow_albedo[index]=alpha_water
l=np.where(ice != np.inf)
l=l[0]
ci=l.size
if ci > 1 :
icethick[index]=(ci-1)*dz
if ci > 1 :
mtemp[1,index]=np.mean(ice[l[0]:l[ci-2]])
else:
mtemp[1,index]=np.inf
if ci > 0 :
stype[index]=1
if ci > 0 :
snow_albedo[index]=alpha_ice
mtemp[0,index]=np.mean(water)
l=np.where(snow[0,] != np.inf)
l=l[0]
ci=l.size
for i in range(1,ci):
snowthick[index]=snowthick[index]+dzs/snow[1,i]
if ci >= 1:
snow_albedo[index]=alpha_snow
if ci > 1 :
mtemp[2,index]=np.mean(snow[0,l[0]:l[ci-1]])
else:
mtemp[2,index]=np.inf
if ci >= 1 :
stype[index]=2
hh=np.where(slush[1,] == 0)
hh=hh[0]
ch=hh.size
if ch > 0 :
slush_thick[index]=np.sum(slush[0,hh])*1.25
else:
slush_thick[index]=0
load[0,index]=(ci-1)*dzs*1000+np.sum(slush[0,])*1000 # kg m-2
a=7000000*pow(icethick[index],2)
b=350000*pow(icethick[index],2)
if load[0,index]*9.81 > b :
load[1,index]=1
# ********************************************
# ********************************************
# PLOT
# one plot every day
if np.mod(index,freq_plots)==0:
plt.xlim(-40, 16)
plt.ylim(-0.6, 0.5)
plt.ylabel('Depth (m)')
plt.xlabel('Temperature (deg C)')
plt.axvline(x=0,color='k',linewidth=0.5).set_dashes([5])
plt.axhline(y=0,color='k',linewidth=0.5)
plt.title(str(df.loc[index,'Date'].date())+' Time '+str(df.loc[index,'When'].strftime("%H-%M")))
if ice[0] != np.inf:
co=0
else:
co=4
ii=np.where(ice != np.inf)
ii=ii[0]
ci=ii.size
if ci > 0:
yi=[float(i)*dz*(-1) for i in range(0,ci)]
xi=ice[0:ci]
plt.plot(xi,yi,color='r',linewidth=1)
plt.axhline(y=min(yi),color='g',linewidth=0.5)
if ci > 0:
offs=ii[ci-1]*dz*(-1)
else:
offs=0
yw=[float(i)*dz*(-1)+offs for i in range(0,nodes[0])]
plt.plot(water,yw,'r',linewidth=1)
ii=np.where(snow[0,] != np.inf)
sc=1
ii=ii[0]
ci=ii.size
if ci > 1:
ys=[float(i)*dzs*sc for i in range(0,ci)]
for j in range(0,ci-1):
ys[j]=ys[j]/snow[1,ii[j]]
ys[0]=dzs/0.5
tt=snow[0,0:ci]
plt.axhline(y=max(ys),color='m',linewidth=0.5)
plt.plot(tt,ys,'r',linewidth=1)
ii=np.where(snow[0,] == np.inf)
ii=ii[0]
ci=ii.size
if ci > 0:
slush[0,ii]=0
ii=np.where(np.logical_and(slush[0,] != 0,slush[1,] <= 0.1))
ii=ii[0]
ci=ii.size
if ci > 0:
if ii[ci-1] >= len(ys):
n=ii[ci-1]-1
else:
n=ii[ci-1]
ii=np.where(np.logical_and(slush[0,] != 0,slush[1,] > 0.1))
ii=ii[0]
ci=ii.size
if ci > 0:
if ii[ci-1] >= len(ys):
n=ii[ci-1]-1
else:
n=ii[ci-1]
pdf.savefig()
plt.close()
# ********************************************
# plot time series
pp = PdfPages('../data/processed/lakeice_series.pdf')
dt=[float(i)/24 for i in range(0,df.shape[0])]
dt=np.array(dt)
plt.xlim(0,index/24)
plt.ylim(-3,50)
plt.axvline(x=0,color='k',linewidth=0.5).set_dashes([5])
plt.ylabel('Ice thickness(cm)')
plt.plot(dt,icethick*100,'r',linewidth=1)
pp.savefig()
plt.clf()
# snow
plt.xlim(0,index/24)
plt.ylim(-3,max(snowthick)*100+3)
plt.ylabel('Snow depth (cm)')
plt.plot(dt,snowthick*100,'r',linewidth=1)
pp.savefig()
plt.clf()
# temp
plt.xlim(0,index/24)
ii=np.where(mtemp!=np.inf)
plt.ylim(min(mtemp[ii]),max(mtemp[0,]))
plt.ylabel('Temperature (deg C)')
ii=np.where(mtemp[2,]!=np.inf)
ii=ii[0]
plt.plot(dt[ii],mtemp[2,ii],'k',linewidth=1)
ii=np.where(mtemp[0,]!=np.inf)
ii=ii[0]
plt.plot(dt[ii],mtemp[0,ii],'r',linewidth=1)
ii=np.where(mtemp[1,]!=np.inf)
ii=ii[0]
plt.plot(dt[ii],mtemp[1,ii],linewidth=1)
pp.savefig()
plt.clf()
# albedo
plt.xlim(0,index/24)
plt.ylim(0,1)
plt.ylabel('Albedo (-)')
plt.plot(dt,snow_albedo,'r',linewidth=1)
pp.savefig()
plt.clf()
pp.close()
dfo['Icethick']=icethick
dfo['Tair']=df['Tair']
#output csv
dfo = dfo[['Date','Time','Type','Temp','Icethick']]
dfo.to_csv('../data/interim/processed_data_4.csv')
| [
"matplotlib.backends.backend_pdf.PdfPages",
"numpy.sum",
"matplotlib.pyplot.clf",
"pandas.read_csv",
"numpy.empty",
"numpy.isnan",
"numpy.mean",
"numpy.exp",
"pandas.DataFrame",
"numpy.full",
"matplotlib.pyplot.axvline",
"matplotlib.pyplot.close",
"numpy.append",
"datetime.timedelta",
"m... | [((378, 399), 'datetime.datetime', 'datetime', (['(2014)', '(12)', '(1)'], {}), '(2014, 12, 1)\n', (386, 399), False, 'from datetime import datetime, timedelta\n'), ((4682, 4894), 'pandas.read_csv', 'pd.read_csv', (['"""../data/raw/samedan_2014_2015.dat"""'], {'header': 'None', 'encoding': '"""latin-1"""', 'skiprows': '(14)', 'sep': '"""\\\\s+"""', 'names': "['STA', 'Year', 'Mo', 'Day', 'HH', 'MM', 'Tair', 'RH', 'Wind', 'Rad',\n 'Pressure', 'Prec']"}), "('../data/raw/samedan_2014_2015.dat', header=None, encoding=\n 'latin-1', skiprows=14, sep='\\\\s+', names=['STA', 'Year', 'Mo', 'Day',\n 'HH', 'MM', 'Tair', 'RH', 'Wind', 'Rad', 'Pressure', 'Prec'])\n", (4693, 4894), True, 'import pandas as pd\n'), ((5065, 5080), 'numpy.array', 'np.array', (['right'], {}), '(right)\n', (5073, 5080), True, 'import numpy as np\n'), ((5627, 5653), 'pandas.to_datetime', 'pd.to_datetime', (["df['When']"], {}), "(df['When'])\n", (5641, 5653), True, 'import pandas as pd\n'), ((5726, 5764), 'numpy.zeros', 'np.zeros', ([], {'shape': '(365, 24)', 'dtype': 'float'}), '(shape=(365, 24), dtype=float)\n', (5734, 5764), True, 'import numpy as np\n'), ((6054, 6094), 'numpy.empty', 'np.empty', ([], {'shape': 'df.shape[0]', 'dtype': 'float'}), '(shape=df.shape[0], dtype=float)\n', (6062, 6094), True, 'import numpy as np\n'), ((7244, 7332), 'pandas.read_csv', 'pd.read_csv', (['"""../data/raw/forecast2016.csv"""'], {'encoding': '"""latin-1"""', 'skiprows': '(1)', 'sep': '""";"""'}), "('../data/raw/forecast2016.csv', encoding='latin-1', skiprows=1,\n sep=';')\n", (7255, 7332), True, 'import pandas as pd\n'), ((7353, 7379), 'pandas.to_datetime', 'pd.to_datetime', (["df['When']"], {}), "(df['When'])\n", (7367, 7379), True, 'import pandas as pd\n'), ((7698, 7721), 'pandas.DataFrame', 'pd.DataFrame', (["{'A': []}"], {}), "({'A': []})\n", (7710, 7721), True, 'import pandas as pd\n'), ((8481, 8504), 'pandas.DataFrame', 'pd.DataFrame', (["{'A': []}"], {}), "({'A': []})\n", (8493, 8504), True, 'import pandas as pd\n'), ((8510, 8533), 'pandas.DataFrame', 'pd.DataFrame', (["{'A': []}"], {}), "({'A': []})\n", (8522, 8533), True, 'import pandas as pd\n'), ((9506, 9533), 'pandas.to_datetime', 'pd.to_datetime', (["dft['When']"], {}), "(dft['When'])\n", (9520, 9533), True, 'import pandas as pd\n'), ((9598, 9625), 'pandas.to_datetime', 'pd.to_datetime', (["dff['When']"], {}), "(dff['When'])\n", (9612, 9625), True, 'import pandas as pd\n'), ((9700, 9723), 'pandas.DataFrame', 'pd.DataFrame', (["{'A': []}"], {}), "({'A': []})\n", (9712, 9723), True, 'import pandas as pd\n'), ((11177, 11204), 'pandas.to_datetime', 'pd.to_datetime', (["dfg['Date']"], {}), "(dfg['Date'])\n", (11191, 11204), True, 'import pandas as pd\n'), ((11818, 11843), 'numpy.full', 'np.full', (['nodes[1]', 'np.inf'], {}), '(nodes[1], np.inf)\n', (11825, 11843), True, 'import numpy as np\n'), ((11848, 11878), 'numpy.full', 'np.full', (['(3, nodes[2])', 'np.inf'], {}), '((3, nodes[2]), np.inf)\n', (11855, 11878), True, 'import numpy as np\n'), ((11890, 11916), 'pandas.to_datetime', 'pd.to_datetime', (["df['Date']"], {}), "(df['Date'])\n", (11904, 11916), True, 'import pandas as pd\n'), ((12011, 12035), 'numpy.zeros', 'np.zeros', ([], {'shape': 'nodes[0]'}), '(shape=nodes[0])\n', (12019, 12035), True, 'import numpy as np\n'), ((12240, 12267), 'numpy.full', 'np.full', (['(3, nodes[2])', '(0.0)'], {}), '((3, nodes[2]), 0.0)\n', (12247, 12267), True, 'import numpy as np\n'), ((12275, 12300), 'numpy.full', 'np.full', (['df.shape[0]', '(0.0)'], {}), '(df.shape[0], 0.0)\n', (12282, 12300), True, 'import numpy as np\n'), ((12305, 12335), 'numpy.full', 'np.full', (['(2, df.shape[0])', '(0.0)'], {}), '((2, df.shape[0]), 0.0)\n', (12312, 12335), True, 'import numpy as np\n'), ((12340, 12370), 'numpy.full', 'np.full', (['(3, df.shape[0])', '(0.0)'], {}), '((3, df.shape[0]), 0.0)\n', (12347, 12370), True, 'import numpy as np\n'), ((12375, 12400), 'numpy.full', 'np.full', (['df.shape[0]', '(0.0)'], {}), '(df.shape[0], 0.0)\n', (12382, 12400), True, 'import numpy as np\n'), ((12410, 12425), 'copy.deepcopy', 'deepcopy', (['stype'], {}), '(stype)\n', (12418, 12425), False, 'from copy import copy, deepcopy\n'), ((12431, 12446), 'copy.deepcopy', 'deepcopy', (['stype'], {}), '(stype)\n', (12439, 12446), False, 'from copy import copy, deepcopy\n'), ((12459, 12474), 'copy.deepcopy', 'deepcopy', (['stype'], {}), '(stype)\n', (12467, 12474), False, 'from copy import copy, deepcopy\n'), ((12487, 12505), 'copy.deepcopy', 'deepcopy', (['icethick'], {}), '(icethick)\n', (12495, 12505), False, 'from copy import copy, deepcopy\n'), ((12512, 12540), 'numpy.full', 'np.full', (['df.shape[0]', 'np.inf'], {}), '(df.shape[0], np.inf)\n', (12519, 12540), True, 'import numpy as np\n'), ((12545, 12571), 'pandas.DataFrame', 'pd.DataFrame', (["{'Type': []}"], {}), "({'Type': []})\n", (12557, 12571), True, 'import pandas as pd\n'), ((38818, 38866), 'matplotlib.backends.backend_pdf.PdfPages', 'PdfPages', (['"""../data/processed/lakeice_series.pdf"""'], {}), "('../data/processed/lakeice_series.pdf')\n", (38826, 38866), False, 'from matplotlib.backends.backend_pdf import PdfPages\n'), ((38918, 38930), 'numpy.array', 'np.array', (['dt'], {}), '(dt)\n', (38926, 38930), True, 'import numpy as np\n'), ((38931, 38954), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(index / 24)'], {}), '(0, index / 24)\n', (38939, 38954), True, 'from matplotlib import pyplot as plt\n'), ((38952, 38968), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-3)', '(50)'], {}), '(-3, 50)\n', (38960, 38968), True, 'from matplotlib import pyplot as plt\n'), ((39025, 39056), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Ice thickness(cm)"""'], {}), "('Ice thickness(cm)')\n", (39035, 39056), True, 'from matplotlib import pyplot as plt\n'), ((39057, 39103), 'matplotlib.pyplot.plot', 'plt.plot', (['dt', '(icethick * 100)', '"""r"""'], {'linewidth': '(1)'}), "(dt, icethick * 100, 'r', linewidth=1)\n", (39065, 39103), True, 'from matplotlib import pyplot as plt\n'), ((39112, 39121), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (39119, 39121), True, 'from matplotlib import pyplot as plt\n'), ((39130, 39153), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(index / 24)'], {}), '(0, index / 24)\n', (39138, 39153), True, 'from matplotlib import pyplot as plt\n'), ((39185, 39214), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Snow depth (cm)"""'], {}), "('Snow depth (cm)')\n", (39195, 39214), True, 'from matplotlib import pyplot as plt\n'), ((39215, 39262), 'matplotlib.pyplot.plot', 'plt.plot', (['dt', '(snowthick * 100)', '"""r"""'], {'linewidth': '(1)'}), "(dt, snowthick * 100, 'r', linewidth=1)\n", (39223, 39262), True, 'from matplotlib import pyplot as plt\n'), ((39271, 39280), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (39278, 39280), True, 'from matplotlib import pyplot as plt\n'), ((39289, 39312), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(index / 24)'], {}), '(0, index / 24)\n', (39297, 39312), True, 'from matplotlib import pyplot as plt\n'), ((39313, 39338), 'numpy.where', 'np.where', (['(mtemp != np.inf)'], {}), '(mtemp != np.inf)\n', (39321, 39338), True, 'import numpy as np\n'), ((39377, 39410), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Temperature (deg C)"""'], {}), "('Temperature (deg C)')\n", (39387, 39410), True, 'from matplotlib import pyplot as plt\n'), ((39414, 39443), 'numpy.where', 'np.where', (['(mtemp[2,] != np.inf)'], {}), '(mtemp[2,] != np.inf)\n', (39422, 39443), True, 'import numpy as np\n'), ((39451, 39499), 'matplotlib.pyplot.plot', 'plt.plot', (['dt[ii]', 'mtemp[2, ii]', '"""k"""'], {'linewidth': '(1)'}), "(dt[ii], mtemp[2, ii], 'k', linewidth=1)\n", (39459, 39499), True, 'from matplotlib import pyplot as plt\n'), ((39499, 39528), 'numpy.where', 'np.where', (['(mtemp[0,] != np.inf)'], {}), '(mtemp[0,] != np.inf)\n', (39507, 39528), True, 'import numpy as np\n'), ((39536, 39584), 'matplotlib.pyplot.plot', 'plt.plot', (['dt[ii]', 'mtemp[0, ii]', '"""r"""'], {'linewidth': '(1)'}), "(dt[ii], mtemp[0, ii], 'r', linewidth=1)\n", (39544, 39584), True, 'from matplotlib import pyplot as plt\n'), ((39584, 39613), 'numpy.where', 'np.where', (['(mtemp[1,] != np.inf)'], {}), '(mtemp[1,] != np.inf)\n', (39592, 39613), True, 'import numpy as np\n'), ((39621, 39664), 'matplotlib.pyplot.plot', 'plt.plot', (['dt[ii]', 'mtemp[1, ii]'], {'linewidth': '(1)'}), '(dt[ii], mtemp[1, ii], linewidth=1)\n', (39629, 39664), True, 'from matplotlib import pyplot as plt\n'), ((39675, 39684), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (39682, 39684), True, 'from matplotlib import pyplot as plt\n'), ((39695, 39718), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(index / 24)'], {}), '(0, index / 24)\n', (39703, 39718), True, 'from matplotlib import pyplot as plt\n'), ((39716, 39730), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(1)'], {}), '(0, 1)\n', (39724, 39730), True, 'from matplotlib import pyplot as plt\n'), ((39730, 39754), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Albedo (-)"""'], {}), "('Albedo (-)')\n", (39740, 39754), True, 'from matplotlib import pyplot as plt\n'), ((39755, 39798), 'matplotlib.pyplot.plot', 'plt.plot', (['dt', 'snow_albedo', '"""r"""'], {'linewidth': '(1)'}), "(dt, snow_albedo, 'r', linewidth=1)\n", (39763, 39798), True, 'from matplotlib import pyplot as plt\n'), ((39809, 39818), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (39816, 39818), True, 'from matplotlib import pyplot as plt\n'), ((425, 443), 'datetime.timedelta', 'timedelta', ([], {'days': '(20)'}), '(days=20)\n', (434, 443), False, 'from datetime import datetime, timedelta\n'), ((5451, 5517), 'datetime.datetime', 'datetime', (["df['Year'][i]", "df['Mo'][i]", "df['Day'][i]", "df['HH'][i]", '(0)'], {}), "(df['Year'][i], df['Mo'][i], df['Day'][i], df['HH'][i], 0)\n", (5459, 5517), False, 'from datetime import datetime, timedelta\n'), ((8709, 8720), 'numpy.array', 'np.array', (['l'], {}), '(l)\n', (8717, 8720), True, 'import numpy as np\n'), ((8930, 8942), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (8938, 8942), True, 'import numpy as np\n'), ((9023, 9039), 'numpy.where', 'np.where', (['(l == c)'], {}), '(l == c)\n', (9031, 9039), True, 'import numpy as np\n'), ((9242, 9254), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (9250, 9254), True, 'import numpy as np\n'), ((9321, 9337), 'numpy.where', 'np.where', (['(l == c)'], {}), '(l == c)\n', (9329, 9337), True, 'import numpy as np\n'), ((9768, 9808), 'numpy.where', 'np.where', (["(df['Day'] == dff['Day'][index])"], {}), "(df['Day'] == dff['Day'][index])\n", (9776, 9808), True, 'import numpy as np\n'), ((10124, 10171), 'numpy.where', 'np.where', (["(dfs1['day'] == dfg.loc[j, 'Date'].day)"], {}), "(dfs1['day'] == dfg.loc[j, 'Date'].day)\n", (10132, 10171), True, 'import numpy as np\n'), ((12689, 12730), 'matplotlib.backends.backend_pdf.PdfPages', 'PdfPages', (['"""../data/processed/figures.pdf"""'], {}), "('../data/processed/figures.pdf')\n", (12697, 12730), False, 'from matplotlib.backends.backend_pdf import PdfPages\n'), ((5918, 5930), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (5926, 5930), True, 'import numpy as np\n'), ((5941, 5956), 'numpy.append', 'np.append', (['(0)', 'l'], {}), '(0, l)\n', (5950, 5956), True, 'import numpy as np\n'), ((5966, 5981), 'numpy.delete', 'np.delete', (['a', '(0)'], {}), '(a, 0)\n', (5975, 5981), True, 'import numpy as np\n'), ((6447, 6459), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (6455, 6459), True, 'import numpy as np\n'), ((6470, 6485), 'numpy.append', 'np.append', (['(0)', 'l'], {}), '(0, l)\n', (6479, 6485), True, 'import numpy as np\n'), ((6495, 6510), 'numpy.delete', 'np.delete', (['b', '(0)'], {}), '(b, 0)\n', (6504, 6510), True, 'import numpy as np\n'), ((7545, 7569), 'datetime.timedelta', 'timedelta', ([], {'days': 'num_days'}), '(days=num_days)\n', (7554, 7569), False, 'from datetime import datetime, timedelta\n'), ((10814, 10832), 'datetime.timedelta', 'timedelta', ([], {'hours': '(1)'}), '(hours=1)\n', (10823, 10832), False, 'from datetime import datetime, timedelta\n'), ((11367, 11396), 'datetime.timedelta', 'timedelta', ([], {'days': 'num_days_scen'}), '(days=num_days_scen)\n', (11376, 11396), False, 'from datetime import datetime, timedelta\n'), ((11530, 11546), 'pandas.DataFrame', 'pd.DataFrame', (['df'], {}), '(df)\n', (11542, 11546), True, 'import pandas as pd\n'), ((11589, 11605), 'pandas.DataFrame', 'pd.DataFrame', (['df'], {}), '(df)\n', (11601, 11605), True, 'import pandas as pd\n'), ((12788, 12816), 'numpy.where', 'np.where', (['(snow[0,] != np.inf)'], {}), '(snow[0,] != np.inf)\n', (12796, 12816), True, 'import numpy as np\n'), ((12859, 12882), 'numpy.where', 'np.where', (['(ice != np.inf)'], {}), '(ice != np.inf)\n', (12867, 12882), True, 'import numpy as np\n'), ((12914, 12939), 'numpy.where', 'np.where', (['(water != np.inf)'], {}), '(water != np.inf)\n', (12922, 12939), True, 'import numpy as np\n'), ((13773, 13791), 'copy.deepcopy', 'deepcopy', (['snow[0,]'], {}), '(snow[0,])\n', (13781, 13791), False, 'from copy import copy, deepcopy\n'), ((13804, 13817), 'copy.deepcopy', 'deepcopy', (['tes'], {}), '(tes)\n', (13812, 13817), False, 'from copy import copy, deepcopy\n'), ((14817, 14845), 'numpy.where', 'np.where', (['(snow[0,] != np.inf)'], {}), '(snow[0,] != np.inf)\n', (14825, 14845), True, 'import numpy as np\n'), ((15491, 15513), 'numpy.full', 'np.full', (['nodes[2]', '(0.0)'], {}), '(nodes[2], 0.0)\n', (15498, 15513), True, 'import numpy as np\n'), ((15527, 15542), 'copy.deepcopy', 'deepcopy', (['csnow'], {}), '(csnow)\n', (15535, 15542), False, 'from copy import copy, deepcopy\n'), ((16807, 16860), 'math.exp', 'math.exp', (['(-attenuation_snow * dzs / (at_rho / 1000.0))'], {}), '(-attenuation_snow * dzs / (at_rho / 1000.0))\n', (16815, 16860), False, 'import math\n'), ((17045, 17073), 'numpy.where', 'np.where', (['(snow[0,] != np.inf)'], {}), '(snow[0,] != np.inf)\n', (17053, 17073), True, 'import numpy as np\n'), ((17861, 17889), 'numpy.where', 'np.where', (['(snow[0,] != np.inf)'], {}), '(snow[0,] != np.inf)\n', (17869, 17889), True, 'import numpy as np\n'), ((23814, 23837), 'numpy.where', 'np.where', (['(ice != np.inf)'], {}), '(ice != np.inf)\n', (23822, 23837), True, 'import numpy as np\n'), ((23910, 23933), 'numpy.where', 'np.where', (['(ice != np.inf)'], {}), '(ice != np.inf)\n', (23918, 23933), True, 'import numpy as np\n'), ((23962, 23985), 'numpy.where', 'np.where', (['(ice == np.inf)'], {}), '(ice == np.inf)\n', (23970, 23985), True, 'import numpy as np\n'), ((24792, 24823), 'math.exp', 'math.exp', (['(-attenuation_ice * dz)'], {}), '(-attenuation_ice * dz)\n', (24800, 24823), False, 'import math\n'), ((25609, 25632), 'numpy.where', 'np.where', (['(ice != np.inf)'], {}), '(ice != np.inf)\n', (25617, 25632), True, 'import numpy as np\n'), ((30961, 30984), 'numpy.where', 'np.where', (['(ice != np.inf)'], {}), '(ice != np.inf)\n', (30969, 30984), True, 'import numpy as np\n'), ((32047, 32080), 'math.exp', 'math.exp', (['(-attenuation_water * dz)'], {}), '(-attenuation_water * dz)\n', (32055, 32080), False, 'import math\n'), ((32129, 32154), 'numpy.where', 'np.where', (['(water != np.inf)'], {}), '(water != np.inf)\n', (32137, 32154), True, 'import numpy as np\n'), ((32200, 32215), 'copy.deepcopy', 'deepcopy', (['water'], {}), '(water)\n', (32208, 32215), False, 'from copy import copy, deepcopy\n'), ((32228, 32241), 'copy.deepcopy', 'deepcopy', (['tew'], {}), '(tew)\n', (32236, 32241), False, 'from copy import copy, deepcopy\n'), ((33986, 33999), 'copy.deepcopy', 'deepcopy', (['tlw'], {}), '(tlw)\n', (33994, 33999), False, 'from copy import copy, deepcopy\n'), ((34012, 34025), 'copy.deepcopy', 'deepcopy', (['tew'], {}), '(tew)\n', (34020, 34025), False, 'from copy import copy, deepcopy\n'), ((34229, 34242), 'copy.deepcopy', 'deepcopy', (['tel'], {}), '(tel)\n', (34237, 34242), False, 'from copy import copy, deepcopy\n'), ((34255, 34268), 'copy.deepcopy', 'deepcopy', (['tel'], {}), '(tel)\n', (34263, 34268), False, 'from copy import copy, deepcopy\n'), ((34829, 34842), 'copy.deepcopy', 'deepcopy', (['tew'], {}), '(tew)\n', (34837, 34842), False, 'from copy import copy, deepcopy\n'), ((35183, 35206), 'numpy.where', 'np.where', (['(ice != np.inf)'], {}), '(ice != np.inf)\n', (35191, 35206), True, 'import numpy as np\n'), ((35553, 35567), 'numpy.mean', 'np.mean', (['water'], {}), '(water)\n', (35560, 35567), True, 'import numpy as np\n'), ((35579, 35607), 'numpy.where', 'np.where', (['(snow[0,] != np.inf)'], {}), '(snow[0,] != np.inf)\n', (35587, 35607), True, 'import numpy as np\n'), ((35980, 36004), 'numpy.where', 'np.where', (['(slush[1,] == 0)'], {}), '(slush[1,] == 0)\n', (35988, 36004), True, 'import numpy as np\n'), ((38968, 39010), 'matplotlib.pyplot.axvline', 'plt.axvline', ([], {'x': '(0)', 'color': '"""k"""', 'linewidth': '(0.5)'}), "(x=0, color='k', linewidth=0.5)\n", (38979, 39010), True, 'from matplotlib import pyplot as plt\n'), ((6552, 6566), 'numpy.mean', 'np.mean', (['cl[b]'], {}), '(cl[b])\n', (6559, 6566), True, 'import numpy as np\n'), ((6710, 6739), 'datetime.timedelta', 'timedelta', ([], {'days': 'num_days_scen'}), '(days=num_days_scen)\n', (6719, 6739), False, 'from datetime import datetime, timedelta\n'), ((6925, 6976), 'numpy.exp', 'np.exp', (["(17.625 * df['Tair'] / (df['Tair'] + 243.04))"], {}), "(17.625 * df['Tair'] / (df['Tair'] + 243.04))\n", (6931, 6976), True, 'import numpy as np\n'), ((10960, 10984), 'math.floor', 'math.floor', (['((i - c) / 24)'], {}), '((i - c) / 24)\n', (10970, 10984), False, 'import math\n'), ((13451, 13463), 'numpy.isnan', 'np.isnan', (['tt'], {}), '(tt)\n', (13459, 13463), True, 'import numpy as np\n'), ((14445, 14473), 'numpy.where', 'np.where', (['(snow[0,] == np.inf)'], {}), '(snow[0,] == np.inf)\n', (14453, 14473), True, 'import numpy as np\n'), ((19048, 19071), 'numpy.where', 'np.where', (['(tls != np.inf)'], {}), '(tls != np.inf)\n', (19056, 19071), True, 'import numpy as np\n'), ((20377, 20405), 'numpy.where', 'np.where', (['(snow[0,] == np.inf)'], {}), '(snow[0,] == np.inf)\n', (20385, 20405), True, 'import numpy as np\n'), ((22125, 22148), 'numpy.where', 'np.where', (['(tls != np.inf)'], {}), '(tls != np.inf)\n', (22133, 22148), True, 'import numpy as np\n'), ((22206, 22219), 'copy.deepcopy', 'deepcopy', (['tls'], {}), '(tls)\n', (22214, 22219), False, 'from copy import copy, deepcopy\n'), ((23334, 23384), 'numpy.logical_and', 'np.logical_and', (['(snow[0,] != np.inf)', '(snow[0,] < -40)'], {}), '(snow[0,] != np.inf, snow[0,] < -40)\n', (23348, 23384), True, 'import numpy as np\n'), ((23467, 23515), 'numpy.logical_and', 'np.logical_and', (['(snow[0,] != np.inf)', '(snow[0,] > 0)'], {}), '(snow[0,] != np.inf, snow[0,] > 0)\n', (23481, 23515), True, 'import numpy as np\n'), ((25701, 25714), 'copy.deepcopy', 'deepcopy', (['ice'], {}), '(ice)\n', (25709, 25714), False, 'from copy import copy, deepcopy\n'), ((25730, 25742), 'copy.deepcopy', 'deepcopy', (['te'], {}), '(te)\n', (25738, 25742), False, 'from copy import copy, deepcopy\n'), ((28773, 28796), 'numpy.where', 'np.where', (['(ice != np.inf)'], {}), '(ice != np.inf)\n', (28781, 28796), True, 'import numpy as np\n'), ((28854, 28866), 'copy.deepcopy', 'deepcopy', (['tl'], {}), '(tl)\n', (28862, 28866), False, 'from copy import copy, deepcopy\n'), ((28883, 28895), 'copy.deepcopy', 'deepcopy', (['te'], {}), '(te)\n', (28891, 28895), False, 'from copy import copy, deepcopy\n'), ((29133, 29146), 'copy.deepcopy', 'deepcopy', (['tel'], {}), '(tel)\n', (29141, 29146), False, 'from copy import copy, deepcopy\n'), ((29163, 29185), 'numpy.where', 'np.where', (['(tl == np.inf)'], {}), '(tl == np.inf)\n', (29171, 29185), True, 'import numpy as np\n'), ((29507, 29523), 'numpy.where', 'np.where', (['(te < 0)'], {}), '(te < 0)\n', (29515, 29523), True, 'import numpy as np\n'), ((30683, 30695), 'copy.deepcopy', 'deepcopy', (['te'], {}), '(te)\n', (30691, 30695), False, 'from copy import copy, deepcopy\n'), ((31134, 31174), 'numpy.logical_and', 'np.logical_and', (['(ice != np.inf)', '(ice < -30)'], {}), '(ice != np.inf, ice < -30)\n', (31148, 31174), True, 'import numpy as np\n'), ((32357, 32373), 'numpy.full', 'np.full', (['ci', '(1.0)'], {}), '(ci, 1.0)\n', (32364, 32373), True, 'import numpy as np\n'), ((35346, 35374), 'numpy.mean', 'np.mean', (['ice[l[0]:l[ci - 2]]'], {}), '(ice[l[0]:l[ci - 2]])\n', (35353, 35374), True, 'import numpy as np\n'), ((35841, 35873), 'numpy.mean', 'np.mean', (['snow[0, l[0]:l[ci - 1]]'], {}), '(snow[0, l[0]:l[ci - 1]])\n', (35848, 35873), True, 'import numpy as np\n'), ((36548, 36573), 'numpy.mod', 'np.mod', (['index', 'freq_plots'], {}), '(index, freq_plots)\n', (36554, 36573), True, 'import numpy as np\n'), ((36589, 36606), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-40)', '(16)'], {}), '(-40, 16)\n', (36597, 36606), True, 'from matplotlib import pyplot as plt\n'), ((36619, 36638), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-0.6)', '(0.5)'], {}), '(-0.6, 0.5)\n', (36627, 36638), True, 'from matplotlib import pyplot as plt\n'), ((36651, 36674), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Depth (m)"""'], {}), "('Depth (m)')\n", (36661, 36674), True, 'from matplotlib import pyplot as plt\n'), ((36687, 36720), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Temperature (deg C)"""'], {}), "('Temperature (deg C)')\n", (36697, 36720), True, 'from matplotlib import pyplot as plt\n'), ((36802, 36844), 'matplotlib.pyplot.axhline', 'plt.axhline', ([], {'y': '(0)', 'color': '"""k"""', 'linewidth': '(0.5)'}), "(y=0, color='k', linewidth=0.5)\n", (36813, 36844), True, 'from matplotlib import pyplot as plt\n'), ((37062, 37085), 'numpy.where', 'np.where', (['(ice != np.inf)'], {}), '(ice != np.inf)\n', (37070, 37085), True, 'import numpy as np\n'), ((37539, 37576), 'matplotlib.pyplot.plot', 'plt.plot', (['water', 'yw', '"""r"""'], {'linewidth': '(1)'}), "(water, yw, 'r', linewidth=1)\n", (37547, 37576), True, 'from matplotlib import pyplot as plt\n'), ((37590, 37618), 'numpy.where', 'np.where', (['(snow[0,] != np.inf)'], {}), '(snow[0,] != np.inf)\n', (37598, 37618), True, 'import numpy as np\n'), ((38036, 38064), 'numpy.where', 'np.where', (['(snow[0,] == np.inf)'], {}), '(snow[0,] == np.inf)\n', (38044, 38064), True, 'import numpy as np\n'), ((38734, 38745), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (38743, 38745), True, 'from matplotlib import pyplot as plt\n'), ((5846, 5895), 'numpy.logical_and', 'np.logical_and', (["(df['HH'] == j)", "(i - 5 <= df['DoY'])"], {}), "(df['HH'] == j, i - 5 <= df['DoY'])\n", (5860, 5895), True, 'import numpy as np\n'), ((6359, 6425), 'numpy.logical_and', 'np.logical_and', (["(df['DoY'] == df.loc[row[0], 'DoY'])", "(10 <= df['HH'])"], {}), "(df['DoY'] == df.loc[row[0], 'DoY'], 10 <= df['HH'])\n", (6373, 6425), True, 'import numpy as np\n'), ((10864, 10888), 'math.floor', 'math.floor', (['((i - c) / 24)'], {}), '((i - c) / 24)\n', (10874, 10888), False, 'import math\n'), ((10907, 10931), 'math.floor', 'math.floor', (['((i - c) / 24)'], {}), '((i - c) / 24)\n', (10917, 10931), False, 'import math\n'), ((13545, 13580), 'numpy.exp', 'np.exp', (['(17.625 * tt / (tt + 243.04))'], {}), '(17.625 * tt / (tt + 243.04))\n', (13551, 13580), True, 'import numpy as np\n'), ((18300, 18362), 'math.exp', 'math.exp', (['(-attenuation_snow * (ci - 1) * dzs / (at_rho / 1000))'], {}), '(-attenuation_snow * (ci - 1) * dzs / (at_rho / 1000))\n', (18308, 18362), False, 'import math\n'), ((20703, 20798), 'numpy.where', 'np.where', (["(df['Date'][index].day == int_slush[0] and df['Date'][index].month ==\n int_slush[1])"], {}), "(df['Date'][index].day == int_slush[0] and df['Date'][index].month ==\n int_slush[1])\n", (20711, 20798), True, 'import numpy as np\n'), ((22330, 22343), 'copy.deepcopy', 'deepcopy', (['tls'], {}), '(tls)\n', (22338, 22343), False, 'from copy import copy, deepcopy\n'), ((22364, 22377), 'copy.deepcopy', 'deepcopy', (['tes'], {}), '(tes)\n', (22372, 22377), False, 'from copy import copy, deepcopy\n'), ((22929, 22942), 'copy.deepcopy', 'deepcopy', (['tel'], {}), '(tel)\n', (22937, 22942), False, 'from copy import copy, deepcopy\n'), ((23068, 23081), 'copy.deepcopy', 'deepcopy', (['tes'], {}), '(tes)\n', (23076, 23081), False, 'from copy import copy, deepcopy\n'), ((27645, 27668), 'numpy.where', 'np.where', (['(ice != np.inf)'], {}), '(ice != np.inf)\n', (27653, 27668), True, 'import numpy as np\n'), ((27737, 27750), 'copy.deepcopy', 'deepcopy', (['ice'], {}), '(ice)\n', (27745, 27750), False, 'from copy import copy, deepcopy\n'), ((29104, 29117), 'copy.deepcopy', 'deepcopy', (['tel'], {}), '(tel)\n', (29112, 29117), False, 'from copy import copy, deepcopy\n'), ((29363, 29399), 'numpy.logical_and', 'np.logical_and', (['(te > 0)', '(te != np.inf)'], {}), '(te > 0, te != np.inf)\n', (29377, 29399), True, 'import numpy as np\n'), ((32483, 32494), 'numpy.mean', 'np.mean', (['ww'], {}), '(ww)\n', (32490, 32494), True, 'import numpy as np\n'), ((32567, 32583), 'numpy.full', 'np.full', (['ci', '(0.0)'], {}), '(ci, 0.0)\n', (32574, 32583), True, 'import numpy as np\n'), ((32676, 32700), 'numpy.where', 'np.where', (['(water > t_wmin)'], {}), '(water > t_wmin)\n', (32684, 32700), True, 'import numpy as np\n'), ((32772, 32788), 'numpy.full', 'np.full', (['ci', '(0.0)'], {}), '(ci, 0.0)\n', (32779, 32788), True, 'import numpy as np\n'), ((33233, 33247), 'numpy.mean', 'np.mean', (['water'], {}), '(water)\n', (33240, 33247), True, 'import numpy as np\n'), ((33466, 33511), 'numpy.mean', 'np.mean', (["df.loc[index - tt:index + 1, 'Tair']"], {}), "(df.loc[index - tt:index + 1, 'Tair'])\n", (33473, 33511), True, 'import numpy as np\n'), ((34966, 34985), 'numpy.mean', 'np.mean', (['water[0:2]'], {}), '(water[0:2])\n', (34973, 34985), True, 'import numpy as np\n'), ((36092, 36112), 'numpy.sum', 'np.sum', (['slush[0, hh]'], {}), '(slush[0, hh])\n', (36098, 36112), True, 'import numpy as np\n'), ((36203, 36220), 'numpy.sum', 'np.sum', (['slush[0,]'], {}), '(slush[0,])\n', (36209, 36220), True, 'import numpy as np\n'), ((37257, 37297), 'matplotlib.pyplot.plot', 'plt.plot', (['xi', 'yi'], {'color': '"""r"""', 'linewidth': '(1)'}), "(xi, yi, color='r', linewidth=1)\n", (37265, 37297), True, 'from matplotlib import pyplot as plt\n'), ((37988, 38022), 'matplotlib.pyplot.plot', 'plt.plot', (['tt', 'ys', '"""r"""'], {'linewidth': '(1)'}), "(tt, ys, 'r', linewidth=1)\n", (37996, 38022), True, 'from matplotlib import pyplot as plt\n'), ((38187, 38235), 'numpy.logical_and', 'np.logical_and', (['(slush[0,] != 0)', '(slush[1,] <= 0.1)'], {}), '(slush[0,] != 0, slush[1,] <= 0.1)\n', (38201, 38235), True, 'import numpy as np\n'), ((38454, 38501), 'numpy.logical_and', 'np.logical_and', (['(slush[0,] != 0)', '(slush[1,] > 0.1)'], {}), '(slush[0,] != 0, slush[1,] > 0.1)\n', (38468, 38501), True, 'import numpy as np\n'), ((22894, 22907), 'copy.deepcopy', 'deepcopy', (['tel'], {}), '(tel)\n', (22902, 22907), False, 'from copy import copy, deepcopy\n'), ((24246, 24264), 'numpy.mean', 'np.mean', (['i_age[ii]'], {}), '(i_age[ii])\n', (24253, 24264), True, 'import numpy as np\n'), ((26210, 26252), 'math.exp', 'math.exp', (['(-attenuation_ice * (ci - 2) * dz)'], {}), '(-attenuation_ice * (ci - 2) * dz)\n', (26218, 26252), False, 'import math\n'), ((26612, 26654), 'math.exp', 'math.exp', (['(-attenuation_ice * (ci - 2) * dz)'], {}), '(-attenuation_ice * (ci - 2) * dz)\n', (26620, 26654), False, 'import math\n'), ((29728, 29742), 'numpy.sum', 'np.sum', (['te[jj]'], {}), '(te[jj])\n', (29734, 29742), True, 'import numpy as np\n'), ((29774, 29811), 'numpy.logical_and', 'np.logical_and', (['(te < -p)', '(te != np.inf)'], {}), '(te < -p, te != np.inf)\n', (29788, 29811), True, 'import numpy as np\n'), ((33612, 33626), 'numpy.mean', 'np.mean', (['water'], {}), '(water)\n', (33619, 33626), True, 'import numpy as np\n'), ((36733, 36775), 'matplotlib.pyplot.axvline', 'plt.axvline', ([], {'x': '(0)', 'color': '"""k"""', 'linewidth': '(0.5)'}), "(x=0, color='k', linewidth=0.5)\n", (36744, 36775), True, 'from matplotlib import pyplot as plt\n'), ((15240, 15275), 'math.exp', 'math.exp', (['(-1 * snow[2, i] / ts_snow)'], {}), '(-1 * snow[2, i] / ts_snow)\n', (15248, 15275), False, 'import math\n'), ((29928, 29942), 'numpy.sum', 'np.sum', (['te[jj]'], {}), '(te[jj])\n', (29934, 29942), True, 'import numpy as np\n'), ((29624, 29638), 'numpy.sum', 'np.sum', (['te[jj]'], {}), '(te[jj])\n', (29630, 29638), True, 'import numpy as np\n'), ((18127, 18188), 'math.exp', 'math.exp', (['(-attenuation_snow * (i + 1) * dzs / (at_rho / 1000))'], {}), '(-attenuation_snow * (i + 1) * dzs / (at_rho / 1000))\n', (18135, 18188), False, 'import math\n'), ((18179, 18234), 'math.exp', 'math.exp', (['(-attenuation_snow * i * dzs / (at_rho / 1000))'], {}), '(-attenuation_snow * i * dzs / (at_rho / 1000))\n', (18187, 18234), False, 'import math\n'), ((29994, 30008), 'numpy.sum', 'np.sum', (['te[jj]'], {}), '(te[jj])\n', (30000, 30008), True, 'import numpy as np\n'), ((33877, 33920), 'math.exp', 'math.exp', (['(-attenuation_water * (i - 1) * dz)'], {}), '(-attenuation_water * (i - 1) * dz)\n', (33885, 33920), False, 'import math\n'), ((33915, 33952), 'math.exp', 'math.exp', (['(-attenuation_water * i * dz)'], {}), '(-attenuation_water * i * dz)\n', (33923, 33952), False, 'import math\n'), ((26095, 26136), 'math.exp', 'math.exp', (['(-attenuation_ice * (i - 1) * dz)'], {}), '(-attenuation_ice * (i - 1) * dz)\n', (26103, 26136), False, 'import math\n'), ((26131, 26166), 'math.exp', 'math.exp', (['(-attenuation_ice * i * dz)'], {}), '(-attenuation_ice * i * dz)\n', (26139, 26166), False, 'import math\n'), ((26493, 26534), 'math.exp', 'math.exp', (['(-attenuation_ice * (i - 1) * dz)'], {}), '(-attenuation_ice * (i - 1) * dz)\n', (26501, 26534), False, 'import math\n'), ((26529, 26564), 'math.exp', 'math.exp', (['(-attenuation_ice * i * dz)'], {}), '(-attenuation_ice * i * dz)\n', (26537, 26564), False, 'import math\n')] |
from pathlib import Path
from functools import cmp_to_key
import attr
import math
import json
import torch
import torch.nn.functional as F
import torchvision.transforms as transforms
import numpy as np
from PIL import Image
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
@attr.s(auto_attribs=True)
class Tag:
tag: str
caption_score: float
word_score: float
caption_length: int
caption_index: int
@property
def score(self):
return self.caption_score*100 + self.word_score
@property
def caption_score_compensated(self):
""" note: the caption score is a sum of logarithmic values"""
return self.caption_score ** (1./self.caption_length)
def compare_tags(tag1: Tag, tag2: Tag):
if tag1.caption_score < tag2.caption_score:
return -1
if tag1.caption_score > tag2.caption_score:
return 1
return -1 if tag1.word_score < tag2.word_score else 1
def caption_image_beam_search(encoder, decoder, image_path, word_map, beam_size=3):
"""
Reads an image and captions it with beam search.
:param encoder: encoder model
:param decoder: decoder model
:param image_path: path to image
:param word_map: word map
:param beam_size: number of sequences to consider at each decode-step
:return: captions, scores for captions, scores for individual words in captions
"""
k = beam_size
vocab_size = len(word_map)
# Read image and process
# img = imread(image_path)
# if len(img.shape) == 2:
# img = img[:, :, np.newaxis]
# img = np.concatenate([img, img, img], axis=2)
img = Image.open(image_path)
img = img.resize((256, 256))
img = np.array(img)
# img = imresize(img, (256, 256))
img = img.transpose(2, 0, 1)
img = img / 255.
img = torch.FloatTensor(img).to(device)
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
transform = transforms.Compose([normalize])
image = transform(img) # (3, 256, 256)
# Encode
image = image.unsqueeze(0) # (1, 3, 256, 256)
encoder_out = encoder(image) # (1, enc_image_size, enc_image_size, encoder_dim)
enc_image_size = encoder_out.size(1)
encoder_dim = encoder_out.size(3)
# Flatten encoding
encoder_out = encoder_out.view(1, -1, encoder_dim) # (1, num_pixels, encoder_dim)
num_pixels = encoder_out.size(1)
# We'll treat the problem as having a batch size of k
encoder_out = encoder_out.expand(k, num_pixels, encoder_dim) # (k, num_pixels, encoder_dim)
# Tensor to store top k previous words at each step; now they're just <start>
k_prev_words = torch.LongTensor([[word_map['<start>']]] * k).to(device) # (k, 1)
# Tensor to store top k sequences; now they're just <start>
seqs = k_prev_words # (k, 1)
# Tensor to store top k sequences' scores; now they're just 0
top_k_scores = torch.zeros(k, 1).to(device) # (k, 1)
# Tensor to store top k sequences' scores per word; now they're just 0
top_k_scores_per_word = torch.zeros(k, 1).to(device) # (k, 1)
# Tensor to store top k sequences' alphas; now they're just 1s
seqs_alpha = torch.ones(k, 1, enc_image_size, enc_image_size).to(device) # (k, 1, enc_image_size, enc_image_size)
# Lists to store completed sequences, their alphas and scores
complete_seqs = list()
complete_seqs_alpha = list()
complete_seqs_scores = list()
complete_seqs_scores_per_word = list()
# Start decoding
step = 1
h, c = decoder.init_hidden_state(encoder_out)
# s is a number less than or equal to k, because sequences are removed from this process once they hit <end>
while True:
embeddings = decoder.embedding(k_prev_words).squeeze(1) # (s, embed_dim)
awe, alpha = decoder.attention(encoder_out, h) # (s, encoder_dim), (s, num_pixels)
alpha = alpha.view(-1, enc_image_size, enc_image_size) # (s, enc_image_size, enc_image_size)
gate = decoder.sigmoid(decoder.f_beta(h)) # gating scalar, (s, encoder_dim)
awe = gate * awe
h, c = decoder.decode_step(torch.cat([embeddings, awe], dim=1), (h, c)) # (s, decoder_dim)
scores_for_individual_words = decoder.fc(h) # (s, vocab_size)
scores_for_individual_words = F.log_softmax(scores_for_individual_words, dim=1)
# Add
scores = top_k_scores.expand_as(scores_for_individual_words) + scores_for_individual_words # (s, vocab_size)
# For the first step, all k points will have the same scores (since same k previous words, h, c)
if step == 1:
top_k_scores, top_k_words = scores[0].topk(k, 0, True, True) # (s)
else:
# Unroll and find top scores, and their unrolled indices
top_k_scores, top_k_words = scores.view(-1).topk(k, 0, True, True) # (s)
# Convert unrolled indices to actual indices of scores
# prev_word_inds = top_k_words / vocab_size # (s)
prev_word_inds = torch.div(top_k_words, vocab_size, rounding_mode='trunc') # fix for pytorch > 0.4.0
next_word_inds = top_k_words % vocab_size # (s)
top_k_scores_individual_word = scores_for_individual_words.view(-1)[top_k_words]
# Add new words to sequences, alphas
seqs = torch.cat([seqs[prev_word_inds], next_word_inds.unsqueeze(1)], dim=1) # (s, step+1)
seqs_alpha = torch.cat([seqs_alpha[prev_word_inds], alpha[prev_word_inds].unsqueeze(1)],
dim=1) # (s, step+1, enc_image_size, enc_image_size)
top_k_scores_per_word = torch.cat([top_k_scores_per_word[prev_word_inds], top_k_scores_individual_word.unsqueeze(1)], dim=1) # (s, step+1)
# Which sequences are incomplete (didn't reach <end>)?
incomplete_inds = [ind for ind, next_word in enumerate(next_word_inds) if
next_word != word_map['<end>']]
complete_inds = list(set(range(len(next_word_inds))) - set(incomplete_inds))
# Set aside complete sequences
if len(complete_inds) > 0:
complete_seqs.extend(seqs[complete_inds].tolist())
complete_seqs_alpha.extend(seqs_alpha[complete_inds].tolist())
complete_seqs_scores.extend(top_k_scores[complete_inds])
complete_seqs_scores_per_word.extend(top_k_scores_per_word[complete_inds].tolist())
k -= len(complete_inds) # reduce beam length accordingly
# Proceed with incomplete sequences
if k == 0:
break
seqs = seqs[incomplete_inds]
seqs_alpha = seqs_alpha[incomplete_inds]
h = h[prev_word_inds[incomplete_inds]]
c = c[prev_word_inds[incomplete_inds]]
encoder_out = encoder_out[prev_word_inds[incomplete_inds]]
top_k_scores = top_k_scores[incomplete_inds].unsqueeze(1)
top_k_scores_per_word = top_k_scores_per_word[incomplete_inds]
k_prev_words = next_word_inds[incomplete_inds].unsqueeze(1)
# Break if things have been going on too long
if step > 50:
break
step += 1
# i = complete_seqs_scores.index(max(complete_seqs_scores))
# seq = complete_seqs[i]
# alphas = complete_seqs_alpha[i]
rev_word_map = {v: k for k, v in word_map.items()}
sentences = [[rev_word_map[i] for i in seq] for seq in complete_seqs]
return sentences, list(map(lambda x: x.tolist(), complete_seqs_scores)), complete_seqs_scores_per_word
def get_tags_from_captions(captions, scores_per_caption, scores_per_word):
"""
takes the captions extracted from the image and converts them to tags
:param captions: the different captions (list[list[str]])
:param scores_per_caption: the log score of the captions (list[float])
:param scores_per_word: the log score of the individual words in the captions (list[list[float]])
:return: list of ordered tags
"""
non_wanted_words = get_non_wanted_tags()
tags = dict()
for i, (words, word_scores, caption_score) in enumerate(zip(captions, scores_per_word, scores_per_caption)):
caption_score = math.exp(caption_score)
caption_length = len(words)
for word, word_score in zip(words, word_scores):
if word not in non_wanted_words:
word_score = math.exp(word_score)
if word not in tags:
tags[word] = Tag(tag=word, word_score=word_score, caption_score=caption_score,
caption_length=caption_length, caption_index=i)
else:
# if word_score > tags[word].word_score:
# tags[word].word_score = word_score
if caption_score > tags[word].caption_score:
tags[word].word_score = word_score
tags[word].caption_score = caption_score
tags[word].caption_length = caption_length
tags[word].caption_index = i
tags = list(tags.values())
t1 = sorted(tags, key=lambda t: t.score, reverse=True)
t2 = sorted(tags, key=lambda t: t.caption_score_compensated+t.word_score, reverse=True)
t3 = sorted(tags, key=cmp_to_key(compare_tags))
return t1, t2, t3
def get_non_wanted_tags():
non_wanted_words = {'<start>', '<end>',
'a', 'with', 'of', 'on', 'the', 'to', 'and', 'in', 'is', 'her', 'his', 'there', 'that', 'an',
'next', 'who', 'while', 'at', 'he', 'she', 'up', 'using', 'each', 'other', 'are', 'something',
'has', 'it', 'doing', 'their', 'for', '<unk>', 'for'}
return non_wanted_words
class Tagger():
def __init__(self, model_checkpoint_file: Path, word_map_file: Path):
self.model_checkpoint_file = model_checkpoint_file
self.word_map_file = word_map_file
checkpoint = torch.load(self.model_checkpoint_file, map_location=str(device))
self.decoder = checkpoint['decoder']
self.decoder = self.decoder.to(device)
self.decoder.eval()
self.encoder = checkpoint['encoder']
self.encoder = self.encoder.to(device)
self.encoder.eval()
self.word_map = json.loads(self.word_map_file.read_text())
def tag(self, image_file: Path, beam_size=15):
# Encode, decode with attention and beam search
captions, scores, scores_per_word = caption_image_beam_search(self.encoder, self.decoder, image_file,
self.word_map, beam_size)
t1, t2, t3 = get_tags_from_captions(captions, scores, scores_per_word)
return {'score': t1, 'combined_score': t2, 'magic_score': t3}
if __name__ == '__main__':
ROOT = Path(__file__).parents[1]
image_file = ROOT / 'images/test_03__001_2021_11_insp_vatertag_thementeaser_querformat_125642.jpg'
model_checkpoint_file = ROOT / 'checkpoint/BEST_checkpoint_coco_5_cap_per_img_5_min_word_freq.pth.tar'
word_map_file = ROOT / 'checkpoint/WORDMAP_coco_5_cap_per_img_5_min_word_freq.json'
tagger = Tagger(model_checkpoint_file=model_checkpoint_file, word_map_file=word_map_file)
t = tagger.tag(image_file, beam_size=15)
print(t) | [
"torch.ones",
"math.exp",
"torch.LongTensor",
"attr.s",
"torch.FloatTensor",
"torch.cat",
"PIL.Image.open",
"pathlib.Path",
"torchvision.transforms.Compose",
"numpy.array",
"torch.cuda.is_available",
"torch.nn.functional.log_softmax",
"torch.zeros",
"torchvision.transforms.Normalize",
"f... | [((299, 324), 'attr.s', 'attr.s', ([], {'auto_attribs': '(True)'}), '(auto_attribs=True)\n', (305, 324), False, 'import attr\n'), ((1649, 1671), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (1659, 1671), False, 'from PIL import Image\n'), ((1715, 1728), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (1723, 1728), True, 'import numpy as np\n'), ((1881, 1956), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'mean': '[0.485, 0.456, 0.406]', 'std': '[0.229, 0.224, 0.225]'}), '(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n', (1901, 1956), True, 'import torchvision.transforms as transforms\n'), ((2010, 2041), 'torchvision.transforms.Compose', 'transforms.Compose', (['[normalize]'], {}), '([normalize])\n', (2028, 2041), True, 'import torchvision.transforms as transforms\n'), ((258, 283), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (281, 283), False, 'import torch\n'), ((4362, 4411), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['scores_for_individual_words'], {'dim': '(1)'}), '(scores_for_individual_words, dim=1)\n', (4375, 4411), True, 'import torch.nn.functional as F\n'), ((5070, 5127), 'torch.div', 'torch.div', (['top_k_words', 'vocab_size'], {'rounding_mode': '"""trunc"""'}), "(top_k_words, vocab_size, rounding_mode='trunc')\n", (5079, 5127), False, 'import torch\n'), ((8174, 8197), 'math.exp', 'math.exp', (['caption_score'], {}), '(caption_score)\n', (8182, 8197), False, 'import math\n'), ((1831, 1853), 'torch.FloatTensor', 'torch.FloatTensor', (['img'], {}), '(img)\n', (1848, 1853), False, 'import torch\n'), ((2721, 2766), 'torch.LongTensor', 'torch.LongTensor', (["([[word_map['<start>']]] * k)"], {}), "([[word_map['<start>']]] * k)\n", (2737, 2766), False, 'import torch\n'), ((2973, 2990), 'torch.zeros', 'torch.zeros', (['k', '(1)'], {}), '(k, 1)\n', (2984, 2990), False, 'import torch\n'), ((3116, 3133), 'torch.zeros', 'torch.zeros', (['k', '(1)'], {}), '(k, 1)\n', (3127, 3133), False, 'import torch\n'), ((3240, 3288), 'torch.ones', 'torch.ones', (['k', '(1)', 'enc_image_size', 'enc_image_size'], {}), '(k, 1, enc_image_size, enc_image_size)\n', (3250, 3288), False, 'import torch\n'), ((4187, 4222), 'torch.cat', 'torch.cat', (['[embeddings, awe]'], {'dim': '(1)'}), '([embeddings, awe], dim=1)\n', (4196, 4222), False, 'import torch\n'), ((9271, 9295), 'functools.cmp_to_key', 'cmp_to_key', (['compare_tags'], {}), '(compare_tags)\n', (9281, 9295), False, 'from functools import cmp_to_key\n'), ((10828, 10842), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (10832, 10842), False, 'from pathlib import Path\n'), ((8365, 8385), 'math.exp', 'math.exp', (['word_score'], {}), '(word_score)\n', (8373, 8385), False, 'import math\n')] |
#!/usr/bin/env python3
import numpy as np
import copy
import utilities as utils
"""
matlab stores data by column order, numpy stores by row order
q matlab: (4, 8, 2) python: (2, 4, 8) Structure of HHMM
PI matlab: (8, 8, 3) python: (3, 8, 8) Initial state distribution (Vertical)
A matlab: (8, 8, 3) python: (3, 8, 8) Transition probabilities (Horizontal)
B matlab: (4, 7, 8) python: (8, 4, 7) Observation probabilities (Emissions)
"""
maxIter = 100
maxError = 1.0e-03
depth = 4
width = 8
np.set_printoptions(suppress=True, linewidth=np.nan, threshold=np.nan)
alphabet = np.array([i for i in range(1, 9)])
# The values inside the matrix correspond to
q = np.zeros((2, depth, width))
# 0 -> No state present at the level
# 1 -> State
# 2 -> Signifies terminal state which recurses back to parent root
q[0] = np.array([[1, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 2, 0, 0, 0, 0, 0],
[1, 1, 2, 1, 1, 2, 0, 0],
[1, 1, 1, 2, 1, 1, 1, 2]])
# 0 -> No children
# x -> x children (in order of occurrence from the above) are assigned to the node
q[1] = np.array([[3, 0, 0, 0, 0, 0, 0, 0],
[3, 3, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 4, 4, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]])
testSeq = np.array([[1, 3, 1, 3, 2, 5, 8, 4, 2, 5, 4, 6, 7, 2, 8],
[7, 3, 5, 8, 3, 5, 2, 3, 7, 5, 4, 6, 3, 2, 5]])
# Here, we need to subtract 1 so we can index from alphabet literal to index
testSeq = testSeq - 1
alphabet = alphabet - 1
allY, allX = np.where(q[0, :, :] == 1)
# Indices of production states, which are nodes which do not have children
prodY, prodX = np.where((q[0, :, :] == 1) & (q[1, :, :] == 0))
# Indices of internal states (states which have children)
intY, intX = np.where(q[1, :, :] != 0)
np.random.seed(0)
IS_RANDOM = False
# Vertical Transitions
def init_vertial_transitions():
PI = np.zeros((depth - 1, width, width))
for i in range(len(allX)):
# Skip the first order (main root)
if allY[i] != 0:
# Walk backwards summing nodes that match that the parent says how many children it has
parent_i, = np.where(np.cumsum(q[1, allY[i] - 1, :]) >= allX[i] + 1)
parent_i = parent_i[0]
PI[allY[i] - 1, parent_i, allX[i]] = 1 + (np.random.random_sample() - 0.5) / 5
if not IS_RANDOM:
PI[allY[i] - 1, parent_i, allX[i]] = 1 + (0.65 - 0.5) / 5
return PI
# Horizontal Transitions
# Here, we assume all hidden states have a directed edge to all other nodes in current subtree/level
# TODO: prune these results to enforce grammar rules
def init_horizontal_transitions(PI):
A = np.zeros((depth - 1, width, width))
for i in range(len(allX)):
if allY[i] != 0:
parent_i, = np.where(np.cumsum(q[1, allY[i] - 1, :]) >= allX[i] + 1)
parent_i = parent_i[0]
jArray, = np.where(PI[allY[i] - 1, parent_i, :] != 0)
jArray = np.append(jArray, jArray[-1] + 1)
A[allY[i] - 1, allX[i], jArray] = 1 + (np.random.random_sample(jArray.shape[0]) - 0.5) / 5
if not IS_RANDOM:
A[allY[i] - 1, allX[i], jArray] = 1 + (np.array([0.45 for i in range(jArray.shape[0])]) - 0.5) / 5
return A
# Emissions
# Here, we assume each production state can emit all possible tokens
# TODO: prune these results to enforce grammar rules
def init_emissions():
B = np.zeros((len(alphabet), depth, width - 1))
for i in range(len(prodX)):
r = np.ones((len(alphabet))) + (np.random.random_sample(len(alphabet)) - 0.5) / 5
if not IS_RANDOM:
r = np.ones((len(alphabet))) + (np.array([0.60 for i in range(len(alphabet))]) - 0.5) / 5
B[:, prodY[i], prodX[i]] = r / np.sum(r)
return B
def train():
PI = init_vertial_transitions()
A = init_horizontal_transitions(PI)
B = init_emissions()
# Standarize
for row in range(width):
for col in range(depth - 1):
A[col, row, :] = np.nan_to_num(A[col, row, :] / np.sum(A[col, row, :]))
PI[col, row, :] = np.nan_to_num(PI[col, row, :] / np.sum(PI[col, row, :]))
# Matlab deepcopies by default
initA = copy.deepcopy(A)
initB = copy.deepcopy(B)
initPI = copy.deepcopy(PI)
Palt = 0
stop = 0
for iteration in range(maxIter):
print('Training iteration {}'.format(iteration))
ergA = np.zeros(initA.shape)
ergB = np.zeros(initB.shape)
ergPI = np.zeros(initPI.shape)
ergAVis = np.zeros(initA.shape)
ergBVis = np.zeros(initB.shape)
ergPIVis = np.zeros(initPI.shape)
Pact = 0
# Over each row of input
for s in range(testSeq.shape[0]):
seq = testSeq[s, :]
# why 0 here, its a never used arg ...
PI, A, B, P = utils.HHMM_EM(q, seq, initA, initPI, initB, alphabet, 0)
Pact = Pact + P
B = np.nan_to_num(B)
A = np.nan_to_num(A)
PI = np.nan_to_num(PI)
ergA = ergA + A
ergB = ergB + B
ergPI = ergPI + PI
# Standardize?
for i in range(len(prodX)):
ergBVis[:, prodY[i], prodX[i]] = np.nan_to_num(ergB[:, prodY[i], prodX[i]] / np.sum(ergB[:, prodY[i], prodX[i]]))
# Standardize?
for row in range(width):
for col in range(depth - 1):
ergAVis[col, row, :] = np.nan_to_num(ergA[col, row, :] / np.sum(ergA[col, row, :]))
ergPIVis[col, row, :] = np.nan_to_num(ergPI[col, row, :] / np.sum(ergPI[col, row, :]))
# Code to draw output.....
# This may not be exactly the same as matlab
if abs(Pact - Palt) / (1 + abs(Palt)) < maxError:
# Mask out q[0] where 1 if 1, 0 else
states = np.where(q[0] == 1, 1, 0)
if np.linalg.norm(ergAVis.flatten() - initA.flatten(), np.inf) / np.sum(states.flatten()) < maxError:
print('Convergence after {} iterations'.format(iteration))
stop = 1
if stop == 0:
Palt = Pact
initA = ergAVis
initB = ergBVis
initPI = ergPIVis
else:
break
# Finished
return ergPIVis, ergAVis, ergBVis
if __name__ == '__main__':
PI, A, B = train()
print(A)
| [
"copy.deepcopy",
"numpy.set_printoptions",
"numpy.random.seed",
"numpy.sum",
"numpy.nan_to_num",
"numpy.random.random_sample",
"numpy.zeros",
"utilities.HHMM_EM",
"numpy.append",
"numpy.cumsum",
"numpy.where",
"numpy.array"
] | [((531, 601), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress': '(True)', 'linewidth': 'np.nan', 'threshold': 'np.nan'}), '(suppress=True, linewidth=np.nan, threshold=np.nan)\n', (550, 601), True, 'import numpy as np\n'), ((699, 726), 'numpy.zeros', 'np.zeros', (['(2, depth, width)'], {}), '((2, depth, width))\n', (707, 726), True, 'import numpy as np\n'), ((851, 970), 'numpy.array', 'np.array', (['[[1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 2, 0, 0, 0, 0, 0], [1, 1, 2, 1, 1, 2, 0, \n 0], [1, 1, 1, 2, 1, 1, 1, 2]]'], {}), '([[1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 2, 0, 0, 0, 0, 0], [1, 1, 2, 1, \n 1, 2, 0, 0], [1, 1, 1, 2, 1, 1, 1, 2]])\n', (859, 970), True, 'import numpy as np\n'), ((1126, 1245), 'numpy.array', 'np.array', (['[[3, 0, 0, 0, 0, 0, 0, 0], [3, 3, 0, 0, 0, 0, 0, 0], [0, 0, 0, 4, 4, 0, 0, \n 0], [0, 0, 0, 0, 0, 0, 0, 0]]'], {}), '([[3, 0, 0, 0, 0, 0, 0, 0], [3, 3, 0, 0, 0, 0, 0, 0], [0, 0, 0, 4, \n 4, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]])\n', (1134, 1245), True, 'import numpy as np\n'), ((1303, 1411), 'numpy.array', 'np.array', (['[[1, 3, 1, 3, 2, 5, 8, 4, 2, 5, 4, 6, 7, 2, 8], [7, 3, 5, 8, 3, 5, 2, 3, 7,\n 5, 4, 6, 3, 2, 5]]'], {}), '([[1, 3, 1, 3, 2, 5, 8, 4, 2, 5, 4, 6, 7, 2, 8], [7, 3, 5, 8, 3, 5,\n 2, 3, 7, 5, 4, 6, 3, 2, 5]])\n', (1311, 1411), True, 'import numpy as np\n'), ((1566, 1591), 'numpy.where', 'np.where', (['(q[0, :, :] == 1)'], {}), '(q[0, :, :] == 1)\n', (1574, 1591), True, 'import numpy as np\n'), ((1682, 1729), 'numpy.where', 'np.where', (['((q[0, :, :] == 1) & (q[1, :, :] == 0))'], {}), '((q[0, :, :] == 1) & (q[1, :, :] == 0))\n', (1690, 1729), True, 'import numpy as np\n'), ((1801, 1826), 'numpy.where', 'np.where', (['(q[1, :, :] != 0)'], {}), '(q[1, :, :] != 0)\n', (1809, 1826), True, 'import numpy as np\n'), ((1828, 1845), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (1842, 1845), True, 'import numpy as np\n'), ((1930, 1965), 'numpy.zeros', 'np.zeros', (['(depth - 1, width, width)'], {}), '((depth - 1, width, width))\n', (1938, 1965), True, 'import numpy as np\n'), ((2718, 2753), 'numpy.zeros', 'np.zeros', (['(depth - 1, width, width)'], {}), '((depth - 1, width, width))\n', (2726, 2753), True, 'import numpy as np\n'), ((4252, 4268), 'copy.deepcopy', 'copy.deepcopy', (['A'], {}), '(A)\n', (4265, 4268), False, 'import copy\n'), ((4281, 4297), 'copy.deepcopy', 'copy.deepcopy', (['B'], {}), '(B)\n', (4294, 4297), False, 'import copy\n'), ((4311, 4328), 'copy.deepcopy', 'copy.deepcopy', (['PI'], {}), '(PI)\n', (4324, 4328), False, 'import copy\n'), ((4466, 4487), 'numpy.zeros', 'np.zeros', (['initA.shape'], {}), '(initA.shape)\n', (4474, 4487), True, 'import numpy as np\n'), ((4503, 4524), 'numpy.zeros', 'np.zeros', (['initB.shape'], {}), '(initB.shape)\n', (4511, 4524), True, 'import numpy as np\n'), ((4541, 4563), 'numpy.zeros', 'np.zeros', (['initPI.shape'], {}), '(initPI.shape)\n', (4549, 4563), True, 'import numpy as np\n'), ((4583, 4604), 'numpy.zeros', 'np.zeros', (['initA.shape'], {}), '(initA.shape)\n', (4591, 4604), True, 'import numpy as np\n'), ((4623, 4644), 'numpy.zeros', 'np.zeros', (['initB.shape'], {}), '(initB.shape)\n', (4631, 4644), True, 'import numpy as np\n'), ((4664, 4686), 'numpy.zeros', 'np.zeros', (['initPI.shape'], {}), '(initPI.shape)\n', (4672, 4686), True, 'import numpy as np\n'), ((2949, 2992), 'numpy.where', 'np.where', (['(PI[allY[i] - 1, parent_i, :] != 0)'], {}), '(PI[allY[i] - 1, parent_i, :] != 0)\n', (2957, 2992), True, 'import numpy as np\n'), ((3014, 3047), 'numpy.append', 'np.append', (['jArray', '(jArray[-1] + 1)'], {}), '(jArray, jArray[-1] + 1)\n', (3023, 3047), True, 'import numpy as np\n'), ((3809, 3818), 'numpy.sum', 'np.sum', (['r'], {}), '(r)\n', (3815, 3818), True, 'import numpy as np\n'), ((4890, 4946), 'utilities.HHMM_EM', 'utils.HHMM_EM', (['q', 'seq', 'initA', 'initPI', 'initB', 'alphabet', '(0)'], {}), '(q, seq, initA, initPI, initB, alphabet, 0)\n', (4903, 4946), True, 'import utilities as utils\n'), ((4992, 5008), 'numpy.nan_to_num', 'np.nan_to_num', (['B'], {}), '(B)\n', (5005, 5008), True, 'import numpy as np\n'), ((5025, 5041), 'numpy.nan_to_num', 'np.nan_to_num', (['A'], {}), '(A)\n', (5038, 5041), True, 'import numpy as np\n'), ((5059, 5076), 'numpy.nan_to_num', 'np.nan_to_num', (['PI'], {}), '(PI)\n', (5072, 5076), True, 'import numpy as np\n'), ((5871, 5896), 'numpy.where', 'np.where', (['(q[0] == 1)', '(1)', '(0)'], {}), '(q[0] == 1, 1, 0)\n', (5879, 5896), True, 'import numpy as np\n'), ((2198, 2229), 'numpy.cumsum', 'np.cumsum', (['q[1, allY[i] - 1, :]'], {}), '(q[1, allY[i] - 1, :])\n', (2207, 2229), True, 'import numpy as np\n'), ((2844, 2875), 'numpy.cumsum', 'np.cumsum', (['q[1, allY[i] - 1, :]'], {}), '(q[1, allY[i] - 1, :])\n', (2853, 2875), True, 'import numpy as np\n'), ((4093, 4115), 'numpy.sum', 'np.sum', (['A[col, row, :]'], {}), '(A[col, row, :])\n', (4099, 4115), True, 'import numpy as np\n'), ((4179, 4202), 'numpy.sum', 'np.sum', (['PI[col, row, :]'], {}), '(PI[col, row, :])\n', (4185, 4202), True, 'import numpy as np\n'), ((5315, 5350), 'numpy.sum', 'np.sum', (['ergB[:, prodY[i], prodX[i]]'], {}), '(ergB[:, prodY[i], prodX[i]])\n', (5321, 5350), True, 'import numpy as np\n'), ((2335, 2360), 'numpy.random.random_sample', 'np.random.random_sample', ([], {}), '()\n', (2358, 2360), True, 'import numpy as np\n'), ((3099, 3139), 'numpy.random.random_sample', 'np.random.random_sample', (['jArray.shape[0]'], {}), '(jArray.shape[0])\n', (3122, 3139), True, 'import numpy as np\n'), ((5523, 5548), 'numpy.sum', 'np.sum', (['ergA[col, row, :]'], {}), '(ergA[col, row, :])\n', (5529, 5548), True, 'import numpy as np\n'), ((5625, 5651), 'numpy.sum', 'np.sum', (['ergPI[col, row, :]'], {}), '(ergPI[col, row, :])\n', (5631, 5651), True, 'import numpy as np\n')] |
import numpy as np
import pytest
from abmarl.sim.corridor import MultiCorridor as Corridor
from abmarl.managers import TurnBasedManager
def test_init():
sim = Corridor()
wrapped_sim = TurnBasedManager(sim)
assert wrapped_sim.sim == sim
assert wrapped_sim.agents == sim.agents
assert next(wrapped_sim.agent_order) == 'agent0'
assert next(wrapped_sim.agent_order) == 'agent1'
assert next(wrapped_sim.agent_order) == 'agent2'
assert next(wrapped_sim.agent_order) == 'agent3'
assert next(wrapped_sim.agent_order) == 'agent4'
def test_reset_and_step():
np.random.seed(24)
sim = TurnBasedManager(Corridor())
obs = sim.reset()
assert sim.sim.corridor[4].id == 'agent3'
assert sim.sim.corridor[5].id == 'agent4'
assert sim.sim.corridor[6].id == 'agent2'
assert sim.sim.corridor[7].id == 'agent1'
assert sim.sim.corridor[8].id == 'agent0'
assert sim.done_agents == set()
assert obs == {'agent0': {'left': [True], 'position': [8], 'right': [False]}}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.RIGHT for agent_id in obs})
assert obs == {'agent1': {'left': [True], 'position': [7], 'right': [False]}}
assert reward == {'agent1': 0}
assert done == {'agent1': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.RIGHT for agent_id in obs})
assert obs == {'agent2': {'left': [True], 'position': [6], 'right': [False]}}
assert reward == {'agent2': 0}
assert done == {'agent2': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.RIGHT for agent_id in obs})
assert obs == {'agent3': {'left': [False], 'position': [4], 'right': [True]}}
assert reward == {'agent3': 0}
assert done == {'agent3': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.RIGHT for agent_id in obs})
assert obs == {'agent4': {'left': [True], 'position': [5], 'right': [False]}}
assert reward == {'agent4': -2}
assert done == {'agent4': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.RIGHT for agent_id in obs})
assert obs == {
'agent0': {'left': [True], 'position': [9], 'right': [False]},
'agent1': {'left': [True], 'position': [8], 'right': [False]}}
assert reward == {'agent0': 100, 'agent1': -1}
assert done == {'agent0': True, 'agent1': False, '__all__': False}
with pytest.raises(AssertionError):
sim.step({'agent0': Corridor.Actions.STAY})
obs, reward, done, info = sim.step({'agent1': Corridor.Actions.STAY})
assert obs == {'agent2': {'left': [True], 'position': [7], 'right': [True]}}
assert reward == {'agent2': -1,}
assert done == {'agent2': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.LEFT for agent_id in obs})
assert obs == {'agent3': {'left': [False], 'position': [4], 'right': [False]}}
assert reward == {'agent3': -5}
assert done == {'agent3': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.STAY for agent_id in obs})
assert obs == {'agent4': {'left': [False], 'position': [6], 'right': [True]}}
assert reward == {'agent4': -3}
assert done == {'agent4': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.LEFT for agent_id in obs})
assert obs == {'agent1': {'left': [True], 'position': [8], 'right': [False]}}
assert reward == {'agent1': -1}
assert done == {'agent1': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.RIGHT for agent_id in obs})
assert obs == {'agent2': {'left': [False], 'position': [7], 'right': [False]}}
assert reward == {'agent2': -5}
assert done == {'agent2': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.RIGHT for agent_id in obs})
assert obs == {'agent3': {'left': [False], 'position': [4], 'right': [True]}}
assert reward == {'agent3': -1}
assert done == {'agent3': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.RIGHT for agent_id in obs})
assert obs == {'agent4': {'left': [True], 'position': [5], 'right': [False]}}
assert reward == {'agent4': -3}
assert done == {'agent4': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.LEFT for agent_id in obs})
assert obs == {
'agent1': {'left': [True], 'position': [9], 'right': [False]},
'agent2': {'left': [False], 'position': [8], 'right': [False]}}
assert reward == {'agent1': 100, 'agent2': -1}
assert done == {'agent1': True, 'agent2': False, '__all__': False}
with pytest.raises(AssertionError):
sim.step({'agent1': Corridor.Actions.STAY})
obs, reward, done, info = sim.step({'agent2': Corridor.Actions.STAY})
assert obs == {'agent3': {'left': [False], 'position': [4], 'right': [True]}}
assert reward == {'agent3': -7,}
assert done == {'agent3': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.LEFT for agent_id in obs})
assert obs == {'agent4': {'left': [False], 'position': [5], 'right': [False]}}
assert reward == {'agent4': -5,}
assert done == {'agent4': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.RIGHT for agent_id in obs})
assert obs == {'agent2': {'left': [False], 'position': [8], 'right': [False]}}
assert reward == {'agent2': -1,}
assert done == {'agent2': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.RIGHT for agent_id in obs})
assert obs == {'agent3': {'left': [False], 'position': [3], 'right': [False]}}
assert reward == {'agent3': -1,}
assert done == {'agent3': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.RIGHT for agent_id in obs})
assert obs == {'agent4': {'left': [False], 'position': [6], 'right': [False]}}
assert reward == {'agent4': -1,}
assert done == {'agent4': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.RIGHT for agent_id in obs})
assert obs == {
'agent2': {'left': [False], 'position': [9], 'right': [False]},
'agent3': {'left': [False], 'position': [4], 'right': [False]}}
assert reward == {'agent2': 100, 'agent3': -1}
assert done == {'agent2': True, 'agent3': False, '__all__': False}
with pytest.raises(AssertionError):
sim.step({'agent2': Corridor.Actions.STAY})
obs, reward, done, info = sim.step({'agent3': Corridor.Actions.RIGHT})
assert obs == {'agent4': {'left': [False], 'position': [7], 'right': [False]}}
assert reward == {'agent4': -1,}
assert done == {'agent4': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.RIGHT for agent_id in obs})
assert obs == {'agent3': {'left': [False], 'position': [5], 'right': [False]}}
assert reward == {'agent3': -1,}
assert done == {'agent3': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.RIGHT for agent_id in obs})
assert obs == {'agent4': {'left': [False], 'position': [8], 'right': [False]}}
assert reward == {'agent4': -1,}
assert done == {'agent4': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.RIGHT for agent_id in obs})
assert obs == {'agent3': {'left': [False], 'position': [6], 'right': [False]}}
assert reward == {'agent3': -1,}
assert done == {'agent3': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.RIGHT for agent_id in obs})
assert obs == {
'agent4': {'left': [False], 'position': [9], 'right': [False]},
'agent3': {'left': [False], 'position': [7], 'right': [False]}}
assert reward == {'agent4': 100, 'agent3': -1}
assert done == {'agent4': True, 'agent3': False, '__all__': False}
with pytest.raises(AssertionError):
sim.step({'agent4': Corridor.Actions.STAY})
obs, reward, done, info = sim.step({'agent3': Corridor.Actions.RIGHT})
assert obs == {'agent3': {'left': [False], 'position': [8], 'right': [False]}}
assert reward == {'agent3': -1,}
assert done == {'agent3': False, '__all__': False}
obs, reward, done, info = sim.step({agent_id: Corridor.Actions.RIGHT for agent_id in obs})
assert obs == {'agent3': {'left': [False], 'position': [9], 'right': [False]}}
assert reward == {'agent3': 100,}
assert done == {'agent3': True, '__all__': True}
| [
"pytest.raises",
"numpy.random.seed",
"abmarl.managers.TurnBasedManager",
"abmarl.sim.corridor.MultiCorridor"
] | [((166, 176), 'abmarl.sim.corridor.MultiCorridor', 'Corridor', ([], {}), '()\n', (174, 176), True, 'from abmarl.sim.corridor import MultiCorridor as Corridor\n'), ((195, 216), 'abmarl.managers.TurnBasedManager', 'TurnBasedManager', (['sim'], {}), '(sim)\n', (211, 216), False, 'from abmarl.managers import TurnBasedManager\n'), ((593, 611), 'numpy.random.seed', 'np.random.seed', (['(24)'], {}), '(24)\n', (607, 611), True, 'import numpy as np\n'), ((639, 649), 'abmarl.sim.corridor.MultiCorridor', 'Corridor', ([], {}), '()\n', (647, 649), True, 'from abmarl.sim.corridor import MultiCorridor as Corridor\n'), ((2485, 2514), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (2498, 2514), False, 'import pytest\n'), ((4819, 4848), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (4832, 4848), False, 'import pytest\n'), ((6626, 6655), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (6639, 6655), False, 'import pytest\n'), ((8165, 8194), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (8178, 8194), False, 'import pytest\n')] |
# Copyright (C) 2020 GreenWaves Technologies, SAS
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This program 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# Copied from TOCO code to reference orders
# // Helper to deal with TensorFlow arrays using a different ordering of
# // dimensions
# // ("axes") than our own.
# // we should have associative arrays mapping symbolic axes identifiers (like
# // "output_depth") to dimensions. We would then not need this anymore.
# enum class AxesOrder {
# kOneAxis, // one-dimensional array, one unique axis.
# kCR, // column-major matrix storage order. Our standard.
# kRC, // row-major matrix storage order. TensorFlow default.
# kOHWI, // Our standard for conv weights
# kHWIO, // TensorFlow conv weights
# k1HWO, // Our standard for DepthwiseConv weights
# kHWIM, // TensorFlow DepthwiseConv weights
# kNHWC, // TensorFlow activations
# kHWOI, // TensorFlow back-prop conv weights
# };
import logging
import os
from copy import deepcopy
from functools import reduce
import numpy as np
from graph.constant_store import ConstantStore
from graph.dim import (Conv2DFilterDim, Dim, FcFilterDim, PadDim,
PoolFilterDim, StrideDim)
from graph.nngraph import NNGraph
from graph.types import (ActivationParameters, ConcatParameters,
Conv2DParameters, FcParameters, GlobalPoolParameters,
MatrixAddParameters, MatrixDivParameters,
MatrixMulParameters, MatrixSubParameters, NNEdge,
NoOPParameters, PadParameters, PoolingParameters,
ReshapeParameters, SoftMaxParameters,
UnconvertedOpParameters, UnknownOpParameters)
from quantization.multiplicative.asymmetric.asymmetric_mult_qtype import \
AsymmetricMultQType
from quantization.multiplicative.mult_quantization import (
MultAddQuantizationRecord, MultConstantQuantizationRecord,
MultQuantizationRecord, MultQuantizationRecordBase,
MultScalableFilterQuantizationRecord)
from quantization.multiplicative.symmetric.mult_mulbias_qtype_new import \
MultMulBiasScaleQType
from quantization.multiplicative.symmetric.symmetric_mult_biases_qtype import \
SymmetricMultBiasesQType
from quantization.multiplicative.symmetric.symmetric_mult_qtype import \
SymmetricMultQType
from quantization.multiplicative.symmetric.symmetric_mult_qtype_wrapper import \
SymmetricMultQTypeWrapper
from quantization.quantization_set import QuantizationSet
from utils.add_sys_path import add_sys_path
from utils.graph import Node
from utils.node_id import NodeId
from utils.sparse_list import SparseList
from ..importer_base import ImporterBase
from . import utils
from .propagate_hints import propagate_hints
from .tflite_schema_head import (ActivationFunctionType, AddOptions,
ConcatenationOptions, Conv2DOptions,
DepthwiseConv2DOptions, DivOptions,
FullyConnectedOptions, Model, MulOptions,
Padding, Pool2DOptions, ReshapeOptions,
SoftmaxOptions, SubOptions, TensorType)
class TFLiteImportException(Exception):
pass
LOG = logging.getLogger('nntool.' + __name__)
# The tensor shape. The meaning of each entry is operator-specific but
# builtin ops use: [batch size, number of channels, height, width] (That's
# Tensorflow's NHWC).
# Map to internal activation function names
TF_ACTIVATIONS = {
ActivationFunctionType.ActivationFunctionType.RELU: "relu",
ActivationFunctionType.ActivationFunctionType.RELU6: "relu6",
ActivationFunctionType.ActivationFunctionType.SIGN_BIT: "sign_bit",
ActivationFunctionType.ActivationFunctionType.TANH: "tanh"
}
TF_ACTIVATION_OPERATORS = {
"LOGISTIC": "hsigmoid",
"RELU": "relu",
"RELU6": "relu6",
"TANH": "tanh",
"HARD_SWISH": "hswish"
}
UNDIGNED_TO_SIGNED = {
np.uint8: np.int8,
np.uint16: np.int16,
np.uint32: np.int32
}
def check(condition, message):
if not condition:
raise TFLiteImportException(message)
# Switch from same/valid padding to actual padding dimensions
def get_tf_padding(padding):
if padding == Padding.Padding.SAME:
return PadDim.same()
if padding == Padding.Padding.VALID:
return PadDim.valid()
raise ValueError("Strange padding type")
TF_LITE_IN_OUT_ORDER = ['n', 'h', 'w', 'c']
TF_LITE_RED_IN_OUT_ORDER = ['h', 'w', 'c']
TF_LITE_FILT_IN_C = 0
TF_LITE_FILT_H = 1
TF_LITE_FILT_W = 2
TF_LITE_FILT_OUT_C = 3
TF_LITE_FILTER_ORDER = ['out_c', 'h', 'w', 'in_c']
# in_c should always be 1 in this case
# Why does TFLite use this weird order for depthwise?
TF_LITE_DW_FILTER_ORDER = ['in_c', 'h', 'w', 'out_c']
TF_LITE_DW_FILTER_TRANSPOSE = [TF_LITE_DW_FILTER_ORDER.index(dim) for dim in TF_LITE_FILTER_ORDER]
def add_node(G: NNGraph, node: Node, anode: Node = None) -> str:
G.add_node(node)
if not anode:
return (node, node)
G.add_node(anode)
G.add_edge(NNEdge(node, anode))
return (node, anode)
def aname(name):
return name + "_activation"
def get_tensor_at_subgraph_idx(model, tensors, tf_idx):
tensor = tensors[tf_idx]
tensor.used = True
return tensor.get_value(model)
def get_tensor(model, tensors, elem, idx):
check(elem.InputsLength() >= idx + 1, "Not enough input tensors")
tf_idx = elem.Inputs(idx)
return get_tensor_at_subgraph_idx(model, tensors, tf_idx)
def get_shape(subgraph, tf_idx, order):
if order is None:
shape = []
tf_tensor = subgraph.Tensors(tf_idx)
for i in range(tf_tensor.ShapeLength()):
shape.append(tf_tensor.Shape(i))
return shape
shape = {}
tf_tensor = subgraph.Tensors(tf_idx)
check(tf_tensor.ShapeLength() == len(order), "Shape incorrect")
for i, j in enumerate(order):
shape[j] = tf_tensor.Shape(i)
return shape
def remove_batch_dim(dim):
check(dim[0] == 1, "batch dimension should be 1")
return dim[1:]
def get_input_size(tensors, subgraph, elem, idx, order=None):
check(elem.InputsLength() >= idx + 1, "Not enough input tensors")
tf_idx = elem.Inputs(idx)
if tensors:
tensors[tf_idx].used = True
return get_shape(subgraph, tf_idx, order)
def get_input_tensors(tensors, elem):
return [tensors[tf_idx] for tf_idx in elem.InputsAsNumpy()]
def get_output_tensors(tensors, elem):
return [tensors[tf_idx] for tf_idx in elem.OutputsAsNumpy()]
def get_broadcasted_shape(model, other):
idx_model = 0
idx_other = 0
res_other = []
while idx_model < len(model):
if len(other) > idx_other and (model[idx_model] == other[idx_other] or other[idx_other] == 1):
res_other.append(other[idx_other])
idx_other += 1
else:
res_other.append(1)
idx_model += 1
assert len(model) == len(res_other), "{} and {} cannot be broadcasted".format(
",".join(model), ",".join(other))
return res_other
def get_all_const_broadcasted_inputs(G, model, tensors, subgraph, elem, load_tensors=False):
"""Special version for nodes that can have constant inputs and support broadcasting"""
shapes = []
constant_nodes = []
max_len = 0
max_len_idx = -1
for idx in range(elem.InputsLength()):
tf_idx = elem.Inputs(idx)
shape = get_shape(subgraph, tf_idx, None)
# if shape is empty then it is a scalar
if len(shape) == 0:
shape = [1]
tensor = tensors[tf_idx]
if tensor.is_constant(model):
constant_nodes.append(tensor)
else:
constant_nodes.append(None)
shapes.append(shape)
if len(shape) > max_len:
max_len = len(shape)
max_len_idx = idx
assert constant_nodes[max_len_idx] is None, "can't handle broadcasting to a constant node"
largest = shapes[max_len_idx]
if len(largest) == 4 and largest[0] == 1:
largest = largest[1:]
for idx in range(elem.InputsLength()):
if idx == max_len_idx:
shapes[idx] = largest
continue
shape = shapes[idx]
# its not constant so should be a standard activation
if constant_nodes[idx] is None:
if len(shape) == 4 and shape[0] == 1:
shapes[idx] = shape[1:]
continue
# strip all ones off the start of the shape
# this has the side effect of getting rid of the batch dimension if there
while len(shape) > 1 and shape[0] == 1:
shape = shape[1:]
shape = get_broadcasted_shape(largest, shape)
tensor = constant_nodes[idx]
constant_node = G.add_constant(Dim.unnamed(shape))
constant_nodes[idx] = constant_node
if load_tensors:
constant_node.value = np.reshape(get_tensor_at_subgraph_idx(
model, tensors, elem.Inputs(idx)), shape)
shapes[idx] = shape
return list(zip(shapes, constant_nodes))
def get_all_input_dims(subgraph, elem, order=None):
inputs = []
for idx in range(elem.InputsLength()):
tf_idx = elem.Inputs(idx)
shape = get_shape(subgraph, tf_idx, order)
if len(shape) == 0:
continue
inputs.append(Dim.unnamed(remove_batch_dim(shape)))
return inputs
def get_all_output_dims(subgraph, elem, order=None):
outputs = []
for idx in range(elem.OutputsLength()):
tf_idx = elem.Outputs(idx)
outputs.append(Dim.unnamed(remove_batch_dim(get_shape(subgraph, tf_idx, order))))
return outputs
def get_fin_cput_size(subgraph, elem, idx):
shape = {}
check(elem.InputsLength() >= idx + 1, "Not enough input tensors")
tf_idx = elem.Inputs(idx)
tf_tensor = subgraph.Tensors(tf_idx)
check(tf_tensor.ShapeLength() >= 2, "Shape incorrect")
shape['n'] = tf_tensor.Shape(0)
tf_idx = elem.Inputs(idx + 1)
tf_tensor = subgraph.Tensors(tf_idx)
shape['filter_c'] = tf_tensor.Shape(0)
shape['filter_sz'] = tf_tensor.Shape(1)
return shape
class TfliteTensorWrapper():
TF_TO_NUMPY_TYPE = {
TensorType.TensorType.FLOAT32: np.float32,
TensorType.TensorType.FLOAT16: np.float16,
TensorType.TensorType.INT32: np.int32,
TensorType.TensorType.UINT8: np.uint8,
TensorType.TensorType.INT8: np.int8,
TensorType.TensorType.INT64: np.int64
}
def __init__(self, tensor):
self._tensor = tensor
self._name = tensor.Name().decode('ascii')
self._used = False
self._inputs = []
self._output = None
@property
def name(self):
return self._name
@name.setter
def name(self, val):
self._name = val
@property
def used(self):
return self._used
@used.setter
def used(self, val):
self._used = val
@property
def inputs(self):
return self._inputs
@property
def output(self):
return self._output
@output.setter
def output(self, val):
self._output = val
@property
def buffer_idx(self):
return self._tensor.Buffer()
@property
def tf_tensor(self):
return self._tensor
@property
def is_variable(self):
return self._tensor.IsVariable()
@property
def shape(self):
return self._tensor.ShapeAsNumpy()
@property
def dtype(self):
return self.TF_TO_NUMPY_TYPE[self._tensor.Type()]
@property
def scale(self):
return self._tensor.Quantization().ScaleAsNumpy()
@property
def zero_point(self):
return self._tensor.Quantization().ZeroPointAsNumpy()
@property
def min_val(self):
return self._tensor.Quantization().MinAsNumpy()
@property
def max_val(self):
return self._tensor.Quantization().MaxAsNumpy()
@property
def is_uint_symmetric(self):
quant = self._tensor.Quantization()
if quant is not None:
return (self.dtype == np.uint8 or self.dtype == np.uint16 or self.dtype == np.uint32) and \
np.all(quant.ZeroPointAsNumpy() == 128)
return False
@property
def qtype(self):
quant = self._tensor.Quantization()
if quant is not None:
if quant.ScaleLength() == 0 and quant.MinLength() == 0 and\
quant.MaxLength() == 0 and quant.ZeroPointLength() == 0:
return None
if self.dtype == np.uint8 or self.dtype == np.uint16 or self.dtype == np.uint32:
if np.all(quant.ZeroPointAsNumpy() == 128):
return SymmetricMultQType.from_tflite(quant, self.dtype)
return SymmetricMultQTypeWrapper(AsymmetricMultQType.from_tflite(quant,
self.dtype))
elif self.dtype == np.int8 or self.dtype == np.int16 or self.dtype == np.int32:
if np.all(quant.ZeroPointAsNumpy() == 0):
return SymmetricMultQType.from_tflite(quant, self.dtype)
return SymmetricMultQTypeWrapper(AsymmetricMultQType.from_tflite(quant,
self.dtype))
return None
return None
def is_constant(self, model):
return self.buffer_idx != 0 and model.Buffers(self.buffer_idx).DataLength() != 0
def get_value(self, model):
tf_buffer = model.Buffers(self.buffer_idx)
np_buffer = np.frombuffer(tf_buffer.DataAsNumpy(), dtype=self.dtype().newbyteorder('L'))
np_buffer = np.resize(np_buffer, self.shape)
return np_buffer
def shape_as(self, order):
assert len(order) == len(self.shape), "tensor does not have correct number of dimensions"
return {k: v for k, v in zip(order, self.shape)}
class NoQuantizationError(Exception):
pass
class TfliteImporter(ImporterBase):
def __init__(self):
self.G = None
self.model = None
self.tensors = None
self.load_quantization = False
self.load_tensors = False
self.load_dequantized = False
self.qrecs = QuantizationSet()
self.rescale_perchannel = True
def fuse_activation(self, tfl_opts, name: str, node: Node):
if NodeId(node) in self.qrecs:
node_qrec = self.qrecs[NodeId(node)]
else:
node_qrec = None
if tfl_opts.FusedActivationFunction() == ActivationFunctionType.ActivationFunctionType.NONE:
if node_qrec is not None and isinstance(node_qrec, MultQuantizationRecordBase):
# here we have no activation in an asymmetric qtype -> may be an omitted relu
if node_qrec.out_qs[0].min_val == 0:
if np.all(np.round(node_qrec.out_qs[0].max_val) == 6):
anode = ActivationParameters.get_activation('relu6', aname(name))
else:
anode = ActivationParameters.get_activation('relu', aname(name))
else:
return add_node(self.G, node)
else:
return add_node(self.G, node)
else:
anode = ActivationParameters.get_activation(TF_ACTIVATIONS[tfl_opts.FusedActivationFunction()],
aname(name))
if self.load_quantization:
# In between the fused operation and activation the
# transfer is in int32 representation
node_qrec = self.qrecs[NodeId(node)]
outa_qtype = deepcopy(node_qrec.out_qs[0])
#node_qrec.out_qs[0].dtype = np.int32
ina_qtype = deepcopy(node_qrec.out_qs[0])
self.qrecs[NodeId(anode)] = MultQuantizationRecord(
in_qs=[ina_qtype], out_qs=[outa_qtype])
return add_node(self.G, node, anode=anode)
def add_unconverted(self, name, subgraph, op_name, op):
LOG.warning("graph has unknown operator %s and cannot be properly processed", op_name)
node = add_node(self.G,
UnconvertedOpParameters(
name,
op_name,
get_all_input_dims(subgraph, op),
get_all_output_dims(subgraph, op),
{
"tflite_op_name": op_name,
"tflite_op": op,
"tflite_subgraph": subgraph
}
))
return node
def make_weights_symmetric(self, node, input_tensors):
biases_scales = input_tensors[2].scale if node.has_bias else np.array([1], dtype=np.int32)
# already symmetric or something we don't know
if input_tensors[1].dtype != np.uint8:
return input_tensors[1].scale, biases_scales, None, None
weights_scales = input_tensors[1].scale
# symmetric unsigned. just change zero point scale stays the same
if np.all(input_tensors[1].zero_point == 128):
node.weights = (node.weights.astype(np.int64) - 128).astype(np.int8)
return weights_scales, biases_scales, None, None
# asymmetric unsigned. change zero point and rescale
if self.rescale_perchannel:
return self.scale_weights_by_channel(node, weights_scales, biases_scales,
input_tensors[0].qtype.scale,
zero_point=input_tensors[1].zero_point)
else:
return self.scale_weights_by_tensor(node, weights_scales, biases_scales,
input_tensors[0].qtype.scale,
zero_point=input_tensors[1].zero_point)
def scale_weights_by_tensor(self, node, weights_scales, biases_scales, in_scale, zero_point=None):
if zero_point is None:
zero_point = np.array([0])
if node.has_bias:
dq_biases = node.biases * biases_scales
else:
dq_biases = np.array([0] * node.filter.out_c, dtype=np.float32)
if len(weights_scales) > 1:
raise ValueError('You should not rescale perchannel weights to pertensor format')
dq_weights = (node.weights.astype(np.float32) - zero_point) * weights_scales
w_min = min(np.min(dq_weights), 0)
w_max = max(np.max(dq_weights), 0)
w_max = w_max if w_min != w_max and w_max == 0 else 1
w_abs_max = max(w_max, np.abs(w_min))
new_weights_scale = w_abs_max / 127
int8_iinfo = np.iinfo(np.int8)
int32_iinfo = np.iinfo(np.int32)
new_biases_scale = new_weights_scale * in_scale
node.weights = np.clip(np.floor(dq_weights / new_weights_scale + 0.5),
int8_iinfo.min,
int8_iinfo.max).astype(np.int8)
node.biases = np.clip(np.floor(dq_biases / new_biases_scale + 0.5),
int32_iinfo.min,
int32_iinfo.max).astype(np.int32)
return np.array([new_weights_scale]), np.array([new_biases_scale]),\
np.array([w_min]), np.array([w_max])
def scale_weights_by_channel(self, node, weights_scales, biases_scales, in_scale, zero_point=None):
# scale weights by channel optionally correcting zero point
if zero_point is None:
zero_point = np.array([0])
out_idx = node.filter.get_order_idx('out_c')
actual_len = len(node.filter.actual_shape)
ones_shape = tuple(node.filter.out_c if idx == out_idx else 1 for idx in range(actual_len))
filter_axis = tuple(idx for idx in range(actual_len) if idx != out_idx)
if node.has_bias:
dq_biases = node.biases * biases_scales
else:
dq_biases = np.array([0] * node.filter.out_c, dtype=np.float32)
if len(weights_scales) > 1:
weights_scales = weights_scales.reshape(ones_shape)
if len(zero_point) > 1:
zero_point = zero_point.reshape(ones_shape)
dq_weights = (node.weights.astype(np.float32) - zero_point) * weights_scales
w_mins = np.minimum(np.min(dq_weights, axis=filter_axis), 0)
w_maxes = np.maximum(np.max(dq_weights, axis=filter_axis), 0)
w_zero_cond = np.logical_and(w_mins == w_maxes, w_maxes == 0)
w_maxes = np.where(w_zero_cond, 1, w_maxes)
w_abs_maxes = np.maximum(np.abs(w_mins), w_maxes)
new_weights_scales = w_abs_maxes / 127
int8_iinfo = np.iinfo(np.int8)
int32_iinfo = np.iinfo(np.int32)
new_biases_scales = new_weights_scales * in_scale
np.seterr(all='raise')
node.weights = np.clip(np.floor(dq_weights / new_weights_scales.reshape(ones_shape) + 0.5),
int8_iinfo.min,
int8_iinfo.max).astype(np.int8)
node.biases = np.clip(np.floor(dq_biases / new_biases_scales + 0.5),
int32_iinfo.min,
int32_iinfo.max).astype(np.int32)
return new_weights_scales, new_biases_scales, w_mins, w_maxes
def detect_small_scales(self, node, weights_scales, biases_scales, in_scale):
# at this point all tensors are in expected formats
# weights int8 biases int32 channel scaled
tiny_weight_scales = weights_scales < SymmetricMultQType.kNearZeroTolerance
if np.count_nonzero(tiny_weight_scales) == 0:
return weights_scales, biases_scales
out_idx = node.filter.get_order_idx('out_c')
shape = tuple(slice(None) if idx !=
out_idx else tiny_weight_scales for idx in range(len(node.weights.shape)))
node.weights[shape] = 0
dq_biases = node.biases * biases_scales
weights_scales = np.where(tiny_weight_scales, 1, weights_scales)
biases_scales = in_scale * weights_scales
int32_iinfo = np.iinfo(np.int32)
node.biases = np.clip(np.floor(dq_biases / biases_scales + 0.5),
int32_iinfo.min,
int32_iinfo.max).astype(np.int32)
return weights_scales, biases_scales
def fix_weights_and_biases(self, node, input_tensors):
weights_scales, biases_scales, w_mins, w_maxes = self.make_weights_symmetric(
node, input_tensors)
if self.rescale_perchannel:
if len(weights_scales) != node.filter.out_c:
weights_scales, biases_scales, w_mins, w_maxes = self.scale_weights_by_channel(
node, weights_scales, biases_scales, input_tensors[0].qtype.scale)
weights_scales, biases_scales = self.detect_small_scales(
node, weights_scales, biases_scales, input_tensors[0].scale)
if w_mins is None:
w_mins = input_tensors[1].min_val
w_maxes = input_tensors[1].max_val
return weights_scales, biases_scales, w_mins, w_maxes
def load_filter_parameters(self, node, input_tensors, output_tensors, converted_to_conv=False):
if self.load_tensors or self.load_quantization:
node.weights = input_tensors[1].get_value(self.model)
if converted_to_conv:
node.weights = node.weights.transpose(TF_LITE_DW_FILTER_TRANSPOSE)
if node.has_bias:
node.biases = input_tensors[2].get_value(self.model)
if self.load_quantization:
if input_tensors[0].qtype is None:
raise NoQuantizationError("quantization not present in tflite file")
weights_scales, biases_scales, w_mins, w_maxes = self.fix_weights_and_biases(
node, input_tensors)
biases_q = SymmetricMultBiasesQType(dtype=np.int32, scale=biases_scales)
weights_q = SymmetricMultQType(
dtype=np.int8, narrow_range=True, scale=weights_scales, min_val=w_mins, max_val=w_maxes)
in_q = input_tensors[0].qtype
out_q = output_tensors[0].qtype
mulbiases_q = MultMulBiasScaleQType.from_filter(in_q, weights_q, out_q, node)
qrec = MultScalableFilterQuantizationRecord(in_qs=[in_q],
out_qs=[out_q],
mul_biases_q=mulbiases_q,
weights_q=weights_q,
biases_q=biases_q)
self.qrecs[NodeId(node)] = qrec
def load_dequantized_filter_parameters(self, node, input_tensors, converted_to_conv=False, is_dw=False):
weights_scales = input_tensors[1].scale
in_scale = input_tensors[0].scale
weights_quant = input_tensors[1].get_value(self.model)
# save in the node the dequantized values
if len(weights_scales) > 1: # tf2 conv and dw (fully connected should be per-tensor)
if is_dw:
# depthwise
shape_pc = tuple(size if idx == 3 else 1 # always along axis 3 from tflite quantization spec
for idx, size in enumerate(weights_quant.shape))
else:
# normal convolution
shape_pc = tuple(size if idx == 0 else 1 # always along axis 0 from tflite quantization spec
for idx, size in enumerate(weights_quant.shape))
node.weights = (weights_quant.astype(np.int64) - input_tensors[1].zero_point.reshape(shape_pc)) \
* weights_scales.reshape(shape_pc)
else:
node.weights = (weights_quant - input_tensors[1].zero_point) * weights_scales
if converted_to_conv:
node.weights = node.weights.transpose(TF_LITE_DW_FILTER_TRANSPOSE)
if node.has_bias:
biases_scales = weights_scales * in_scale
node.biases = input_tensors[2].get_value(self.model) * biases_scales
def add_convolution(self, name, subgraph, _, op):
del subgraph
conv_opts = Conv2DOptions.Conv2DOptions()
conv_opts.Init(op.BuiltinOptions().Bytes, op.BuiltinOptions().Pos)
input_tensors = get_input_tensors(self.tensors, op)
output_tensors = get_output_tensors(self.tensors, op)
# get filter dimensions
filt = input_tensors[1].shape_as(TF_LITE_FILTER_ORDER)
input_tensors[1].used = True
filt = Conv2DFilterDim(filt['h'], filt['w'],
filt['out_c'], in_c=filt['in_c'])
filt = filt.impose_order(TF_LITE_FILTER_ORDER)
# compute padding
pad = get_tf_padding(conv_opts.Padding())
# does it have biases
has_bias = op.InputsLength() > 2
if has_bias:
input_tensors[2].used = True
node = Conv2DParameters(name,
filt=filt,
stride=StrideDim(conv_opts.StrideH(),
conv_opts.StrideW()),
padding=pad,
has_bias=has_bias,
in_dims_hint=SparseList([['h', 'w', 'c']]),
out_dims_hint=SparseList([['h', 'w', 'c']]),
constant_store=self.G.constant_store)
if self.load_dequantized:
self.load_dequantized_filter_parameters(node, input_tensors)
else:
self.load_filter_parameters(node, input_tensors, output_tensors)
return self.fuse_activation(conv_opts, name, node)
def add_depthwise_convolution(self, name, subgraph, _, op):
del subgraph
conv_opts = DepthwiseConv2DOptions.DepthwiseConv2DOptions()
conv_opts.Init(op.BuiltinOptions().Bytes, op.BuiltinOptions().Pos)
input_tensors = get_input_tensors(self.tensors, op)
output_tensors = get_output_tensors(self.tensors, op)
# get filter dimensions
inp = input_tensors[0].shape_as(TF_LITE_IN_OUT_ORDER)
filt = input_tensors[1].shape_as(TF_LITE_DW_FILTER_ORDER)
input_tensors[1].used = True
filt = Conv2DFilterDim(filt['h'], filt['w'],
filt['out_c'], in_c=1)
# multiplier should match filter
check(filt.out_c == conv_opts.DepthMultiplier() * inp['c'],
"invalid multiplier")
groups = filt.out_c // conv_opts.DepthMultiplier()
# compute padding
pad = get_tf_padding(conv_opts.Padding())
# does it have biases
has_bias = op.InputsLength() > 2
if has_bias:
input_tensors[2].used = True
# TFLITE produces single channel input DW convolutions with the
# multiplier equal to the number of out channels. This is just
# a normal convolution and since we don't handle the channel
# multiplier at present (but can) just convert them to normal
# convolutions
convert_to_conv = inp['c'] == 1 and groups == 1
if convert_to_conv:
filt.impose_order(TF_LITE_FILTER_ORDER)
node = Conv2DParameters(name,
filt=filt,
stride=StrideDim(conv_opts.StrideH(), conv_opts.StrideW()),
padding=pad,
has_bias=has_bias,
in_dims_hint=SparseList([['h', 'w', 'c']]),
out_dims_hint=SparseList([['h', 'w', 'c']]),
constant_store=self.G.constant_store)
else:
filt.impose_order(TF_LITE_DW_FILTER_ORDER)
node = Conv2DParameters(name,
filt=filt,
stride=StrideDim(conv_opts.StrideH(), conv_opts.StrideW()),
padding=pad,
groups=groups,
multiplier=conv_opts.DepthMultiplier(),
has_bias=has_bias,
tf_depthwise=True,
in_dims_hint=SparseList([['h', 'w', 'c']]),
out_dims_hint=SparseList([['h', 'w', 'c']]),
constant_store=self.G.constant_store)
if self.load_dequantized:
self.load_dequantized_filter_parameters(
node, input_tensors, convert_to_conv, is_dw=True)
else:
self.load_filter_parameters(node, input_tensors, output_tensors,
converted_to_conv=convert_to_conv)
return self.fuse_activation(conv_opts, name, node)
TF_LITE_FC_ORDER = ['out_c', 'sz']
TF_LITE_FC_EXP_ORDER = ['out_c', 'h', 'w', 'in_c']
def add_fully_connected(self, name, subgraph, _, op):
del subgraph
fc_opts = FullyConnectedOptions.FullyConnectedOptions()
fc_opts.Init(op.BuiltinOptions().Bytes, op.BuiltinOptions().Pos)
input_tensors = get_input_tensors(self.tensors, op)
output_tensors = get_output_tensors(self.tensors, op)
# get filter dimensions
inp = input_tensors[0].shape
check(inp[0] == 1,
"Multi batch not supported")
filt = input_tensors[1].shape_as(self.TF_LITE_FC_ORDER)
input_tensors[1].used = True
check(filt['sz'] == reduce(lambda i, j: i * j, inp, 1), "filter doesn't match input size")
# in the case we get an input of 1 batch with everything flattened fill h and w with 1
if len(inp) == 2:
inp = {'h': 1, 'w': 1, 'c': inp[1]}
elif len(inp) == 3:
inp = {'h': 1, 'w': inp[1], 'c': inp[2]}
elif len(inp) == 4:
inp = {'h': inp[1], 'w': inp[2], 'c': inp[3]}
else:
raise NotImplementedError('FC input size not implemented')
filt_dim = FcFilterDim(inp['h'], inp['w'], filt['out_c'],
in_c=inp['c'], order=self.TF_LITE_FC_EXP_ORDER)
# does it have biases
has_bias = op.InputsLength() > 2
if has_bias:
input_tensors[2].used = True
node = FcParameters(name, filt=filt_dim, has_bias=has_bias,
in_dims_hint=SparseList([['h', 'w', 'c']]),
out_dims_hint=SparseList([['c']]),
constant_store=self.G.constant_store)
if self.load_dequantized:
self.load_dequantized_filter_parameters(node, input_tensors)
else:
self.load_filter_parameters(node, input_tensors, output_tensors)
return self.fuse_activation(fc_opts, name, node)
# map to internal pool layer types
TF_POOL_OPS = {
"AVERAGE_POOL_2D": "average",
"MAX_POOL_2D": "max"
}
def load_tf_quantization(self, input_tensors, output_tensors, qrec_class=None):
if qrec_class is None:
qrec_class = MultQuantizationRecord
qrec = qrec_class(in_qs=[tensor.qtype for tensor in input_tensors],
out_qs=[tensor.qtype for tensor in output_tensors])
return qrec
# pylint: disable=unused-argument
def add_pool(self, name, subgraph, op_name, op):
pool_opts = Pool2DOptions.Pool2DOptions()
pool_opts.Init(op.BuiltinOptions().Bytes, op.BuiltinOptions().Pos)
pad = get_tf_padding(pool_opts.Padding())
pool_type = self.TF_POOL_OPS[op_name]
input_tensors = get_input_tensors(self.tensors, op)
inp = input_tensors[0].shape_as(TF_LITE_IN_OUT_ORDER)
check(inp['n'] == 1,
"Multi batch not supported")
filter_matches_input = inp['h'] == pool_opts.FilterHeight(
) and inp['w'] == pool_opts.FilterWidth()
stride_is_one = pool_opts.StrideH() == 1 and pool_opts.StrideW() == 1
if filter_matches_input and stride_is_one:
node = GlobalPoolParameters(name,
pool_type=pool_type,
in_dims_hint=SparseList([['h', 'w', 'c']]),
out_dims_hint=SparseList([['h', 'w', 'c']]))
else:
node = PoolingParameters(name,
filt=PoolFilterDim(pool_opts.FilterHeight(),
pool_opts.FilterWidth()),
stride=StrideDim(pool_opts.StrideH(),
pool_opts.StrideW()),
padding=pad,
pool_type=pool_type,
in_dims_hint=SparseList([['h', 'w', 'c']]),
out_dims_hint=SparseList([['h', 'w', 'c']]))
if self.load_quantization:
self.qrecs[NodeId(node)] = self.load_tf_quantization(
input_tensors, get_output_tensors(self.tensors, op))
return self.fuse_activation(pool_opts, name, node)
# pylint: disable=unused-argument
def add_softmax(self, name, subgraph, _, op):
softmax_opts = SoftmaxOptions.SoftmaxOptions()
softmax_opts.Init(op.BuiltinOptions().Bytes, op.BuiltinOptions().Pos)
node = SoftMaxParameters(name, softmax_opts.Beta())
if self.load_quantization:
input_tensors = get_input_tensors(self.tensors, op)
iqtype = input_tensors[0].qtype
iqtype.scale_to_pow2()
oqtype = SymmetricMultQType(min_val=-1, max_val=1, dtype=np.int16, scale=2**(-15))
qrec = MultQuantizationRecord(in_qs=[iqtype],
out_qs=[oqtype])
self.qrecs[NodeId(node)] = qrec
return add_node(self.G, node)
def add_noop(self, name, subgraph, op_name, op):
node = NoOPParameters(name, desc=op_name)
if self.load_quantization:
self.qrecs[NodeId(node)] = self.load_tf_quantization(get_input_tensors(self.tensors, op),
get_output_tensors(self.tensors, op))
return add_node(self.G, node)
# pylint: disable=unused-argument
def add_concatenation(self, name, subgraph, _, op):
concat_opts = ConcatenationOptions.ConcatenationOptions()
concat_opts.Init(op.BuiltinOptions().Bytes, op.BuiltinOptions().Pos)
input_tensors = get_input_tensors(self.tensors, op)
output_tensors = get_output_tensors(self.tensors, op)
buffer_idxes = [tensor.buffer_idx for tensor in input_tensors]
if len(set(buffer_idxes)) != len(buffer_idxes):
raise NotImplementedError("concats with multiple versions of the same input are not supported. This is normally a graph design problem.")
axis_hint = None
axis = None
# nasty hack to try to figure out how the axis relates to our
# internal axis representation
if concat_opts.Axis() == 0:
if len(output_tensors[0].shape) == 2:
axis_hint = 'c'
axis = 0
elif len(output_tensors[0].shape) == 4:
axis_hint = 'h'
axis = 0
elif concat_opts.Axis() == 1:
if len(output_tensors[0].shape) == 2:
axis_hint = 'c'
axis = 0
elif len(output_tensors[0].shape) == 3:
axis = 0
elif len(output_tensors[0].shape) == 4:
axis_hint = 'h'
axis = 0
elif concat_opts.Axis() == 2:
if all(tensor.shape[1] == 1 for tensor in input_tensors):
axis_hint = 'w'
axis = 1
elif concat_opts.Axis() == 3:
if len(output_tensors[0].shape) == 4:
axis_hint = 'c'
axis = 2
if axis is None:
axis = concat_opts.Axis() - 1
node = ConcatParameters(name, axis=axis, axis_hint=axis_hint)
if self.load_quantization:
self.qrecs[NodeId(node)] = self.load_tf_quantization(input_tensors,
output_tensors)
return self.fuse_activation(concat_opts, name, node)
# pylint: disable=unused-argument
def add_reshape(self, name, subgraph, _, op):
reshape_opts = ReshapeOptions.ReshapeOptions()
reshape_opts.Init(op.BuiltinOptions().Bytes, op.BuiltinOptions().Pos)
input_tensors = get_input_tensors(self.tensors, op)
inp = input_tensors[0].shape
set_shape_tensor = input_tensors[1]
set_shape_tensor.used = True
# TODO - Which to use? Attribute or input? TFLITE seems to set both
new_shape = list(reshape_opts.NewShapeAsNumpy())
if -1 in new_shape:
new_shape_size = reduce(lambda x, y: x * 1 if y == -1 else x * y, new_shape, 1)
inp_size = reduce(lambda x, y: x * y, inp, 1)
new_shape[new_shape.index(-1)] = inp_size // new_shape_size
old_shape = Dim.unnamed(remove_batch_dim(inp), is_ordered=True)
new_shape = Dim.unnamed(remove_batch_dim(new_shape), is_ordered=True)
node = ReshapeParameters(name, old_shape=old_shape, shape=new_shape)
if self.load_quantization:
self.qrecs[NodeId(node)] = self.load_tf_quantization(
[input_tensors[0]], get_output_tensors(self.tensors, op))
return add_node(self.G, node)
# pylint: disable=unused-argument
def add_activation(self, name, subgraph, op_name, op):
check(op.InputsLength() == 1,
"Very odd " + str(op.InputsAsNumpy()))
node = ActivationParameters.get_activation(TF_ACTIVATION_OPERATORS[op_name], name)
if self.load_quantization:
self.qrecs[NodeId(node)] = self.load_tf_quantization(get_input_tensors(self.tensors, op),
get_output_tensors(self.tensors, op))
return add_node(self.G, node)
def add_pad(self, name, subgraph, op_name, op):
check(op.InputsLength() == 2,
"Very odd " + str(op.InputsAsNumpy()))
pad_dim = get_tensor(self.model, self.tensors, op, 1)
assert np.all(pad_dim[3] == 0), "channel padding not supported"
pad_dim = [int(pad_dim[i][j]) for i in range(1, 3) for j in range(2)]
node = PadParameters(name,
PadDim(*pad_dim))
if self.load_quantization:
self.qrecs[NodeId(node)] = self.load_tf_quantization(get_input_tensors(self.tensors, op),
get_output_tensors(self.tensors, op))
return add_node(self.G, node)
def add_broadcasted_op(self, name, subgraph, op_name, op, tf_opts, params, qrec_class=None):
tf_opts.Init(op.BuiltinOptions().Bytes, op.BuiltinOptions().Pos)
inputs = get_all_const_broadcasted_inputs(
self.G, self.model, self.tensors, subgraph, op, load_tensors=self.load_tensors)
check(len(inputs) == 2,
"broadcasted ops should only have 2 inputs " + str(op.InputsAsNumpy()))
if self.load_quantization:
self.qrecs[NodeId(params)] = self.load_tf_quantization(get_input_tensors(self.tensors, op),
get_output_tensors(
self.tensors, op),
qrec_class=qrec_class)
node_pair = self.fuse_activation(tf_opts, name, params)
for idx, input_node in enumerate(inputs):
if input_node[1] is not None:
if self.load_quantization:
node_qrec = self.qrecs[NodeId(params)]
self.qrecs[NodeId(input_node[1])] = MultConstantQuantizationRecord(
in_qs=[node_qrec.in_qs[idx]],
out_qs=[node_qrec.in_qs[idx]])
self.G.add_edge(NNEdge(input_node[1], node_pair[0], to_idx=idx))
return node_pair
def add_add(self, name, subgraph, op_name, op):
return self.add_broadcasted_op(name, subgraph, op_name, op,
AddOptions.AddOptions(),
MatrixAddParameters(name),
MultAddQuantizationRecord)
def add_div(self, name, subgraph, op_name, op):
return self.add_broadcasted_op(name, subgraph, op_name, op,
DivOptions.DivOptions(),
MatrixDivParameters(name))
def add_mul(self, name, subgraph, op_name, op):
return self.add_broadcasted_op(name, subgraph, op_name, op,
MulOptions.MulOptions(),
MatrixMulParameters(name))
def add_sub(self, name, subgraph, op_name, op):
return self.add_broadcasted_op(name, subgraph, op_name, op,
SubOptions.SubOptions(),
MatrixSubParameters(name),
MultAddQuantizationRecord)
def add_mean(self, name, subgraph, op_name, op):
check(op.InputsLength() == 2,
"Very odd " + str(op.InputsAsNumpy()))
mean_dims = get_tensor(self.model, self.tensors, op, 1)
if len(mean_dims) != 2 or mean_dims[0] != 1 or mean_dims[1] != 2:
LOG.warning("MEAN operator seen but can't convert to global average pool")
return self.add_unconverted(name, subgraph, op_name, op)
LOG.info("MEAN operator converted to global average pool")
inp = get_input_size(None, subgraph, op, 0, order=TF_LITE_IN_OUT_ORDER)
check(inp['n'] == 1,
"Multi batch not supported")
node = GlobalPoolParameters(name,
in_dims_hint=SparseList([['h', 'w', 'c']]),
out_dims_hint=SparseList([['h', 'w', 'c']]))
if self.load_quantization:
self.qrecs[NodeId(node)] = self.load_tf_quantization(get_input_tensors(self.tensors, op),
get_output_tensors(self.tensors, op))
return add_node(self.G, node)
# pylint: disable=unused-argument
def add_custom(self, name, subgraph, op_name, op):
return add_node(self.G,
UnknownOpParameters(
name,
{
"tflite_op_name": op_name,
"tflite_op": op,
"tflite_subgraph": subgraph
}
))
SWITCH_ADD_FUNCTIONS = {
"CONV_2D": add_convolution,
"AVERAGE_POOL_2D": add_pool,
"MAX_POOL_2D": add_pool,
"DEPTHWISE_CONV_2D": add_depthwise_convolution,
"FULLY_CONNECTED": add_fully_connected,
"SOFTMAX": add_softmax,
"CONCATENATION": add_concatenation,
"RESHAPE": add_reshape,
"PAD": add_pad,
"ADD": add_add,
"MUL": add_mul,
"SUB": add_sub,
"DIV": add_div,
"MEAN": add_mean,
"QUANTIZE": add_noop,
"DEQUANTIZE": add_noop
}
for operator in TF_ACTIVATION_OPERATORS:
SWITCH_ADD_FUNCTIONS[operator] = add_activation
def add_operator(self, subgraph, subgraph_idx, op, op_idx):
op_name, is_custom = utils.get_operator_name(self.model, op.OpcodeIndex())
node_name = "{}_{}_{}".format(op_name, subgraph_idx, op_idx)
if is_custom:
return self.add_custom(node_name, subgraph, op_name, op)
if op_name in self.SWITCH_ADD_FUNCTIONS:
return self.SWITCH_ADD_FUNCTIONS[op_name](self, node_name, subgraph, op_name, op)
return self.add_unconverted(node_name, subgraph, op_name, op)
def create_subgraph(self, graph_index):
graph = self.model.Subgraphs(graph_index)
self.tensors = []
for i in range(graph.TensorsLength()):
tensor = TfliteTensorWrapper(graph.Tensors(i))
self.tensors.append(tensor)
for i in range(graph.InputsLength()):
dims = get_input_size(None, graph, graph, i, order=None)
node = self.G.add_input(Dim.unnamed(remove_batch_dim(dims)))
tensor = self.tensors[graph.Inputs(i)]
tensor.output = node.name
if self.load_quantization and tensor.qtype:
self.qrecs[NodeId(node)] = MultQuantizationRecord(in_qs=[], out_qs=[tensor.qtype])
for i in range(graph.OutputsLength()):
node = self.G.add_output()
tensor = self.tensors[graph.Outputs(i)]
tensor.inputs.append((node.name, 0))
if self.load_quantization and tensor.qtype:
self.qrecs[NodeId(node)] = MultQuantizationRecord(
in_qs=[tensor.qtype], out_qs=[tensor.qtype])
for i in range(graph.OperatorsLength()):
op = graph.Operators(i)
in_node, out_node =\
self.add_operator(graph, graph_index, op, i)
# keep track of which input the tensor is attached to
for j in range(op.InputsLength()):
self.tensors[op.Inputs(j)].inputs.append((in_node.name, j))
for j in range(op.OutputsLength()):
self.tensors[op.Outputs(j)].output = out_node.name
for tensor in self.tensors:
if tensor.output is not None:
for in_rec in tensor.inputs:
self.G.add_edge(NNEdge(tensor.output, in_rec[0], to_idx=in_rec[1]))
elif self.load_tensors and not tensor.used:
LOG.warning("unused tensors in graph")
def create_graph(self, filename, opts):
add_sys_path(os.path.dirname(__file__))
buf = open(filename, "rb").read()
self.model = Model.Model.GetRootAsModel(buf, 0)
self.load_quantization = opts.get('load_quantization')
self.load_tensors = opts.get('load_tensors')
self.load_dequantized = opts.get('load_dequantized')
LOG.info("Importing TFLITE model version %s", self.model.Version())
check(self.model.Version() == 3, "Only support version 3 graphs at present")
check(self.model.SubgraphsLength() == 1, "Only supports one subgraph at present")
self.G = NNGraph(model=self.model, filename=filename, name=opts.get('name'),
constant_store=ConstantStore())
self.create_subgraph(0)
if self.load_quantization:
self.G.quantization = self.qrecs
self.G.has_quantized_parameters = True
self.G.graph_identity.quantization_type = 'SQ8'
propagate_hints(self.G)
return self.G
| [
"utils.sparse_list.SparseList",
"numpy.abs",
"quantization.multiplicative.mult_quantization.MultQuantizationRecord",
"numpy.resize",
"quantization.multiplicative.symmetric.symmetric_mult_biases_qtype.SymmetricMultBiasesQType",
"quantization.multiplicative.symmetric.symmetric_mult_qtype.SymmetricMultQType"... | [((3866, 3905), 'logging.getLogger', 'logging.getLogger', (["('nntool.' + __name__)"], {}), "('nntool.' + __name__)\n", (3883, 3905), False, 'import logging\n'), ((4901, 4914), 'graph.dim.PadDim.same', 'PadDim.same', ([], {}), '()\n', (4912, 4914), False, 'from graph.dim import Conv2DFilterDim, Dim, FcFilterDim, PadDim, PoolFilterDim, StrideDim\n'), ((4971, 4985), 'graph.dim.PadDim.valid', 'PadDim.valid', ([], {}), '()\n', (4983, 4985), False, 'from graph.dim import Conv2DFilterDim, Dim, FcFilterDim, PadDim, PoolFilterDim, StrideDim\n'), ((5671, 5690), 'graph.types.NNEdge', 'NNEdge', (['node', 'anode'], {}), '(node, anode)\n', (5677, 5690), False, 'from graph.types import ActivationParameters, ConcatParameters, Conv2DParameters, FcParameters, GlobalPoolParameters, MatrixAddParameters, MatrixDivParameters, MatrixMulParameters, MatrixSubParameters, NNEdge, NoOPParameters, PadParameters, PoolingParameters, ReshapeParameters, SoftMaxParameters, UnconvertedOpParameters, UnknownOpParameters\n'), ((14307, 14339), 'numpy.resize', 'np.resize', (['np_buffer', 'self.shape'], {}), '(np_buffer, self.shape)\n', (14316, 14339), True, 'import numpy as np\n'), ((14872, 14889), 'quantization.quantization_set.QuantizationSet', 'QuantizationSet', ([], {}), '()\n', (14887, 14889), False, 'from quantization.quantization_set import QuantizationSet\n'), ((17772, 17814), 'numpy.all', 'np.all', (['(input_tensors[1].zero_point == 128)'], {}), '(input_tensors[1].zero_point == 128)\n', (17778, 17814), True, 'import numpy as np\n'), ((19393, 19410), 'numpy.iinfo', 'np.iinfo', (['np.int8'], {}), '(np.int8)\n', (19401, 19410), True, 'import numpy as np\n'), ((19433, 19451), 'numpy.iinfo', 'np.iinfo', (['np.int32'], {}), '(np.int32)\n', (19441, 19451), True, 'import numpy as np\n'), ((21144, 21191), 'numpy.logical_and', 'np.logical_and', (['(w_mins == w_maxes)', '(w_maxes == 0)'], {}), '(w_mins == w_maxes, w_maxes == 0)\n', (21158, 21191), True, 'import numpy as np\n'), ((21210, 21243), 'numpy.where', 'np.where', (['w_zero_cond', '(1)', 'w_maxes'], {}), '(w_zero_cond, 1, w_maxes)\n', (21218, 21243), True, 'import numpy as np\n'), ((21371, 21388), 'numpy.iinfo', 'np.iinfo', (['np.int8'], {}), '(np.int8)\n', (21379, 21388), True, 'import numpy as np\n'), ((21411, 21429), 'numpy.iinfo', 'np.iinfo', (['np.int32'], {}), '(np.int32)\n', (21419, 21429), True, 'import numpy as np\n'), ((21496, 21518), 'numpy.seterr', 'np.seterr', ([], {'all': '"""raise"""'}), "(all='raise')\n", (21505, 21518), True, 'import numpy as np\n'), ((22669, 22716), 'numpy.where', 'np.where', (['tiny_weight_scales', '(1)', 'weights_scales'], {}), '(tiny_weight_scales, 1, weights_scales)\n', (22677, 22716), True, 'import numpy as np\n'), ((22789, 22807), 'numpy.iinfo', 'np.iinfo', (['np.int32'], {}), '(np.int32)\n', (22797, 22807), True, 'import numpy as np\n'), ((27288, 27359), 'graph.dim.Conv2DFilterDim', 'Conv2DFilterDim', (["filt['h']", "filt['w']", "filt['out_c']"], {'in_c': "filt['in_c']"}), "(filt['h'], filt['w'], filt['out_c'], in_c=filt['in_c'])\n", (27303, 27359), False, 'from graph.dim import Conv2DFilterDim, Dim, FcFilterDim, PadDim, PoolFilterDim, StrideDim\n'), ((29022, 29082), 'graph.dim.Conv2DFilterDim', 'Conv2DFilterDim', (["filt['h']", "filt['w']", "filt['out_c']"], {'in_c': '(1)'}), "(filt['h'], filt['w'], filt['out_c'], in_c=1)\n", (29037, 29082), False, 'from graph.dim import Conv2DFilterDim, Dim, FcFilterDim, PadDim, PoolFilterDim, StrideDim\n'), ((32869, 32968), 'graph.dim.FcFilterDim', 'FcFilterDim', (["inp['h']", "inp['w']", "filt['out_c']"], {'in_c': "inp['c']", 'order': 'self.TF_LITE_FC_EXP_ORDER'}), "(inp['h'], inp['w'], filt['out_c'], in_c=inp['c'], order=self.\n TF_LITE_FC_EXP_ORDER)\n", (32880, 32968), False, 'from graph.dim import Conv2DFilterDim, Dim, FcFilterDim, PadDim, PoolFilterDim, StrideDim\n'), ((36861, 36895), 'graph.types.NoOPParameters', 'NoOPParameters', (['name'], {'desc': 'op_name'}), '(name, desc=op_name)\n', (36875, 36895), False, 'from graph.types import ActivationParameters, ConcatParameters, Conv2DParameters, FcParameters, GlobalPoolParameters, MatrixAddParameters, MatrixDivParameters, MatrixMulParameters, MatrixSubParameters, NNEdge, NoOPParameters, PadParameters, PoolingParameters, ReshapeParameters, SoftMaxParameters, UnconvertedOpParameters, UnknownOpParameters\n'), ((38944, 38998), 'graph.types.ConcatParameters', 'ConcatParameters', (['name'], {'axis': 'axis', 'axis_hint': 'axis_hint'}), '(name, axis=axis, axis_hint=axis_hint)\n', (38960, 38998), False, 'from graph.types import ActivationParameters, ConcatParameters, Conv2DParameters, FcParameters, GlobalPoolParameters, MatrixAddParameters, MatrixDivParameters, MatrixMulParameters, MatrixSubParameters, NNEdge, NoOPParameters, PadParameters, PoolingParameters, ReshapeParameters, SoftMaxParameters, UnconvertedOpParameters, UnknownOpParameters\n'), ((40208, 40269), 'graph.types.ReshapeParameters', 'ReshapeParameters', (['name'], {'old_shape': 'old_shape', 'shape': 'new_shape'}), '(name, old_shape=old_shape, shape=new_shape)\n', (40225, 40269), False, 'from graph.types import ActivationParameters, ConcatParameters, Conv2DParameters, FcParameters, GlobalPoolParameters, MatrixAddParameters, MatrixDivParameters, MatrixMulParameters, MatrixSubParameters, NNEdge, NoOPParameters, PadParameters, PoolingParameters, ReshapeParameters, SoftMaxParameters, UnconvertedOpParameters, UnknownOpParameters\n'), ((40688, 40763), 'graph.types.ActivationParameters.get_activation', 'ActivationParameters.get_activation', (['TF_ACTIVATION_OPERATORS[op_name]', 'name'], {}), '(TF_ACTIVATION_OPERATORS[op_name], name)\n', (40723, 40763), False, 'from graph.types import ActivationParameters, ConcatParameters, Conv2DParameters, FcParameters, GlobalPoolParameters, MatrixAddParameters, MatrixDivParameters, MatrixMulParameters, MatrixSubParameters, NNEdge, NoOPParameters, PadParameters, PoolingParameters, ReshapeParameters, SoftMaxParameters, UnconvertedOpParameters, UnknownOpParameters\n'), ((41263, 41286), 'numpy.all', 'np.all', (['(pad_dim[3] == 0)'], {}), '(pad_dim[3] == 0)\n', (41269, 41286), True, 'import numpy as np\n'), ((9376, 9394), 'graph.dim.Dim.unnamed', 'Dim.unnamed', (['shape'], {}), '(shape)\n', (9387, 9394), False, 'from graph.dim import Conv2DFilterDim, Dim, FcFilterDim, PadDim, PoolFilterDim, StrideDim\n'), ((15005, 15017), 'utils.node_id.NodeId', 'NodeId', (['node'], {}), '(node)\n', (15011, 15017), False, 'from utils.node_id import NodeId\n'), ((16296, 16325), 'copy.deepcopy', 'deepcopy', (['node_qrec.out_qs[0]'], {}), '(node_qrec.out_qs[0])\n', (16304, 16325), False, 'from copy import deepcopy\n'), ((16400, 16429), 'copy.deepcopy', 'deepcopy', (['node_qrec.out_qs[0]'], {}), '(node_qrec.out_qs[0])\n', (16408, 16429), False, 'from copy import deepcopy\n'), ((16470, 16532), 'quantization.multiplicative.mult_quantization.MultQuantizationRecord', 'MultQuantizationRecord', ([], {'in_qs': '[ina_qtype]', 'out_qs': '[outa_qtype]'}), '(in_qs=[ina_qtype], out_qs=[outa_qtype])\n', (16492, 16532), False, 'from quantization.multiplicative.mult_quantization import MultAddQuantizationRecord, MultConstantQuantizationRecord, MultQuantizationRecord, MultQuantizationRecordBase, MultScalableFilterQuantizationRecord\n'), ((17438, 17467), 'numpy.array', 'np.array', (['[1]'], {'dtype': 'np.int32'}), '([1], dtype=np.int32)\n', (17446, 17467), True, 'import numpy as np\n'), ((18734, 18747), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (18742, 18747), True, 'import numpy as np\n'), ((18864, 18915), 'numpy.array', 'np.array', (['([0] * node.filter.out_c)'], {'dtype': 'np.float32'}), '([0] * node.filter.out_c, dtype=np.float32)\n', (18872, 18915), True, 'import numpy as np\n'), ((19153, 19171), 'numpy.min', 'np.min', (['dq_weights'], {}), '(dq_weights)\n', (19159, 19171), True, 'import numpy as np\n'), ((19196, 19214), 'numpy.max', 'np.max', (['dq_weights'], {}), '(dq_weights)\n', (19202, 19214), True, 'import numpy as np\n'), ((19313, 19326), 'numpy.abs', 'np.abs', (['w_min'], {}), '(w_min)\n', (19319, 19326), True, 'import numpy as np\n'), ((19899, 19928), 'numpy.array', 'np.array', (['[new_weights_scale]'], {}), '([new_weights_scale])\n', (19907, 19928), True, 'import numpy as np\n'), ((19930, 19958), 'numpy.array', 'np.array', (['[new_biases_scale]'], {}), '([new_biases_scale])\n', (19938, 19958), True, 'import numpy as np\n'), ((19973, 19990), 'numpy.array', 'np.array', (['[w_min]'], {}), '([w_min])\n', (19981, 19990), True, 'import numpy as np\n'), ((19992, 20009), 'numpy.array', 'np.array', (['[w_max]'], {}), '([w_max])\n', (20000, 20009), True, 'import numpy as np\n'), ((20239, 20252), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (20247, 20252), True, 'import numpy as np\n'), ((20655, 20706), 'numpy.array', 'np.array', (['([0] * node.filter.out_c)'], {'dtype': 'np.float32'}), '([0] * node.filter.out_c, dtype=np.float32)\n', (20663, 20706), True, 'import numpy as np\n'), ((21010, 21046), 'numpy.min', 'np.min', (['dq_weights'], {'axis': 'filter_axis'}), '(dq_weights, axis=filter_axis)\n', (21016, 21046), True, 'import numpy as np\n'), ((21080, 21116), 'numpy.max', 'np.max', (['dq_weights'], {'axis': 'filter_axis'}), '(dq_weights, axis=filter_axis)\n', (21086, 21116), True, 'import numpy as np\n'), ((21278, 21292), 'numpy.abs', 'np.abs', (['w_mins'], {}), '(w_mins)\n', (21284, 21292), True, 'import numpy as np\n'), ((22276, 22312), 'numpy.count_nonzero', 'np.count_nonzero', (['tiny_weight_scales'], {}), '(tiny_weight_scales)\n', (22292, 22312), True, 'import numpy as np\n'), ((24578, 24639), 'quantization.multiplicative.symmetric.symmetric_mult_biases_qtype.SymmetricMultBiasesQType', 'SymmetricMultBiasesQType', ([], {'dtype': 'np.int32', 'scale': 'biases_scales'}), '(dtype=np.int32, scale=biases_scales)\n', (24602, 24639), False, 'from quantization.multiplicative.symmetric.symmetric_mult_biases_qtype import SymmetricMultBiasesQType\n'), ((24664, 24775), 'quantization.multiplicative.symmetric.symmetric_mult_qtype.SymmetricMultQType', 'SymmetricMultQType', ([], {'dtype': 'np.int8', 'narrow_range': '(True)', 'scale': 'weights_scales', 'min_val': 'w_mins', 'max_val': 'w_maxes'}), '(dtype=np.int8, narrow_range=True, scale=weights_scales,\n min_val=w_mins, max_val=w_maxes)\n', (24682, 24775), False, 'from quantization.multiplicative.symmetric.symmetric_mult_qtype import SymmetricMultQType\n'), ((24901, 24964), 'quantization.multiplicative.symmetric.mult_mulbias_qtype_new.MultMulBiasScaleQType.from_filter', 'MultMulBiasScaleQType.from_filter', (['in_q', 'weights_q', 'out_q', 'node'], {}), '(in_q, weights_q, out_q, node)\n', (24934, 24964), False, 'from quantization.multiplicative.symmetric.mult_mulbias_qtype_new import MultMulBiasScaleQType\n'), ((24984, 25120), 'quantization.multiplicative.mult_quantization.MultScalableFilterQuantizationRecord', 'MultScalableFilterQuantizationRecord', ([], {'in_qs': '[in_q]', 'out_qs': '[out_q]', 'mul_biases_q': 'mulbiases_q', 'weights_q': 'weights_q', 'biases_q': 'biases_q'}), '(in_qs=[in_q], out_qs=[out_q],\n mul_biases_q=mulbiases_q, weights_q=weights_q, biases_q=biases_q)\n', (25020, 25120), False, 'from quantization.multiplicative.mult_quantization import MultAddQuantizationRecord, MultConstantQuantizationRecord, MultQuantizationRecord, MultQuantizationRecordBase, MultScalableFilterQuantizationRecord\n'), ((36518, 36591), 'quantization.multiplicative.symmetric.symmetric_mult_qtype.SymmetricMultQType', 'SymmetricMultQType', ([], {'min_val': '(-1)', 'max_val': '(1)', 'dtype': 'np.int16', 'scale': '(2 ** -15)'}), '(min_val=-1, max_val=1, dtype=np.int16, scale=2 ** -15)\n', (36536, 36591), False, 'from quantization.multiplicative.symmetric.symmetric_mult_qtype import SymmetricMultQType\n'), ((36611, 36666), 'quantization.multiplicative.mult_quantization.MultQuantizationRecord', 'MultQuantizationRecord', ([], {'in_qs': '[iqtype]', 'out_qs': '[oqtype]'}), '(in_qs=[iqtype], out_qs=[oqtype])\n', (36633, 36666), False, 'from quantization.multiplicative.mult_quantization import MultAddQuantizationRecord, MultConstantQuantizationRecord, MultQuantizationRecord, MultQuantizationRecordBase, MultScalableFilterQuantizationRecord\n'), ((39849, 39911), 'functools.reduce', 'reduce', (['(lambda x, y: x * 1 if y == -1 else x * y)', 'new_shape', '(1)'], {}), '(lambda x, y: x * 1 if y == -1 else x * y, new_shape, 1)\n', (39855, 39911), False, 'from functools import reduce\n'), ((39935, 39969), 'functools.reduce', 'reduce', (['(lambda x, y: x * y)', 'inp', '(1)'], {}), '(lambda x, y: x * y, inp, 1)\n', (39941, 39969), False, 'from functools import reduce\n'), ((41462, 41478), 'graph.dim.PadDim', 'PadDim', (['*pad_dim'], {}), '(*pad_dim)\n', (41468, 41478), False, 'from graph.dim import Conv2DFilterDim, Dim, FcFilterDim, PadDim, PoolFilterDim, StrideDim\n'), ((43381, 43406), 'graph.types.MatrixAddParameters', 'MatrixAddParameters', (['name'], {}), '(name)\n', (43400, 43406), False, 'from graph.types import ActivationParameters, ConcatParameters, Conv2DParameters, FcParameters, GlobalPoolParameters, MatrixAddParameters, MatrixDivParameters, MatrixMulParameters, MatrixSubParameters, NNEdge, NoOPParameters, PadParameters, PoolingParameters, ReshapeParameters, SoftMaxParameters, UnconvertedOpParameters, UnknownOpParameters\n'), ((43698, 43723), 'graph.types.MatrixDivParameters', 'MatrixDivParameters', (['name'], {}), '(name)\n', (43717, 43723), False, 'from graph.types import ActivationParameters, ConcatParameters, Conv2DParameters, FcParameters, GlobalPoolParameters, MatrixAddParameters, MatrixDivParameters, MatrixMulParameters, MatrixSubParameters, NNEdge, NoOPParameters, PadParameters, PoolingParameters, ReshapeParameters, SoftMaxParameters, UnconvertedOpParameters, UnknownOpParameters\n'), ((43949, 43974), 'graph.types.MatrixMulParameters', 'MatrixMulParameters', (['name'], {}), '(name)\n', (43968, 43974), False, 'from graph.types import ActivationParameters, ConcatParameters, Conv2DParameters, FcParameters, GlobalPoolParameters, MatrixAddParameters, MatrixDivParameters, MatrixMulParameters, MatrixSubParameters, NNEdge, NoOPParameters, PadParameters, PoolingParameters, ReshapeParameters, SoftMaxParameters, UnconvertedOpParameters, UnknownOpParameters\n'), ((44200, 44225), 'graph.types.MatrixSubParameters', 'MatrixSubParameters', (['name'], {}), '(name)\n', (44219, 44225), False, 'from graph.types import ActivationParameters, ConcatParameters, Conv2DParameters, FcParameters, GlobalPoolParameters, MatrixAddParameters, MatrixDivParameters, MatrixMulParameters, MatrixSubParameters, NNEdge, NoOPParameters, PadParameters, PoolingParameters, ReshapeParameters, SoftMaxParameters, UnconvertedOpParameters, UnknownOpParameters\n'), ((45588, 45692), 'graph.types.UnknownOpParameters', 'UnknownOpParameters', (['name', "{'tflite_op_name': op_name, 'tflite_op': op, 'tflite_subgraph': subgraph}"], {}), "(name, {'tflite_op_name': op_name, 'tflite_op': op,\n 'tflite_subgraph': subgraph})\n", (45607, 45692), False, 'from graph.types import ActivationParameters, ConcatParameters, Conv2DParameters, FcParameters, GlobalPoolParameters, MatrixAddParameters, MatrixDivParameters, MatrixMulParameters, MatrixSubParameters, NNEdge, NoOPParameters, PadParameters, PoolingParameters, ReshapeParameters, SoftMaxParameters, UnconvertedOpParameters, UnknownOpParameters\n'), ((49035, 49060), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (49050, 49060), False, 'import os\n'), ((15068, 15080), 'utils.node_id.NodeId', 'NodeId', (['node'], {}), '(node)\n', (15074, 15080), False, 'from utils.node_id import NodeId\n'), ((16257, 16269), 'utils.node_id.NodeId', 'NodeId', (['node'], {}), '(node)\n', (16263, 16269), False, 'from utils.node_id import NodeId\n'), ((16453, 16466), 'utils.node_id.NodeId', 'NodeId', (['anode'], {}), '(anode)\n', (16459, 16466), False, 'from utils.node_id import NodeId\n'), ((25364, 25376), 'utils.node_id.NodeId', 'NodeId', (['node'], {}), '(node)\n', (25370, 25376), False, 'from utils.node_id import NodeId\n'), ((28020, 28049), 'utils.sparse_list.SparseList', 'SparseList', (["[['h', 'w', 'c']]"], {}), "([['h', 'w', 'c']])\n", (28030, 28049), False, 'from utils.sparse_list import SparseList\n'), ((28097, 28126), 'utils.sparse_list.SparseList', 'SparseList', (["[['h', 'w', 'c']]"], {}), "([['h', 'w', 'c']])\n", (28107, 28126), False, 'from utils.sparse_list import SparseList\n'), ((32357, 32391), 'functools.reduce', 'reduce', (['(lambda i, j: i * j)', 'inp', '(1)'], {}), '(lambda i, j: i * j, inp, 1)\n', (32363, 32391), False, 'from functools import reduce\n'), ((33239, 33268), 'utils.sparse_list.SparseList', 'SparseList', (["[['h', 'w', 'c']]"], {}), "([['h', 'w', 'c']])\n", (33249, 33268), False, 'from utils.sparse_list import SparseList\n'), ((33312, 33331), 'utils.sparse_list.SparseList', 'SparseList', (["[['c']]"], {}), "([['c']])\n", (33322, 33331), False, 'from utils.sparse_list import SparseList\n'), ((35864, 35876), 'utils.node_id.NodeId', 'NodeId', (['node'], {}), '(node)\n', (35870, 35876), False, 'from utils.node_id import NodeId\n'), ((36732, 36744), 'utils.node_id.NodeId', 'NodeId', (['node'], {}), '(node)\n', (36738, 36744), False, 'from utils.node_id import NodeId\n'), ((36954, 36966), 'utils.node_id.NodeId', 'NodeId', (['node'], {}), '(node)\n', (36960, 36966), False, 'from utils.node_id import NodeId\n'), ((39057, 39069), 'utils.node_id.NodeId', 'NodeId', (['node'], {}), '(node)\n', (39063, 39069), False, 'from utils.node_id import NodeId\n'), ((40328, 40340), 'utils.node_id.NodeId', 'NodeId', (['node'], {}), '(node)\n', (40334, 40340), False, 'from utils.node_id import NodeId\n'), ((40822, 40834), 'utils.node_id.NodeId', 'NodeId', (['node'], {}), '(node)\n', (40828, 40834), False, 'from utils.node_id import NodeId\n'), ((41538, 41550), 'utils.node_id.NodeId', 'NodeId', (['node'], {}), '(node)\n', (41544, 41550), False, 'from utils.node_id import NodeId\n'), ((42248, 42262), 'utils.node_id.NodeId', 'NodeId', (['params'], {}), '(params)\n', (42254, 42262), False, 'from utils.node_id import NodeId\n'), ((45046, 45075), 'utils.sparse_list.SparseList', 'SparseList', (["[['h', 'w', 'c']]"], {}), "([['h', 'w', 'c']])\n", (45056, 45075), False, 'from utils.sparse_list import SparseList\n'), ((45127, 45156), 'utils.sparse_list.SparseList', 'SparseList', (["[['h', 'w', 'c']]"], {}), "([['h', 'w', 'c']])\n", (45137, 45156), False, 'from utils.sparse_list import SparseList\n'), ((45216, 45228), 'utils.node_id.NodeId', 'NodeId', (['node'], {}), '(node)\n', (45222, 45228), False, 'from utils.node_id import NodeId\n'), ((47730, 47785), 'quantization.multiplicative.mult_quantization.MultQuantizationRecord', 'MultQuantizationRecord', ([], {'in_qs': '[]', 'out_qs': '[tensor.qtype]'}), '(in_qs=[], out_qs=[tensor.qtype])\n', (47752, 47785), False, 'from quantization.multiplicative.mult_quantization import MultAddQuantizationRecord, MultConstantQuantizationRecord, MultQuantizationRecord, MultQuantizationRecordBase, MultScalableFilterQuantizationRecord\n'), ((48073, 48140), 'quantization.multiplicative.mult_quantization.MultQuantizationRecord', 'MultQuantizationRecord', ([], {'in_qs': '[tensor.qtype]', 'out_qs': '[tensor.qtype]'}), '(in_qs=[tensor.qtype], out_qs=[tensor.qtype])\n', (48095, 48140), False, 'from quantization.multiplicative.mult_quantization import MultAddQuantizationRecord, MultConstantQuantizationRecord, MultQuantizationRecord, MultQuantizationRecordBase, MultScalableFilterQuantizationRecord\n'), ((49713, 49728), 'graph.constant_store.ConstantStore', 'ConstantStore', ([], {}), '()\n', (49726, 49728), False, 'from graph.constant_store import ConstantStore\n'), ((13297, 13346), 'quantization.multiplicative.symmetric.symmetric_mult_qtype.SymmetricMultQType.from_tflite', 'SymmetricMultQType.from_tflite', (['quant', 'self.dtype'], {}), '(quant, self.dtype)\n', (13327, 13346), False, 'from quantization.multiplicative.symmetric.symmetric_mult_qtype import SymmetricMultQType\n'), ((13396, 13446), 'quantization.multiplicative.asymmetric.asymmetric_mult_qtype.AsymmetricMultQType.from_tflite', 'AsymmetricMultQType.from_tflite', (['quant', 'self.dtype'], {}), '(quant, self.dtype)\n', (13427, 13446), False, 'from quantization.multiplicative.asymmetric.asymmetric_mult_qtype import AsymmetricMultQType\n'), ((19539, 19585), 'numpy.floor', 'np.floor', (['(dq_weights / new_weights_scale + 0.5)'], {}), '(dq_weights / new_weights_scale + 0.5)\n', (19547, 19585), True, 'import numpy as np\n'), ((19727, 19771), 'numpy.floor', 'np.floor', (['(dq_biases / new_biases_scale + 0.5)'], {}), '(dq_biases / new_biases_scale + 0.5)\n', (19735, 19771), True, 'import numpy as np\n'), ((21759, 21804), 'numpy.floor', 'np.floor', (['(dq_biases / new_biases_scales + 0.5)'], {}), '(dq_biases / new_biases_scales + 0.5)\n', (21767, 21804), True, 'import numpy as np\n'), ((22838, 22879), 'numpy.floor', 'np.floor', (['(dq_biases / biases_scales + 0.5)'], {}), '(dq_biases / biases_scales + 0.5)\n', (22846, 22879), True, 'import numpy as np\n'), ((30312, 30341), 'utils.sparse_list.SparseList', 'SparseList', (["[['h', 'w', 'c']]"], {}), "([['h', 'w', 'c']])\n", (30322, 30341), False, 'from utils.sparse_list import SparseList\n'), ((30393, 30422), 'utils.sparse_list.SparseList', 'SparseList', (["[['h', 'w', 'c']]"], {}), "([['h', 'w', 'c']])\n", (30403, 30422), False, 'from utils.sparse_list import SparseList\n'), ((31087, 31116), 'utils.sparse_list.SparseList', 'SparseList', (["[['h', 'w', 'c']]"], {}), "([['h', 'w', 'c']])\n", (31097, 31116), False, 'from utils.sparse_list import SparseList\n'), ((31168, 31197), 'utils.sparse_list.SparseList', 'SparseList', (["[['h', 'w', 'c']]"], {}), "([['h', 'w', 'c']])\n", (31178, 31197), False, 'from utils.sparse_list import SparseList\n'), ((35046, 35075), 'utils.sparse_list.SparseList', 'SparseList', (["[['h', 'w', 'c']]"], {}), "([['h', 'w', 'c']])\n", (35056, 35075), False, 'from utils.sparse_list import SparseList\n'), ((35131, 35160), 'utils.sparse_list.SparseList', 'SparseList', (["[['h', 'w', 'c']]"], {}), "([['h', 'w', 'c']])\n", (35141, 35160), False, 'from utils.sparse_list import SparseList\n'), ((35692, 35721), 'utils.sparse_list.SparseList', 'SparseList', (["[['h', 'w', 'c']]"], {}), "([['h', 'w', 'c']])\n", (35702, 35721), False, 'from utils.sparse_list import SparseList\n'), ((35774, 35803), 'utils.sparse_list.SparseList', 'SparseList', (["[['h', 'w', 'c']]"], {}), "([['h', 'w', 'c']])\n", (35784, 35803), False, 'from utils.sparse_list import SparseList\n'), ((42910, 43006), 'quantization.multiplicative.mult_quantization.MultConstantQuantizationRecord', 'MultConstantQuantizationRecord', ([], {'in_qs': '[node_qrec.in_qs[idx]]', 'out_qs': '[node_qrec.in_qs[idx]]'}), '(in_qs=[node_qrec.in_qs[idx]], out_qs=[\n node_qrec.in_qs[idx]])\n', (42940, 43006), False, 'from quantization.multiplicative.mult_quantization import MultAddQuantizationRecord, MultConstantQuantizationRecord, MultQuantizationRecord, MultQuantizationRecordBase, MultScalableFilterQuantizationRecord\n'), ((43083, 43130), 'graph.types.NNEdge', 'NNEdge', (['input_node[1]', 'node_pair[0]'], {'to_idx': 'idx'}), '(input_node[1], node_pair[0], to_idx=idx)\n', (43089, 43130), False, 'from graph.types import ActivationParameters, ConcatParameters, Conv2DParameters, FcParameters, GlobalPoolParameters, MatrixAddParameters, MatrixDivParameters, MatrixMulParameters, MatrixSubParameters, NNEdge, NoOPParameters, PadParameters, PoolingParameters, ReshapeParameters, SoftMaxParameters, UnconvertedOpParameters, UnknownOpParameters\n'), ((47714, 47726), 'utils.node_id.NodeId', 'NodeId', (['node'], {}), '(node)\n', (47720, 47726), False, 'from utils.node_id import NodeId\n'), ((48057, 48069), 'utils.node_id.NodeId', 'NodeId', (['node'], {}), '(node)\n', (48063, 48069), False, 'from utils.node_id import NodeId\n'), ((13706, 13755), 'quantization.multiplicative.symmetric.symmetric_mult_qtype.SymmetricMultQType.from_tflite', 'SymmetricMultQType.from_tflite', (['quant', 'self.dtype'], {}), '(quant, self.dtype)\n', (13736, 13755), False, 'from quantization.multiplicative.symmetric.symmetric_mult_qtype import SymmetricMultQType\n'), ((13805, 13855), 'quantization.multiplicative.asymmetric.asymmetric_mult_qtype.AsymmetricMultQType.from_tflite', 'AsymmetricMultQType.from_tflite', (['quant', 'self.dtype'], {}), '(quant, self.dtype)\n', (13836, 13855), False, 'from quantization.multiplicative.asymmetric.asymmetric_mult_qtype import AsymmetricMultQType\n'), ((42838, 42852), 'utils.node_id.NodeId', 'NodeId', (['params'], {}), '(params)\n', (42844, 42852), False, 'from utils.node_id import NodeId\n'), ((42885, 42906), 'utils.node_id.NodeId', 'NodeId', (['input_node[1]'], {}), '(input_node[1])\n', (42891, 42906), False, 'from utils.node_id import NodeId\n'), ((48806, 48856), 'graph.types.NNEdge', 'NNEdge', (['tensor.output', 'in_rec[0]'], {'to_idx': 'in_rec[1]'}), '(tensor.output, in_rec[0], to_idx=in_rec[1])\n', (48812, 48856), False, 'from graph.types import ActivationParameters, ConcatParameters, Conv2DParameters, FcParameters, GlobalPoolParameters, MatrixAddParameters, MatrixDivParameters, MatrixMulParameters, MatrixSubParameters, NNEdge, NoOPParameters, PadParameters, PoolingParameters, ReshapeParameters, SoftMaxParameters, UnconvertedOpParameters, UnknownOpParameters\n'), ((15495, 15532), 'numpy.round', 'np.round', (['node_qrec.out_qs[0].max_val'], {}), '(node_qrec.out_qs[0].max_val)\n', (15503, 15532), True, 'import numpy as np\n')] |
# Author: <NAME>
# Purpose: Train a Neural Network to mimic the funcitonality of adding
# two numbers together.
#
# Results:
# Numbers between 1 and 100 gives perfect accuracy.
#
# Numbers between 1 and 500 gives 0.42 error.
#
# Numbers between 1 and 1000 gives 0.87 error.
#
# With numbers between 1 and 500, the output is off by 1 whenever the sum is
# greater than 620.
#
# The best architecture for the neural network is a single hidden layer of 2
# nodes.
# ============================================================================
import numpy as np
import pandas as pd
from tensorflow.contrib import skflow
from sklearn.metrics import accuracy_score
from sklearn.cross_validation import train_test_split
# import threading
from trainingFunctions import addThem
# class myThread(threading.Thread):
# def __init__(self, size):
# threading.Thread.__init__(self)
# self.size = size
# self.x = np.zeros((size, 2))
# self.y = np.zeros(size)
# def run(self):
# for i in range(self.size):
# a = float(np.random.randint(1, 500))
# b = float(np.random.randint(1, 500))
# self.x[i] = [a, b]
# self.y[i] = addThem(a, b)
def train(ID):
# # Create new threads
# thread1 = myThread(1000000)
# thread2 = myThread(1000000)
# # Start new Threads
# thread1.start()
# thread2.start()
# # Wait for threads to complete
# thread1.join()
# thread2.join()
# # Combine two threads output together
# input_ = thread1.x + thread2.x
# target = thread1.y + thread2.y
size = 1000000
x = np.zeros((size, 2))
y = np.zeros(size)
for i in range(size):
a = float(np.random.randint(1, 500))
b = float(np.random.randint(1, 500))
x[i] = [a, b]
y[i] = addThem(a, b)
x_train, x_test, y_train, y_test = train_test_split(x, y,
test_size=0.2, random_state=0)
# Neural Network from skflow
try:
NN = skflow.TensorFlowEstimator.restore('/home/derrowap/models/addThem'+str(ID))
except:
NN = skflow.TensorFlowDNNRegressor(hidden_units=[2], steps=5000)
# Train the NN with training data
NN.fit(x_train, y_train)
# Calculates training error
# pred = NN.predict(x_train)
# pred = np.reshape(pred, -1)
# pred = np.rint(pred)
# error_train = 1 - accuracy_score(y_train, pred)
# Calculates testing error
pred = NN.predict(x_test)
pred = np.reshape(pred, -1)
pred = np.rint(pred)
error_test = 1 - accuracy_score(y_test, pred)
NN.save('/home/derrowap/models/addThem'+str(ID))
return(error_test)
# NN = train(-1)
NN = skflow.TensorFlowEstimator.restore('/home/derrowap/models/addThem1')
# Enters loop to predict inputs from user.
print("\nEnter exit to leave loop.")
while True:
first = input("Number 1... ")
try:
# succeeds if user typed a number
first = int(first)
except:
# exit loop
break
second = input("Number 2... ")
try:
# succeeds if user typed a number
second = int(second)
except:
# exit loop
break
# Calculates prediction from NN
result = NN.predict(np.array([[first, second]]))
print("I think %d + %d = %d"
% (first, second, int(np.rint(result[0][0])))) | [
"sklearn.cross_validation.train_test_split",
"tensorflow.contrib.skflow.TensorFlowEstimator.restore",
"sklearn.metrics.accuracy_score",
"numpy.zeros",
"trainingFunctions.addThem",
"numpy.rint",
"numpy.random.randint",
"numpy.array",
"numpy.reshape",
"tensorflow.contrib.skflow.TensorFlowDNNRegresso... | [((2459, 2527), 'tensorflow.contrib.skflow.TensorFlowEstimator.restore', 'skflow.TensorFlowEstimator.restore', (['"""/home/derrowap/models/addThem1"""'], {}), "('/home/derrowap/models/addThem1')\n", (2493, 2527), False, 'from tensorflow.contrib import skflow\n'), ((1513, 1532), 'numpy.zeros', 'np.zeros', (['(size, 2)'], {}), '((size, 2))\n', (1521, 1532), True, 'import numpy as np\n'), ((1538, 1552), 'numpy.zeros', 'np.zeros', (['size'], {}), '(size)\n', (1546, 1552), True, 'import numpy as np\n'), ((1730, 1783), 'sklearn.cross_validation.train_test_split', 'train_test_split', (['x', 'y'], {'test_size': '(0.2)', 'random_state': '(0)'}), '(x, y, test_size=0.2, random_state=0)\n', (1746, 1783), False, 'from sklearn.cross_validation import train_test_split\n'), ((2274, 2294), 'numpy.reshape', 'np.reshape', (['pred', '(-1)'], {}), '(pred, -1)\n', (2284, 2294), True, 'import numpy as np\n'), ((2303, 2316), 'numpy.rint', 'np.rint', (['pred'], {}), '(pred)\n', (2310, 2316), True, 'import numpy as np\n'), ((1679, 1692), 'trainingFunctions.addThem', 'addThem', (['a', 'b'], {}), '(a, b)\n', (1686, 1692), False, 'from trainingFunctions import addThem\n'), ((2335, 2363), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_test', 'pred'], {}), '(y_test, pred)\n', (2349, 2363), False, 'from sklearn.metrics import accuracy_score\n'), ((2927, 2954), 'numpy.array', 'np.array', (['[[first, second]]'], {}), '([[first, second]])\n', (2935, 2954), True, 'import numpy as np\n'), ((1588, 1613), 'numpy.random.randint', 'np.random.randint', (['(1)', '(500)'], {}), '(1, 500)\n', (1605, 1613), True, 'import numpy as np\n'), ((1627, 1652), 'numpy.random.randint', 'np.random.randint', (['(1)', '(500)'], {}), '(1, 500)\n', (1644, 1652), True, 'import numpy as np\n'), ((1922, 1981), 'tensorflow.contrib.skflow.TensorFlowDNNRegressor', 'skflow.TensorFlowDNNRegressor', ([], {'hidden_units': '[2]', 'steps': '(5000)'}), '(hidden_units=[2], steps=5000)\n', (1951, 1981), False, 'from tensorflow.contrib import skflow\n'), ((3010, 3031), 'numpy.rint', 'np.rint', (['result[0][0]'], {}), '(result[0][0])\n', (3017, 3031), True, 'import numpy as np\n')] |
from __future__ import print_function
from __future__ import division
import torch
import numpy as np
import pandas as pd
from torchvision import transforms
import os
from tqdm import tqdm
import joblib
from utils import CollectionsDataset, CollectionsDatasetTest
from model import find_best_fixed_threshold
import argparse
from nnet import model_ft
parser = argparse.ArgumentParser()
parser.add_argument("--fold", default=-1)
args = parser.parse_args()
BASE_DIR = "../input/"
FOLD = int(args.fold)
if FOLD == -1:
FOLD = 0
MODEL_NAME = os.environ["MODEL_NAME"]
TRAINING_BATCH_SIZE = int(os.environ["TRAINING_BATCH_SIZE"])
TEST_BATCH_SIZE = int(os.environ["TEST_BATCH_SIZE"])
NUM_CLASSES = int(os.environ["NUM_CLASSES"])
IMAGE_SIZE = int(os.environ["IMAGE_SIZE"])
FOLD_NAME = "fold{0}".format(FOLD)
if FOLD == 0:
training_folds = [1, 2, 3, 4]
val_folds = [0]
elif FOLD == 1:
training_folds = [0, 2, 3, 4]
val_folds = [1]
elif FOLD == 2:
training_folds = [0, 1, 3, 4]
val_folds = [2]
elif FOLD == 3:
training_folds = [0, 1, 2, 4]
val_folds = [3]
else:
training_folds = [0, 1, 2, 3]
val_folds = [4]
device = torch.device("cuda:0")
IMG_MEAN = model_ft.mean
IMG_STD = model_ft.std
test_transform=transforms.Compose([
transforms.Resize(IMAGE_SIZE),
transforms.CenterCrop(IMAGE_SIZE),
transforms.ToTensor(),
transforms.Normalize(IMG_MEAN,IMG_STD)
])
val_transform = transforms.Compose([
transforms.Resize(IMAGE_SIZE),
transforms.CenterCrop(IMAGE_SIZE),
transforms.ToTensor(),
transforms.Normalize(IMG_MEAN, IMG_STD)
])
valid_dataset = CollectionsDataset(csv_file='../input/folds.csv',
root_dir='../input/train/',
num_classes=NUM_CLASSES,
image_size=IMAGE_SIZE,
folds=val_folds,
transform=val_transform)
valid_dataset_loader = torch.utils.data.DataLoader(valid_dataset,
batch_size=TEST_BATCH_SIZE,
shuffle=False,
num_workers=4)
test_dataset = CollectionsDatasetTest(csv_file='../input/sample_submission.csv',
root_dir='../input/test/',
image_size=IMAGE_SIZE,
transform=test_transform)
test_dataset_loader = torch.utils.data.DataLoader(test_dataset,
batch_size=TEST_BATCH_SIZE,
shuffle=False,
num_workers=4)
model_ft.load_state_dict(torch.load(os.path.join(FOLD_NAME, "model.bin")))
model_ft = model_ft.to(device)
for param in model_ft.parameters():
param.requires_grad = False
model_ft.eval()
valid_preds = np.zeros((len(valid_dataset), NUM_CLASSES))
valid_labels = np.zeros((len(valid_dataset), NUM_CLASSES))
tk0 = tqdm(valid_dataset_loader)
for i, _batch in enumerate(tk0):
x_batch = _batch["image"]
y_batch = _batch["labels"]
pred = model_ft(x_batch.to(device))
valid_labels[i * TEST_BATCH_SIZE:(i + 1) * TEST_BATCH_SIZE, :] = y_batch.detach().cpu().squeeze().numpy()
valid_preds[i * TEST_BATCH_SIZE:(i + 1) * TEST_BATCH_SIZE, :] = pred.detach().cpu().squeeze().numpy()
best_thr, best_score = find_best_fixed_threshold(valid_preds, valid_labels, device=device)
test_preds = np.zeros((len(test_dataset), NUM_CLASSES))
tk0 = tqdm(test_dataset_loader)
for i, x_batch in enumerate(tk0):
x_batch = x_batch["image"]
pred = model_ft(x_batch.to(device))
test_preds[i * TEST_BATCH_SIZE:(i + 1) * TEST_BATCH_SIZE, :] = pred.detach().cpu().squeeze().numpy()
test_preds = torch.from_numpy(test_preds).float().to(device).sigmoid()
test_preds = test_preds.detach().cpu().squeeze().numpy()
sample = pd.read_csv("../input/sample_submission.csv")
predicted = []
for i, name in tqdm(enumerate(sample['id'])):
score_predict = test_preds[i, :].ravel()
label_predict = np.arange(NUM_CLASSES)[score_predict >= best_thr]
str_predict_label = ' '.join(str(l) for l in label_predict)
predicted.append(str_predict_label)
sample['attribute_ids'] = predicted
# save all the stuff
sample.to_csv(os.path.join(FOLD_NAME, 'submission.csv'), index=False)
joblib.dump(valid_preds, os.path.join(FOLD_NAME, "valid_preds.pkl"))
joblib.dump(test_preds, os.path.join(FOLD_NAME, "test_preds.pkl"))
joblib.dump(valid_labels, os.path.join(FOLD_NAME, "valid_labels.pkl"))
| [
"tqdm.tqdm",
"nnet.model_ft.to",
"nnet.model_ft.parameters",
"argparse.ArgumentParser",
"torch.utils.data.DataLoader",
"os.path.join",
"pandas.read_csv",
"torch.from_numpy",
"torchvision.transforms.CenterCrop",
"utils.CollectionsDataset",
"torchvision.transforms.ToTensor",
"numpy.arange",
"u... | [((360, 385), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (383, 385), False, 'import argparse\n'), ((1154, 1176), 'torch.device', 'torch.device', (['"""cuda:0"""'], {}), "('cuda:0')\n", (1166, 1176), False, 'import torch\n'), ((1613, 1789), 'utils.CollectionsDataset', 'CollectionsDataset', ([], {'csv_file': '"""../input/folds.csv"""', 'root_dir': '"""../input/train/"""', 'num_classes': 'NUM_CLASSES', 'image_size': 'IMAGE_SIZE', 'folds': 'val_folds', 'transform': 'val_transform'}), "(csv_file='../input/folds.csv', root_dir=\n '../input/train/', num_classes=NUM_CLASSES, image_size=IMAGE_SIZE,\n folds=val_folds, transform=val_transform)\n", (1631, 1789), False, 'from utils import CollectionsDataset, CollectionsDatasetTest\n'), ((1981, 2085), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['valid_dataset'], {'batch_size': 'TEST_BATCH_SIZE', 'shuffle': '(False)', 'num_workers': '(4)'}), '(valid_dataset, batch_size=TEST_BATCH_SIZE,\n shuffle=False, num_workers=4)\n', (2008, 2085), False, 'import torch\n'), ((2251, 2397), 'utils.CollectionsDatasetTest', 'CollectionsDatasetTest', ([], {'csv_file': '"""../input/sample_submission.csv"""', 'root_dir': '"""../input/test/"""', 'image_size': 'IMAGE_SIZE', 'transform': 'test_transform'}), "(csv_file='../input/sample_submission.csv', root_dir=\n '../input/test/', image_size=IMAGE_SIZE, transform=test_transform)\n", (2273, 2397), False, 'from utils import CollectionsDataset, CollectionsDatasetTest\n'), ((2518, 2621), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['test_dataset'], {'batch_size': 'TEST_BATCH_SIZE', 'shuffle': '(False)', 'num_workers': '(4)'}), '(test_dataset, batch_size=TEST_BATCH_SIZE,\n shuffle=False, num_workers=4)\n', (2545, 2621), False, 'import torch\n'), ((2841, 2860), 'nnet.model_ft.to', 'model_ft.to', (['device'], {}), '(device)\n', (2852, 2860), False, 'from nnet import model_ft\n'), ((2875, 2896), 'nnet.model_ft.parameters', 'model_ft.parameters', ([], {}), '()\n', (2894, 2896), False, 'from nnet import model_ft\n'), ((2932, 2947), 'nnet.model_ft.eval', 'model_ft.eval', ([], {}), '()\n', (2945, 2947), False, 'from nnet import model_ft\n'), ((3071, 3097), 'tqdm.tqdm', 'tqdm', (['valid_dataset_loader'], {}), '(valid_dataset_loader)\n', (3075, 3097), False, 'from tqdm import tqdm\n'), ((3472, 3539), 'model.find_best_fixed_threshold', 'find_best_fixed_threshold', (['valid_preds', 'valid_labels'], {'device': 'device'}), '(valid_preds, valid_labels, device=device)\n', (3497, 3539), False, 'from model import find_best_fixed_threshold\n'), ((3603, 3628), 'tqdm.tqdm', 'tqdm', (['test_dataset_loader'], {}), '(test_dataset_loader)\n', (3607, 3628), False, 'from tqdm import tqdm\n'), ((3979, 4024), 'pandas.read_csv', 'pd.read_csv', (['"""../input/sample_submission.csv"""'], {}), "('../input/sample_submission.csv')\n", (3990, 4024), True, 'import pandas as pd\n'), ((4378, 4419), 'os.path.join', 'os.path.join', (['FOLD_NAME', '"""submission.csv"""'], {}), "(FOLD_NAME, 'submission.csv')\n", (4390, 4419), False, 'import os\n'), ((4459, 4501), 'os.path.join', 'os.path.join', (['FOLD_NAME', '"""valid_preds.pkl"""'], {}), "(FOLD_NAME, 'valid_preds.pkl')\n", (4471, 4501), False, 'import os\n'), ((4527, 4568), 'os.path.join', 'os.path.join', (['FOLD_NAME', '"""test_preds.pkl"""'], {}), "(FOLD_NAME, 'test_preds.pkl')\n", (4539, 4568), False, 'import os\n'), ((4596, 4639), 'os.path.join', 'os.path.join', (['FOLD_NAME', '"""valid_labels.pkl"""'], {}), "(FOLD_NAME, 'valid_labels.pkl')\n", (4608, 4639), False, 'import os\n'), ((1267, 1296), 'torchvision.transforms.Resize', 'transforms.Resize', (['IMAGE_SIZE'], {}), '(IMAGE_SIZE)\n', (1284, 1296), False, 'from torchvision import transforms\n'), ((1302, 1335), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['IMAGE_SIZE'], {}), '(IMAGE_SIZE)\n', (1323, 1335), False, 'from torchvision import transforms\n'), ((1341, 1362), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1360, 1362), False, 'from torchvision import transforms\n'), ((1368, 1407), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['IMG_MEAN', 'IMG_STD'], {}), '(IMG_MEAN, IMG_STD)\n', (1388, 1407), False, 'from torchvision import transforms\n'), ((1452, 1481), 'torchvision.transforms.Resize', 'transforms.Resize', (['IMAGE_SIZE'], {}), '(IMAGE_SIZE)\n', (1469, 1481), False, 'from torchvision import transforms\n'), ((1487, 1520), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['IMAGE_SIZE'], {}), '(IMAGE_SIZE)\n', (1508, 1520), False, 'from torchvision import transforms\n'), ((1526, 1547), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1545, 1547), False, 'from torchvision import transforms\n'), ((1553, 1592), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['IMG_MEAN', 'IMG_STD'], {}), '(IMG_MEAN, IMG_STD)\n', (1573, 1592), False, 'from torchvision import transforms\n'), ((2791, 2827), 'os.path.join', 'os.path.join', (['FOLD_NAME', '"""model.bin"""'], {}), "(FOLD_NAME, 'model.bin')\n", (2803, 2827), False, 'import os\n'), ((4151, 4173), 'numpy.arange', 'np.arange', (['NUM_CLASSES'], {}), '(NUM_CLASSES)\n', (4160, 4173), True, 'import numpy as np\n'), ((3854, 3882), 'torch.from_numpy', 'torch.from_numpy', (['test_preds'], {}), '(test_preds)\n', (3870, 3882), False, 'import torch\n')] |
#! /usr/bin/env python
import gym
import numpy as np
import rospy
import utils.warning_ignore
import drone_goto
from stable_baselines.deepq import DQN, MlpPolicy
def callback(lcl, _glb):
"""
The callback function for logging and saving
:param lcl: (dict) the local variables
:param _glb: (dict) the global variables
:return: (bool) is solved
"""
# stop training if reward exceeds 199
if len(lcl['episode_rewards'][-101:-1]) == 0:
mean_100ep_reward = -np.inf
else:
mean_100ep_reward = round(float(np.mean(lcl['episode_rewards'][-101:-1])), 1)
is_solved = lcl['self'].num_timesteps > 100 and mean_100ep_reward >= 0.9
return not is_solved
def main():
rospy.init_node('train_node', anonymous=True)
env = gym.make("DroneGoto-v0")
model = DQN(
env=env,
policy=MlpPolicy,
learning_rate=1e-3,
buffer_size=50000,
exploration_fraction=0.1,
exploration_final_eps=0.02,
)
model.learn(total_timesteps=1000, callback=callback)
# model.save("model.zip")
if __name__ == '__main__':
main()
| [
"stable_baselines.deepq.DQN",
"gym.make",
"numpy.mean",
"rospy.init_node"
] | [((719, 764), 'rospy.init_node', 'rospy.init_node', (['"""train_node"""'], {'anonymous': '(True)'}), "('train_node', anonymous=True)\n", (734, 764), False, 'import rospy\n'), ((775, 799), 'gym.make', 'gym.make', (['"""DroneGoto-v0"""'], {}), "('DroneGoto-v0')\n", (783, 799), False, 'import gym\n'), ((812, 940), 'stable_baselines.deepq.DQN', 'DQN', ([], {'env': 'env', 'policy': 'MlpPolicy', 'learning_rate': '(0.001)', 'buffer_size': '(50000)', 'exploration_fraction': '(0.1)', 'exploration_final_eps': '(0.02)'}), '(env=env, policy=MlpPolicy, learning_rate=0.001, buffer_size=50000,\n exploration_fraction=0.1, exploration_final_eps=0.02)\n', (815, 940), False, 'from stable_baselines.deepq import DQN, MlpPolicy\n'), ((553, 593), 'numpy.mean', 'np.mean', (["lcl['episode_rewards'][-101:-1]"], {}), "(lcl['episode_rewards'][-101:-1])\n", (560, 593), True, 'import numpy as np\n')] |
"""Simulation box utilities
"""
import numpy as np
import math
def pbc_place_inside(box: np.ndarray, r_out: np.ndarray) -> np.ndarray:
"""Places point inside simulation box applying periodic boundary condition.
:param box Simulation box.
:param r_out Point possibly outside box.
:return r_in Point inside simulation.
"""
r_in = np.array([r_out[0], r_out[1], r_out[2]])
for k in (0, 1, 2):
r_k = r_in[k]
box_k = box[k]
n = np.rint(math.floor(r_k/box_k))
r_in[k] -= n * box_k
return r_in
def pbc_distance(box: np.ndarray, r_i: np.ndarray, r_j: np.ndarray) -> np.ndarray:
"""Returns distance between two points applying periodic boundary condition.
:param box Simulation box.
:param r_i Point i.
:param r_j Point j.
:return rij = r_i - r_j
"""
r_ij = np.array([0.0, 0.0, 0.0])
for k in (0, 1, 2):
box_k = box[k]
dr = r_i[k] - r_j[k]
ratio = dr / box_k
n = np.rint(ratio)
r_ij[k] = dr - n * box_k
return r_ij
| [
"numpy.rint",
"numpy.array",
"math.floor"
] | [((355, 395), 'numpy.array', 'np.array', (['[r_out[0], r_out[1], r_out[2]]'], {}), '([r_out[0], r_out[1], r_out[2]])\n', (363, 395), True, 'import numpy as np\n'), ((845, 870), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (853, 870), True, 'import numpy as np\n'), ((986, 1000), 'numpy.rint', 'np.rint', (['ratio'], {}), '(ratio)\n', (993, 1000), True, 'import numpy as np\n'), ((485, 508), 'math.floor', 'math.floor', (['(r_k / box_k)'], {}), '(r_k / box_k)\n', (495, 508), False, 'import math\n')] |
# created by Minghan
from __future__ import print_function
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
from torch.autograd import Variable
import torch.nn.functional as F
import skimage
import skimage.io
import skimage.transform
import numpy as np
import time
import math
from utils import preprocess
from models import *
# 2012 data /media/jiaren/ImageNet/data_scene_flow_2012/testing/
class DisparityNet():
def __init__(self, params):
self.args = params
self.args.cuda = not self.args.no_cuda and torch.cuda.is_available()
torch.manual_seed(self.args.seed)
if self.args.cuda:
torch.cuda.manual_seed(self.args.seed)
# load model
if self.args.model == 'stackhourglass':
self.model = stackhourglass(self.args.maxdisp)
elif self.args.model == 'basic':
self.model = basic(self.args.maxdisp)
else:
print('no model')
self.model = nn.DataParallel(self.model, device_ids=[0])
self.model.cuda()
if self.args.loadmodel is not None:
state_dict = torch.load(self.args.loadmodel)
self.model.load_state_dict(state_dict['state_dict'])
print('Number of model parameters: {}'.format(sum([p.data.nelement() for p in self.model.parameters()])))
# process operations
self.processed = preprocess.get_transform(augment=False)
def test(self, imgL,imgR):
self.model.eval()
if self.args.cuda:
imgL = torch.FloatTensor(imgL).cuda()
imgR = torch.FloatTensor(imgR).cuda()
imgL, imgR= Variable(imgL), Variable(imgR)
with torch.no_grad():
output = self.model(imgL,imgR)
output = torch.squeeze(output)
pred_disp = output.data.cpu().numpy()
return pred_disp
def test_preprocess(self, imgL_o):
imgL = self.processed(imgL_o).numpy()
imgL = np.reshape(imgL,[1,3,imgL.shape[1],imgL.shape[2]])
# pad to (384, 1248)
top_pad = 384-imgL.shape[2]
left_pad = 1248-imgL.shape[3]
imgL = np.lib.pad(imgL,((0,0),(0,0),(top_pad,0),(0,left_pad)),mode='constant',constant_values=0)
return imgL
def run(self, imgL_o, imgR_o):
imgL = self.test_preprocess(imgL_o)
imgR = self.test_preprocess(imgR_o)
# inference
start_time = time.time()
pred_disp = self.test(imgL,imgR)
print('time for disparity prediction = %.2f' %(time.time() - start_time))
# postprocess
top_pad = 384 - imgL_o.shape[0]
left_pad = 1248 - imgL_o.shape[1]
if left_pad != 0:
img = pred_disp[top_pad:,:-left_pad]
return img
return pred_disp
| [
"torch.manual_seed",
"utils.preprocess.get_transform",
"torch.load",
"torch.cuda.manual_seed",
"torch.autograd.Variable",
"torch.FloatTensor",
"time.time",
"torch.squeeze",
"torch.cuda.is_available",
"numpy.reshape",
"numpy.lib.pad",
"torch.nn.DataParallel",
"torch.no_grad"
] | [((703, 736), 'torch.manual_seed', 'torch.manual_seed', (['self.args.seed'], {}), '(self.args.seed)\n', (720, 736), False, 'import torch\n'), ((1109, 1152), 'torch.nn.DataParallel', 'nn.DataParallel', (['self.model'], {'device_ids': '[0]'}), '(self.model, device_ids=[0])\n', (1124, 1152), True, 'import torch.nn as nn\n'), ((1516, 1555), 'utils.preprocess.get_transform', 'preprocess.get_transform', ([], {'augment': '(False)'}), '(augment=False)\n', (1540, 1555), False, 'from utils import preprocess\n'), ((1891, 1912), 'torch.squeeze', 'torch.squeeze', (['output'], {}), '(output)\n', (1904, 1912), False, 'import torch\n'), ((2095, 2149), 'numpy.reshape', 'np.reshape', (['imgL', '[1, 3, imgL.shape[1], imgL.shape[2]]'], {}), '(imgL, [1, 3, imgL.shape[1], imgL.shape[2]])\n', (2105, 2149), True, 'import numpy as np\n'), ((2265, 2369), 'numpy.lib.pad', 'np.lib.pad', (['imgL', '((0, 0), (0, 0), (top_pad, 0), (0, left_pad))'], {'mode': '"""constant"""', 'constant_values': '(0)'}), "(imgL, ((0, 0), (0, 0), (top_pad, 0), (0, left_pad)), mode=\n 'constant', constant_values=0)\n", (2275, 2369), True, 'import numpy as np\n'), ((2541, 2552), 'time.time', 'time.time', ([], {}), '()\n', (2550, 2552), False, 'import time\n'), ((668, 693), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (691, 693), False, 'import torch\n'), ((776, 814), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['self.args.seed'], {}), '(self.args.seed)\n', (798, 814), False, 'import torch\n'), ((1249, 1280), 'torch.load', 'torch.load', (['self.args.loadmodel'], {}), '(self.args.loadmodel)\n', (1259, 1280), False, 'import torch\n'), ((1769, 1783), 'torch.autograd.Variable', 'Variable', (['imgL'], {}), '(imgL)\n', (1777, 1783), False, 'from torch.autograd import Variable\n'), ((1785, 1799), 'torch.autograd.Variable', 'Variable', (['imgR'], {}), '(imgR)\n', (1793, 1799), False, 'from torch.autograd import Variable\n'), ((1814, 1829), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1827, 1829), False, 'import torch\n'), ((1662, 1685), 'torch.FloatTensor', 'torch.FloatTensor', (['imgL'], {}), '(imgL)\n', (1679, 1685), False, 'import torch\n'), ((1712, 1735), 'torch.FloatTensor', 'torch.FloatTensor', (['imgR'], {}), '(imgR)\n', (1729, 1735), False, 'import torch\n'), ((2649, 2660), 'time.time', 'time.time', ([], {}), '()\n', (2658, 2660), False, 'import time\n')] |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 4 18:14:29 2016
@author: becker
"""
import numpy as np
import scipy.linalg as linalg
import scipy.sparse as sparse
try:
from simfempy.meshes.simplexmesh import SimplexMesh
except ModuleNotFoundError:
from simfempy.meshes.simplexmesh import SimplexMesh
import simfempy.fems.bdrydata
#=================================================================#
class FemP1(object):
def __init__(self, mesh=None):
if mesh is not None:
self.setMesh(mesh)
self.dirichlet_al = 10
def setMesh(self, mesh, bdrycond=None):
self.mesh = mesh
self.nloc = self.mesh.dimension+1
simps = self.mesh.simplices
self.cols = np.tile(simps, self.nloc).reshape(-1)
self.rows = np.repeat(simps, self.nloc).reshape(-1)
self.cellgrads = self.computeCellGrads()
self.massmatrix = self.computeMassMatrix()
if bdrycond:
self.robinmassmatrix = self.computeBdryMassMatrix(bdrycond, type="Robin")
def computeCellGrads(self):
ncells, normals, cellsOfFaces, facesOfCells, dV = self.mesh.ncells, self.mesh.normals, self.mesh.cellsOfFaces, self.mesh.facesOfCells, self.mesh.dV
scale = -1/self.mesh.dimension
# print("dV", np.where(dV<0.0001))
# print("dV", dV[dV<0.00001])
return scale*(normals[facesOfCells].T * self.mesh.sigma.T / dV.T).T
def computeMassMatrix(self, lumped=False):
nnodes = self.mesh.nnodes
scalemass = 1 / self.nloc / (self.nloc+1);
massloc = np.tile(scalemass, (self.nloc,self.nloc))
massloc.reshape((self.nloc*self.nloc))[::self.nloc+1] *= 2
mass = np.einsum('n,kl->nkl', self.mesh.dV, massloc).ravel()
return sparse.coo_matrix((mass, (self.rows, self.cols)), shape=(nnodes, nnodes)).tocsr()
def computeBdryMassMatrix(self, bdrycond, type, lumped=False):
# TODO: find a way to get linear solution exactly with lumped=True
nnodes = self.mesh.nnodes
rows = np.empty(shape=(0), dtype=int)
cols = np.empty(shape=(0), dtype=int)
mat = np.empty(shape=(0), dtype=float)
if lumped:
for color, faces in self.mesh.bdrylabels.items():
if bdrycond.type[color] != type: continue
scalemass = bdrycond.param[color]/ self.mesh.dimension
normalsS = self.mesh.normals[faces]
dS = linalg.norm(normalsS, axis=1)
nodes = self.mesh.faces[faces]
rows = np.append(rows, nodes)
cols = np.append(cols, nodes)
mass = np.repeat(scalemass*dS, self.mesh.dimension)
mat = np.append(mat, mass)
return sparse.coo_matrix((mat, (rows, cols)), shape=(nnodes, nnodes)).tocsr()
else:
for color, faces in self.mesh.bdrylabels.items():
if bdrycond.type[color] != type: continue
scalemass = bdrycond.param[color] / (1+self.mesh.dimension)/self.mesh.dimension
normalsS = self.mesh.normals[faces]
dS = linalg.norm(normalsS, axis=1)
nodes = self.mesh.faces[faces]
nloc = self.nloc-1
rows = np.append(rows, np.repeat(nodes, nloc).reshape(-1))
cols = np.append(cols, np.tile(nodes, nloc).reshape(-1))
massloc = np.tile(scalemass, (nloc, nloc))
massloc.reshape((nloc*nloc))[::nloc+1] *= 2
mat = np.append(mat, np.einsum('n,kl->nkl', dS, massloc).reshape(-1))
return sparse.coo_matrix((mat, (rows, cols)), shape=(nnodes, nnodes)).tocsr()
def prepareBoundary(self, colorsdir, colorsflux=[]):
bdrydata = simfempy.fems.bdrydata.BdryData()
bdrydata.nodesdir={}
bdrydata.nodedirall = np.empty(shape=(0), dtype=int)
for color in colorsdir:
facesdir = self.mesh.bdrylabels[color]
bdrydata.nodesdir[color] = np.unique(self.mesh.faces[facesdir].flat[:])
bdrydata.nodedirall = np.unique(np.union1d(bdrydata.nodedirall, bdrydata.nodesdir[color]))
bdrydata.nodesinner = np.setdiff1d(np.arange(self.mesh.nnodes, dtype=int),bdrydata.nodedirall)
bdrydata.nodesdirflux={}
for color in colorsflux:
facesdir = self.mesh.bdrylabels[color]
bdrydata.nodesdirflux[color] = np.unique(self.mesh.faces[facesdir].ravel())
return bdrydata
def matrixDiffusion(self, k, bdrycond, method, bdrydata):
# alpha = problemdata.bdrycond.param[color]
# print(f"??? {alpha=}")
nnodes = self.mesh.nnodes
matxx = np.einsum('nk,nl->nkl', self.cellgrads[:, :, 0], self.cellgrads[:, :, 0])
matyy = np.einsum('nk,nl->nkl', self.cellgrads[:, :, 1], self.cellgrads[:, :, 1])
matzz = np.einsum('nk,nl->nkl', self.cellgrads[:, :, 2], self.cellgrads[:, :, 2])
mat = ( (matxx+matyy+matzz).T*self.mesh.dV*k).T.ravel()
A = sparse.coo_matrix((mat, (self.rows, self.cols)), shape=(nnodes, nnodes)).tocsr()
A += self.robinmassmatrix
return self.matrixDirichlet(A, bdrycond, method, bdrydata)
def formDiffusion(self, du, u, k):
graduh = np.einsum('nij,ni->nj', self.cellgrads, u[self.mesh.simplices])
graduh = np.einsum('ni,n->ni', graduh, self.mesh.dV*k)
# du += np.einsum('nj,nij->ni', graduh, self.cellgrads)
raise ValueError(f"graduh {graduh.shape} {du.shape}")
return du
def computeRhs(self, u, problemdata, kheatcell, method, bdrydata):
rhs = problemdata.rhs
rhscell = problemdata.rhscell
rhspoint = problemdata.rhspoint
bdrycond = problemdata.bdrycond
normals = self.mesh.normals
b = np.zeros(self.mesh.nnodes)
if rhs:
x, y, z = self.mesh.points.T
b += self.massmatrix * rhs(x, y, z)
if rhscell:
scale = 1/(self.mesh.dimension+1)
for label,fct in rhscell.items():
if fct is None: continue
cells = self.mesh.cellsoflabel[label]
xc, yc, zc = self.mesh.pointsc[cells].T
bC = scale*fct(xc, yc, zc)*self.mesh.dV[cells]
# print("bC", bC)
np.add.at(b, self.mesh.simplices[cells].T, bC)
if rhspoint:
for label,fct in rhspoint.items():
if fct is None: continue
points = self.mesh.verticesoflabel[label]
xc, yc, zc = self.mesh.points[points].T
# print("xc, yc, zc, f", xc, yc, zc, fct(xc, yc, zc))
b[points] += fct(xc, yc, zc)
help = np.zeros(self.mesh.nnodes)
for color, faces in self.mesh.bdrylabels.items():
if bdrycond.type[color] != "Robin": continue
if not color in bdrycond.fct or bdrycond.fct[color] is None: continue
nodes = np.unique(self.mesh.faces[faces].reshape(-1))
x, y, z = self.mesh.points[nodes].T
# print(f"normals {normals.shape}")
# raise ValueError(f"normals = {np.mean(normals, axis=0)}")
# nx, ny, nz = normals[faces].T
nx, ny, nz = np.mean(normals[faces], axis=0)
help[nodes] = bdrycond.fct[color](x, y, z, nx, ny, nz)
b += self.robinmassmatrix*help
scale = 1 / self.mesh.dimension
for color, faces in self.mesh.bdrylabels.items():
if bdrycond.type[color] != "Neumann": continue
if not color in bdrycond.fct or bdrycond.fct[color] is None: continue
normalsS = normals[faces]
dS = linalg.norm(normalsS,axis=1)
normalsS = normalsS/dS[:,np.newaxis]
assert(dS.shape[0] == len(faces))
x1, y1, z1 = self.mesh.pointsf[faces].T
nx, ny, nz = normalsS.T
bS = scale * bdrycond.fct[color](x1, y1, z1, nx, ny, nz) * dS
np.add.at(b, self.mesh.faces[faces].T, bS)
if bdrycond.hasExactSolution():
for color, faces in self.mesh.bdrylabels.items():
if bdrycond.type[color] != "Robin": continue
normalsS = normals[faces]
dS = linalg.norm(normalsS, axis=1)
normalsS = normalsS / dS[:, np.newaxis]
assert (dS.shape[0] == len(faces))
x1, y1, z1 = self.mesh.pointsf[faces].T
nx, ny, nz = normalsS.T
bS = scale * bdrycond.fctexact["Neumann"](x1, y1, z1, nx, ny, nz) * dS
np.add.at(b, self.mesh.faces[faces].T, bS)
return self.vectorDirichlet(b, u, bdrycond, method, bdrydata)
def matrixDirichlet(self, A, bdrycond, method, bdrydata):
nodesdir, nodedirall, nodesinner, nodesdirflux = bdrydata.nodesdir, bdrydata.nodedirall, bdrydata.nodesinner, bdrydata.nodesdirflux
nnodes = self.mesh.nnodes
for color, nodes in nodesdirflux.items():
nb = nodes.shape[0]
help = sparse.dok_matrix((nb, nnodes))
for i in range(nb): help[i, nodes[i]] = 1
bdrydata.Asaved[color] = help.dot(A)
bdrydata.A_inner_dir = A[nodesinner, :][:, nodedirall]
if method == 'strong':
help = np.ones((nnodes))
help[nodedirall] = 0
help = sparse.dia_matrix((help, 0), shape=(nnodes, nnodes))
A = help.dot(A.dot(help))
help = np.zeros((nnodes))
help[nodedirall] = 1.0
help = sparse.dia_matrix((help, 0), shape=(nnodes, nnodes))
A += help
else:
bdrydata.A_dir_dir = self.dirichlet_al*A[nodedirall, :][:, nodedirall]
help = np.ones(nnodes)
help[nodedirall] = 0
help = sparse.dia_matrix((help, 0), shape=(nnodes, nnodes))
help2 = np.zeros(nnodes)
help2[nodedirall] = np.sqrt(self.dirichlet_al)
help2 = sparse.dia_matrix((help2, 0), shape=(nnodes, nnodes))
A = help.dot(A.dot(help)) + help2.dot(A.dot(help2))
return A, bdrydata
def vectorDirichlet(self, b, u, bdrycond, method, bdrydata):
nodesdir, nodedirall, nodesinner, nodesdirflux = bdrydata.nodesdir, bdrydata.nodedirall, bdrydata.nodesinner, bdrydata.nodesdirflux
if u is None: u = np.zeros_like(b)
elif u.shape != b.shape : raise ValueError("u.shape != b.shape {} != {}".format(u.shape, b.shape))
x, y, z = self.mesh.points.T
for color, nodes in nodesdirflux.items():
bdrydata.bsaved[color] = b[nodes]
if method == 'strong':
for color, nodes in nodesdir.items():
if color in bdrycond.fct:
dirichlet = bdrycond.fct[color](x[nodes], y[nodes], z[nodes])
b[nodes] = dirichlet
else:
b[nodes] = 0
u[nodes] = b[nodes]
b[nodesinner] -= bdrydata.A_inner_dir * b[nodedirall]
else:
for color, nodes in nodesdir.items():
dirichlet = bdrycond.fct[color]
if dirichlet:
u[nodes] = dirichlet(x[nodes], y[nodes], z[nodes])
else:
u[nodes] = 0
b[nodes] = 0
b[nodesinner] -= bdrydata.A_inner_dir * u[nodedirall]
b[nodedirall] += bdrydata.A_dir_dir * u[nodedirall]
return b, u, bdrydata
def vectorDirichletZero(self, du, bdrydata):
nodesdir = bdrydata.nodesdir
for color, nodes in nodesdir.items():
du[nodes] = 0
return du
def tonode(self, u):
return u
# def grad(self, ic):
# normals = self.mesh.normals[self.mesh.facesOfCells[ic,:]]
# grads = 0.5*normals/self.mesh.dV[ic]
# chsg = (ic == self.mesh.cellsOfFaces[self.mesh.facesOfCells[ic,:],0])
# # print("### chsg", chsg, "normals", normals)
# grads[chsg] *= -1.
# return grads
def computeErrorL2(self, solexact, uh):
x, y, z = self.mesh.points.T
en = solexact(x, y, z) - uh
xc, yc, zc = self.mesh.pointsc.T
ec = solexact(xc, yc, zc) - np.mean(uh[self.mesh.simplices], axis=1)
return np.sqrt( np.dot(en, self.massmatrix*en) ), np.sqrt(np.sum(ec**2* self.mesh.dV)), en
def computeErrorFluxL2(self, solexact, diffcell, uh):
xc, yc, zc = self.mesh.pointsc.T
graduh = np.einsum('nij,ni->nj', self.cellgrads, uh[self.mesh.simplices])
errv = 0
for i in range(self.mesh.dimension):
solxi = solexact.d(i, xc, yc, zc)
errv += np.sum( diffcell*(solxi-graduh[:,i])**2* self.mesh.dV)
return np.sqrt(errv)
def computeBdryMean(self, u, colors):
# colors = [int(x) for x in data.split(',')]
mean, omega = np.zeros(len(colors)), np.zeros(len(colors))
for i,color in enumerate(colors):
faces = self.mesh.bdrylabels[color]
normalsS = self.mesh.normals[faces]
dS = linalg.norm(normalsS, axis=1)
omega[i] = np.sum(dS)
mean[i] = np.sum(dS*np.mean(u[self.mesh.faces[faces]],axis=1))
return mean/omega
def comuteFluxOnRobin(self, u, faces, dS, uR, cR):
uhmean = np.sum(dS * np.mean(u[self.mesh.faces[faces]], axis=1))
xf, yf, zf = self.mesh.pointsf[faces].T
nx, ny, nz = np.mean(self.mesh.normals[faces], axis=0)
if uR: uRmean = np.sum(dS * uR(xf, yf, zf, nx, ny, nz))
else: uRmean=0
return cR*(uRmean-uhmean)
def computeBdryDn(self, u, colors, bdrydata, bdrycond):
# colors = [int(x) for x in data.split(',')]
flux, omega = np.zeros(len(colors)), np.zeros(len(colors))
for i,color in enumerate(colors):
faces = self.mesh.bdrylabels[color]
normalsS = self.mesh.normals[faces]
dS = linalg.norm(normalsS, axis=1)
omega[i] = np.sum(dS)
if bdrycond.type[color] == "Robin":
flux[i] = self.comuteFluxOnRobin(u, faces, dS, bdrycond.fct[color], bdrycond.param[color])
elif bdrycond.type[color] == "Dirichlet":
bs, As = bdrydata.bsaved[color], bdrydata.Asaved[color]
flux[i] = np.sum(As * u - bs)
else:
raise NotImplementedError(f"computeBdryDn for condition '{bdrycond.type[color]}' color={color}")
return flux
def computeBdryFct(self, u, colors):
# colors = [int(x) for x in data.split(',')]
nodes = np.empty(shape=(0), dtype=int)
for color in colors:
faces = self.mesh.bdrylabels[color]
nodes = np.unique(np.union1d(nodes, self.mesh.faces[faces].ravel()))
return self.mesh.points[nodes], u[nodes]
def computePointValues(self, u, colors):
# colors = [int(x) for x in data.split(',')]
up = np.empty(len(colors))
for i,color in enumerate(colors):
nodes = self.mesh.verticesoflabel[color]
up[i] = u[nodes]
return up
def computeMeanValues(self, u, colors):
# colors = [int(x) for x in data.split(',')]
up = np.empty(len(colors))
for i, color in enumerate(colors):
up[i] = self.computeMeanValue(u,color)
return up
def computeMeanValue(self, u, color):
cells = self.mesh.cellsoflabel[color]
# print("umean", np.mean(u[self.mesh.simplices[cells]],axis=1))
return np.sum(np.mean(u[self.mesh.simplices[cells]],axis=1)*self.mesh.dV[cells])
# ------------------------------------- #
if __name__ == '__main__':
trimesh = SimplexMesh(geomname="backwardfacingstep", hmean=0.3)
fem = FemP1(trimesh)
fem.testgrad()
import plotmesh
import matplotlib.pyplot as plt
plotmesh.meshWithBoundaries(trimesh)
plt.show()
| [
"numpy.sum",
"numpy.empty",
"numpy.einsum",
"numpy.ones",
"numpy.mean",
"numpy.arange",
"numpy.tile",
"numpy.add.at",
"numpy.unique",
"numpy.zeros_like",
"numpy.append",
"scipy.sparse.coo_matrix",
"scipy.sparse.dia_matrix",
"scipy.sparse.dok_matrix",
"numpy.union1d",
"numpy.repeat",
... | [((15635, 15688), 'simfempy.meshes.simplexmesh.SimplexMesh', 'SimplexMesh', ([], {'geomname': '"""backwardfacingstep"""', 'hmean': '(0.3)'}), "(geomname='backwardfacingstep', hmean=0.3)\n", (15646, 15688), False, 'from simfempy.meshes.simplexmesh import SimplexMesh\n'), ((15793, 15829), 'plotmesh.meshWithBoundaries', 'plotmesh.meshWithBoundaries', (['trimesh'], {}), '(trimesh)\n', (15820, 15829), False, 'import plotmesh\n'), ((15834, 15844), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (15842, 15844), True, 'import matplotlib.pyplot as plt\n'), ((1566, 1608), 'numpy.tile', 'np.tile', (['scalemass', '(self.nloc, self.nloc)'], {}), '(scalemass, (self.nloc, self.nloc))\n', (1573, 1608), True, 'import numpy as np\n'), ((2033, 2061), 'numpy.empty', 'np.empty', ([], {'shape': '(0)', 'dtype': 'int'}), '(shape=0, dtype=int)\n', (2041, 2061), True, 'import numpy as np\n'), ((2079, 2107), 'numpy.empty', 'np.empty', ([], {'shape': '(0)', 'dtype': 'int'}), '(shape=0, dtype=int)\n', (2087, 2107), True, 'import numpy as np\n'), ((2124, 2154), 'numpy.empty', 'np.empty', ([], {'shape': '(0)', 'dtype': 'float'}), '(shape=0, dtype=float)\n', (2132, 2154), True, 'import numpy as np\n'), ((3838, 3866), 'numpy.empty', 'np.empty', ([], {'shape': '(0)', 'dtype': 'int'}), '(shape=0, dtype=int)\n', (3846, 3866), True, 'import numpy as np\n'), ((4669, 4742), 'numpy.einsum', 'np.einsum', (['"""nk,nl->nkl"""', 'self.cellgrads[:, :, 0]', 'self.cellgrads[:, :, 0]'], {}), "('nk,nl->nkl', self.cellgrads[:, :, 0], self.cellgrads[:, :, 0])\n", (4678, 4742), True, 'import numpy as np\n'), ((4759, 4832), 'numpy.einsum', 'np.einsum', (['"""nk,nl->nkl"""', 'self.cellgrads[:, :, 1]', 'self.cellgrads[:, :, 1]'], {}), "('nk,nl->nkl', self.cellgrads[:, :, 1], self.cellgrads[:, :, 1])\n", (4768, 4832), True, 'import numpy as np\n'), ((4849, 4922), 'numpy.einsum', 'np.einsum', (['"""nk,nl->nkl"""', 'self.cellgrads[:, :, 2]', 'self.cellgrads[:, :, 2]'], {}), "('nk,nl->nkl', self.cellgrads[:, :, 2], self.cellgrads[:, :, 2])\n", (4858, 4922), True, 'import numpy as np\n'), ((5238, 5301), 'numpy.einsum', 'np.einsum', (['"""nij,ni->nj"""', 'self.cellgrads', 'u[self.mesh.simplices]'], {}), "('nij,ni->nj', self.cellgrads, u[self.mesh.simplices])\n", (5247, 5301), True, 'import numpy as np\n'), ((5319, 5366), 'numpy.einsum', 'np.einsum', (['"""ni,n->ni"""', 'graduh', '(self.mesh.dV * k)'], {}), "('ni,n->ni', graduh, self.mesh.dV * k)\n", (5328, 5366), True, 'import numpy as np\n'), ((5778, 5804), 'numpy.zeros', 'np.zeros', (['self.mesh.nnodes'], {}), '(self.mesh.nnodes)\n', (5786, 5804), True, 'import numpy as np\n'), ((6687, 6713), 'numpy.zeros', 'np.zeros', (['self.mesh.nnodes'], {}), '(self.mesh.nnodes)\n', (6695, 6713), True, 'import numpy as np\n'), ((12427, 12491), 'numpy.einsum', 'np.einsum', (['"""nij,ni->nj"""', 'self.cellgrads', 'uh[self.mesh.simplices]'], {}), "('nij,ni->nj', self.cellgrads, uh[self.mesh.simplices])\n", (12436, 12491), True, 'import numpy as np\n'), ((12690, 12703), 'numpy.sqrt', 'np.sqrt', (['errv'], {}), '(errv)\n', (12697, 12703), True, 'import numpy as np\n'), ((13387, 13428), 'numpy.mean', 'np.mean', (['self.mesh.normals[faces]'], {'axis': '(0)'}), '(self.mesh.normals[faces], axis=0)\n', (13394, 13428), True, 'import numpy as np\n'), ((14540, 14568), 'numpy.empty', 'np.empty', ([], {'shape': '(0)', 'dtype': 'int'}), '(shape=0, dtype=int)\n', (14548, 14568), True, 'import numpy as np\n'), ((3991, 4035), 'numpy.unique', 'np.unique', (['self.mesh.faces[facesdir].flat[:]'], {}), '(self.mesh.faces[facesdir].flat[:])\n', (4000, 4035), True, 'import numpy as np\n'), ((4182, 4220), 'numpy.arange', 'np.arange', (['self.mesh.nnodes'], {'dtype': 'int'}), '(self.mesh.nnodes, dtype=int)\n', (4191, 4220), True, 'import numpy as np\n'), ((7214, 7245), 'numpy.mean', 'np.mean', (['normals[faces]'], {'axis': '(0)'}), '(normals[faces], axis=0)\n', (7221, 7245), True, 'import numpy as np\n'), ((7647, 7676), 'scipy.linalg.norm', 'linalg.norm', (['normalsS'], {'axis': '(1)'}), '(normalsS, axis=1)\n', (7658, 7676), True, 'import scipy.linalg as linalg\n'), ((7945, 7987), 'numpy.add.at', 'np.add.at', (['b', 'self.mesh.faces[faces].T', 'bS'], {}), '(b, self.mesh.faces[faces].T, bS)\n', (7954, 7987), True, 'import numpy as np\n'), ((9001, 9032), 'scipy.sparse.dok_matrix', 'sparse.dok_matrix', (['(nb, nnodes)'], {}), '((nb, nnodes))\n', (9018, 9032), True, 'import scipy.sparse as sparse\n'), ((9249, 9264), 'numpy.ones', 'np.ones', (['nnodes'], {}), '(nnodes)\n', (9256, 9264), True, 'import numpy as np\n'), ((9319, 9371), 'scipy.sparse.dia_matrix', 'sparse.dia_matrix', (['(help, 0)'], {'shape': '(nnodes, nnodes)'}), '((help, 0), shape=(nnodes, nnodes))\n', (9336, 9371), True, 'import scipy.sparse as sparse\n'), ((9429, 9445), 'numpy.zeros', 'np.zeros', (['nnodes'], {}), '(nnodes)\n', (9437, 9445), True, 'import numpy as np\n'), ((9502, 9554), 'scipy.sparse.dia_matrix', 'sparse.dia_matrix', (['(help, 0)'], {'shape': '(nnodes, nnodes)'}), '((help, 0), shape=(nnodes, nnodes))\n', (9519, 9554), True, 'import scipy.sparse as sparse\n'), ((9693, 9708), 'numpy.ones', 'np.ones', (['nnodes'], {}), '(nnodes)\n', (9700, 9708), True, 'import numpy as np\n'), ((9761, 9813), 'scipy.sparse.dia_matrix', 'sparse.dia_matrix', (['(help, 0)'], {'shape': '(nnodes, nnodes)'}), '((help, 0), shape=(nnodes, nnodes))\n', (9778, 9813), True, 'import scipy.sparse as sparse\n'), ((9834, 9850), 'numpy.zeros', 'np.zeros', (['nnodes'], {}), '(nnodes)\n', (9842, 9850), True, 'import numpy as np\n'), ((9883, 9909), 'numpy.sqrt', 'np.sqrt', (['self.dirichlet_al'], {}), '(self.dirichlet_al)\n', (9890, 9909), True, 'import numpy as np\n'), ((9930, 9983), 'scipy.sparse.dia_matrix', 'sparse.dia_matrix', (['(help2, 0)'], {'shape': '(nnodes, nnodes)'}), '((help2, 0), shape=(nnodes, nnodes))\n', (9947, 9983), True, 'import scipy.sparse as sparse\n'), ((10307, 10323), 'numpy.zeros_like', 'np.zeros_like', (['b'], {}), '(b)\n', (10320, 10323), True, 'import numpy as np\n'), ((12170, 12210), 'numpy.mean', 'np.mean', (['uh[self.mesh.simplices]'], {'axis': '(1)'}), '(uh[self.mesh.simplices], axis=1)\n', (12177, 12210), True, 'import numpy as np\n'), ((12620, 12681), 'numpy.sum', 'np.sum', (['(diffcell * (solxi - graduh[:, i]) ** 2 * self.mesh.dV)'], {}), '(diffcell * (solxi - graduh[:, i]) ** 2 * self.mesh.dV)\n', (12626, 12681), True, 'import numpy as np\n'), ((13023, 13052), 'scipy.linalg.norm', 'linalg.norm', (['normalsS'], {'axis': '(1)'}), '(normalsS, axis=1)\n', (13034, 13052), True, 'import scipy.linalg as linalg\n'), ((13076, 13086), 'numpy.sum', 'np.sum', (['dS'], {}), '(dS)\n', (13082, 13086), True, 'import numpy as np\n'), ((13887, 13916), 'scipy.linalg.norm', 'linalg.norm', (['normalsS'], {'axis': '(1)'}), '(normalsS, axis=1)\n', (13898, 13916), True, 'import scipy.linalg as linalg\n'), ((13940, 13950), 'numpy.sum', 'np.sum', (['dS'], {}), '(dS)\n', (13946, 13950), True, 'import numpy as np\n'), ((725, 750), 'numpy.tile', 'np.tile', (['simps', 'self.nloc'], {}), '(simps, self.nloc)\n', (732, 750), True, 'import numpy as np\n'), ((783, 810), 'numpy.repeat', 'np.repeat', (['simps', 'self.nloc'], {}), '(simps, self.nloc)\n', (792, 810), True, 'import numpy as np\n'), ((1690, 1735), 'numpy.einsum', 'np.einsum', (['"""n,kl->nkl"""', 'self.mesh.dV', 'massloc'], {}), "('n,kl->nkl', self.mesh.dV, massloc)\n", (1699, 1735), True, 'import numpy as np\n'), ((1759, 1832), 'scipy.sparse.coo_matrix', 'sparse.coo_matrix', (['(mass, (self.rows, self.cols))'], {'shape': '(nnodes, nnodes)'}), '((mass, (self.rows, self.cols)), shape=(nnodes, nnodes))\n', (1776, 1832), True, 'import scipy.sparse as sparse\n'), ((2440, 2469), 'scipy.linalg.norm', 'linalg.norm', (['normalsS'], {'axis': '(1)'}), '(normalsS, axis=1)\n', (2451, 2469), True, 'import scipy.linalg as linalg\n'), ((2540, 2562), 'numpy.append', 'np.append', (['rows', 'nodes'], {}), '(rows, nodes)\n', (2549, 2562), True, 'import numpy as np\n'), ((2586, 2608), 'numpy.append', 'np.append', (['cols', 'nodes'], {}), '(cols, nodes)\n', (2595, 2608), True, 'import numpy as np\n'), ((2632, 2678), 'numpy.repeat', 'np.repeat', (['(scalemass * dS)', 'self.mesh.dimension'], {}), '(scalemass * dS, self.mesh.dimension)\n', (2641, 2678), True, 'import numpy as np\n'), ((2699, 2719), 'numpy.append', 'np.append', (['mat', 'mass'], {}), '(mat, mass)\n', (2708, 2719), True, 'import numpy as np\n'), ((3113, 3142), 'scipy.linalg.norm', 'linalg.norm', (['normalsS'], {'axis': '(1)'}), '(normalsS, axis=1)\n', (3124, 3142), True, 'import scipy.linalg as linalg\n'), ((3399, 3431), 'numpy.tile', 'np.tile', (['scalemass', '(nloc, nloc)'], {}), '(scalemass, (nloc, nloc))\n', (3406, 3431), True, 'import numpy as np\n'), ((4080, 4137), 'numpy.union1d', 'np.union1d', (['bdrydata.nodedirall', 'bdrydata.nodesdir[color]'], {}), '(bdrydata.nodedirall, bdrydata.nodesdir[color])\n', (4090, 4137), True, 'import numpy as np\n'), ((4999, 5071), 'scipy.sparse.coo_matrix', 'sparse.coo_matrix', (['(mat, (self.rows, self.cols))'], {'shape': '(nnodes, nnodes)'}), '((mat, (self.rows, self.cols)), shape=(nnodes, nnodes))\n', (5016, 5071), True, 'import scipy.sparse as sparse\n'), ((6286, 6332), 'numpy.add.at', 'np.add.at', (['b', 'self.mesh.simplices[cells].T', 'bC'], {}), '(b, self.mesh.simplices[cells].T, bC)\n', (6295, 6332), True, 'import numpy as np\n'), ((8214, 8243), 'scipy.linalg.norm', 'linalg.norm', (['normalsS'], {'axis': '(1)'}), '(normalsS, axis=1)\n', (8225, 8243), True, 'import scipy.linalg as linalg\n'), ((8550, 8592), 'numpy.add.at', 'np.add.at', (['b', 'self.mesh.faces[faces].T', 'bS'], {}), '(b, self.mesh.faces[faces].T, bS)\n', (8559, 8592), True, 'import numpy as np\n'), ((12235, 12267), 'numpy.dot', 'np.dot', (['en', '(self.massmatrix * en)'], {}), '(en, self.massmatrix * en)\n', (12241, 12267), True, 'import numpy as np\n'), ((12277, 12307), 'numpy.sum', 'np.sum', (['(ec ** 2 * self.mesh.dV)'], {}), '(ec ** 2 * self.mesh.dV)\n', (12283, 12307), True, 'import numpy as np\n'), ((13274, 13316), 'numpy.mean', 'np.mean', (['u[self.mesh.faces[faces]]'], {'axis': '(1)'}), '(u[self.mesh.faces[faces]], axis=1)\n', (13281, 13316), True, 'import numpy as np\n'), ((15482, 15528), 'numpy.mean', 'np.mean', (['u[self.mesh.simplices[cells]]'], {'axis': '(1)'}), '(u[self.mesh.simplices[cells]], axis=1)\n', (15489, 15528), True, 'import numpy as np\n'), ((2739, 2801), 'scipy.sparse.coo_matrix', 'sparse.coo_matrix', (['(mat, (rows, cols))'], {'shape': '(nnodes, nnodes)'}), '((mat, (rows, cols)), shape=(nnodes, nnodes))\n', (2756, 2801), True, 'import scipy.sparse as sparse\n'), ((3597, 3659), 'scipy.sparse.coo_matrix', 'sparse.coo_matrix', (['(mat, (rows, cols))'], {'shape': '(nnodes, nnodes)'}), '((mat, (rows, cols)), shape=(nnodes, nnodes))\n', (3614, 3659), True, 'import scipy.sparse as sparse\n'), ((13119, 13161), 'numpy.mean', 'np.mean', (['u[self.mesh.faces[faces]]'], {'axis': '(1)'}), '(u[self.mesh.faces[faces]], axis=1)\n', (13126, 13161), True, 'import numpy as np\n'), ((14258, 14277), 'numpy.sum', 'np.sum', (['(As * u - bs)'], {}), '(As * u - bs)\n', (14264, 14277), True, 'import numpy as np\n'), ((3264, 3286), 'numpy.repeat', 'np.repeat', (['nodes', 'nloc'], {}), '(nodes, nloc)\n', (3273, 3286), True, 'import numpy as np\n'), ((3339, 3359), 'numpy.tile', 'np.tile', (['nodes', 'nloc'], {}), '(nodes, nloc)\n', (3346, 3359), True, 'import numpy as np\n'), ((3529, 3564), 'numpy.einsum', 'np.einsum', (['"""n,kl->nkl"""', 'dS', 'massloc'], {}), "('n,kl->nkl', dS, massloc)\n", (3538, 3564), True, 'import numpy as np\n')] |
import csv
import os
import sys
import cv2
import subprocess
import re
import numpy
# import tensorflow as tf
import math
import numpy as np
import h5py
# In OpenCV3.X, this is available as cv2.CAP_PROP_POS_MSEC
# In OpenCV2.X, this is available as cv2.cv.CV_CAP_PROP_POS_MSEC
CAP_PROP_POS_MSEC = 0
class Extractor:
def __init__(self,video_file, segment_len, frame_rate):
self.video_path = video_file
self.segment_len = segment_len
self.frame_rate = frame_rate
def __calc_frames(self):
process = subprocess.Popen(['ffmpeg', '-i', self.video_path], stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, stderr = process.communicate()
#testing comment
matches = re.search(r"Duration:\s{1}(?P<hours>\d+?):(?P<minutes>\d+?):(?P<seconds>\d+\.\d+?),",stdout.decode('utf-8'), re.DOTALL).groupdict()
fps = float(re.findall(r"\d*\.?\d* fps,", stdout.decode('utf-8'))[0].split(' ')[0].rstrip("'").lstrip("'"))
video_len = ((int(matches['hours']) * 3600) + (int(matches['minutes']) * 60) + float(matches['seconds']))
total_frames = int(video_len * self.frame_rate)
return total_frames
def __calc_segments(self, total_frames):
# total_frames = self.__calc_frames()
segments = math.ceil(total_frames / (self.frame_rate * self.segment_len))
return segments
def __frame_iterator(self, max_prev_frames, every_ms=1000, max_num_frames=360):
"""Uses OpenCV to iterate over all frames of filename at a given frequency.
Args:
filename: Path to video file (e.g. mp4)
every_ms: The duration (in milliseconds) to pick between frames.
max_num_frames: Maximum number of frames to process, taken from the
beginning of the video.
Yields:
RGB frame with shape (image height, image width, channels)
"""
video_capture = cv2.VideoCapture()
if not video_capture.open(self.video_path):
print(sys.stderr, 'Error: Cannot open video file ' + self.video_path)
return
last_ts = -99999 # The timestamp of last retrieved frame.
num_retrieved = 0
while num_retrieved <= max_num_frames:
# Skip frames
while video_capture.get(CAP_PROP_POS_MSEC) < every_ms + last_ts:
if not video_capture.read()[0]:
return
last_ts = video_capture.get(CAP_PROP_POS_MSEC)
has_frames, frame = video_capture.read()
if not has_frames:
break
if num_retrieved >= max_prev_frames:
yield frame
# num_retrieved += 1
num_retrieved += 1
def __quantize(self, features, min_quantized_value=-2.0, max_quantized_value=2.0):
"""Quantizes float32 `features` into string."""
assert features.dtype == 'float32'
assert len(features.shape) == 1 # 1-D array
features = numpy.clip(features, min_quantized_value, max_quantized_value)
quantize_range = max_quantized_value - min_quantized_value
features = (features - min_quantized_value) * (255.0 / quantize_range)
features = [int(round(f)) for f in features]
return features
def __extract_features(self):
total_error = 0
frames = self.__calc_frames()
seg = self.__calc_segments(frames)
seg_features = {}
for iter in range(seg):
rgb_features = []
sum_rgb_features = None
prev_max_frames= iter * self.segment_len
if frames > prev_max_frames:
for rgb in self.__frame_iterator(every_ms=1000.0 / self.frame_rate, max_prev_frames=prev_max_frames, max_num_frames=prev_max_frames + self.segment_len):
features = self.extractor.extract_rgb_frame_features(rgb[:, :, ::-1])
if sum_rgb_features is None:
sum_rgb_features = features
else:
sum_rgb_features += features
rgb_features.append(self.__quantize(features))
if not rgb_features:
print >> sys.stderr, 'Could not get features for ' + self.video_path
total_error +=1
continue
mean_rgb_features = sum_rgb_features / len(rgb_features)
seg_features['seg'+ str(iter +1)] = mean_rgb_features
return seg_features
def write_h5(self, file_name):
features = self.__extract_features()
print("*******feature shape ********", features['seg1'].shape)
dt = h5py.special_dtype(vlen=str)
h5f = h5py.File("/home/khawar/Documents/AutoEncoder/Samran_Code/"+file_name, 'w')
h5f.create_dataset('id', data=self.video_path, dtype=dt)
h5f.create_dataset('mean_rgb', data=np.array(list(features.values()), dtype=float))
h5f.create_dataset('seg_num', data=len(features), dtype=int)
h5f.close()
print("features written")
# same function as above but it also returns a list of frames for each segment
def write_h5_and_return_frames(self, file_name):
video_frame , features = self.segment_video_extract_features() # note this function returns extracted featuers plus video frames
print("*******feature shape ********", features['seg1'].shape)
dt = h5py.special_dtype(vlen=str)
h5f = h5py.File("/home/khawar/Documents/AutoEncoder/Samran_Code/"+file_name, 'w')
h5f.create_dataset('id', data=self.video_path, dtype=dt)
h5f.create_dataset('mean_rgb', data=np.array(list(features.values()), dtype=float))
h5f.create_dataset('seg_num', data=len(features), dtype=int)
h5f.close()
print("features written")
return video_frame
def load_vid_data(self, width, height, normalize = True):
total_error = 0
frames = self.__calc_frames()
seg = self.__calc_segments(frames)
seg_features = {}
dim = (width, height)
i = 0
for iter in range(seg):
rgb_frames = []
sum_rgb_features = None
prev_max_frames= iter * self.segment_len
if frames > prev_max_frames:
for rgb in self.__frame_iterator(every_ms=1000.0 / self.frame_rate, max_prev_frames=prev_max_frames, max_num_frames=prev_max_frames + self.segment_len):
# resizing images
rgb = cv2.resize(rgb, dim, interpolation = cv2.INTER_AREA)
if normalize:
# normalizing the frames
rgb = rgb/255.0
imgs = np.array(rgb)
rgb_frames.append(imgs)
if i == 0:
rgb_img = np.array(rgb_frames)
else:
img = np.array(rgb_frames)
rgb_img = np.vstack((rgb_img,img))
i+=1
return rgb_img
def load_segmentated_video(self):
total_error = 0
frames = self.__calc_frames()
seg = self.__calc_segments(frames)
seg_features = {}
total_segs_rgb = []
for iter in range(seg):
rgb_features = []
rgb_frames = []
sum_rgb_features = None
prev_max_frames= iter * self.segment_len
if frames > prev_max_frames:
for rgb in self.__frame_iterator(every_ms=1000.0 / self.frame_rate, max_prev_frames=prev_max_frames, max_num_frames=prev_max_frames + self.segment_len):
features = self.extractor.extract_rgb_frame_features(rgb[:, :, ::-1])
rgb_frames.append(rgb)
if sum_rgb_features is None:
sum_rgb_features = features
else:
sum_rgb_features += features
rgb_features.append(self.__quantize(features))
if not rgb_features:
print >> sys.stderr, 'Could not get features for ' + self.video_path
total_error +=1
continue
mean_rgb_features = sum_rgb_features / len(rgb_features)
seg_features['seg'+ str(iter +1)] = mean_rgb_features
rgb_img= np.array(rgb_frames)
total_segs_rgb.append(rgb_img)
print("segments +++++ ", seg)
print("total_seg_rgb +++++ ",len(total_segs_rgb))
return total_segs_rgb
def segment_video_extract_features(self):
total_error = 0
frames = self.__calc_frames()
seg = self.__calc_segments(frames)
seg_features = {}
total_segs_rgb = []
for iter in range(seg):
rgb_features = []
rgb_frames = []
sum_rgb_features = None
prev_max_frames= iter * self.segment_len
if frames > prev_max_frames:
for rgb in self.__frame_iterator(every_ms=1000.0 / self.frame_rate, max_prev_frames=prev_max_frames, max_num_frames=prev_max_frames + self.segment_len):
features = self.extractor.extract_rgb_frame_features(rgb[:, :, ::-1])
rgb_frames.append(rgb)
if sum_rgb_features is None:
sum_rgb_features = features
else:
sum_rgb_features += features
rgb_features.append(self.__quantize(features))
if not rgb_features:
print >> sys.stderr, 'Could not get features for ' + self.video_path
total_error +=1
continue
mean_rgb_features = sum_rgb_features / len(rgb_features)
seg_features['seg'+ str(iter +1)] = mean_rgb_features
rgb_img= np.array(rgb_frames)
total_segs_rgb.append(rgb_img)
print("total_seg_rgb +++++ ",len(total_segs_rgb))
print("testing ")
print("length of seg_features", len(seg_features))
print("segments +++++ ", seg)
return total_segs_rgb , seg_features;
def get_frames(self):
total_error = 0
frames = self.__calc_frames()
seg = self.__calc_segments(frames)
seg_features = {}
total_segs_rgb = []
for iter in range(seg):
rgb_features = []
rgb_frames = []
sum_rgb_features = None
prev_max_frames= iter * self.segment_len
dim = (224, 224)
if frames > prev_max_frames:
for rgb in self.__frame_iterator(every_ms=1000.0 / self.frame_rate, max_prev_frames=prev_max_frames, max_num_frames=prev_max_frames + self.segment_len):
# resizing images to 224 X 224
rgb = cv2.resize(rgb, dim, interpolation = cv2.INTER_AREA)
# normalizing the frames
rgb = rgb/255.0
rgb_frames.append(rgb)
rgb_img= np.array(rgb_frames)
total_segs_rgb.append(rgb_img)
print("total_seg_rgb +++++ ",len(total_segs_rgb))
print("testing ")
return np.array(total_segs_rgb)
| [
"cv2.resize",
"subprocess.Popen",
"h5py.File",
"h5py.special_dtype",
"math.ceil",
"numpy.clip",
"cv2.VideoCapture",
"numpy.array",
"numpy.vstack"
] | [((541, 646), 'subprocess.Popen', 'subprocess.Popen', (["['ffmpeg', '-i', self.video_path]"], {'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.STDOUT'}), "(['ffmpeg', '-i', self.video_path], stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n", (557, 646), False, 'import subprocess\n'), ((1336, 1398), 'math.ceil', 'math.ceil', (['(total_frames / (self.frame_rate * self.segment_len))'], {}), '(total_frames / (self.frame_rate * self.segment_len))\n', (1345, 1398), False, 'import math\n'), ((1968, 1986), 'cv2.VideoCapture', 'cv2.VideoCapture', ([], {}), '()\n', (1984, 1986), False, 'import cv2\n'), ((3029, 3091), 'numpy.clip', 'numpy.clip', (['features', 'min_quantized_value', 'max_quantized_value'], {}), '(features, min_quantized_value, max_quantized_value)\n', (3039, 3091), False, 'import numpy\n'), ((4727, 4755), 'h5py.special_dtype', 'h5py.special_dtype', ([], {'vlen': 'str'}), '(vlen=str)\n', (4745, 4755), False, 'import h5py\n'), ((4770, 4847), 'h5py.File', 'h5py.File', (["('/home/khawar/Documents/AutoEncoder/Samran_Code/' + file_name)", '"""w"""'], {}), "('/home/khawar/Documents/AutoEncoder/Samran_Code/' + file_name, 'w')\n", (4779, 4847), False, 'import h5py\n'), ((5481, 5509), 'h5py.special_dtype', 'h5py.special_dtype', ([], {'vlen': 'str'}), '(vlen=str)\n', (5499, 5509), False, 'import h5py\n'), ((5524, 5601), 'h5py.File', 'h5py.File', (["('/home/khawar/Documents/AutoEncoder/Samran_Code/' + file_name)", '"""w"""'], {}), "('/home/khawar/Documents/AutoEncoder/Samran_Code/' + file_name, 'w')\n", (5533, 5601), False, 'import h5py\n'), ((11431, 11455), 'numpy.array', 'np.array', (['total_segs_rgb'], {}), '(total_segs_rgb)\n', (11439, 11455), True, 'import numpy as np\n'), ((6913, 6933), 'numpy.array', 'np.array', (['rgb_frames'], {}), '(rgb_frames)\n', (6921, 6933), True, 'import numpy as np\n'), ((6974, 6994), 'numpy.array', 'np.array', (['rgb_frames'], {}), '(rgb_frames)\n', (6982, 6994), True, 'import numpy as np\n'), ((7021, 7046), 'numpy.vstack', 'np.vstack', (['(rgb_img, img)'], {}), '((rgb_img, img))\n', (7030, 7046), True, 'import numpy as np\n'), ((8441, 8461), 'numpy.array', 'np.array', (['rgb_frames'], {}), '(rgb_frames)\n', (8449, 8461), True, 'import numpy as np\n'), ((10011, 10031), 'numpy.array', 'np.array', (['rgb_frames'], {}), '(rgb_frames)\n', (10019, 10031), True, 'import numpy as np\n'), ((11250, 11270), 'numpy.array', 'np.array', (['rgb_frames'], {}), '(rgb_frames)\n', (11258, 11270), True, 'import numpy as np\n'), ((6569, 6619), 'cv2.resize', 'cv2.resize', (['rgb', 'dim'], {'interpolation': 'cv2.INTER_AREA'}), '(rgb, dim, interpolation=cv2.INTER_AREA)\n', (6579, 6619), False, 'import cv2\n'), ((6793, 6806), 'numpy.array', 'np.array', (['rgb'], {}), '(rgb)\n', (6801, 6806), True, 'import numpy as np\n'), ((11013, 11063), 'cv2.resize', 'cv2.resize', (['rgb', 'dim'], {'interpolation': 'cv2.INTER_AREA'}), '(rgb, dim, interpolation=cv2.INTER_AREA)\n', (11023, 11063), False, 'import cv2\n')] |
'''
DistCalc2: estimates the distance to the supernova from the neutrino data by constraining the progenitor
assuming one-to-one correspondence bt f_delta and N50_exp (expected 0-50ms count) (f_delta = m*N50_exp + b)
Data assumptions:
- 1 ms binning
- first 100 bins of each data have no SN emission (for background calculation)
Constructor arguments:
detector: string, "detector name, ordering" ,
one of ["IceCube, NO","IceCube, IO","HK, NO","HK, IO","SK, NO","SK, IO",
"DUNE, NO","DUNE, IO","JUNO, NO","JUNO, IO"]
in_field: string, "n",
to get the count numbers from data["n"]
out_field: string, "dist" (as an example),
used for adding/updating the field in the data dict
t0: the "measured/estimated" time of the start of SN emission (ms)
'''
import logging
import numpy as np
from snewpdag.dag import Node
class DistCalc2(Node):
# dict of f_delta-N50 fit parameters at 10kpc
# {'detector, ordering': [m, b, progenitor model variance = b_err]}
fit_par = {'IceCube, NO': [0.000182, 0.779, 0.11], \
'IceCube, IO': [0.000125, 0.342, 0.0656], \
'HK, NO': [0.00152, 0.894, 0.0973], \
'HK, IO': [0.00119, 0.439, 0.0529], \
'SK, NO': [0.0105, 0.894, 0.0973], \
'SK, IO': [0.00815, 0.439, 0.0529], \
'DUNE, NO': [0.0158, -0.0304, 0.0641], \
'DUNE, IO': [0.00978, -0.706, 0.0411], \
'JUNO, NO': [0.0109, 0.746, 0.0909], \
'JUNO, IO': [0.0088, 0.319, 0.0515]}
def __init__(self, detector, in_field, out_field, t0, **kwargs):
self.in_field = in_field
self.out_field = out_field
self.t0 = t0
self.detector = detector
self.m = self.fit_par[self.detector][0]
self.b = self.fit_par[self.detector][1]
self.b_err = self.fit_par[self.detector][2]
super().__init__(**kwargs)
def dist_calc2(self, data):
bg = np.mean(data[self.in_field][0: self.t0]) #averaged bins before t0 to find background
bg_err = np.sqrt(bg)
n50 = np.sum(data[self.in_field][self.t0: self.t0+50]) #uncorrected
n50_err = np.sqrt(n50)
N50 = np.sum(data[self.in_field][self.t0: self.t0+50]-bg) #N(0-50ms) corrected for background
N50_err = np.sqrt(N50) #assume Gaussian
n100_150 = np.sum(data[self.in_field][self.t0+100: self.t0+150])
n100_150_err = np.sqrt(n100_150)
N100_150 = np.sum(data[self.in_field][self.t0+100: self.t0+150]-bg) #N(100-150ms) corrected for background
N100_150_err = np.sqrt(N100_150) #assume Gaussian
f_delta = N100_150/N50
f_delta_err = f_delta*np.sqrt((N50_err/N50)**2+(N100_150_err/N100_150)**2)
dist_par = 10.0
m = self.m
b = self.b
b_err = self.b_err
N50_exp = (f_delta-b)/m
N50_exp_err = np.sqrt(f_delta_err**2+b_err**2)/m
dist2 = dist_par*np.sqrt(N50_exp/N50)
#diff dist2 wrt N50 or n50
d1 = 10*m**(-0.5)*((N100_150-b*N50)**(0.5)*N50**(-2)+0.5*b*N50**(-1)*(N100_150-b*N50)**(-0.5))
#diff dist2 wrt N100_150 or n100_150
d2 = 10*m**(-0.5)*(0.5*(N100_150-b*N50)**(-0.5)/N50)
#diff dist2 wrt bg
d3 = -(d1 + d2)
dist2_stats = np.sqrt((d1*n50_err)**2 + (d2*n100_150_err)**2 + (d3*bg_err)**2)
dist2_sys = 5*b_err*(m*(N100_150-b*N50))**(-0.5)
dist2_err = np.sqrt(dist2_stats**2+dist2_sys**2)
return (dist2, dist2_err, dist2_stats, dist2_sys, bg, n50, N50, n100_150, N100_150, m, b, b_err)
def alert(self, data):
(dist2, dist2_err, dist2_stats, dist2_sys, bg, n50, N50, n100_150, N100_150, m, b, b_err) = self.dist_calc2(data)
d = { self.out_field: dist2, self.out_field+"_err": dist2_err, self.out_field+"_stats": dist2_stats, self.out_field+"_sys": dist2_sys, self.out_field+"background": bg, \
self.out_field+"N50": N50, self.out_field+"N100_150": N100_150, self.out_field+"n50": n50, self.out_field+"n100_150": n100_150}
data.update(d)
return True
| [
"numpy.mean",
"numpy.sum",
"numpy.sqrt"
] | [((2023, 2062), 'numpy.mean', 'np.mean', (['data[self.in_field][0:self.t0]'], {}), '(data[self.in_field][0:self.t0])\n', (2030, 2062), True, 'import numpy as np\n'), ((2125, 2136), 'numpy.sqrt', 'np.sqrt', (['bg'], {}), '(bg)\n', (2132, 2136), True, 'import numpy as np\n'), ((2151, 2200), 'numpy.sum', 'np.sum', (['data[self.in_field][self.t0:self.t0 + 50]'], {}), '(data[self.in_field][self.t0:self.t0 + 50])\n', (2157, 2200), True, 'import numpy as np\n'), ((2231, 2243), 'numpy.sqrt', 'np.sqrt', (['n50'], {}), '(n50)\n', (2238, 2243), True, 'import numpy as np\n'), ((2258, 2312), 'numpy.sum', 'np.sum', (['(data[self.in_field][self.t0:self.t0 + 50] - bg)'], {}), '(data[self.in_field][self.t0:self.t0 + 50] - bg)\n', (2264, 2312), True, 'import numpy as np\n'), ((2364, 2376), 'numpy.sqrt', 'np.sqrt', (['N50'], {}), '(N50)\n', (2371, 2376), True, 'import numpy as np\n'), ((2413, 2469), 'numpy.sum', 'np.sum', (['data[self.in_field][self.t0 + 100:self.t0 + 150]'], {}), '(data[self.in_field][self.t0 + 100:self.t0 + 150])\n', (2419, 2469), True, 'import numpy as np\n'), ((2490, 2507), 'numpy.sqrt', 'np.sqrt', (['n100_150'], {}), '(n100_150)\n', (2497, 2507), True, 'import numpy as np\n'), ((2527, 2588), 'numpy.sum', 'np.sum', (['(data[self.in_field][self.t0 + 100:self.t0 + 150] - bg)'], {}), '(data[self.in_field][self.t0 + 100:self.t0 + 150] - bg)\n', (2533, 2588), True, 'import numpy as np\n'), ((2646, 2663), 'numpy.sqrt', 'np.sqrt', (['N100_150'], {}), '(N100_150)\n', (2653, 2663), True, 'import numpy as np\n'), ((3338, 3414), 'numpy.sqrt', 'np.sqrt', (['((d1 * n50_err) ** 2 + (d2 * n100_150_err) ** 2 + (d3 * bg_err) ** 2)'], {}), '((d1 * n50_err) ** 2 + (d2 * n100_150_err) ** 2 + (d3 * bg_err) ** 2)\n', (3345, 3414), True, 'import numpy as np\n'), ((3480, 3522), 'numpy.sqrt', 'np.sqrt', (['(dist2_stats ** 2 + dist2_sys ** 2)'], {}), '(dist2_stats ** 2 + dist2_sys ** 2)\n', (3487, 3522), True, 'import numpy as np\n'), ((2742, 2804), 'numpy.sqrt', 'np.sqrt', (['((N50_err / N50) ** 2 + (N100_150_err / N100_150) ** 2)'], {}), '((N50_err / N50) ** 2 + (N100_150_err / N100_150) ** 2)\n', (2749, 2804), True, 'import numpy as np\n'), ((2939, 2977), 'numpy.sqrt', 'np.sqrt', (['(f_delta_err ** 2 + b_err ** 2)'], {}), '(f_delta_err ** 2 + b_err ** 2)\n', (2946, 2977), True, 'import numpy as np\n'), ((3000, 3022), 'numpy.sqrt', 'np.sqrt', (['(N50_exp / N50)'], {}), '(N50_exp / N50)\n', (3007, 3022), True, 'import numpy as np\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.