prompt
stringlengths 15
655k
| completion
stringlengths 3
32.4k
| api
stringlengths 8
52
|
---|---|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from builtins import zip
from builtins import range
import os
import numpy as np
import subprocess
import pkg_resources
from .generalTools import calcForLogQ
from .nebAbundTools import getNebAbunds
def cloudyInput(dir_, model_name, **kwargs):
'''
cloudyInput('./test/', 'ZAU115', logZ=-1.5, age=5.0e6, logU=-4.0)
writes standard cloudy input to ./test/ZAU115.in
defaults: 1Myr, logZ=-0.5, logU=-2.0, nH=100, r_inner=3 pc
'''
pars = {"age":1.0e6, #age in years
"logZ": -0.5, #logZ/Zsol (-2.0 to 0.2)
"gas_logZ":None,
"logQ":47.0,
"logU":-2.0, #log of ionization parameter
"dens":100.0, # number density of hydrogen
"r_inner":1.0, #inner radius of cloud
"r_in_pc":False,
"use_Q":True,
"set_name":"dopita",
"dust":True,
"re_z":False,
"cloudy_mod":"FSPS_SPS.mod",
"efrac":-1.0,
"extras":"",
"extra_output":True,
"to_file":True,
"verbose":False,
"par1":"age",
"par1val":5.0e6,
"par2":"logz",
"par2val":0.0,
"maxStellar":None,
"use_extended_lines":False,
"geometry":"sphere"
}
for key, value in list(kwargs.items()):
pars[key] = value
# -----
if pars["to_file"]:
file_name = dir_+model_name+".in"
f = open(file_name, "w")
def this_print(s, eol=True):
if s is None:
print('"None" parameter not printed')
else:
to_print = s.strip()
if pars["verbose"]:
print(to_print)
if pars["to_file"]:
if eol: to_print += "\n"
f.write(to_print)
#-----------------------------------------------------
if pars["gas_logZ"] is None:
pars["gas_logZ"] = pars["logZ"]
abunds = getNebAbunds(pars["set_name"],
pars["gas_logZ"],
dust=pars["dust"],
re_z=pars["re_z"])
this_print('////////////////////////////////////')
this_print('title {0}'.format(model_name.split('/')[-1]))
this_print('////////////////////////////////////')
this_print('set punch prefix "{0}"'.format(model_name))
this_print('print line precision 6')
####
if pars['par1'] == "age":
pars['par1val'] = pars['age']
if pars['par2'] == "logz":
pars['par2val'] = pars['logZ']
if pars['maxStellar'] is not None:
if pars['logZ'] > pars['maxStellar']:
pars['par2val'] = pars['maxStellar']
else:
pars['par2val'] = pars['logZ']
this_print('table star "{0}" {1}={2:.2e} {3}={4:.2e}'.format(pars['cloudy_mod'], pars['par1'], pars['par1val'],pars['par2'], pars['par2val']))
if pars['use_Q']:
this_print('Q(H) = {0:.3f} log'.format(pars['logQ']))
else:
this_print('ionization parameter = {0:.3f} log'.format(pars['logU']))
####
this_print(abunds.solarstr)
if pars['dust']:
#this_print('metals grains {0:.2f} log'.format(pars['gas_logZ']))
this_print('grains {0:.2f} log'.format(pars['gas_logZ']))
#else:
# #this_print('metals {0:.2f} log'.format(pars['gas_logZ']))
for line in abunds.elem_strs:
this_print(line)
####
if pars['r_in_pc']:
pc_to_cm = 3.08568e18
r_out = np.log10(pars['r_inner']*pc_to_cm)
else:
r_out = pars['r_inner']
if pars['use_extended_lines']:
linefile = 'cloudyLinesEXT.dat'
else:
linefile = 'cloudyLines.dat'
this_print('radius {0:.3f} log'.format(r_out))
this_print('hden {0:.3f} log'.format(np.log10(pars['dens'])))
this_print('{}'.format(pars['geometry']))
this_print('cosmic ray background')
this_print('iterate to convergence max=5')
this_print('stop temperature 100.0')
this_print('stop efrac {0:.2f}'.format(pars['efrac']))
this_print('save last linelist ".lin" "{}" absolute column'.format(linefile))
this_print('save last outward continuum ".outwcont" units Angstrom no title')
this_print('save last incident continuum ".inicont" units Angstrom no title')
if len(pars["extras"]) > 0:
this_print(pars["extras"])
if pars["extra_output"]:
this_print(extra_str)
if pars["verbose"]:
print("Input written in {0}".format(file_name))
f.close()
extra_str = '''
save last radius ".rad"
save last physical conditions ".phys"
save last element hydrogen ".ele_H"
save last element helium ".ele_He"
save last element carbon ".ele_C"
save last element nitrogen ".ele_N"
save last element oxygen ".ele_O"
save last element sulphur ".ele_S"
save last element silicon ".ele_Si"
save last element iron ".ele_Fe"
save last hydrogen Lya ".H_lya"
save last hydrogen ionization ".H_ion"
save last lines emissivity ".emis"
H 1 6562.85A
H 1 4861.36A
H 1 4340.49A
He 1 3888.63A
He 1 4471.47A
He 1 5875.61A
He 2 1640.00A
O 1 6300.00A
O 1 6363.00A
O II 3729.00A
O II 3726.00A
O 3 5007.00A
TOTL 4363.00A
O 3 4959.00A
O 3 51.8000m
N 2 6584.00A
N 2 6548.00A
S II 6731.00A
S II 6716.00A
S 3 9069.00A
S 3 9532.00A
S 3 18.6700m
S 4 10.5100m
Ar 3 7135.00A
Ar 3 9.00000m
Ne 3 3869.00A
Ne 2 12.8100m
Ne 3 15.5500m
C 3 1910.00A
C 3 1907.00A
end of lines
'''
def writeMake(dir_=None):
'''
writes makefile that runs Cloudy on all files in directory with
the same prefix.
'''
makefile = open("{0}/Makefile".format(dir_), "w")
txt_exe = "CLOUDY = {0}\n".format(os.environ["CLOUDY_EXE"])
txt = """
SRC = $(wildcard ${name}*.in)
OBJ = $(SRC:.in=.out)
#Usage: make -j n_proc name='NAME'
#optional: NAME is a generic name, all models named NAME*.in will be run
all: $(OBJ)
%.out: %.in
\t-$(CLOUDY) < $< > $@
#notice the previous line has TAB in first column
"""
makefile.write(txt_exe)
makefile.write(txt)
makefile.close()
def runMake(dir_=None, n_proc=1, model_name=None):
if dir_ is None:
dir_="./"
to_run = "cd {0} ; make -j {1:d}".format(dir_, n_proc)
if model_name is not None:
to_run += " name='{0}'".format(model_name)
stdin = None
stdout = subprocess.PIPE
print("running: {0}".format(to_run))
proc = subprocess.Popen(to_run, shell=True, stdout=stdout, stdin=stdin)
proc.communicate()
def printParFile(dir_, mod_prefix, pars):
'''
prints parameter file for easy parsing later
modnum, Z, a, U, R, logQ, n, efrac
'''
outfile = "{}{}.pars".format(dir_, mod_prefix)
f = open(outfile, "w")
for i in range(len(pars)):
par = pars[i]
if len(par) > 7:
pstr = "{0} {1:.2f} {2:.2e} {3:.2f} {4:.2f} {5:.2f} {6:.2f} {7:.2f} {8:.2e}\n".format(i+1, *par)
else:
pstr = "{0} {1:.2f} {2:.2e} {3:.2f} {4:.2f} {5:.2f} {6:.2f} {7:.2f}\n".format(i+1, *par)
f.write(pstr)
f.close()
return
def writeParamFiles(**kwargs):
'''
for making grids of parameters.
can pass arrays of ages, logZs, logUs, nHs.
cloudy_input.param_files(extras='extra line to add to input')
'''
nom_dict = {"dir_":"./output/",
"model_prefix":"ZAU",
"ages":np.arange(1.0e6, 6.0e6, 1.0e6),
"logZs":np.linspace(-2.0, 0.2, 5),
"logQs":
|
np.linspace(45,49, 5)
|
numpy.linspace
|
#!/usr/bin/env python
import unittest
from unittest.mock import MagicMock
import nbconvert
import numpy as np
with open("assignmenttest.ipynb") as f:
exporter = nbconvert.PythonExporter()
python_file, _ = exporter.from_file(f)
with open("assignmenttest.py", "w") as f:
f.write(python_file)
from assignmenttest import IterativeSolver
class TestSolution(unittest.TestCase):
def test_solver(self):
A = np.array([[2, -1, 0], [-1, 2, -1], [0, -1, 2]])
b = np.array([1, 2, 3])
solver = IterativeSolver(A, b)
np.testing.assert_array_almost_equal(solver.gauss_seidel_solve(),
|
np.array([2.5, 4., 3.5])
|
numpy.array
|
import os
import csv
import json
import logging
import random
import numpy as np
from PIL import Image
from torch.utils.data import Dataset
from smoke.modeling.heatmap_coder import (
get_transfrom_matrix,
affine_transform,
gaussian_radius,
draw_umich_gaussian,
)
from smoke.modeling.smoke_coder import encode_label
from smoke.structures.params_3d import ParamsList
TYPE_ID_CONVERSION = {
'bicycle': 0,
'bus': 1,
'car': 2,
'construction_vehicle': 3,
'motorcycle': 4,
'pedestrian': 5,
'trailer': 6,
'truck': 7
}
class NuScenesDataset(Dataset):
def __init__(self, cfg, root, json_file, is_train=True, transforms=None):
super(NuScenesDataset, self).__init__()
self.root = root
self.json_file = os.path.join(root, json_file)
with open(self.json_file, 'r') as f:
infos = json.load(f)
self.image_infos = infos['images']
self.anns_infos = infos['annotations']
self.is_train = is_train
self.transforms = transforms
self.classes = cfg.DATASETS.DETECT_CLASSES
if self.is_train:
self.filter_samples(self.classes)
self.num_samples = len(self.image_infos)
self.flip_prob = cfg.INPUT.FLIP_PROB_TRAIN if is_train else 0
self.aug_prob = cfg.INPUT.SHIFT_SCALE_PROB_TRAIN if is_train else 0
self.shift_scale = cfg.INPUT.SHIFT_SCALE_TRAIN
self.num_classes = len(self.classes)
self.input_width = cfg.INPUT.WIDTH_TRAIN
self.input_height = cfg.INPUT.HEIGHT_TRAIN
self.output_width = self.input_width // cfg.MODEL.BACKBONE.DOWN_RATIO
self.output_height = self.input_height // cfg.MODEL.BACKBONE.DOWN_RATIO
self.max_objs = cfg.DATASETS.MAX_OBJECTS
self.logger = logging.getLogger(__name__)
self.logger.info("Initializing NuScenes {} with {} samples loaded".format(json_file, self.num_samples))
def __len__(self):
return self.num_samples
def __getitem__(self, idx):
img, image_id, anns, calib = self.load_data(idx)
K = calib['K']
center = np.array([i / 2 for i in img.size], dtype=np.float32)
size = np.array([i for i in img.size], dtype=np.float32)
"""
resize, horizontal flip, and affine augmentation are performed here.
since it is complicated to compute heatmap w.r.t transform.
"""
flipped = False
if (self.is_train) and (random.random() < self.flip_prob):
flipped = True
img = img.transpose(Image.FLIP_LEFT_RIGHT)
center[0] = size[0] - center[0] - 1
K[0, 2] = size[0] - K[0, 2] - 1
K[0, 3] *= -1
affine = False
if (self.is_train) and (random.random() < self.aug_prob):
affine = True
shift, scale = self.shift_scale[0], self.shift_scale[1]
shift_ranges = np.arange(-shift, shift + 0.1, 0.1)
center[0] += size[0] * random.choice(shift_ranges)
center[1] += size[1] * random.choice(shift_ranges)
scale_ranges = np.arange(1 - scale, 1 + scale + 0.1, 0.1)
size *= random.choice(scale_ranges)
center_size = [center, size]
trans_affine = get_transfrom_matrix(
center_size,
[self.input_width, self.input_height]
)
trans_affine_inv = np.linalg.inv(trans_affine)
img = img.transform(
(self.input_width, self.input_height),
method=Image.AFFINE,
data=trans_affine_inv.flatten()[:6],
resample=Image.BILINEAR,
)
trans_mat = get_transfrom_matrix(
center_size,
[self.output_width, self.output_height]
)
if not self.is_train:
# for inference we parametrize with original size
target = ParamsList(image_size=size,
is_train=self.is_train)
target.add_field("trans_mat", trans_mat)
target.add_field("K", K)
target.add_field("ego_T_cam", calib['ego_T_cam'])
target.add_field("global_T_ego", calib['global_T_ego'])
if self.transforms is not None:
img, target = self.transforms(img, target)
return img, target, image_id
heat_map = np.zeros([self.num_classes, self.output_height, self.output_width], dtype=np.float32)
regression = np.zeros([self.max_objs, 3, 8], dtype=np.float32)
cls_ids = np.zeros([self.max_objs], dtype=np.int32)
proj_points = np.zeros([self.max_objs, 2], dtype=np.int32)
p_offsets = np.zeros([self.max_objs, 2], dtype=np.float32)
dimensions =
|
np.zeros([self.max_objs, 3], dtype=np.float32)
|
numpy.zeros
|
import pandas as pd
import scanpy as sc
import numpy as np
from sklearn.metrics import pairwise_distances
from scipy.sparse import issparse, csr_matrix
def kfilter(x, k=5, keep_values=True):
"""
Sorts and array and return either a boolean array with
True set to k smallest values (if keep_values is False) or
sets all values to 0 and keeps k smallest values.
Parameters
----------
x
A numpy array ()
k
Integer, number of smallest values to keep
keep_values
bool, whether to return boolean (if False) or values (if True)
Returns
-------
numpy array, bool (if keep_values is False), otherwise dtype of x
"""
inds = np.argsort(x)[range(k)]
if keep_values:
out = np.zeros(x.shape, dtype=x.dtype)
out[inds] = x[inds]
else:
out = np.zeros(x.shape, dtype='bool')
out[inds] = True
return out
def kneighbor_mask(array, k, axis=1):
"""
Runs kfilter on a 2 dimensional array, along the specified axis.
"""
array01 = np.apply_along_axis(kfilter, axis=axis, arr=array, k=k)
return array01
def custom_scale(adata, mean, std, copy=True):
'''
Zero-centered scaling (with unit variance) with defined means and
standard deviations. Can be used to match scaled gene expression
values to some refernce dataset.
This is based on scanpy sc.pp.scale function and works with both
sparse or dense arrays.
Note: scanpy stores means and std after scaling in the .var slot
Parameters
----------
X
adata - AnnData object (with .X sparse or dense)
mean
numpy array with mean gene expression
std
numpy array with standard deviations
copy
boolean, whether to modify in place or return a copy
'''
adata = adata.copy() if copy else adata
X = adata.X
if issparse(X):
X = X.toarray()
X -= mean
X /= std
adata.X = X
if copy:
return adata
def get_label_mode(x):
"""
Convert array to pd.Series and return the mode.
In case of ties the first value is returned.
"""
x = pd.Series(x)
return x.mode()[0] # what if there ties?
def get_label_by_threshold(x, tr=0.6):
"""
Get the most prevalent label above a threshold
Parameters
----------
x
list/array/pd.Series with labels (strings)
tr
float, between 0 and 1. Defines the label fraction threshold.
Returns
-------
Returns the most prevalent value if it occurs more than tr
fraction. Otherwise returns unassigned.
"""
x = pd.Series(x)
x = x.value_counts()
if any(x >= tr*sum(x)):
return(x.idxmax())
else:
return('unassigned')
def assign_numeric(nn, values, fun=np.mean):
"""
Assign summarised numeric values based on these values among nearest neighbors
in the reference datasets.
Parameters
----------
nn
bolean numpy array with nearest neighbors between target dataset
(each cell is a row) and reference dataset (each cell is a column)
value
numpy array/pd.Series with numeric values in the reference, needs
to match the nnmatrix column order
fun
function used to summarise the values. Applied to each vector
of length equal to the number of nearest neighbors
Returns
-------
Numpy array (length equal to rows in nnmatrix) with summarised values
"""
nobs = nn.shape[0]
out = np.empty(nobs, dtype=values.dtype)
for i in range(nobs):
sub = nn[i, :]
x = values[sub]
out[i] = fun(x)
return out
def count_label_distribution(nn, labels):
"""
Count normalised label occurences among nearest neighbors.
Parameters
----------
nn
a numpy boolean array representing nn adjacency matrix (cells x cells shape)
each row corresponds to a cell and its k nearest neighbors labelled as True.
labels
numpy array/pd.Series with labels, has to correspond to columns in the nn array
Returns
pd.DataFrame, rows are cells, columns are labels, values are number of label
occurences for each label divided by the number of neighbors
"""
# Detecting k and number of cells (n)
k = nn[0, :].sum()
n = nn.shape[0]
dl = np.empty((n, k), dtype='object')
for i in range(n):
dl[i, :] = labels[nn[i, :]]
dl = pd.DataFrame(dl)
dl = dl.melt(ignore_index=False, var_name='k', value_name='label')
out = pd.crosstab(index=dl.index, columns=dl.label)
out = out/k
return out
# Another way: use .value_counts() for each cell and store in an array
# CAUTION then categories needs to be ordered Otherwise the order changes!
def get_label_by_nndistribution(cross_nn, ref_nn, ref_labels):
"""
Assign label based on correlation in label distribution among nearest neighbors.
First we compute the the number of each label among nearest neighbors in the
reference dataset, then do the same but for nearest neighbors between the
projected and reference dataset. Finally we compute pairwise correlations
between and choose the best matching cells in the reference and assign its label.
In case of ties we take the mode of labels of the best matching cells, and if there
are ties there we take the first value.
Parameters
----------
cross_nn
dense numpy array or scipy sparse array (csr) with projected cells as rows and
reference data in columns. Values are boolean and indicate if reference cells
are nearest neighbors of projected cells
ref_nn
as in cross_nn but a square matrix indicating nearest neighbors within the
reference dataset (from rows to columns)
ref_labels
numpy array/pd.Series with labels, has to correspond to columns in the
cross_nn or ref_nn array
Returns
-------
Numpy array with assigned labels. Length equal to the number of projected cells.
All cells are assigned a label.
"""
if issparse(cross_nn):
cross_nn = cross_nn.toarray()
if issparse(ref_nn):
ref_nn = ref_nn.toarray()
ref_ncounts = count_label_distribution(ref_nn, ref_labels)
target_ncounts = count_label_distribution(cross_nn, ref_labels)
ref_ncounts = ref_ncounts.loc[:, target_ncounts.columns]
cordists = pairwise_distances(target_ncounts, ref_ncounts)
n = target_ncounts.shape[0]
new_labels = np.empty(n, dtype='object')
for i in range(n):
x = cordists[i, :]
best = np.where(x == x.min())[0]
if len(best) == 1:
new_labels[i] = ref_labels[best][0]
else:
new_labels[i] = ref_labels[best].mode()[0]
return new_labels
def assign_label(cross_nn, ref_nn, ref_labels, how='mode'):
"""
Assign label to projected cells based on the labels among their nearest neighbors
in the reference dataset.
Parameters
----------
cross_nn
dense numpy array or scipy sparse array (csr) with projected cells as rows and
reference data in columns. Values are boolean and indicate if reference cells
are nearest neighbors of projected cells
ref_nn
as in cross_nn but a square matrix indicating nearest neighbors within the
reference dataset (from rows to columns)
ref_labels
numpy array/pd.Series with labels, has to correspond to columns in the cross_nn
or ref_nn array
how
string, either 'mode', 'threshold' or 'distribution'. Specified the mode
modified operation, and how the labels will be assigned. See the functions:
get_label_mode, get_label_by_threshold and get_label_by_nndistribution for
details.
Returns
-------
Numpy array with assigned labels. Length equal to the number of projected cells.
If how = 'threshold', some cells may be labelled as 'unassigned'.
"""
if how == 'mode' or how == 'threshold':
nobs = cross_nn.shape[0]
out =
|
np.empty(nobs, dtype='object')
|
numpy.empty
|
import argparse
import glob
import cv2
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, BatchNormalization, Lambda, Activation
from keras.layers import Conv2D, MaxPooling2D, concatenate, Input
from keras.callbacks import TensorBoard
from keras.models import load_model, Model
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ModelCheckpoint
import tqdm
from moviepy.editor import VideoFileClip
from scipy.ndimage.measurements import label
from sklearn.model_selection import train_test_split
import matplotlib
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import json
from PIL import Image, ImageDraw, ImageFont
import multiprocessing
matplotlib.style.use('ggplot')
import logging
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
#The background is set with 40 plus the number of the color, and the foreground with 30
#These are the sequences need to get colored ouput
RESET_SEQ = "\033[0m"
COLOR_SEQ = "\033[1;%dm"
BOLD_SEQ = "\033[1m"
def formatter_message(message, use_color = True):
if use_color:
message = message.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ)
else:
message = message.replace("$RESET", "").replace("$BOLD", "")
return message
COLORS = {
'WARNING': YELLOW,
'INFO': WHITE,
'DEBUG': BLUE,
'CRITICAL': YELLOW,
'ERROR': RED
}
class ColoredFormatter(logging.Formatter):
def __init__(self, msg, use_color = True):
logging.Formatter.__init__(self, msg)
self.use_color = use_color
def format(self, record):
levelname = record.levelname
if self.use_color and levelname in COLORS:
levelname_color = COLOR_SEQ % (30 + COLORS[levelname]) + levelname + RESET_SEQ
record.levelname = levelname_color
return logging.Formatter.format(self, record)
# Custom logger class with multiple destinations
class ColoredLogger(logging.Logger):
FORMAT = "[$BOLD%(name)-20s$RESET][%(levelname)-18s] %(message)s ($BOLD%(filename)s$RESET:%(lineno)d)"
COLOR_FORMAT = formatter_message(FORMAT, True)
def __init__(self, name):
logging.Logger.__init__(self, name, logging.DEBUG)
color_formatter = ColoredFormatter(self.COLOR_FORMAT)
console = logging.StreamHandler()
console.setFormatter(color_formatter)
self.addHandler(console)
return
logging.setLoggerClass(ColoredLogger)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
####################################################### MAIN CODE ########################################################
class Frames:
def __init__(self):
self._initialized = False
self._current_frame = 0
self._prev_bboxes = []
def init(self, img):
self._heatmap = np.zeros_like(img)
def _add_heat(self, bbox_list):
for box in bbox_list:
self._heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += 1
return self._heatmap
def _apply_threshold(self, threshold):
self._heatmap[self._heatmap <= threshold] = 0
return self._heatmap
def get_labels(self, bboxes, threshold):
if len(self._prev_bboxes) > threshold:
# Then remove the last bbox list from the previous frames
self._prev_bboxes.pop(0)
for pbboxes in self._prev_bboxes:
self._add_heat(pbboxes)
self._add_heat(bboxes)
# Add the latest one
self._prev_bboxes.append(bboxes)
# Figure out the thresholded value
# self._apply_threshold(threshold)
labels = label(self._heatmap)
bboxes = []
# Iterate through all detected cars
for car_number in range(1, labels[1] + 1):
# Find pixels with each car_number label value
nonzero = (labels[0] == car_number).nonzero()
# Identify x and y values of those pixels
nonzeroy = np.array(nonzero[0])
nonzerox = np.array(nonzero[1])
# Define a bounding box based on min/max x and y
bbox = ((np.min(nonzerox), np.min(nonzeroy)), (np.max(nonzerox), np.max(nonzeroy)))
bboxes.append(bbox)
# Get a viewable heatmap
heatmap = np.clip(self._heatmap, 0, 255)
heatmap[heatmap[:, :, 0] > 0] += 100
heatmap[:, :, 1] = 0
heatmap[:, :, 2] = 0
return bboxes, heatmap
frames = Frames()
def overlay_text(image, text, pos=(0, 0), color=(255, 255, 255)):
image = Image.fromarray(image)
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("./fonts/liberation-sans.ttf", 64)
draw.text(pos, text, color, font=font)
image = np.asarray(image)
return image
def overlay_image(img1, img2):
img1[0:img2.shape[0], 0:img2.shape[1]] = img2[:, :]
return img1
# Here is your draw_boxes function from the previous exercise
def draw_boxes(img, bboxes, color=(0, 255, 0), thick=2):
# Make a copy of the image
imcopy = np.copy(img)
for bbox in bboxes:
# Draw a rectangle given bbox coordinates
cv2.rectangle(imcopy, bbox[0], bbox[1], color, thick)
# Return the image copy with boxes drawn
return imcopy
class LeNet:
@staticmethod
def build(width, height, depth, weightsPath=None):
model = Sequential()
# First set Conv Layers
model.add(Conv2D(8, (3, 3), padding='valid', input_shape=(width, height, depth), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(BatchNormalization())
# 2nd set Conv layers
model.add(Conv2D(16, (3, 3), padding='valid', input_shape=(width, height, depth), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(BatchNormalization())
model.add(Conv2D(32, (3, 3), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(BatchNormalization())
model.add(Conv2D(64, (3, 3), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(BatchNormalization())
model.add(Dropout(0.5))
# Set of FC => Relu layers
model.add(Flatten())
model.add(Dense(256))
model.add(Activation('relu'))
model.add(Dropout(0.5))
# Softmax classifier
model.add(Dense(1))
model.add(Activation('sigmoid'))
if weightsPath is not None:
model.load_weights(weightsPath)
return model
class SimpleInception:
@staticmethod
def build(width, height, depth, weightsPath=None):
input_img = Input(shape=(width, height, depth))
model = Sequential()
# First set Conv Layers
tower_1 = Conv2D(32, (1, 1), padding='same', activation='relu')(input_img)
tower_1 = Conv2D(32, (3, 3), padding='same', activation='relu')(tower_1)
tower_2 = Conv2D(32, (1, 1), padding='same', activation='relu')(input_img)
tower_2 = Conv2D(32, (5, 5), padding='same', activation='relu')(tower_2)
tower_3 = MaxPooling2D((3, 3), strides=(1, 1), padding='same')(input_img)
tower_3 = Conv2D(32, (1, 1), padding='same', activation='relu')(tower_3)
concat = concatenate([tower_1, tower_2, tower_3], axis=3)
# Set of FC => Relu layers
flatten = Flatten()(concat)
dense1 = (Dense(256)(flatten))
activation1 = Activation('relu')(dense1)
dropout1 = Dropout(0.5)(activation1)
# Softmax classifier
dense2 = Dense(1)(dropout1)
output = Activation('sigmoid')(dense2)
model = Model(inputs=input_img, outputs=output)
if weightsPath is not None:
model.load_weights(weightsPath)
return model
def read_image(filename):
logger.debug("Reading an image")
img = mpimg.imread(filename)
return img
def create_training_data():
logger.info("Creating Training Data")
vehicles = []
for filename in tqdm.tqdm(glob.iglob('training/vehicles/**/*.png', recursive=True)):
img = read_image(filename)
vehicles.append(img)
nonvehicles = []
for filename in tqdm.tqdm(glob.iglob('training/non-vehicles/**/*.png', recursive=True)):
img = read_image(filename)
nonvehicles.append(img)
return vehicles, nonvehicles
def train_model(vehicles, non_vehicles):
generator = ImageDataGenerator( featurewise_center=True,
samplewise_center=False,
featurewise_std_normalization=False,
samplewise_std_normalization=False,
zca_whitening=False,
rotation_range=20.,
width_shift_range=0.4,
height_shift_range=0.4,
shear_range=0.2,
zoom_range=0.2,
channel_shift_range=0.1,
fill_mode='nearest',
horizontal_flip=True,
vertical_flip=False,
rescale=1.2,
preprocessing_function=None)
logger.info("Training the Model")
vehicles_labels = np.ones(len(vehicles))
non_vehicles_labels = np.zeros(len(non_vehicles))
labels = np.hstack((vehicles_labels, non_vehicles_labels))
data = np.array(vehicles + non_vehicles)
if len(vehicles[0].shape) == 3:
width, height, depth = vehicles[0].shape[1], vehicles[0].shape[0], vehicles[0].shape[2]
else:
width, height, depth = vehicles[0].shape[1], vehicles[0].shape[0], 1
# model = LeNet.build(width, height, depth)
model = SimpleInception.build(width, height, depth)
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
trainData, testData, trainLabels, testLabels = train_test_split(data, labels, random_state=20)
filepath = "inception.best.h5"
checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')
generator.fit(trainData)
hist = model.fit_generator(generator.flow(trainData, trainLabels, batch_size=16),
steps_per_epoch= int(len(trainData) / 16),
epochs=30,
verbose=1,
validation_data=(testData, testLabels),
callbacks=[TensorBoard(log_dir='logs'), checkpoint])
print("[INFO] dumping weights to file...")
model.save("inception.h5", overwrite=True)
model.save_weights("inception_weights.hdf5", overwrite=True)
fp = open("history_inception.json", 'w')
json.dump(hist.history, fp)
def generate_sliding_windows_old(img, window_sizes):
height, width = img.shape[0], img.shape[1]
# x_start = width // 2 - 100
x_start = 0
x_stop = width
y_start = height // 2 + 20
y_stop = height - 70
current_x = x_start
current_y = y_start
# Towards the bottom of the image use bigger bounding boxes
window_list = []
for (window_size, overlap) in window_sizes:
while current_x < x_stop:
end_x = current_x + window_size[0]
while current_y < y_stop:
end_y = current_y + window_size[1]
window_list.append(((int(current_x), int(current_y)), (int(end_x), int(end_y))))
current_y = end_y - window_size[1] * overlap[1]
# At this point reset the x and update the y
current_y = y_start
current_x = end_x - (window_size[0] * overlap[0])
return window_list
def slide_window(img, x_start_stop=[None, None], y_start_stop=[None, None],
xy_window=(64, 64), xy_overlap=(0.5, 0.5)):
# If x and/or y start/stop positions not defined, set to image size
if x_start_stop[0] == None:
x_start_stop[0] = 0
if x_start_stop[1] == None:
x_start_stop[1] = img.shape[1]
if y_start_stop[0] == None:
y_start_stop[0] = 0
if y_start_stop[1] == None:
y_start_stop[1] = img.shape[0]
# Compute the span of the region to be searched
xspan = x_start_stop[1] - x_start_stop[0]
yspan = y_start_stop[1] - y_start_stop[0]
# Compute the number of pixels per step in x/y
nx_pix_per_step = np.int(xy_window[0] * (1 - xy_overlap[0]))
ny_pix_per_step = np.int(xy_window[1] * (1 - xy_overlap[1]))
# Compute the number of windows in x/y
nx_buffer = np.int(xy_window[0] * (xy_overlap[0]))
ny_buffer = np.int(xy_window[1] * (xy_overlap[1]))
nx_windows = np.int((xspan - nx_buffer) / nx_pix_per_step)
ny_windows = np.int((yspan - ny_buffer) / ny_pix_per_step)
# Initialize a list to append window positions to
window_list = []
# Loop through finding x and y window positions
# Note: you could vectorize this step, but in practice
# you'll be considering windows one by one with your
# classifier, so looping makes sense
for ys in range(ny_windows):
for xs in range(nx_windows):
# Calculate window position
startx = xs * nx_pix_per_step + x_start_stop[0]
endx = startx + xy_window[0]
starty = ys * ny_pix_per_step + y_start_stop[0]
endy = starty + xy_window[1]
# Append window position to list
window_list.append(((startx, starty), (endx, endy)))
# Return the list of windows
return window_list
def generate_sliding_windows(img):
n_win_size = 3
min_size = (30, 30)
max_size = (120, 120)
roi_upper = 380
roi_lower = 650
win_step_w = int((max_size[0] - min_size[0]) / n_win_size)
win_step_h = int((max_size[1] - min_size[1]) / n_win_size)
window_sizes = [(min_size[0] + i * win_step_w, min_size[1] + i * win_step_h) for i in range(n_win_size + 1)]
all_windows = []
for win_size in window_sizes:
windows = slide_window(img, x_start_stop=[None, None], y_start_stop=[roi_upper, roi_lower],
xy_window=win_size, xy_overlap=(0.5, 0.5))
all_windows += windows
f = open('all_windows_mine.csv', 'w')
for w in all_windows:
f.write(str(w))
f.write("\n")
f.close()
return all_windows
def crop_and_predict(idx, img, window, spatial_size):
global model
cropped = img[window[0][1]:window[1][1], window[0][0]:window[1][0]]
# cv2.imwrite("cropped/" + str(idx) + ".png", cropped)
cropped = cv2.resize(cropped, spatial_size)
cropped = np.array([cropped])
return (window, cropped)
def add_heat(heatmap, bbox_list):
# Iterate through list of bboxes
for box in bbox_list:
# Add += 1 for all pixels inside each bbox
# Assuming each "box" takes the form ((x1, y1), (x2, y2))
heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += 1
# Return updated heatmap
return heatmap # Iterate through list of bboxes
def apply_threshold(heatmap, threshold):
# Zero out pixels below the threshold
heatmap[heatmap <= threshold] = 0
# Return thresholded map
return heatmap
def draw_labeled_bboxes(img, labels):
# Iterate through all detected cars
for car_number in range(1, labels[1]+1):
# Find pixels with each car_number label value
nonzero = (labels[0] == car_number).nonzero()
# Identify x and y values of those pixels
nonzeroy = np.array(nonzero[0])
nonzerox =
|
np.array(nonzero[1])
|
numpy.array
|
import numpy as np
import cv2
import numpy as np
import cmath
import math
def RA(img):
kernel = np.ones((5,5), np.uint8)
dilation = cv2.dilate(img, kernel, iterations = 7)
kernel = np.ones((5,5), np.uint8)
erosion = cv2.erode(dilation, kernel, iterations = 15)
r1 = erosion[:,:,2].astype(np.float32) - erosion[:,:,0].astype(np.float32)
r2 = erosion[:,:,2].astype(np.float32) - erosion[:,:,1].astype(np.float32)
img1 = cv2.normalize(r1, None, 0, 1, cv2.NORM_MINMAX, cv2.CV_8U)
img2 = cv2.normalize(r2, None, 0, 1, cv2.NORM_MINMAX, cv2.CV_8U)
bitwiseAnd = cv2.bitwise_and(img1, img2)
ret, thresh1 = cv2.threshold(bitwiseAnd, 0, 255, cv2.THRESH_BINARY)
#plt.imshow(cv2.cvtColor(thresh1, cv2.COLOR_BGR2RGB))
return thresh1
def RC(img):
r3 = img[:,:,2].astype(np.float32)-img[:,:,0].astype(np.float32)
r4 = img[:,:,2].astype(np.float32)-img[:,:,1].astype(np.float32)
img3 = cv2.normalize(r3, None, 0, 1, cv2.NORM_MINMAX, cv2.CV_8U)
img4 = cv2.normalize(r4, None, 0, 1, cv2.NORM_MINMAX, cv2.CV_8U)
bitwiseAnd2 = cv2.bitwise_and(img3, img4)
ret, thresh2 = cv2.threshold(bitwiseAnd2, 0, 255, cv2.THRESH_BINARY_INV)
#plt.imshow(cv2.cvtColor(thresh2, cv2.COLOR_BGR2RGB))
return thresh2
def Merge(img1, img2):
bitwiseAnd3 = cv2.bitwise_and(img1, img2)
#plt.imshow(cv2.cvtColor(bitwiseAnd3, cv2.COLOR_BGR2RGB))
return bitwiseAnd3
def Thinning(img):
thinned = cv2.ximgproc.thinning(img)
#plt.imshow(cv2.cvtColor(thinned, cv2.COLOR_BGR2RGB))
return thinned
def Edges(img):
edges = cv2.Canny(img, 50, 150, apertureSize = 3)
#plt.imshow(cv2.cvtColor(edges, cv2.COLOR_BGR2RGB))
return edges
def HoughLinesP(img, Original):
lines = cv2.HoughLinesP(img, 1, np.pi/180, 100, minLineLength=180, maxLineGap=250)
lines_data = np.empty([0,10])
if lines is not None:
for line in lines:
x1, y1, x2, y2 = line[0]
if(x2-x1 != 0):
# slope = abs((y2-y1)/(x2-x1))
slope = (y1-y2)/(x1-x2)
Linear_Equation_A = -slope
Linear_Equation_B = 1
Linear_Equation_C = y1-slope*x1
print(slope)
angle_in_radians = math.atan(slope)
angle_in_degrees = math.degrees(angle_in_radians)
cv2.line(Original, (x1, y1), (x2, y2), (0, 255, 0), 1)
print("(",x1,",",y1,") ",'(',x2,",",y2,')')
cv2.circle(Original, (x1,y1), 5, (0,255,0), -1)
cv2.circle(Original, (x2,y2), 5, (0,255,0), -1)
a = np.array([(Linear_Equation_A, Linear_Equation_B, Linear_Equation_C,slope,x1,x2,y1,y2,angle_in_degrees,1)])
lines_data = np.append(lines_data,a, axis=0)
else:
print('Nothing!!!')
return Original, lines_data
def Intersection(img, lines_data):
for i in range(len(lines_data)):
for j in range(i+1,len(lines_data)):
A =
|
np.array([[lines_data[i][0], lines_data[i][1]], [lines_data[j][0], lines_data[j][1]]])
|
numpy.array
|
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap as lcmap
from scipy.ndimage.filters import gaussian_filter, median_filter
pred = np.load('prob_pred_full.npy')
print(pred.shape)
#print(pred.max())
#print(pred.min())
print(pred.dtype)
if False:
vis = np.where(pred.max(axis=-1) == 0, 0 , np.argmax(pred, axis=2)+1)
elif True:
vis = np.zeros(pred.shape[:-1], dtype=np.uint8)
water = ((pred[...,0] > 0.05)|(pred[...,6] > 0.05)).astype(np.bool)
xz = (pred[...,4] > 0.1).astype(np.bool)
build = (pred[...,3] > 0.1).astype(np.bool)
manmade = (pred[...,1] > 0.1).astype(np.bool)
manmade_2 = (pred[...,5] > 0.1).astype(np.bool)
green_1 = (pred[...,2] > 0.3).astype(np.bool)
#green_2 = (pred[...,3] > 0.3).astype(np.bool)
vis = np.where(green_1, 6, 0)
vis = np.where(xz, 5, vis)
vis = np.where(manmade_2, 4, vis)
vis = np.where(manmade, 3, vis)
vis = np.where(build, 2, vis)
vis = np.where(water, 1, vis)
vis = np.where(vis == 0, np.where(pred.max(axis=-1) == 0, 0 , np.argmax(pred, axis=2)+1) , vis)
else:
vis = (pred[...,5] > 0.05).astype(np.bool)
np.save('tovect.npy', vis)
print(np.unique(vis))
#vis = median_filter(vis,4)
cs3 = plt.get_cmap('Set3').colors
colors = []
colors.append((0,0,0))
#colors.extend(cs3)
colors.append((0,0,1.))
colors.append((1.,0.,0.))
colors.append((1.,0.3,0))
colors.append((1.,0.7,0))
colors.append((1.,0.99,0))
colors.append((0.,1.,0.3))
#colors.append((0.,1.,0.8))
#colors.append((1.,0.,1.))
#cmap.colors = tuple(colors)
cmap = lcmap(colors)
if True:
import map_envi as envi
import re
print('clusterized')
fnames = envi.locate()
fnames = [el for el in fnames if not re.search(r'_[dD][bB]', el)]
fnames = [el for el in fnames if re.search(r'(Sigma)|(coh)', el)]
full_shape, hdict = envi.read_header(fnames[0])
colors = (np.array(colors) * 254).astype(np.uint8)
imgc = np.empty(vis.shape + (3,))
np.choose(vis, colors[...,0], out=imgc[...,0])
np.choose(vis, colors[...,1], out=imgc[...,1])
np.choose(vis, colors[...,2], out=imgc[...,2])
imgc[0,0,:] = np.array((0,0,0), dtype=np.uint8)
imgc[-1,-1,:] =
|
np.array((255,255,255), dtype=np.uint8)
|
numpy.array
|
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
#
# Copyright 2021 The NiPreps Developers <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# We support and encourage derived works from this project, please read
# about our expectations at
#
# https://www.nipreps.org/community/licensing/
#
"""Plotting tools shared across MRIQC and FMRIPREP."""
import numpy as np
import nibabel as nb
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import gridspec as mgs
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap, Normalize
from matplotlib.colorbar import ColorbarBase
DINA4_LANDSCAPE = (11.69, 8.27)
class fMRIPlot:
"""Generates the fMRI Summary Plot."""
__slots__ = ("func_file", "mask_data", "tr", "seg_data", "confounds", "spikes")
def __init__(
self,
func_file,
mask_file=None,
data=None,
conf_file=None,
seg_file=None,
tr=None,
usecols=None,
units=None,
vlines=None,
spikes_files=None,
):
func_img = nb.load(func_file)
self.func_file = func_file
self.tr = tr or _get_tr(func_img)
self.mask_data = None
self.seg_data = None
if not isinstance(func_img, nb.Cifti2Image):
self.mask_data = nb.fileslice.strided_scalar(
func_img.shape[:3], np.uint8(1)
)
if mask_file:
self.mask_data = np.asanyarray(nb.load(mask_file).dataobj).astype(
"uint8"
)
if seg_file:
self.seg_data = np.asanyarray(nb.load(seg_file).dataobj)
if units is None:
units = {}
if vlines is None:
vlines = {}
self.confounds = {}
if data is None and conf_file:
data = pd.read_csv(
conf_file, sep=r"[\t\s]+", usecols=usecols, index_col=False
)
if data is not None:
for name in data.columns.ravel():
self.confounds[name] = {
"values": data[[name]].values.ravel().tolist(),
"units": units.get(name),
"cutoff": vlines.get(name),
}
self.spikes = []
if spikes_files:
for sp_file in spikes_files:
self.spikes.append((np.loadtxt(sp_file), None, False))
def plot(self, figure=None):
"""Main plotter"""
import seaborn as sns
sns.set_style("whitegrid")
sns.set_context("paper", font_scale=0.8)
if figure is None:
figure = plt.gcf()
nconfounds = len(self.confounds)
nspikes = len(self.spikes)
nrows = 1 + nconfounds + nspikes
# Create grid
grid = mgs.GridSpec(
nrows, 1, wspace=0.0, hspace=0.05, height_ratios=[1] * (nrows - 1) + [5]
)
grid_id = 0
for tsz, name, iszs in self.spikes:
spikesplot(
tsz, title=name, outer_gs=grid[grid_id], tr=self.tr, zscored=iszs
)
grid_id += 1
if self.confounds:
from seaborn import color_palette
palette = color_palette("husl", nconfounds)
for i, (name, kwargs) in enumerate(self.confounds.items()):
tseries = kwargs.pop("values")
confoundplot(
tseries,
grid[grid_id],
tr=self.tr,
color=palette[i],
name=name,
**kwargs
)
grid_id += 1
plot_carpet(
self.func_file, atlaslabels=self.seg_data, subplot=grid[-1], tr=self.tr
)
# spikesplot_cb([0.7, 0.78, 0.2, 0.008])
return figure
def plot_carpet(
func,
atlaslabels=None,
detrend=True,
nskip=0,
size=(950, 800),
subplot=None,
title=None,
output_file=None,
legend=False,
tr=None,
lut=None,
):
"""
Plot an image representation of voxel intensities across time also know
as the "carpet plot" or "Power plot". See Jonathan Power Neuroimage
2017 Jul 1; 154:150-158.
Parameters
----------
func : string or nibabel-image object
Path to NIfTI or CIFTI BOLD image, or a nibabel-image object
atlaslabels: ndarray, optional
A 3D array of integer labels from an atlas, resampled into ``img`` space.
Required if ``func`` is a NIfTI image.
detrend : boolean, optional
Detrend and standardize the data prior to plotting.
nskip : int, optional
Number of volumes at the beginning of the scan marked as nonsteady state.
Only used by volumetric NIfTI.
size : tuple, optional
Size of figure.
subplot : matplotlib Subplot, optional
Subplot to plot figure on.
title : string, optional
The title displayed on the figure.
output_file : string, or None, optional
The name of an image file to export the plot to. Valid extensions
are .png, .pdf, .svg. If output_file is not None, the plot
is saved to a file, and the display is closed.
legend : bool
Whether to render the average functional series with ``atlaslabels`` as
overlay.
tr : float , optional
Specify the TR, if specified it uses this value. If left as None,
# of frames is plotted instead of time.
lut : ndarray, optional
Look up table for segmentations
"""
epinii = None
segnii = None
nslices = None
img = nb.load(func) if isinstance(func, str) else func
if isinstance(img, nb.Cifti2Image):
assert (
img.nifti_header.get_intent()[0] == "ConnDenseSeries"
), "Not a dense timeseries"
data = img.get_fdata().T
matrix = img.header.matrix
struct_map = {
"LEFT_CORTEX": 1,
"RIGHT_CORTEX": 2,
"SUBCORTICAL": 3,
"CEREBELLUM": 4,
}
seg = np.zeros((data.shape[0],), dtype="uint32")
for bm in matrix.get_index_map(1).brain_models:
if "CORTEX" in bm.brain_structure:
lidx = (1, 2)["RIGHT" in bm.brain_structure]
elif "CEREBELLUM" in bm.brain_structure:
lidx = 4
else:
lidx = 3
index_final = bm.index_offset + bm.index_count
seg[bm.index_offset:index_final] = lidx
assert len(seg[seg < 1]) == 0, "Unassigned labels"
# Decimate data
data, seg = _decimate_data(data, seg, size)
# preserve as much continuity as possible
order = seg.argsort(kind="stable")
cmap = ListedColormap([cm.get_cmap("Paired").colors[i] for i in (1, 0, 7, 3)])
assert len(cmap.colors) == len(
struct_map
), "Mismatch between expected # of structures and colors"
# ensure no legend for CIFTI
legend = False
else: # Volumetric NIfTI
from nilearn._utils import check_niimg_4d
from nilearn._utils.niimg import _safe_get_data
img_nii = check_niimg_4d(img, dtype="auto",)
func_data = _safe_get_data(img_nii, ensure_finite=True)
func_data = func_data[..., nskip:]
ntsteps = func_data.shape[-1]
data = func_data[atlaslabels > 0].reshape(-1, ntsteps)
oseg = atlaslabels[atlaslabels > 0].reshape(-1)
# Map segmentation
if lut is None:
lut = np.zeros((256,), dtype="int")
lut[1:11] = 1
lut[255] = 2
lut[30:99] = 3
lut[100:201] = 4
# Apply lookup table
seg = lut[oseg.astype(int)]
# Decimate data
data, seg = _decimate_data(data, seg, size)
# Order following segmentation labels
order = np.argsort(seg)[::-1]
# Set colormap
cmap = ListedColormap(cm.get_cmap("tab10").colors[:4][::-1])
if legend:
epiavg = func_data.mean(3)
epinii = nb.Nifti1Image(epiavg, img_nii.affine, img_nii.header)
segnii = nb.Nifti1Image(
lut[atlaslabels.astype(int)], epinii.affine, epinii.header
)
segnii.set_data_dtype("uint8")
nslices = epiavg.shape[-1]
return _carpet(
data,
seg,
order,
cmap,
epinii=epinii,
segnii=segnii,
nslices=nslices,
tr=tr,
subplot=subplot,
legend=legend,
title=title,
output_file=output_file,
)
def _carpet(
data,
seg,
order,
cmap,
tr=None,
detrend=True,
subplot=None,
legend=False,
title=None,
output_file=None,
epinii=None,
segnii=None,
nslices=None,
):
"""Common carpetplot building code for volumetric / CIFTI plots"""
from nilearn.plotting import plot_img
from nilearn.signal import clean
notr = False
if tr is None:
notr = True
tr = 1.0
# Detrend data
v = (None, None)
if detrend:
data = clean(data.T, t_r=tr).T
v = (-2, 2)
# If subplot is not defined
if subplot is None:
subplot = mgs.GridSpec(1, 1)[0]
# Define nested GridSpec
wratios = [1, 100, 20]
gs = mgs.GridSpecFromSubplotSpec(
1,
2 + int(legend),
subplot_spec=subplot,
width_ratios=wratios[: 2 + int(legend)],
wspace=0.0,
)
# Segmentation colorbar
ax0 = plt.subplot(gs[0])
ax0.set_yticks([])
ax0.set_xticks([])
ax0.imshow(seg[order, np.newaxis], interpolation="none", aspect="auto", cmap=cmap)
ax0.grid(False)
ax0.spines["left"].set_visible(False)
ax0.spines["bottom"].set_color("none")
ax0.spines["bottom"].set_visible(False)
# Carpet plot
ax1 = plt.subplot(gs[1])
ax1.imshow(
data[order],
interpolation="nearest",
aspect="auto",
cmap="gray",
vmin=v[0],
vmax=v[1],
)
ax1.grid(False)
ax1.set_yticks([])
ax1.set_yticklabels([])
# Set 10 frame markers in X axis
interval = max((int(data.shape[-1] + 1) // 10, int(data.shape[-1] + 1) // 5, 1))
xticks = list(range(0, data.shape[-1])[::interval])
if notr:
xlabel = "time-points (index)"
xticklabels = [round(xtick) for xtick in xticks]
else:
xlabel = "time (s)"
xticklabels = ["%.02f" % (tr * xtick) for xtick in xticks]
ax1.set_xticks(xticks)
ax1.set_xlabel(xlabel)
ax1.set_xticklabels(xticklabels)
# Remove and redefine spines
for side in ["top", "right"]:
# Toggle the spine objects
ax0.spines[side].set_color("none")
ax0.spines[side].set_visible(False)
ax1.spines[side].set_color("none")
ax1.spines[side].set_visible(False)
ax1.yaxis.set_ticks_position("left")
ax1.xaxis.set_ticks_position("bottom")
ax1.spines["bottom"].set_visible(False)
ax1.spines["left"].set_color("none")
ax1.spines["left"].set_visible(False)
if title:
ax1.set_title(title)
ax2 = None
if legend:
gslegend = mgs.GridSpecFromSubplotSpec(
5, 1, subplot_spec=gs[2], wspace=0.0, hspace=0.0
)
coords = np.linspace(int(0.10 * nslices), int(0.95 * nslices), 5).astype(
np.uint8
)
for i, c in enumerate(coords.tolist()):
ax2 = plt.subplot(gslegend[i])
plot_img(
segnii,
bg_img=epinii,
axes=ax2,
display_mode="z",
annotate=False,
cut_coords=[c],
threshold=0.1,
cmap=cmap,
interpolation="nearest",
)
if output_file is not None:
figure = plt.gcf()
figure.savefig(output_file, bbox_inches="tight")
plt.close(figure)
figure = None
return output_file
return (ax0, ax1, ax2), gs
def spikesplot(
ts_z,
outer_gs=None,
tr=None,
zscored=True,
spike_thresh=6.0,
title="Spike plot",
ax=None,
cmap="viridis",
hide_x=True,
nskip=0,
):
"""
A spikes plot. Thanks to <NAME> (this docstring needs be improved with proper ack)
"""
if ax is None:
ax = plt.gca()
if outer_gs is not None:
gs = mgs.GridSpecFromSubplotSpec(
1, 2, subplot_spec=outer_gs, width_ratios=[1, 100], wspace=0.0
)
ax = plt.subplot(gs[1])
# Define TR and number of frames
if tr is None:
tr = 1.0
# Load timeseries, zscored slice-wise
nslices = ts_z.shape[0]
ntsteps = ts_z.shape[1]
# Load a colormap
my_cmap = cm.get_cmap(cmap)
norm = Normalize(vmin=0, vmax=float(nslices - 1))
colors = [my_cmap(norm(sl)) for sl in range(nslices)]
stem = len(np.unique(ts_z).tolist()) == 2
# Plot one line per axial slice timeseries
for sl in range(nslices):
if not stem:
ax.plot(ts_z[sl, :], color=colors[sl], lw=0.5)
else:
markerline, stemlines, baseline = ax.stem(ts_z[sl, :])
plt.setp(markerline, "markerfacecolor", colors[sl])
plt.setp(baseline, "color", colors[sl], "linewidth", 1)
plt.setp(stemlines, "color", colors[sl], "linewidth", 1)
# Handle X, Y axes
ax.grid(False)
# Handle X axis
last = ntsteps - 1
ax.set_xlim(0, last)
xticks = list(range(0, last)[::20]) + [last] if not hide_x else []
ax.set_xticks(xticks)
if not hide_x:
if tr is None:
ax.set_xlabel("time (frame #)")
else:
ax.set_xlabel("time (s)")
ax.set_xticklabels(["%.02f" % t for t in (tr * np.array(xticks)).tolist()])
# Handle Y axis
ylabel = "slice-wise noise average on background"
if zscored:
ylabel += " (z-scored)"
zs_max = np.abs(ts_z).max()
ax.set_ylim(
(
-(np.abs(ts_z[:, nskip:]).max()) * 1.05,
(np.abs(ts_z[:, nskip:]).max()) * 1.05,
)
)
ytick_vals = np.arange(0.0, zs_max, float(np.floor(zs_max / 2.0)))
yticks = (
list(reversed((-1.0 * ytick_vals[ytick_vals > 0]).tolist()))
+ ytick_vals.tolist()
)
# TODO plot min/max or mark spikes
# yticks.insert(0, ts_z.min())
# yticks += [ts_z.max()]
for val in ytick_vals:
ax.plot((0, ntsteps - 1), (-val, -val), "k:", alpha=0.2)
ax.plot((0, ntsteps - 1), (val, val), "k:", alpha=0.2)
# Plot spike threshold
if zs_max < spike_thresh:
ax.plot((0, ntsteps - 1), (-spike_thresh, -spike_thresh), "k:")
ax.plot((0, ntsteps - 1), (spike_thresh, spike_thresh), "k:")
else:
yticks = [
ts_z[:, nskip:].min(),
np.median(ts_z[:, nskip:]),
ts_z[:, nskip:].max(),
]
ax.set_ylim(
0, max(yticks[-1] * 1.05, (yticks[-1] - yticks[0]) * 2.0 + yticks[-1])
)
# ax.set_ylim(ts_z[:, nskip:].min() * 0.95,
# ts_z[:, nskip:].max() * 1.05)
ax.annotate(
ylabel,
xy=(0.0, 0.7),
xycoords="axes fraction",
xytext=(0, 0),
textcoords="offset points",
va="center",
ha="left",
color="gray",
size=4,
bbox={
"boxstyle": "round",
"fc": "w",
"ec": "none",
"color": "none",
"lw": 0,
"alpha": 0.8,
},
)
ax.set_yticks([])
ax.set_yticklabels([])
# if yticks:
# # ax.set_yticks(yticks)
# # ax.set_yticklabels(['%.02f' % y for y in yticks])
# # Plot maximum and minimum horizontal lines
# ax.plot((0, ntsteps - 1), (yticks[0], yticks[0]), 'k:')
# ax.plot((0, ntsteps - 1), (yticks[-1], yticks[-1]), 'k:')
for side in ["top", "right"]:
ax.spines[side].set_color("none")
ax.spines[side].set_visible(False)
if not hide_x:
ax.spines["bottom"].set_position(("outward", 10))
ax.xaxis.set_ticks_position("bottom")
else:
ax.spines["bottom"].set_color("none")
ax.spines["bottom"].set_visible(False)
# ax.spines["left"].set_position(('outward', 30))
# ax.yaxis.set_ticks_position('left')
ax.spines["left"].set_visible(False)
ax.spines["left"].set_color(None)
# labels = [label for label in ax.yaxis.get_ticklabels()]
# labels[0].set_weight('bold')
# labels[-1].set_weight('bold')
if title:
ax.set_title(title)
return ax
def spikesplot_cb(position, cmap="viridis", fig=None):
# Add colorbar
if fig is None:
fig = plt.gcf()
cax = fig.add_axes(position)
cb = ColorbarBase(
cax,
cmap=cm.get_cmap(cmap),
spacing="proportional",
orientation="horizontal",
drawedges=False,
)
cb.set_ticks([0, 0.5, 1.0])
cb.set_ticklabels(["Inferior", "(axial slice)", "Superior"])
cb.outline.set_linewidth(0)
cb.ax.xaxis.set_tick_params(width=0)
return cax
def confoundplot(
tseries,
gs_ts,
gs_dist=None,
name=None,
units=None,
tr=None,
hide_x=True,
color="b",
nskip=0,
cutoff=None,
ylims=None,
):
import seaborn as sns
# Define TR and number of frames
notr = False
if tr is None:
notr = True
tr = 1.0
ntsteps = len(tseries)
tseries = np.array(tseries)
# Define nested GridSpec
gs = mgs.GridSpecFromSubplotSpec(
1, 2, subplot_spec=gs_ts, width_ratios=[1, 100], wspace=0.0
)
ax_ts = plt.subplot(gs[1])
ax_ts.grid(False)
# Set 10 frame markers in X axis
interval = max((ntsteps // 10, ntsteps // 5, 1))
xticks = list(range(0, ntsteps)[::interval])
ax_ts.set_xticks(xticks)
if not hide_x:
if notr:
ax_ts.set_xlabel("time (frame #)")
else:
ax_ts.set_xlabel("time (s)")
labels = tr * np.array(xticks)
ax_ts.set_xticklabels(["%.02f" % t for t in labels.tolist()])
else:
ax_ts.set_xticklabels([])
if name is not None:
if units is not None:
name += " [%s]" % units
ax_ts.annotate(
name,
xy=(0.0, 0.7),
xytext=(0, 0),
xycoords="axes fraction",
textcoords="offset points",
va="center",
ha="left",
color=color,
size=8,
bbox={
"boxstyle": "round",
"fc": "w",
"ec": "none",
"color": "none",
"lw": 0,
"alpha": 0.8,
},
)
for side in ["top", "right"]:
ax_ts.spines[side].set_color("none")
ax_ts.spines[side].set_visible(False)
if not hide_x:
ax_ts.spines["bottom"].set_position(("outward", 20))
ax_ts.xaxis.set_ticks_position("bottom")
else:
ax_ts.spines["bottom"].set_color("none")
ax_ts.spines["bottom"].set_visible(False)
# ax_ts.spines["left"].set_position(('outward', 30))
ax_ts.spines["left"].set_color("none")
ax_ts.spines["left"].set_visible(False)
# ax_ts.yaxis.set_ticks_position('left')
ax_ts.set_yticks([])
ax_ts.set_yticklabels([])
nonnan = tseries[~
|
np.isnan(tseries)
|
numpy.isnan
|
import cv2
import sys
import os
import argparse
import numpy as np
import random
import math
import time
WIDTH = 1000
HEIGHT = 1000
def example_draw():
Scene = np.ones((HEIGHT, WIDTH, 3), np.uint8) * 255
# Draw rectangle
cv2.rectangle(Scene, (100, 100), (200, 200), (0, 255, 0), cv2.FILLED)
# Draw circle
cv2.circle(Scene, (500, 500), 50, (0, 0, 255), lineType=cv2.LINE_4, thickness=1)
for i in range(4):
for j in range(4):
cv2.circle(Scene, (500+i*200, 500+j*200), 50, (0, 0, 255), cv2.FILLED)
return Scene
def tablechair_symx():
"""Arrangement of 1 table and 4 chairs that is symmetric across the x axis"""
Scene = np.ones((HEIGHT, WIDTH, 3), np.uint8) * 255
# Table
table_tl= (300,430)
table_br = (700,570)
cv2.rectangle(Scene, table_tl, table_br, (0, 255, 0), cv2.FILLED)
radius = 50
numpairs = 3
dist_chairs = 20 # distance between the circumference
offsets_x = np.random.randint(0, 25, size=numpairs)
offsets_y = np.random.randint(-0.8*20, 30, size=numpairs)
# Symmetric chairs
offsetted_circlecenter = table_tl[0]+radius
for j in range(numpairs): # number of pairs
if j == 0:
offsetted_circlecenter += offsets_x[j]
else:
offsetted_circlecenter += 2*radius + dist_chairs + offsets_x[j]
cv2.circle(Scene, (offsetted_circlecenter, table_tl[1]-radius-dist_chairs-offsets_y[j]), radius, (0, 0, 255), cv2.FILLED)
cv2.circle(Scene, (offsetted_circlecenter, table_br[1]+radius+dist_chairs+offsets_y[j]), radius, (0, 0, 255), cv2.FILLED)
return Scene
def tablechair_symx_rot():
"""Arrangement of 1 table and 4 chairs that is symmetric across the x axis"""
Scene = np.ones((HEIGHT, WIDTH, 3), np.uint8) * 255
# Table
table_tl= (300,430)
table_br = (700,570)
table_tr = (table_br[0], table_tl[1])
table_bl = (table_tl[0], table_br[1])
radius = 50
numpairs = 3
dist_chairs = 20 # distance between the circumference
offsets_x = np.random.randint(0, 25, size=numpairs)
offsets_y = np.random.randint(-0.6*20, 30, size=numpairs)
degree = np.random.randint(0, 180)
# print("# degree =", degree)
pts = np.array([[rot_degree(degree, table_tl[0], table_tl[1]), rot_degree(degree, table_tr[0], table_tr[1]), \
rot_degree(degree, table_br[0], table_br[1]), rot_degree(degree, table_bl[0], table_bl[1])]])
cv2.fillPoly(Scene, pts, (0, 255, 0))
offsetted_circlecenter = table_tl[0]+radius
for j in range(numpairs): # number of pairs
if j == 0:
offsetted_circlecenter += offsets_x[j]
else:
offsetted_circlecenter += 2*radius + dist_chairs + offsets_x[j]
cv2.circle(Scene, tuple(rot_degree(degree, offsetted_circlecenter, table_tl[1]-radius-dist_chairs-offsets_y[j])),
radius, (0, 0, 255), cv2.FILLED)
cv2.circle(Scene, tuple(rot_degree(degree, offsetted_circlecenter, table_br[1]+radius+dist_chairs+offsets_y[j])),
radius, (0, 0, 255), cv2.FILLED)
return Scene
def rot_degree(degree, x, y, origin=[WIDTH/2, HEIGHT/2]):
"""Rotate x and y by degree in counterclockwise direction with center of rotation being origin. Returns numpy array."""
# print(x, y)
theta = np.radians(degree)
R = np.array(( (np.cos(theta), -np.sin(theta)), (np.sin(theta), np.cos(theta)) ))
rot_xy = np.dot(R,np.array((x-origin[0],y-origin[1])))
rot_xy = [int(rot_xy[0].item()+origin[0]), int(rot_xy[1].item()+origin[1])]
return rot_xy
def gen_data_sample():
Scene, centers = gen_tablechair()
show_image(Scene)
def show_image(Scene):
cv2.namedWindow('Scene')
while True:
cv2.imshow('Scene', Scene)
Key = cv2.waitKey(-1)
if Key == ord('s'):
cv2.imwrite('scene.png', Scene)
if Key == 27:
break
def chairoffset_2_center(table_center, table_w, table_h, offsets_x, offsets_y, radius, mindist):
"""Returns (numObj x 2) array describing x and y coordinates of objects topleft -> bottomright in row by row order"""
numPairs = offsets_x.shape[0]-1 # assume even for now
centers = np.zeros((2*numPairs, 2))
table_top, table_bottom = table_center[1]-table_h/2, table_center[1]+table_h/2
centers[0] = [table_center[0]-table_w/2+radius+offsets_x[0], table_top-radius-mindist-offsets_y[0]] # row 1
centers[numPairs] = [centers[0,0], table_bottom+radius+mindist+offsets_y[0]] # row 2
for pair_i in range(1, numPairs):
centers[pair_i] = [(centers[pair_i-1, 0]+2*radius+mindist+offsets_x[pair_i]), (table_top-radius-mindist-offsets_y[pair_i])]
centers[pair_i+numPairs] = [centers[pair_i, 0], table_bottom+radius+mindist+offsets_y[pair_i]]
return centers
def tablecenter_2_pt(center, table_w, table_h):
table_pts = np.array([[center[0]-table_w/2, center[1]-table_h/2],
[center[0]+table_w/2, center[1]-table_h/2], \
[center[0]+table_w/2, center[1]+table_h/2],
[center[0]-table_w/2, center[1]+table_h/2]], dtype=np.int32)
return table_pts
def build_rot_scene(unrotcenters, table_w, table_h, radius, degree):
"""Given unrotated centers, build rotated cv2 scene return rotated copy of the centers"""
Scene = np.ones((HEIGHT, WIDTH, 3), np.uint8) * 255
table_pts = tablecenter_2_pt(unrotcenters[0, :], table_w, table_h)
table_pts = np.array([rot_degree(degree, p[0], p[1]) for p in table_pts], dtype=np.int32)
cv2.fillPoly(Scene, [table_pts], (0, 255, 0))
rotcenters = np.zeros(unrotcenters.shape,dtype=np.int32)
rotcenters[0] = unrotcenters[0]
for i in range(1, unrotcenters.shape[0]):
rotcenters[i] = rot_degree(degree, unrotcenters[i, 0], unrotcenters[i, 1])
cv2.circle(Scene, tuple(rotcenters[i]), radius, (0, 0, 255), cv2.FILLED)
if degree==0:
degposes=np.zeros((rotcenters.shape[0], 1)) -1
degposes[0, 0] = 0
else:
degposes=np.zeros((rotcenters.shape[0], 1))+degree
rotcenters_degrees = np.concatenate((rotcenters, degposes), axis=1)
return Scene, rotcenters_degrees
def gen_tablechair(numpairs=None, radius=None, rot=False, to_perturb=True):
"""Arrangement of 1 table and 4 chairs that is symmetric across the x axis"""
radius = radius if radius else random.randint(30,50)
table_w = random.randint(400, numpairs*radius*2/0.4) if numpairs else random.randint(400, 800)
table_h = 140
table_center = [[int(WIDTH/2), int(HEIGHT/2)]] # 1x2 (center of rotation)
mindist_chairs = 20 # distance between the circumference
maxnumpairs = math.floor((table_w + mindist_chairs)/(2*radius + mindist_chairs))
minnumpairs = math.ceil(table_w/(radius*2) *0.4) # same 0.4 as table_w above
numpairs = numpairs if numpairs else random.randint(minnumpairs,maxnumpairs)
degree = np.random.randint(0, 180) if rot else 0
offsets_x = np.random.random(size=numpairs+1)
offsets_x_exp = [math.exp(e) for e in offsets_x]
offsets_x = np.array([e/sum(offsets_x_exp) for e in offsets_x_exp])* (table_w - numpairs*2*radius - (numpairs-1)*mindist_chairs) # softmax
offsets_y = np.random.randint(-0.5*mindist_chairs, 0.5*mindist_chairs, size=numpairs)
chair_centers = chairoffset_2_center(table_center[0], table_w, table_h, offsets_x, offsets_y, radius, mindist_chairs) # list
unrotcenters = np.concatenate((np.array(table_center), np.array(chair_centers)), axis=0) # nx2
if to_perturb:
per_unrotcenters = perturb(np.copy(unrotcenters), table_w, table_h, radius, degree)
Scene, rotcenters_degrees = build_rot_scene(unrotcenters, table_w, table_h, radius, degree)
per_Scene, per_rotcenters_degrees = build_rot_scene(per_unrotcenters, table_w, table_h, radius, degree)
shapes = np.repeat([[2,radius,radius]], (numpairs*2+1), axis=0)
shapes[0] = [1, table_w, table_h]
return Scene, rotcenters_degrees, per_Scene, per_rotcenters_degrees, shapes
def perturb(unrotcenters, table_w, table_h, radius, degree=0):
"""Given unortated center (np array), return unrotated perturbed centers"""
# translation perturbation (applied to center of table and whole scene)
unrotcenters += np.random.normal(0,30,2)
random_indices = list(range(1, unrotcenters.shape[0]-1))
random.shuffle(random_indices) # in-place
for chair_i in random_indices:
new_chair_cen = unrotcenters[chair_i] + np.random.normal(0,30,2)
while (not is_valid(unrotcenters, chair_i, new_chair_cen, radius, table_w, table_h)):
new_chair_cen = unrotcenters[chair_i] + np.random.normal(0,30,2)
unrotcenters[chair_i] = new_chair_cen
return unrotcenters
def is_valid(centers, chair_i, new_chair_cen, radius, table_w, table_h):
"""checks if new_chair_cen for the ith chair is valid: no overlap with any other object"""
# check against table
if (abs(centers[0,0]-new_chair_cen[0])<radius+table_w/2) and (abs(centers[0,1]-new_chair_cen[1])<radius+table_h/2):
return False
# check against other chairs
for i in range(1, centers.shape[0]):
if i==chair_i:
continue
if np.linalg.norm(new_chair_cen-centers[i]) < 2*radius: # euclidean distance
return False
return True
def gen_data(numinstances=10, numpairs=3, radius=50, rot=False, show=False, dir="./2dsimulator_data", save=True, start_idx=0):
"""Generate n data samples:
1. per_poses, per_shape: n x dim numpy array, where ith row describes pose/shape of the ith perturbed scene. (1st row=table)
2. clean_poses, clean_shape: n x dim numpy array, where ith row describes pose/shape of the ith clean scene (corresponds to ith perturbed scene)
3. Images of clean and pertubed scene for reference
"""
pose_d = 3 # center, rotation
shape_d = 3
# Table: center, rotation, | type=1, width (fixed), height (fixed)
# Chair: center, -1 (rotation) | type=2, radius (fixed), radius (fixed)
clean_poses, per_poses =
|
np.zeros((numinstances,pose_d*(numpairs*2+1)))
|
numpy.zeros
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : <NAME>
# @Date : 2020-12-14
# @Contact : <EMAIL>
import numpy as np
import multiprocessing as mp
def check_n_jobs(n_jobs):
cpu_count = mp.cpu_count()
if n_jobs == 0:
return 1
elif n_jobs > 0:
return min(cpu_count, n_jobs)
else:
return max(1, cpu_count + 1 + n_jobs)
def pairwise_distance(X, Y):
A, M = X.shape
B, _ = Y.shape
matrix1 = X.reshape([A, 1, M])
matrix1 = np.repeat(matrix1, B, axis=1)
matrix2 = Y.reshape([1, B, M])
matrix2 = np.repeat(matrix2, A, axis=0)
distance_sqr =
|
np.sum((matrix1 - matrix2) ** 2, axis=-1)
|
numpy.sum
|
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import pickle
import glob
def get_camera_param():
# read in and make a list of calibration images
cameraParam = np.load("../param/camera_param.npy", allow_pickle=True)[()]
mtxParam = cameraParam["mtx"]
distParam = cameraParam["dist"]
return mtxParam, distParam
def get_transform_param():
# read in and make a list of calibration images
cameraParam = np.load("../param/transform_param.npy", allow_pickle=True)[()]
MParam = cameraParam["M"]
MinvParam = cameraParam["Minv"]
return MParam, MinvParam
def undistort_image(img, mtx, dist):
return cv2.undistort(img, mtx, dist, None, mtx)
def abs_sobel_thresh(img, orient='x', sobel_kernel=3, thresh=(0, 255)):
# Apply the following steps to img
# 1) Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# 2) Take the derivative in x or y given orient = 'x' or 'y'
# 3) Take the absolute value of the derivative or gradient
if orient == 'x':
abs_sobel = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel))
if orient == 'y':
abs_sobel = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel))
# 4) Scale to 8-bit (0 - 255) then convert to type = np.uint8
scaled_sobel = np.uint8(255 * abs_sobel / np.max(abs_sobel))
# 5) Create a mask of 1's where the scaled gradient magnitude
# is > thresh_min and < thresh_max
# 6) Return this mask as your binary_output image
binary_output = np.zeros_like(scaled_sobel)
# Here I'm using inclusive (>=, <=) thresholds, but exclusive is ok too
binary_output[(scaled_sobel >= thresh[0]) & (scaled_sobel <= thresh[1])] = 1
return binary_output
def mag_thresh(img, sobel_kernel=3, mag_thresh=(0, 255)):
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Take both Sobel x and y gradients
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)
# Calculate the gradient magnitude
gradmag = np.sqrt(sobelx ** 2 + sobely ** 2)
# Rescale to 8 bit
scale_factor = np.max(gradmag) / 255
gradmag = (gradmag / scale_factor).astype(np.uint8)
# Create a binary image of ones where threshold is met, zeros otherwise
binary_output = np.zeros_like(gradmag)
binary_output[(gradmag >= mag_thresh[0]) & (gradmag <= mag_thresh[1])] = 1
# Return the binary image
return binary_output
def dir_threshold(img, sobel_kernel=3, thresh=(0, np.pi / 2)):
# Grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Calculate the x and y gradients
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)
# Take the absolute value of the gradient direction,
# apply a threshold, and create a binary image result
absgraddir = np.arctan2(np.absolute(sobely), np.absolute(sobelx))
binary_output = np.zeros_like(absgraddir)
binary_output[(absgraddir >= thresh[0]) & (absgraddir <= thresh[1])] = 1
# Return the binary image
return binary_output
def hls_select(img, thresh_s=(0, 255), thresh_l=(0, 255)):
# 1) Convert to HLS color space
hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)
# 2) Apply a threshold to the S channel
s_channel = hls[:, :, 2]
l_channel = hls[:, :, 1]
binary_output_s = np.zeros_like(s_channel)
binary_output_s[(s_channel > thresh_s[0]) & (s_channel <= thresh_s[1])] = 1
binary_output_l = np.zeros_like(l_channel)
binary_output_l[(l_channel > thresh_l[0]) & (l_channel <= thresh_l[1])] = 1
# 3) Return a binary image of threshold result
binary_output = cv2.bitwise_and(binary_output_l, binary_output_s)
return binary_output
def roi(img, vertices):
# Next we'll create a masked edges image using cv2.fillPoly()
mask = np.zeros_like(img)
ignore_mask_color = 1
cv2.fillPoly(mask, vertices, ignore_mask_color)
masked_img = cv2.bitwise_and(img, mask)
return masked_img
def find_lane_pixels(binary_warped):
# Take a histogram of the bottom half of the image
histogram = np.sum(binary_warped[binary_warped.shape[0] // 2:, :], axis=0)
# Create an output image to draw on and visualize the result
out_img = np.dstack((binary_warped, binary_warped, binary_warped))
# Find the peak of the left and right halves of the histogram
# These will be the starting point for the left and right lines
midpoint = np.int(histogram.shape[0] // 2)
leftx_base = np.argmax(histogram[:midpoint])
rightx_base = np.argmax(histogram[midpoint:]) + midpoint
# HYPERPARAMETERS
# Choose the number of sliding windows
nwindows = 9
# Set the width of the windows +/- margin
margin = 100
# Set minimum number of pixels found to recenter window
minpix = 50
# Set height of windows - based on nwindows above and image shape
window_height = np.int(binary_warped.shape[0] // nwindows)
# Identify the x and y positions of all nonzero pixels in the image
nonzero = binary_warped.nonzero()
nonzeroy = np.array(nonzero[0])
nonzerox = np.array(nonzero[1])
# Current positions to be updated later for each window in nwindows
leftx_current = leftx_base
rightx_current = rightx_base
# Create empty lists to receive left and right lane pixel indices
left_lane_inds = []
right_lane_inds = []
# Step through the windows one by one
for window in range(nwindows):
# Identify window boundaries in x and y (and right and left)
win_y_low = binary_warped.shape[0] - (window + 1) * window_height
win_y_high = binary_warped.shape[0] - window * window_height
### TO-DO: Find the four below boundaries of the window ###
win_xleft_low = leftx_current - margin
win_xleft_high = leftx_current + margin
win_xright_low = rightx_current - margin
win_xright_high = rightx_current + margin
# Draw the windows on the visualization image
cv2.rectangle(out_img, (win_xleft_low, win_y_low),
(win_xleft_high, win_y_high), (0, 255, 0), 2)
cv2.rectangle(out_img, (win_xright_low, win_y_low),
(win_xright_high, win_y_high), (0, 255, 0), 2)
### TO-DO: Identify the nonzero pixels in x and y within the window ###
good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &
(nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0]
good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &
(nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0]
# Append these indices to the lists
left_lane_inds.append(good_left_inds)
right_lane_inds.append(good_right_inds)
### TO-DO: If you found > minpix pixels, recenter next window ###
### (`right` or `leftx_current`) on their mean position ###
if len(good_left_inds) > minpix:
leftx_current = np.int(
|
np.mean(nonzerox[good_left_inds])
|
numpy.mean
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module provides tools to extract cutouts of stars and data
structures to hold the cutouts for fitting and building ePSFs.
"""
import warnings
from astropy.nddata import NDData
from astropy.nddata.utils import (overlap_slices, NoOverlapError,
PartialOverlapError)
from astropy.table import Table
from astropy.utils import lazyproperty
from astropy.utils.exceptions import AstropyUserWarning
import numpy as np
from ..aperture import BoundingBox
__all__ = ['EPSFStar', 'EPSFStars', 'LinkedEPSFStar', 'extract_stars']
class EPSFStar:
"""
A class to hold a 2D cutout image and associated metadata of a star
used to build an ePSF.
Parameters
----------
data : `~numpy.ndarray`
A 2D cutout image of a single star.
weights : `~numpy.ndarray` or `None`, optional
A 2D array of the weights associated with the input ``data``.
cutout_center : tuple of two floats or `None`, optional
The ``(x, y)`` position of the star's center with respect to the
input cutout ``data`` array. If `None`, then the center of of
the input cutout ``data`` array will be used.
origin : tuple of two int, optional
The ``(x, y)`` index of the origin (bottom-left corner) pixel of
the input cutout array with respect to the original array from
which the cutout was extracted. This can be used to convert
positions within the cutout image to positions in the original
image. ``origin`` and ``wcs_large`` must both be input for a
linked star (a single star extracted from different images).
wcs_large : `None` or WCS object, optional
A WCS object associated with the large image from which
the cutout array was extracted. It should not be the
WCS object of the input cutout ``data`` array. The WCS
object must support the `astropy shared interface for WCS
<https://docs.astropy.org/en/stable/wcs/wcsapi.html>`_ (e.g.,
`astropy.wcs.WCS`, `gwcs.wcs.WCS`). ``origin`` and ``wcs_large``
must both be input for a linked star (a single star extracted
from different images).
id_label : int, str, or `None`, optional
An optional identification number or label for the star.
"""
def __init__(self, data, weights=None, cutout_center=None, origin=(0, 0),
wcs_large=None, id_label=None):
self._data = np.asanyarray(data)
self.shape = self._data.shape
if weights is not None:
if weights.shape != data.shape:
raise ValueError('weights must have the same shape as the '
'input data array.')
self.weights = np.asanyarray(weights, dtype=float).copy()
else:
self.weights = np.ones_like(self._data, dtype=float)
self.mask = (self.weights <= 0.)
# mask out invalid image data
invalid_data = np.logical_not(np.isfinite(self._data))
if np.any(invalid_data):
self.weights[invalid_data] = 0.
self.mask[invalid_data] = True
self._cutout_center = cutout_center
self.origin = np.asarray(origin)
self.wcs_large = wcs_large
self.id_label = id_label
self.flux = self.estimate_flux()
self._excluded_from_fit = False
self._fitinfo = None
def __array__(self):
"""
Array representation of the mask data array (e.g., for
matplotlib).
"""
return self._data
@property
def data(self):
"""The 2D cutout image."""
return self._data
@property
def cutout_center(self):
"""
A `~numpy.ndarray` of the ``(x, y)`` position of the star's
center with respect to the input cutout ``data`` array.
"""
return self._cutout_center
@cutout_center.setter
def cutout_center(self, value):
if value is None:
value = ((self.shape[1] - 1) / 2., (self.shape[0] - 1) / 2.)
else:
if len(value) != 2:
raise ValueError('The "cutout_center" attribute must have '
'two elements in (x, y) form.')
self._cutout_center = np.asarray(value)
@property
def center(self):
"""
A `~numpy.ndarray` of the ``(x, y)`` position of the star's
center in the original (large) image (not the cutout image).
"""
return self.cutout_center + self.origin
@lazyproperty
def slices(self):
"""
A tuple of two slices representing the cutout region with
respect to the original (large) image.
"""
return (slice(self.origin[1], self.origin[1] + self.shape[1]),
slice(self.origin[0], self.origin[0] + self.shape[0]))
@lazyproperty
def bbox(self):
"""
The minimal `~photutils.aperture.BoundingBox` for the cutout
region with respect to the original (large) image.
"""
return BoundingBox(self.slices[1].start, self.slices[1].stop,
self.slices[0].start, self.slices[0].stop)
def estimate_flux(self):
"""
Estimate the star's flux by summing values in the input cutout
array.
Missing data is filled in by interpolation to better estimate
the total flux.
"""
from .epsf import _interpolate_missing_data
if np.any(self.mask):
data_interp = _interpolate_missing_data(self.data, method='cubic',
mask=self.mask)
data_interp = _interpolate_missing_data(data_interp,
method='nearest',
mask=self.mask)
flux = np.sum(data_interp, dtype=float)
else:
flux = np.sum(self.data, dtype=float)
return flux
def register_epsf(self, epsf):
"""
Register and scale (in flux) the input ``epsf`` to the star.
Parameters
----------
epsf : `EPSFModel`
The ePSF to register.
Returns
-------
data : `~numpy.ndarray`
A 2D array of the registered/scaled ePSF.
"""
yy, xx = np.indices(self.shape, dtype=float)
xx = xx - self.cutout_center[0]
yy = yy - self.cutout_center[1]
return self.flux * epsf.evaluate(xx, yy, flux=1.0, x_0=0.0, y_0=0.0)
def compute_residual_image(self, epsf):
"""
Compute the residual image of the star data minus the
registered/scaled ePSF.
Parameters
----------
epsf : `EPSFModel`
The ePSF to subtract.
Returns
-------
data : `~numpy.ndarray`
A 2D array of the residual image.
"""
return self.data - self.register_epsf(epsf)
@lazyproperty
def _xy_idx(self):
"""
1D arrays of x and y indices of unmasked pixels in the cutout
reference frame.
"""
yidx, xidx = np.indices(self._data.shape)
return xidx[~self.mask].ravel(), yidx[~self.mask].ravel()
@lazyproperty
def _xidx(self):
"""
1D arrays of x indices of unmasked pixels in the cutout
reference frame.
"""
return self._xy_idx[0]
@lazyproperty
def _yidx(self):
"""
1D arrays of y indices of unmasked pixels in the cutout
reference frame.
"""
return self._xy_idx[1]
@property
def _xidx_centered(self):
"""
1D array of x indices of unmasked pixels, with respect to the
star center, in the cutout reference frame.
"""
return self._xy_idx[0] - self.cutout_center[0]
@property
def _yidx_centered(self):
"""
1D array of y indices of unmasked pixels, with respect to the
star center, in the cutout reference frame.
"""
return self._xy_idx[1] - self.cutout_center[1]
@lazyproperty
def _data_values(self):
"""1D array of unmasked cutout data values."""
return self.data[~self.mask].ravel()
@lazyproperty
def _data_values_normalized(self):
"""
1D array of unmasked cutout data values, normalized by the
star's total flux.
"""
return self._data_values / self.flux
@lazyproperty
def _weight_values(self):
"""
1D array of unmasked weight values.
"""
return self.weights[~self.mask].ravel()
class EPSFStars:
"""
Class to hold a list of `EPSFStar` and/or `LinkedEPSFStar` objects.
Parameters
----------
star_list : list of `EPSFStar` or `LinkedEPSFStar` objects
A list of `EPSFStar` and/or `LinkedEPSFStar` objects.
"""
def __init__(self, stars_list):
if isinstance(stars_list, (EPSFStar, LinkedEPSFStar)):
self._data = [stars_list]
elif isinstance(stars_list, list):
self._data = stars_list
else:
raise ValueError('stars_list must be a list of EPSFStar and/or '
'LinkedEPSFStar objects.')
def __len__(self):
return len(self._data)
def __getitem__(self, index):
return self.__class__(self._data[index])
def __delitem__(self, index):
del self._data[index]
def __iter__(self):
for i in self._data:
yield i
# explicit set/getstate to avoid infinite recursion
# from pickler using __getattr__
def __getstate__(self):
return self.__dict__
def __setstate__(self, d):
self.__dict__ = d
def __getattr__(self, attr):
if attr in ['cutout_center', 'center', 'flux',
'_excluded_from_fit']:
result = np.array([getattr(star, attr) for star in self._data])
else:
result = [getattr(star, attr) for star in self._data]
if len(self._data) == 1:
result = result[0]
return result
def _getattr_flat(self, attr):
values = []
for item in self._data:
if isinstance(item, LinkedEPSFStar):
values.extend(getattr(item, attr))
else:
values.append(getattr(item, attr))
return np.array(values)
@property
def cutout_center_flat(self):
"""
A `~numpy.ndarray` of the ``(x, y)`` position of all the
stars' centers (including linked stars) with respect to the
input cutout ``data`` array, as a 2D array (``n_all_stars`` x
2).
Note that when `EPSFStars` contains any `LinkedEPSFStar`, the
``cutout_center`` attribute will be a nested 3D array.
"""
return self._getattr_flat('cutout_center')
@property
def center_flat(self):
"""
A `~numpy.ndarray` of the ``(x, y)`` position of all the stars'
centers (including linked stars) with respect to the original
(large) image (not the cutout image) as a 2D array
(``n_all_stars`` x 2).
Note that when `EPSFStars` contains any `LinkedEPSFStar`, the
``center`` attribute will be a nested 3D array.
"""
return self._getattr_flat('center')
@lazyproperty
def all_stars(self):
"""
A list of all `EPSFStar` objects stored in this object,
including those that comprise linked stars (i.e.,
`LinkedEPSFStar`), as a flat list.
"""
stars = []
for item in self._data:
if isinstance(item, LinkedEPSFStar):
stars.extend(item.all_stars)
else:
stars.append(item)
return stars
@property
def all_good_stars(self):
"""
A list of all `EPSFStar` objects stored in this object that have
not been excluded from fitting, including those that comprise
linked stars (i.e., `LinkedEPSFStar`), as a flat list.
"""
stars = []
for star in self.all_stars:
if star._excluded_from_fit:
continue
else:
stars.append(star)
return stars
@lazyproperty
def n_stars(self):
"""
The total number of stars.
A linked star is counted only once.
"""
return len(self._data)
@lazyproperty
def n_all_stars(self):
"""
The total number of `EPSFStar` objects, including all the linked
stars within `LinkedEPSFStar`. Each linked star is included in
the count.
"""
return len(self.all_stars)
@property
def n_good_stars(self):
"""
The total number of `EPSFStar` objects, including all the linked
stars within `LinkedEPSFStar`, that have not been excluded from
fitting. Each non-excluded linked star is included in the
count.
"""
return len(self.all_good_stars)
@lazyproperty
def _max_shape(self):
"""
The maximum x and y shapes of all the `EPSFStar` objects
(including linked stars).
"""
return np.max([star.shape for star in self.all_stars],
axis=0)
class LinkedEPSFStar(EPSFStars):
"""
A class to hold a list of `EPSFStar` objects for linked stars.
Linked stars are `EPSFStar` cutouts from different images that
represent the same physical star. When building the ePSF, linked
stars are constrained to have the same sky coordinates.
Parameters
----------
star_list : list of `EPSFStar` objects
A list of `EPSFStar` objects for the same physical star. Each
`EPSFStar` object must have a valid ``wcs_large`` attribute to
convert between pixel and sky coordinates.
"""
def __init__(self, stars_list):
for star in stars_list:
if not isinstance(star, EPSFStar):
raise ValueError('stars_list must contain only EPSFStar '
'objects.')
if star.wcs_large is None:
raise ValueError('Each EPSFStar object must have a valid '
'wcs_large attribute.')
super().__init__(stars_list)
def constrain_centers(self):
"""
Constrain the centers of linked `EPSFStar` objects (i.e., the
same physical star) to have the same sky coordinate.
Only `EPSFStar` objects that have not been excluded during the
ePSF build process will be used to constrain the centers.
The single sky coordinate is calculated as the mean of sky
coordinates of the linked stars.
"""
if len(self._data) < 2: # no linked stars
return
idx =
|
np.logical_not(self._excluded_from_fit)
|
numpy.logical_not
|
DATASET_DIR = '/home/ds/Projects/SARA/datasets/fields_segmentation'
SRC_IMAGES_PREFIX = '/home/ds/Projects/SARA/data/generated_images/document_crops_rotated/'
DST_IMAGES_PREFIX = '/home/ds/Projects/SARA/data/generated_images/fields_segm_resize_640_v1/'
SRC_MASKS_PREFIX = '/home/ds/Projects/SARA/annotations/fields_segmentation/'
DST_MASKS_PREFIX = '/home/ds/Projects/SARA/data/generated_images/fields_segm_resize_640_v1_masks/'
import pandas as pd
from torch.utils.data import DataLoader
import os
import torch
from torchvision.transforms import ToTensor
import cv2
import numpy as np
import json
import albumentations as alb
from fline.pipelines.base_pipeline import BasePipeline
from fline.utils.logging.trains import TrainsLogger
from fline.utils.saver import Saver, MetricStrategies
from fline.utils.data.dataset import BaseDataset
from fline.utils.wrappers import ModelWrapper, DataWrapper
from fline.utils.logging.base import EnumLogDataTypes
from fline.utils.logging.groups import ProcessImage
from fline.models.models.research.history.object_detection_model import (
ObjectDetectionSMP,
ObjectDetectionSMPV2,
)
from sklearn.model_selection import train_test_split
from torch.utils.data._utils.collate import default_collate
from fline.losses.segmentation.dice import BCEDiceLoss
from fline.utils.data.image.io import imread_padding
os.environ['TORCH_HOME'] = '/home/ds'
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
os.environ['NO_PROXY'] = 'koala03.ftc.ru'
os.environ['no_proxy'] = 'koala03.ftc.ru'
#SHAPE = (256, 256)
PROECT_NAME = '[RESEARCH]ObjectDetection'
TASK_NAME = 'test_corner_net'
SEG_MODEL = 'seg_model'
MASK = 'mask'
BBOX = 'bbox'
IMAGE = 'IMAGE'
CONNECTIONS = 'connections'
CORNERS = 'CORNERS'
DEVICE = 'cuda:1'
df = pd.read_csv(os.path.join(DATASET_DIR, 'dataset_v93.csv'))
df[IMAGE] = df['image'].str.replace(SRC_IMAGES_PREFIX, DST_IMAGES_PREFIX)
df[MASK] = df['annotation'].str.replace(SRC_MASKS_PREFIX, DST_MASKS_PREFIX) + '.png'
df['original_image'] = df['image'].str.split('/').str[-3]
#df = df.iloc[500:700]
def add_classes(df):
cdf = pd.read_csv('/home/ds/Projects/SARA/datasets/classification/dataset_v75.csv')
def extract_class(annot_path):
with open(annot_path) as f:
annot = json.loads(f.read())
document_types = annot['file_attributes']['document_type']
if len(document_types.keys()) == 1:
return list(document_types.keys())[0]
cdf['class'] = cdf['annotation'].apply(extract_class)
cdf['original_image'] = cdf['image'].str.split('/').str[-1]
cdf = cdf.dropna(subset=['class'])
del(cdf['annotation'])
df = pd.merge(
left=df,
right=cdf,
left_on='original_image',
right_on='original_image',
how='inner',
)
return df
df = add_classes(df)
df = df[~df['class'].str.contains('играц')]
df['valid_mask'] = df[MASK].apply(lambda x: cv2.imread(x) is not None)
df = df[df['valid_mask']]
train_df, val_df = train_test_split(df, test_size=0.25, random_state=42)
train_augs_geometric = alb.Compose([
# alb.ShiftScaleRotate(),
# alb.ElasticTransform(),
])
train_augs_values = alb.Compose([
alb.RandomBrightnessContrast(),
alb.RandomGamma(),
alb.RandomShadow(),
alb.Blur(),
])
def generate_get_bboxes(mode='train'):
def get_bboxes(row, res_dict):
im = imread_padding(row[IMAGE], 64, 0).astype('uint8')
mask = imread_padding(row[MASK], 64, 0).astype('uint8')
#im = cv2.imread(row[IMAGE]).astype('uint8')
#im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
#mask = cv2.imread(row[MASK]).astype('uint8')
#mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB)
mask = mask[:, :, 2]
SHAPE = im.shape
#print(np.unique(mask))
r_mask = np.zeros((*SHAPE, 50), dtype='int')
last_i = 0
bboxes = np.zeros((50, 4), dtype='float32')
is_one_field = np.zeros((50,), dtype='int')
bbox_corners = np.zeros((*SHAPE,))
bbox_corners_mask = np.zeros((*SHAPE, 3))
bbox_corners_labels = np.zeros((*SHAPE, 50))
#lt_corner = np.zeros((50,), dtype='int')
#rb_corner = np.zeros((50,), dtype='int')
for i, m in enumerate(np.unique(mask)):
if m != 0:
c_mask = (mask == m).astype('uint8')
c_mask = cv2.resize(
c_mask.astype('uint8'),
SHAPE,
interpolation=cv2.INTER_NEAREST,
).astype('uint8')
cntrs, _ = cv2.findContours(c_mask, 1, 2)
max_it = 0
for t, cnt in enumerate(cntrs):
x, y, w, h = cv2.boundingRect(cnt)
#print(x,y,w,h, y+h, x+w)
if w <= 1 and h <= 1:
w = w + 2
h = h + 2
if y+h >= SHAPE[1]:
y = SHAPE[1]-h-1
if x+w >= SHAPE[0]:
x = SHAPE[0]-w-1
if y-h <= 0:
y = 1
if x-w >= 0:
x = 1
if bbox_corners[y, x] == 1 or bbox_corners[y+h, x+w] == 2:
continue
if bbox_corners_mask[y, x, 1] == 1 or bbox_corners_mask[y+h, x+w, 2] == 1:
continue
bbox_corners[y, x] = 1
bbox_corners[y+h, x+w] = 2
bbox_corners_mask[y, x, 1] = 1
bbox_corners_mask[y+h, x+w, 2] = 1
#print(y,x, y+h, x+w, bbox_corners_mask[:, :, 1].sum(), bbox_corners_mask[:, :, 2].sum(), len(cntrs))
bbox_corners_labels[y, x, last_i + t] = 1
bbox_corners_labels[y+h, x+w, last_i + t] = 1
#lt_corner[last_i+t] = last_i+1
#rb_corner[last_i+t] = last_i+1
# buf = np.zeros(SHAPE)
# buf = cv2.drawContours(
# buf,
# [cnt], -1, 1, -1,
# )
# r_mask[:, :, last_i + t] = buf
x = (x + w/2) / c_mask.shape[1]
y = (y + h/2) / c_mask.shape[0]
w = w / c_mask.shape[1]
h = h / c_mask.shape[0]
bboxes[last_i+t] = (x, y, w, h)
max_it += 1
if len(cntrs) > 1:
is_one_field[last_i+t] = last_i+1
# conn_max, conn = cv2.connectedComponents(c_mask)
# for t in range(1, max_it):
# r_mask[:, :, last_i+t] = (conn == t)
# #print(last_i+t)
last_i += max_it
#print('last_i=', last_i)
#print('-'*60)
bboxes = bboxes[:last_i]
#bbox_corners = bbox_corners[:last_i]
#idx = np.arange(len(bboxes))
#np.random.shuffle(idx)
#bboxes = bboxes[idx]
#is_one_field = is_one_field[:last_i]
#is_one_field = is_one_field[idx]
#np.random.choice(bboxes, len(bboxes))
# idx = [i+1 for i in idx]
#idx.insert(0, 0)
#r_mask = r_mask[:, :, idx]
bbox_corners_labels = bbox_corners_labels[:,:,:last_i].argmax(axis=2)
lt_mask = bbox_corners_mask[:,:,1] == 1
rb_mask = bbox_corners_mask[:,:,2] == 1
#print(lt_mask.sum(), rb_mask.sum())
#print(bbox_corners.shape, lt_mask.shape, bbox_corners_labels.shape)
lt = bbox_corners_labels[lt_mask[:,:]]
rb = bbox_corners_labels[rb_mask[:,:]]
bbox_corners_links = np.zeros((1, len(lt), len(rb)), dtype='float32')
for i, p1 in enumerate(lt):
for j, p2 in enumerate(rb):
if p1 == p2:
#print(i,j)
bbox_corners_links[0, i, j] = 1
#r_mask = r_mask.argmax(axis=2)
# connections_mask = np.zeros((3, len(bboxes), len(bboxes)), dtype='float32')
# for i, box1 in enumerate(bboxes):
# dif_up_y_min = np.inf
# select_up = None
# dif_down_y_min = np.inf
# select_down = None
# for j, box2 in enumerate(bboxes):
# if i != j:
# #connections_mask[0, i, j] = box1[0] - box2[0] > 0.05
# #connections_mask[1, i, j] = box2[0] - box1[0] > 0.05
# #connections_mask[2, i, j] = box1[1] - box2[1] > 0.05
# #connections_mask[3, i, j] = box2[1] - box1[1] > 0.05
# cur_dif_down = box1[1] - box2[1]
# cur_dif_up = - cur_dif_down
# if cur_dif_down > 0.05 and cur_dif_down < dif_down_y_min:
# dif_down_y_min = cur_dif_down
# select_down = j
# if cur_dif_up > 0.05 and cur_dif_up < dif_up_y_min:
# dif_up_y_min = cur_dif_up
# select_up = j
# if select_up is not None:
# connections_mask[0, i, select_up] = 1
# if select_down is not None:
# connections_mask[1, i, select_down] = 1
#print(is_one_field)
#print(r_mask.max())
# for u in np.unique(is_one_field):
# if u != 0:
# cur_field_mask = (is_one_field == u)
# cur_indexes = np.where(cur_field_mask)[0]
# #print(cur_indexes)
# for i in cur_indexes:
# for j in cur_indexes:
# if i != j:
# connections_mask[2, i, j] = 1
#mask = r_mask
#a = len(np.unique(mask))
im = cv2.resize(im.astype('uint8'), SHAPE).astype('uint8')
#mask = cv2.resize(mask.astype('uint8'), SHAPE, interpolation=cv2.INTER_NEAREST).astype('uint8')
#print(a, len(np.unique(mask)))
bboxes = torch.tensor(bboxes, dtype=torch.float32)
im = im.astype('float32')
res_dict[IMAGE] = ToTensor()((im / 255).astype('float32'))
res_dict[BBOX] = bboxes
res_dict[CORNERS] = torch.tensor(bbox_corners)
res_dict[MASK] = ToTensor()(bbox_corners_mask)
#res_dict[MASK] = ToTensor()(mask.astype('float32'))
res_dict[CONNECTIONS] = torch.tensor(bbox_corners_links)
return res_dict
return get_bboxes
def generate_get_bboxes(mode='train'):
def get_bboxes(row, res_dict):
im = imread_padding(row[IMAGE], 64, 0).astype('uint8')
mask = imread_padding(row[MASK], 64, 0).astype('uint8')
#im = cv2.imread(row[IMAGE]).astype('uint8')
#im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
#mask = cv2.imread(row[MASK]).astype('uint8')
#mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB)
mask = mask[:, :, 2]
SHAPE = (im.shape[0], im.shape[1])
left_top_points = np.zeros((*SHAPE, 50))
right_bottom_points = np.zeros((*SHAPE, 50))
pairs_counter = 0
for i, m in enumerate(np.unique(mask)):
if m != 0:
c_mask = (mask == m).astype('uint8')
# c_mask = cv2.resize(
# c_mask.astype('uint8'),
# SHAPE,
# interpolation=cv2.INTER_NEAREST,
# ).astype('uint8')
cntrs, _ = cv2.findContours(c_mask, 1, 2)
for cnt in cntrs:
x, y, w, h = cv2.boundingRect(cnt)
left_top_points[y, x, pairs_counter] = 1
right_bottom_points[y+h-1, x+w-1, pairs_counter] = 1
pairs_counter += 1
left_top_points = left_top_points[:, :, :pairs_counter]
right_bottom_points = right_bottom_points[:, :, :pairs_counter]
idx = np.arange(pairs_counter)
np.random.shuffle(idx)
right_bottom_points = right_bottom_points[:, :, idx]
bbox_corners_links = np.zeros((1, pairs_counter, pairs_counter), dtype='float32')
for p in range(pairs_counter):
bbox_corners_links[0, p, idx[p]] = 1
left_top_mask =
|
np.max(left_top_points, axis=2)
|
numpy.max
|
"""
Utils for generative models adapted from https://github.com/DataResponsibly/DataSynthesizer
Copyright <2018> <dataresponsibly.<EMAIL>>
Licensed under MIT License
"""
from math import log, ceil
from numpy import array, exp, isinf, full_like
from numpy.random import choice, laplace
from string import ascii_lowercase
from itertools import combinations, product
from pandas import Series, DataFrame, merge
from sklearn.metrics import mutual_info_score, normalized_mutual_info_score
def mutual_information(labels_x: Series, labels_y: DataFrame):
"""Mutual information of distributions in format of Series or DataFrame.
Parameters
----------
labels_x : Series
labels_y : DataFrame
"""
if labels_y.shape[1] == 1:
labels_y = labels_y.iloc[:, 0]
else:
labels_y = labels_y.apply(lambda x: ' '.join(x.values), axis=1)
return mutual_info_score(labels_x, labels_y)
def pairwise_attributes_mutual_information(dataset):
"""Compute normalized mutual information for all pairwise attributes. Return a DataFrame."""
sorted_columns = sorted(dataset.columns)
mi_df = DataFrame(columns=sorted_columns, index=sorted_columns, dtype=float)
for row in mi_df.columns:
for col in mi_df.columns:
mi_df.loc[row, col] = normalized_mutual_info_score(dataset[row].astype(str),
dataset[col].astype(str),
average_method='arithmetic')
return mi_df
def normalize_given_distribution(frequencies):
distribution = array(frequencies, dtype=float)
distribution = distribution.clip(0) # replace negative values with 0
summation = distribution.sum()
if summation > 0:
if isinf(summation):
return normalize_given_distribution(isinf(distribution))
else:
return distribution / summation
else:
return full_like(distribution, 1 / distribution.size)
def infer_numerical_attributes_in_dataframe(dataframe):
describe = dataframe.describe()
# DataFrame.describe() usually returns 8 rows.
if describe.shape[0] == 8:
return set(describe.columns)
# DataFrame.describe() returns less than 8 rows when there is no numerical attribute.
else:
return set()
def display_bayesian_network(bn):
length = 0
for child, _ in bn:
if len(child) > length:
length = len(child)
print('Constructed Bayesian network:')
for child, parents in bn:
print(" {0:{width}} has parents {1}.".format(child, parents, width=length))
def generate_random_string(length):
return ''.join(choice(list(ascii_lowercase), size=length))
def bayes_worker(paras):
child, V, num_parents, split, dataset = paras
parents_pair_list = []
mutual_info_list = []
if split + num_parents - 1 < len(V):
for other_parents in combinations(V[split + 1:], num_parents - 1):
parents = list(other_parents)
parents.append(V[split])
parents_pair_list.append((child, parents))
mi = mutual_information(dataset[child], dataset[parents])
mutual_info_list.append(mi)
return parents_pair_list, mutual_info_list
def get_encoded_attribute_distribution(attributes, encoded_dataset):
data = encoded_dataset.copy().loc[:, attributes]
data['count'] = 1
stats = data.groupby(attributes).sum()
iterables = [range(int(encoded_dataset[attr].max()) + 1) for attr in attributes]
full_space = DataFrame(columns=attributes, data=list(product(*iterables)))
stats.reset_index(inplace=True)
stats = merge(full_space, stats, how='left')
stats.fillna(0, inplace=True)
return stats
def get_noisy_distribution_of_attributes(attributes, encoded_dataset, epsilon=0.1):
data = encoded_dataset.copy().loc[:, attributes]
data['count'] = 1
stats = data.groupby(attributes).sum()
iterables = [range(int(encoded_dataset[attr].max()) + 1) for attr in attributes]
full_space = DataFrame(columns=attributes, data=list(product(*iterables)))
stats.reset_index(inplace=True)
stats = merge(full_space, stats, how='left')
stats.fillna(0, inplace=True)
if epsilon:
k = len(attributes) - 1
num_tuples, num_attributes = encoded_dataset.shape
noise_para = laplace_noise_parameter(k, num_attributes, num_tuples, epsilon)
laplace_noises = laplace(0, scale=noise_para, size=stats.index.size)
stats['count'] += laplace_noises
stats.loc[stats['count'] < 0, 'count'] = 0
return stats
def laplace_noise_parameter(k, num_attributes, num_tuples, epsilon):
"""The noises injected into conditional distributions. PrivBayes Algorithm 1."""
return 2 * (num_attributes - k) / (num_tuples * epsilon)
def calculate_sensitivity(num_tuples, child, parents, attr_to_is_binary):
"""Sensitivity function for Bayesian network construction. PrivBayes Lemma 1.
Parameters
----------
num_tuples : int
Number of tuples in sensitive dataset.
Return
--------
int
Sensitivity value.
"""
if attr_to_is_binary[child] or (len(parents) == 1 and attr_to_is_binary[parents[0]]):
a = log(num_tuples) / num_tuples
b = (num_tuples - 1) / num_tuples
b_inv = num_tuples / (num_tuples - 1)
return a + b * log(b_inv)
else:
a = (2 / num_tuples) * log((num_tuples + 1) / 2)
b = (1 - 1 / num_tuples) * log(1 + 2 / (num_tuples - 1))
return a + b
def calculate_delta(num_attributes, sensitivity, epsilon):
"""Computing delta, which is a factor when applying differential privacy.
More info is in PrivBayes Section 4.2 "A First-Cut Solution".
Parameters
----------
num_attributes : int
Number of attributes in dataset.
sensitivity : float
Sensitivity of removing one tuple.
epsilon : float
Parameter of differential privacy.
"""
return (num_attributes - 1) * sensitivity / epsilon
def exponential_mechanism(epsilon, mutual_info_list, parents_pair_list, attr_to_is_binary, num_tuples, num_attributes):
"""Applied in Exponential Mechanism to sample outcomes."""
delta_array = []
for (child, parents) in parents_pair_list:
sensitivity = calculate_sensitivity(num_tuples, child, parents, attr_to_is_binary)
delta = calculate_delta(num_attributes, sensitivity, epsilon)
delta_array.append(delta)
mi_array = array(mutual_info_list) / (2 * array(delta_array))
mi_array =
|
exp(mi_array)
|
numpy.exp
|
import collections
import numpy as np
import time
import datetime
import os
import networkx as nx
import pytz
import cloudvolume
import pandas as pd
from multiwrapper import multiprocessing_utils as mu
from . import mincut
from google.api_core.retry import Retry, if_exception_type
from google.api_core.exceptions import Aborted, DeadlineExceeded, \
ServiceUnavailable
from google.auth import credentials
from google.cloud import bigtable
from google.cloud.bigtable.row_filters import TimestampRange, \
TimestampRangeFilter, ColumnRangeFilter, ValueRangeFilter, RowFilterChain, \
ColumnQualifierRegexFilter, RowFilterUnion, ConditionalRowFilter, \
PassAllFilter, BlockAllFilter, RowFilter
from google.cloud.bigtable.column_family import MaxVersionsGCRule
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Union
# global variables
HOME = os.path.expanduser("~")
N_DIGITS_UINT64 = len(str(np.iinfo(np.uint64).max))
LOCK_EXPIRED_TIME_DELTA = datetime.timedelta(minutes=2, seconds=00)
UTC = pytz.UTC
# Setting environment wide credential path
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = \
HOME + "/.cloudvolume/secrets/google-secret.json"
def compute_indices_pandas(data) -> pd.Series:
""" Computes indices of all unique entries
Make sure to remap your array to a dense range starting at zero
https://stackoverflow.com/questions/33281957/faster-alternative-to-numpy-where
:param data: np.ndarray
:return: pandas dataframe
"""
d = data.ravel()
f = lambda x: np.unravel_index(x.index, data.shape)
return pd.Series(d).groupby(d).apply(f)
def log_n(arr, n):
""" Computes log to base n
:param arr: array or float
:param n: int
base
:return: return log_n(arr)
"""
if n == 2:
return np.log2(arr)
elif n == 10:
return np.log10(arr)
else:
return np.log(arr) / np.log(n)
def pad_node_id(node_id: np.uint64) -> str:
""" Pad node id to 20 digits
:param node_id: int
:return: str
"""
return "%.20d" % node_id
def serialize_uint64(node_id: np.uint64) -> bytes:
""" Serializes an id to be ingested by a bigtable table row
:param node_id: int
:return: str
"""
return serialize_key(pad_node_id(node_id)) # type: ignore
def deserialize_uint64(node_id: bytes) -> np.uint64:
""" De-serializes a node id from a BigTable row
:param node_id: bytes
:return: np.uint64
"""
return np.uint64(node_id.decode()) # type: ignore
def serialize_key(key: str) -> bytes:
""" Serializes a key to be ingested by a bigtable table row
:param key: str
:return: bytes
"""
return key.encode("utf-8")
def deserialize_key(key: bytes) -> str:
""" Deserializes a row key
:param key: bytes
:return: str
"""
return key.decode()
def row_to_byte_dict(row: bigtable.row.Row, f_id: str = None, idx: int = None
) -> Dict[int, Dict]:
""" Reads row entries to a dictionary
:param row: row
:param f_id: str
:param idx: int
:return: dict
"""
row_dict = {}
for fam_id in row.cells.keys():
row_dict[fam_id] = {}
for row_k in row.cells[fam_id].keys():
if idx is None:
row_dict[fam_id][deserialize_key(row_k)] = \
[c.value for c in row.cells[fam_id][row_k]]
else:
row_dict[fam_id][deserialize_key(row_k)] = \
row.cells[fam_id][row_k][idx].value
if f_id is not None and f_id in row_dict:
return row_dict[f_id]
elif f_id is None:
return row_dict
else:
raise Exception("Family id not found")
def compute_bitmasks(n_layers: int, fan_out: int) -> Dict[int, int]:
"""
:param n_layers: int
:return: dict
layer -> bits for layer id
"""
bitmask_dict = {}
for i_layer in range(n_layers, 0, -1):
if i_layer == 1:
# Lock this layer to an 8 bit layout to maintain compatibility with
# the exported segmentation
# n_bits_for_layers = np.ceil(log_n(fan_out**(n_layers - 2), fan_out))
n_bits_for_layers = 8
else:
n_bits_for_layers = max(1,
np.ceil(log_n(fan_out**(n_layers - i_layer),
fan_out)))
# n_bits_for_layers = fan_out ** int(np.ceil(log_n(n_bits_for_layers, fan_out)))
n_bits_for_layers = int(n_bits_for_layers)
assert n_bits_for_layers <= 8
bitmask_dict[i_layer] = n_bits_for_layers
return bitmask_dict
class ChunkedGraph(object):
def __init__(self,
table_id: str,
instance_id: str = "pychunkedgraph",
project_id: str = "neuromancer-seung-import",
chunk_size: Tuple[int, int, int] = None,
fan_out: Optional[int] = None,
n_layers: Optional[int] = None,
credentials: Optional[credentials.Credentials] = None,
client: bigtable.Client = None,
cv_path: str = None,
is_new: bool = False) -> None:
if client is not None:
self._client = client
else:
self._client = bigtable.Client(project=project_id, admin=True,
credentials=credentials)
self._instance = self.client.instance(instance_id)
self._table_id = table_id
self._table = self.instance.table(self.table_id)
if is_new:
self.check_and_create_table()
self._n_layers = self.check_and_write_table_parameters("n_layers",
n_layers)
self._fan_out = self.check_and_write_table_parameters("fan_out",
fan_out)
self._cv_path = self.check_and_write_table_parameters("cv_path",
cv_path)
self._chunk_size = self.check_and_write_table_parameters("chunk_size",
chunk_size)
self._bitmasks = compute_bitmasks(self.n_layers, self.fan_out)
self._cv = None
# Hardcoded parameters
self._n_bits_for_layer_id = 8
self._cv_mip = 3
@property
def client(self) -> bigtable.Client:
return self._client
@property
def instance(self) -> bigtable.instance.Instance:
return self._instance
@property
def table(self) -> bigtable.table.Table:
return self._table
@property
def table_id(self) -> str:
return self._table_id
@property
def instance_id(self):
return self.instance.instance_id
@property
def project_id(self):
return self.client.project
@property
def family_id(self) -> str:
return "0"
@property
def incrementer_family_id(self) -> str:
return "1"
@property
def log_family_id(self) -> str:
return "2"
@property
def cross_edge_family_id(self) -> str:
return "3"
@property
def fan_out(self) -> int:
return self._fan_out
@property
def chunk_size(self) -> np.ndarray:
return self._chunk_size
@property
def n_layers(self) -> int:
return self._n_layers
@property
def bitmasks(self) -> Dict[int, int]:
return self._bitmasks
@property
def cv_path(self) -> str:
return self._cv_path
@property
def cv_mip(self) -> int:
return self._cv_mip
@property
def cv(self) -> cloudvolume.CloudVolume:
if self._cv is None:
self._cv = cloudvolume.CloudVolume(self.cv_path, mip=self._cv_mip)
return self._cv
@property
def root_chunk_id(self):
return self.get_chunk_id(layer=int(self.n_layers), x=0, y=0, z=0)
def check_and_create_table(self) -> None:
""" Checks if table exists and creates new one if necessary """
table_ids = [t.table_id for t in self.instance.list_tables()]
if not self.table_id in table_ids:
self.table.create()
f = self.table.column_family(self.family_id)
f.create()
f_inc = self.table.column_family(self.incrementer_family_id,
gc_rule=MaxVersionsGCRule(1))
f_inc.create()
f_log = self.table.column_family(self.log_family_id)
f_log.create()
f_ce = self.table.column_family(self.cross_edge_family_id,
gc_rule=MaxVersionsGCRule(1))
f_ce.create()
print("Table created")
def check_and_write_table_parameters(self, param_key: str,
value: Optional[np.uint64] = None
) -> np.uint64:
""" Checks if a parameter already exists in the table. If it already
exists it returns the stored value, else it stores the given value. It
raises an exception if no value is passed and the parameter does not
exist, yet.
:param param_key: str
:param value: np.uint64
:return: np.uint64
value
"""
ser_param_key = serialize_key(param_key)
row = self.table.read_row(serialize_key("params"))
if row is None or ser_param_key not in row.cells[self.family_id]:
assert value is not None
if param_key in ["fan_out", "n_layers"]:
val_dict = {param_key: np.array(value,
dtype=np.uint64).tobytes()}
elif param_key in ["cv_path"]:
val_dict = {param_key: serialize_key(value)}
elif param_key in ["chunk_size"]:
val_dict = {param_key: np.array(value,
dtype=np.uint64).tobytes()}
else:
raise Exception("Unknown type for parameter")
row = self.mutate_row(serialize_key("params"), self.family_id,
val_dict)
self.bulk_write([row])
else:
value = row.cells[self.family_id][ser_param_key][0].value
if param_key in ["fan_out", "n_layers"]:
value = np.frombuffer(value, dtype=np.uint64)[0]
elif param_key in ["cv_path"]:
value = deserialize_key(value)
elif param_key in ["chunk_size"]:
value = np.frombuffer(value, dtype=np.uint64)
else:
raise Exception("Unknown key")
return value
def get_serialized_info(self):
""" Rerturns dictionary that can be used to load this ChunkedGraph
:return: dict
"""
info = {"table_id": self.table_id,
"instance_id": self.instance_id,
"project_id": self.project_id}
try:
info["credentials"] = self.client.credentials
except:
info["credentials"] = self.client._credentials
return info
def get_chunk_layer(self, node_or_chunk_id: np.uint64) -> int:
""" Extract Layer from Node ID or Chunk ID
:param node_or_chunk_id: np.uint64
:return: int
"""
return int(node_or_chunk_id) >> 64 - self._n_bits_for_layer_id
def get_chunk_coordinates(self, node_or_chunk_id: np.uint64
) -> np.ndarray:
""" Extract X, Y and Z coordinate from Node ID or Chunk ID
:param node_or_chunk_id: np.uint64
:return: Tuple(int, int, int)
"""
layer = self.get_chunk_layer(node_or_chunk_id)
bits_per_dim = self.bitmasks[layer]
x_offset = 64 - self._n_bits_for_layer_id - bits_per_dim
y_offset = x_offset - bits_per_dim
z_offset = y_offset - bits_per_dim
x = int(node_or_chunk_id) >> x_offset & 2 ** bits_per_dim - 1
y = int(node_or_chunk_id) >> y_offset & 2 ** bits_per_dim - 1
z = int(node_or_chunk_id) >> z_offset & 2 ** bits_per_dim - 1
return
|
np.array([x, y, z])
|
numpy.array
|
# -*- coding: utf-8 -*-
"""Description of NEXTXY flow direction type and methods to convert to/from general
nextidx. This type is mainly used for the CaMa-Flood model. Note that X (column) and Y
(row) coordinates are one-based."""
from pathlib import Path
from typing import List, Union
from numba import njit
import numpy as np
from . import core, gis_utils
__all__ = ["read_nextxy"]
# NEXTXY type
_ftype = "nextxy"
_mv = np.int32(-9999)
# -10 is inland termination, -9 river outlet at ocean
_pv = np.array([-9, -10], dtype=np.int32)
# NOTE: data below for consistency with LDD / D8 types and testing
_us = np.ones((2, 3, 3), dtype=np.int32) * 2
_us[:, 1, 1] = _pv[0]
def from_array(flwdir, dtype=np.intp):
if not (
(isinstance(flwdir, tuple) and len(flwdir) == 2)
or (
isinstance(flwdir, np.ndarray) and flwdir.ndim == 3 and flwdir.shape[0] == 2
)
):
raise TypeError("NEXTXY flwdir data not understood")
nextx, nexty = flwdir # convert [2,:,:] OR ([:,:], [:,:]) to [:,:], [:,:]
return _from_array(nextx, nexty, dtype=dtype)
def to_array(idxs_ds, shape, mv=core._mv):
nextx, nexty = _to_array(idxs_ds, shape, mv=mv)
return np.stack([nextx, nexty])
@njit
def _from_array(nextx, nexty, _mv=_mv, dtype=np.intp):
size = nextx.size
nrow, ncol = nextx.shape[0], nextx.shape[-1]
nextx_flat = nextx.ravel()
nexty_flat = nexty.ravel()
# allocate output arrays
pits_lst = []
idxs_ds = np.full(nextx.size, core._mv, dtype=dtype)
n = 0
for idx0 in range(nextx.size):
if nextx_flat[idx0] == _mv:
continue
c1 = nextx_flat[idx0]
r1 = nexty_flat[idx0]
pit = ispit(c1) or ispit(r1)
# convert from one- to zero-based index
r_ds, c_ds = np.intp(r1 - 1), np.intp(c1 - 1)
outside = r_ds >= nrow or c_ds >= ncol or r_ds < 0 or c_ds < 0
idx_ds = c_ds + r_ds * ncol
# pit or outside or ds cell is mv
if pit or outside or nextx_flat[idx_ds] == _mv:
pits_lst.append(idx0)
idxs_ds[idx0] = idx0
else:
idxs_ds[idx0] = idx_ds
n += 1
return idxs_ds, np.array(pits_lst, dtype=dtype), n
@njit
def _to_array(idxs_ds, shape, mv=core._mv):
"""convert 1D index to 3D NEXTXY raster"""
ncol = shape[1]
nextx = np.full(idxs_ds.size, _mv, dtype=np.int32)
nexty = np.full(idxs_ds.size, _mv, dtype=np.int32)
for idx0 in range(idxs_ds.size):
idx_ds = idxs_ds[idx0]
if idx_ds == mv:
continue
elif idx0 == idx_ds: # pit
nextx[idx0] = _pv[0]
nexty[idx0] = _pv[0]
else:
# convert idx_ds to one-based row / col indices
nextx[idx0] = idx_ds % ncol + 1
nexty[idx0] = idx_ds // ncol + 1
return nextx.reshape(shape), nexty.reshape(shape)
def isvalid(flwdir):
"""True if NEXTXY raster is valid"""
isfmt1 = isinstance(flwdir, tuple) and len(flwdir) == 2
isfmt2 = (
isinstance(flwdir, np.ndarray) and flwdir.ndim == 3 and flwdir.shape[0] == 2
)
if not (isfmt1 or isfmt2):
return False
nextx, nexty = flwdir # should work for [2,:,:] and ([:,:], [:,:])
mask = np.logical_or(isnodata(nextx), ispit(nextx))
return (
nexty.dtype == "int32"
and nextx.dtype == "int32"
and np.all(nexty.shape == nextx.shape)
and np.all(nextx[~mask] >= 0)
and
|
np.all(nextx[mask] == nexty[mask])
|
numpy.all
|
import unittest
import numpy as np
from subt.artf_node import result2report, check_results, check_borders, get_border_lines
DRONE_FX = 554.25469
class ArtifactDetectorDNNTest(unittest.TestCase):
def test_result2report(self):
result = [('backpack', [(60, 180, 0.9785775), (72, 180, 0.9795098), (60, 184, 0.97716093), (72, 184, 0.9782014)]),
['backpack', 0.99990773, [50, 150, 200, 250]]]
row = [5000]*640
depth =
|
np.array([row]*360, dtype=np.uint16)
|
numpy.array
|
# -*- coding: utf-8 -*-
"""backend movie, get movie file
* backend movie file to search timeline
* get movie from YouTube as mp4 720p or 360p
"""
import numpy as np
from pytube import YouTube
from pytube import extract
from pytube import exceptions
import time as tm
import cv2
import characters as cd
import after_caluculation as ac
import app as ap
import common as cm
import state_list as state
# character name template
CHARACTERS_DATA = []
# timer template
SEC_DATA = []
# menu button template
MENU_DATA = []
# score template
SCORE_DATA = []
# total damage template
DAMAGE_DATA = []
# anna icon template
ICON_DATA = []
# SPEED icon template
SPEED_DATA = []
# character names
CHARACTERS = cd.characters_name
# numbers
NUMBERS = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
]
# analyzable resolution
FRAME_RESOLUTION = [
# width, height
(1280, 720), # RESOLUTION_16_9
(1280, 590), # RESOLUTION_2_1_a
(1280, 592), # RESOLUTION_2_1_b
(960, 720), # RESOLUTION_4_3
(640, 360) # RESOLUTION_16_9_SD
]
RESOLUTION_16_9 = 0
RESOLUTION_2_1_a = 1
RESOLUTION_2_1_b = 2
RESOLUTION_4_3 = 3
RESOLUTION_16_9_SD = 4
# frame roi (x-min, y-min, x-max, y-max)
UB_ROI = (0, 0, 0, 0)
MIN_ROI = (0, 0, 0, 0)
TEN_SEC_ROI = (0, 0, 0, 0)
ONE_SEC_ROI = (0, 0, 0, 0)
MENU_ROI = (0, 0, 0, 0)
SCORE_ROI = (0, 0, 0, 0)
DAMAGE_DATA_ROI = (0, 0, 0, 0)
CHARACTER_ICON_ROI = (0, 0, 0, 0)
SPEED_ICON_ROI = (0, 0, 0, 0)
MENU_LOC = (0, 0)
FRAME_THRESH = 200
SPEED_ICON_THRESH = 240
# timer storage place
TIMER_MIN = 2
TIMER_TEN_SEC = 1
TIMER_SEC = 0
# analyze thresh values
UB_THRESH = 0.6
TIMER_THRESH = 0.6
MENU_THRESH = 0.6
DAMAGE_THRESH = 0.65
ICON_THRESH = 0.6
SPEED_THRESH = 0.4
FOUND = 1
NOT_FOUND = 0
# analyzable movie length (res:1s)
MOVIE_LENGTH_MAX = 600
ENEMY_UB = "――――敵UB――――"
def model_init(video_type):
"""init model
init model for template matching
Args:
video_type (int): movie resolution type
Returns:
"""
global CHARACTERS_DATA # character name template
global SEC_DATA # timer template
global MENU_DATA # menu button template
global SCORE_DATA # score template
global DAMAGE_DATA # total damage template
global ICON_DATA # anna icon template
global SPEED_DATA # SPEED icon template
if video_type is RESOLUTION_16_9:
CHARACTERS_DATA = np.load("model/16_9/UB_name_16_9.npy")
SEC_DATA = np.load("model/16_9/timer_sec_16_9.npy")
MENU_DATA = np.load("model/16_9/menu_16_9.npy")
SCORE_DATA = np.load("model/16_9/score_data_16_9.npy")
DAMAGE_DATA = np.load("model/16_9/damage_data_16_9.npy")
ICON_DATA = np.load("model/16_9/icon_data_16_9.npy")
SPEED_DATA = np.load("model/16_9/speed_data_16_9.npy")
elif video_type is RESOLUTION_2_1_a:
CHARACTERS_DATA = np.load("model/2_1/UB_name_2_1.npy")
SEC_DATA = np.load("model/2_1/timer_sec_2_1.npy")
MENU_DATA = np.load("model/2_1/menu_2_1.npy")
SCORE_DATA = np.load("model/2_1/score_data_2_1.npy")
DAMAGE_DATA = np.load("model/2_1/damage_data_2_1.npy")
ICON_DATA = np.load("model/2_1/icon_data_2_1.npy")
SPEED_DATA = np.load("model/2_1/speed_data_2_1.npy")
elif video_type is RESOLUTION_2_1_b:
CHARACTERS_DATA = np.load("model/2_1/UB_name_2_1.npy")
SEC_DATA = np.load("model/2_1/timer_sec_2_1.npy")
MENU_DATA = np.load("model/2_1/menu_2_1.npy")
SCORE_DATA = np.load("model/2_1/score_data_2_1.npy")
DAMAGE_DATA = np.load("model/2_1/damage_data_2_1.npy")
ICON_DATA = np.load("model/2_1/icon_data_2_1.npy")
SPEED_DATA = np.load("model/2_1/speed_data_2_1.npy")
elif video_type is RESOLUTION_4_3:
CHARACTERS_DATA = np.load("model/4_3/UB_name_4_3.npy")
SEC_DATA = np.load("model/4_3/timer_sec_4_3.npy")
MENU_DATA = np.load("model/4_3/menu_4_3.npy")
SCORE_DATA = np.load("model/4_3/score_data_4_3.npy")
DAMAGE_DATA = np.load("model/4_3/damage_data_4_3.npy")
ICON_DATA = np.load("model/4_3/icon_data_4_3.npy")
SPEED_DATA =
|
np.load("model/4_3/speed_data_4_3.npy")
|
numpy.load
|
# Authors: <NAME>
from __future__ import print_function
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
try:
import Queue
except ImportError:
import queue as Queue
try:
import urllib.request as urllib # for backwards compatibility
except ImportError:
import urllib2 as urllib
try:
import cPickle as pickle
except ImportError:
import pickle
import heapq
import copy
import threading
import logging
import uuid
from collections import OrderedDict
import socket
import random
import os
import glob
import subprocess
import numpy as np
from itertools import cycle
import __main__ as main
import re
import shutil
import numbers
import theano
import sys
import warnings
import inspect
import zipfile
import time
import pprint
from collections import defaultdict
from functools import reduce
from ..externals import dill
sys.setrecursionlimit(40000)
logging.basicConfig(level=logging.INFO,
format='%(message)s')
logger = logging.getLogger(__name__)
string_f = StringIO()
ch = logging.StreamHandler(string_f)
# Automatically put the HTML break characters on there
formatter = logging.Formatter('%(message)s<br>')
ch.setFormatter(formatter)
logger.addHandler(ch)
def get_logger():
"""
Fetch the global dagbldr logger.
"""
return logger
FINALIZE_TRAINING = False
def _get_finalize_train():
return FINALIZE_TRAINING
def _set_finalize_train():
global FINALIZE_TRAINING
FINALIZE_TRAINING = True
# Storage of internal shared
_lib_shared_params = OrderedDict()
def get_lib_shared_params():
return _lib_shared_params
# universal time
tt = str(time.time()).split(".")[0]
def get_time_string():
return tt
def get_name():
base = str(uuid.uuid4())
return base
def get_script():
py_file = None
for argv in sys.argv[::-1]:
if argv[-3:] == ".py":
py_file = argv
# slurm_script
elif "slurm_" in argv:
py_file = argv
if "slurm" in py_file:
script_name = os.environ['SLURM_JOB_NAME']
script_name = script_name.split(".")[0]
else:
assert py_file is not None
script_path = os.path.abspath(py_file)
script_name = script_path.split(os.path.sep)[-1].split(".")[0]
# gotta play games for slurm runner
return script_name
def get_shared(name):
if name in _lib_shared_params.keys():
logger.info("Found name %s in shared parameters" % name)
return _lib_shared_params[name]
else:
raise NameError("Name not found in shared params!")
def set_shared(name, variable):
if name in _lib_shared_params.keys():
raise ValueError("Trying to set key %s which already exists!" % name)
_lib_shared_params[name] = variable
def del_shared():
for key in _lib_shared_params.keys():
del _lib_shared_params[key]
def get_params():
"""
Returns {name: param}
"""
params = OrderedDict()
for name in _lib_shared_params.keys():
params[name] = _lib_shared_params[name]
return params
_type = "float32"
def get_type():
return _type
# TODO: Fetch from env
NUM_SAVED_TO_KEEP = 2
# copied from utils to avoid circular deps
def safe_zip(*args):
"""Like zip, but ensures arguments are of same length.
Borrowed from pylearn2 - copied from utils to avoid circular import
"""
base = len(args[0])
for i, arg in enumerate(args[1:]):
if len(arg) != base:
raise ValueError("Argument 0 has length %d but argument %d has "
"length %d" % (base, i+1, len(arg)))
return zip(*args)
def convert_to_one_hot(itr, n_classes, dtype="int32"):
""" Convert 1D or 2D iterators of class to 2D or 3D iterators of one hot
class indicators.
Parameters
----------
itr : iterator
itr can be list of list, 1D or 2D np.array. In all cases, the
fundamental element must have type int32 or int64.
n_classes : int
number of classes to expand itr to - this will become shape[-1] of
the returned array.
dtype : optional, default "int32"
dtype for the returned array.
Returns
-------
one_hot : array
A 2D or 3D numpy array of one_hot values. List of list or 2D
np.array will return a 3D numpy array, while 1D itr or list will
return a 2D one_hot.
"""
is_two_d = False
error_msg = """itr not understood. convert_to_one_hot accepts\n
list of list of int, 1D or 2D numpy arrays of\n
dtype int32 or int64"""
if type(itr) is np.ndarray and itr.dtype not in [np.object]:
if len(itr.shape) == 2:
is_two_d = True
if itr.dtype not in [np.int32, np.int64]:
raise ValueError(error_msg)
elif not isinstance(itr[0], numbers.Real):
# Assume list of list
# iterable of iterable, feature dim must be consistent
is_two_d = True
elif itr.dtype in [np.object]:
is_two_d = True
else:
raise ValueError(error_msg)
if is_two_d:
lengths = [len(i) for i in itr]
one_hot = np.zeros((max(lengths), len(itr), n_classes), dtype=dtype)
for n in range(len(itr)):
one_hot[np.arange(lengths[n]), n, itr[n]] = 1
else:
one_hot = np.zeros((len(itr), n_classes), dtype=dtype)
one_hot[np.arange(len(itr)), itr] = 1
return one_hot
def _special_check():
ip_addr = socket.gethostbyname(socket.gethostname())
subnet = ".".join(ip_addr.split(".")[:-1])
if subnet == "132.204.25":
logger.info("Found special runtime environment")
return True
else:
return False
# decided at import, should be consistent over training
checkpoint_uuid = get_name()[:6]
def get_checkpoint_dir(checkpoint_dir=None, folder=None, create_dir=True):
""" Get checkpoint directory path """
if checkpoint_dir is None:
checkpoint_dir = os.getenv("DAGBLDR_MODELS", os.path.join(
os.path.expanduser("~"), "dagbldr_models"))
# Figure out if this is necessary to run on localdisk @ U de M
if _special_check():
checkpoint_dir = "/Tmp/kastner/dagbldr_models"
if folder is None:
checkpoint_name = get_script()
tmp = checkpoint_dir + os.path.sep + checkpoint_name + "_" + checkpoint_uuid
checkpoint_dir = tmp
else:
checkpoint_dir = os.path.join(checkpoint_dir, folder)
if not os.path.exists(checkpoint_dir) and create_dir:
os.makedirs(checkpoint_dir)
return checkpoint_dir
def in_nosetest():
return sys.argv[0].endswith('nosetests')
def make_character_level_from_text(text):
""" Create mapping and inverse mappings for text -> one_hot_char
Parameters
----------
text : iterable of strings
Returns
-------
cleaned : list of list of ints, length (len(text), )
The original text, converted into list of list of integers
mapper_func : function
A function that can be used to map text into the correct form
inverse_mapper_func : function
A function that can be used to invert the output of mapper_func
mapper : dict
Dictionary containing the mapping of char -> integer
"""
# Try to catch invalid input
try:
ord(text[0])
raise ValueError("Text should be iterable of strings")
except TypeError:
pass
all_chars = reduce(lambda x, y: set(x) | set(y), text, set())
mapper = {k: n + 2 for n, k in enumerate(list(all_chars))}
# 1 is EOS
mapper["EOS"] = 1
# 0 is UNK/MASK - unused here but needed in general
mapper["UNK"] = 0
inverse_mapper = {v: k for k, v in mapper.items()}
def mapper_func(text_line):
return [mapper[c] if c in mapper.keys() else mapper["UNK"]
for c in text_line] + [mapper["EOS"]]
def inverse_mapper_func(symbol_line):
return "".join([inverse_mapper[s] for s in symbol_line
if s != mapper["EOS"]])
# Remove blank lines
cleaned = [mapper_func(t) for t in text if t != ""]
return cleaned, mapper_func, inverse_mapper_func, mapper
def whitespace_tokenizer(line):
'''Return the tokens of a sentence including punctuation.
>>> tokenize('Bob dropped the apple. Where is the apple?')
['Bob', 'dropped', 'the', 'apple', '.', 'Where', 'is', 'the', 'apple', '?']
'''
return [x.strip() for x in re.split('(\W+)?', line) if x.strip()]
def make_word_level_from_text(text, tokenizer="default"):
""" Create mapping and inverse mappings for text -> one_hot_char
Parameters
----------
text : iterable of strings
Returns
-------
cleaned : list of list of ints, length (len(text), )
The original text, converted into list of list of integers
mapper_func : function
A function that can be used to map text into the correct form
inverse_mapper_func : function
A function that can be used to invert the output of mapper_func
mapper : dict
Dictionary containing the mapping of char -> integer
"""
# Try to catch invalid input
try:
ord(text[0])
raise ValueError("Text should be iterable of strings")
except TypeError:
pass
all_words = reduce(lambda x, y: set(
whitespace_tokenizer(x)) | set(whitespace_tokenizer(y)), text, set())
mapper = {k: n + 2 for n, k in enumerate(list(all_words))}
# 1 is EOS
mapper["EOS"] = 1
# 0 is UNK/MASK - unused here but needed in general
mapper["UNK"] = 0
inverse_mapper = {v: k for k, v in mapper.items()}
def mapper_func(text_line):
return [mapper[c] if c in mapper.keys() else mapper["UNK"]
for c in text_line] + [mapper["EOS"]]
def inverse_mapper_func(symbol_line):
return "".join([inverse_mapper[s] for s in symbol_line
if s != mapper["EOS"]])
# Remove blank lines
cleaned = [mapper_func(t) for t in text if t != ""]
return cleaned, mapper_func, inverse_mapper_func, mapper
def dpickle(save_path, pickle_item):
""" Simple wrapper for checkpoint dictionaries """
old_recursion_limit = sys.getrecursionlimit()
sys.setrecursionlimit(40000)
with open(save_path, mode="wb") as f:
dill.dump(pickle_item, f, protocol=-1)
sys.setrecursionlimit(old_recursion_limit)
def dunpickle(save_path):
""" Simple pickle wrapper for checkpoint dictionaries """
old_recursion_limit = sys.getrecursionlimit()
sys.setrecursionlimit(40000)
with open(save_path, mode="rb") as f:
pickle_item = dill.load(f)
sys.setrecursionlimit(old_recursion_limit)
return pickle_item
def get_shared_variables_from_function(func):
"""
Get all shared variables out of a compiled Theano function
Parameters
----------
func : theano function
Returns
-------
shared_variables : list
A list of theano shared variables
"""
shared_variable_indices = [n for n, var in enumerate(func.maker.inputs)
if isinstance(var.variable,
theano.compile.SharedVariable)]
shared_variables = [func.maker.inputs[i].variable
for i in shared_variable_indices]
return shared_variables
def get_values_from_function(func):
"""
Get all shared values out of a compiled Theano function
Parameters
----------
func : theano function
Returns
-------
list_of_values : list
A list of numpy arrays
"""
return [v.get_value() for v in get_shared_variables_from_function(func)]
def set_shared_variables_in_function(func, list_of_values):
"""
Set all shared variables in a compiled Theano function
Parameters
----------
func : theano function
list_of_values : list
List of numpy arrays to add into shared variables
"""
# TODO : Add checking that sizes are OK
shared_variable_indices = [n for n, var in enumerate(func.maker.inputs)
if isinstance(var.variable,
theano.compile.SharedVariable)]
shared_variables = [func.maker.inputs[i].variable
for i in shared_variable_indices]
[s.set_value(v) for s, v in safe_zip(shared_variables, list_of_values)]
def load_checkpoint(saved_checkpoint_path):
""" Simple pickle wrapper for checkpoint dictionaries """
old_recursion_limit = sys.getrecursionlimit()
sys.setrecursionlimit(40000)
with open(saved_checkpoint_path, mode="rb") as f:
pickle_item = dill.load(f)
sys.setrecursionlimit(old_recursion_limit)
return pickle_item
def load_last_checkpoint(append_name=None):
""" Simple pickle wrapper for checkpoint dictionaries """
save_paths = glob.glob(os.path.join(get_checkpoint_dir(), "*.pkl"))
save_paths = [s for s in save_paths if "results" not in s]
if append_name is not None:
save_paths = [s.split(append_name)[:-1] + s.split(append_name)[-1:]
for s in save_paths]
sorted_paths = get_file_matches("*.pkl", "best")
sorted_paths = [s for s in sorted_paths if "results" not in s]
if len(sorted_paths) == 0:
raise ValueError("No checkpoint found in %s" % get_checkpoint_dir())
last_checkpoint_path = sorted_paths[-1]
logger.info("Loading checkpoint from %s" % last_checkpoint_path)
return load_checkpoint(last_checkpoint_path)
def write_results_as_html(results_dict, save_path, default_show="all"):
as_html = filled_js_template_from_results_dict(
results_dict, default_show=default_show)
with open(save_path, "w") as f:
f.writelines(as_html)
def get_file_matches(glob_ext, append_name):
all_files = glob.glob(
os.path.join(get_checkpoint_dir(), glob_ext))
if append_name is None:
# This 3 is definitely brittle - need better checks
selected = [f for n, f in enumerate(all_files)
if len(f.split(os.sep)[-1].split("_")) == 3]
else:
selected = [f for n, f in enumerate(all_files)
if append_name in f.split(os.sep)[-1]]
def key_func(x):
return int(x.split(os.sep)[-1].split(".")[0].split("_")[-1])
int_selected = []
for s in selected:
try:
key_func(s)
int_selected.append(s)
except ValueError:
pass
selected = sorted(int_selected, key=key_func)
return selected
def argsort(seq):
return sorted(range(len(seq)), key=seq.__getitem__)
def remove_old_files(sorted_files_list):
n_saved_to_keep = NUM_SAVED_TO_KEEP
if len(sorted_files_list) > n_saved_to_keep:
times = [os.path.getctime(f) for f in sorted_files_list]
times_rank = argsort(times)
for t, f in zip(times_rank, sorted_files_list):
if t not in range(0, len(times))[-n_saved_to_keep:]:
os.remove(f)
def cleanup_monitors(partial_match, append_name=None):
selected_monitors = get_file_matches(
"*" + partial_match + "*.html", append_name)
remove_old_files(selected_monitors)
def cleanup_checkpoints(append_name=None):
selected_checkpoints = get_file_matches("*.pkl", append_name)
remove_old_files(selected_checkpoints)
selected_checkpoints = get_file_matches("*.npz", append_name)
remove_old_files(selected_checkpoints)
def zip_dir(src, dst):
zf = zipfile.ZipFile(dst, "w", zipfile.ZIP_DEFLATED)
abs_src = os.path.abspath(src)
exclude_exts = [".js", ".pyc", ".html", ".txt", ".csv", ".gz"]
for root, dirs, files in os.walk(src):
for fname in files:
if all([e not in fname for e in exclude_exts]):
absname = os.path.abspath(os.path.join(root, fname))
arcname = "dagbldr" + os.sep + absname[len(abs_src) + 1:]
zf.write(absname, arcname)
zf.close()
def archive_dagbldr():
checkpoint_dir = get_checkpoint_dir()
code_snapshot_dir = checkpoint_dir + os.path.sep + "code_snapshot"
if not os.path.exists(code_snapshot_dir):
os.mkdir(code_snapshot_dir)
try:
theano_flags = os.environ["THEANO_FLAGS"]
command_string = 'THEANO_FLAGS="' + theano_flags + '" ' + "python "
command_string += get_script() + ".py "
command_string += " ".join(sys.argv[1:])
except KeyError:
command_string += get_script() + ".py "
command_string += " ".join(sys.argv[1:])
command_script_path = code_snapshot_dir + os.path.sep + "run.sh"
if not os.path.exists(command_script_path):
with open(command_script_path, 'w') as f:
f.writelines(command_string)
save_script_path = code_snapshot_dir + os.path.sep + get_script() + ".py"
lib_dir = str(os.sep).join(save_script_path.split(os.sep)[:-2])
save_lib_path = code_snapshot_dir + os.path.sep + "dagbldr_archive.zip"
existing_reports = glob.glob(os.path.join(checkpoint_dir, "*.html"))
existing_models = glob.glob(os.path.join(checkpoint_dir, "*.pkl"))
empty = all([len(l) == 0 for l in (existing_reports, existing_models)])
if not os.path.exists(save_script_path) or empty:
logger.info("Saving code archive %s at %s" % (lib_dir, save_lib_path))
script_name = get_script() + ".py"
script_location = os.path.abspath(script_name)
shutil.copy2(script_location, save_script_path)
zip_dir(lib_dir, save_lib_path)
def monitor_status_func(results_dict, append_name=None,
status_type="checkpoint",
nan_check=True, print_output=True):
""" Dump the last results from a results dictionary """
n_seen = max([len(l) for l in results_dict.values()])
last_results = {k: v[-1] for k, v in results_dict.items()}
# This really, really assumes a 1D numpy array (1,) or (1, 1)
last_results = {k: float("%.15f" % v.ravel()[-1])
if isinstance(v, (np.generic, np.ndarray))
else float("%.15f" % v)
for k, v in last_results.items()}
pp = pprint.PrettyPrinter()
filename = main.__file__
fileline = "Script %s" % str(filename)
if status_type == "checkpoint":
statusline = "Checkpoint %i" % n_seen
else:
raise ValueError("Unknown status_type %s" % status_type)
breakline = "".join(["-"] * (len(statusline) + 1))
if print_output:
logger.info(breakline)
logger.info(fileline)
logger.info(statusline)
logger.info(breakline)
logger.info(pp.pformat(last_results))
if status_type == "checkpoint":
save_path = os.path.join(get_checkpoint_dir(),
"model_checkpoint_%i.html" % n_seen)
if append_name is not None:
split = save_path.split("_")
save_path = "_".join(
split[:-1] + [append_name] + split[-1:])
if not in_nosetest():
# Don't dump if testing!
# Only enable user defined keys
nan_test = [(k, True) for k, r_v in results_dict.items()
for v in r_v if np.isnan(v)]
if nan_check and len(nan_test) > 0:
nan_keys = set([tup[0] for tup in nan_test])
raise ValueError("Found NaN values in the following keys ",
"%s, exiting training" % nan_keys)
show_keys = [k for k in results_dict.keys()
if "_auto" not in k]
write_results_as_html(results_dict, save_path,
default_show=show_keys)
if status_type == "checkpoint":
cleanup_monitors("checkpoint", append_name)
def checkpoint_status_func(training_loop, results,
append_name=None, nan_check=True):
""" Saves a checkpoint dict """
checkpoint_dict = training_loop.checkpoint_dict
checkpoint_dict["previous_results"] = results
nan_test = [(k, True) for k, e_v in results.items()
for v in e_v if np.isnan(v)]
if nan_check and len(nan_test) > 0:
nan_keys = set([tup[0] for tup in nan_test])
raise ValueError("Found NaN values in the following keys ",
"%s, exiting training without saving" % nan_keys)
n_seen = max([len(l) for l in results.values()])
checkpoint_save_path = os.path.join(
get_checkpoint_dir(), "model_checkpoint_%i.pkl" % n_seen)
weight_save_path = os.path.join(
get_checkpoint_dir(), "model_weights_%i.npz" % n_seen)
results_save_path = os.path.join(
get_checkpoint_dir(), "model_results_%i.pkl" % n_seen)
if append_name is not None:
def mkpath(name):
split = name.split("_")
return "_".join(split[:-1] + [append_name] + split[-1:])
checkpoint_save_path = mkpath(checkpoint_save_path)
weight_save_path = mkpath(weight_save_path)
results_save_path = mkpath(results_save_path)
if not in_nosetest():
# Don't dump if testing!
save_checkpoint(checkpoint_save_path, training_loop)
save_weights(weight_save_path, checkpoint_dict)
save_results(results_save_path, results)
cleanup_checkpoints(append_name)
monitor_status_func(results, append_name=append_name)
def default_status_func(status_number, epoch_number, epoch_results):
""" Default status function for iterate_function. Prints epoch info.
This is exactly equivalent to defining your own status_function as such:
def status_func(status_number, epoch_number, epoch_results):
print_status_func(epoch_results)
Parameters
----------
status_number
epoch_number
epoch_results
"""
monitor_status_func(epoch_results)
def even_slice(arr, size):
""" Force array to be even by slicing off the end """
extent = -(len(arr) % size)
if extent == 0:
extent = None
return arr[:extent]
def make_minibatch(arg, slice_or_indices_list):
""" Does not handle off-size minibatches
returns list of [arg, mask] mask of ones if 3D
else [arg]
"""
if len(arg.shape) == 3:
sliced = arg[:, slice_or_indices_list, :]
return [sliced, np.ones_like(sliced[:, :, 0].astype(
theano.config.floatX))]
elif len(arg.shape) == 2:
return [arg[slice_or_indices_list, :]]
else:
return [arg[slice_or_indices_list]]
def make_masked_minibatch(arg, slice_or_indices_list):
""" Create masked minibatches
returns list of [arg, mask]
"""
sliced = arg[slice_or_indices_list]
is_two_d = True
if len(sliced[0].shape) > 1:
is_two_d = False
if hasattr(arg, 'shape'):
# should handle numpy arrays and hdf5
if is_two_d:
data = arg[slice_or_indices_list]
mask = np.ones_like(data[:, 0]).astype(theano.config.floatX)
else:
data = arg[:, slice_or_indices_list]
mask = np.ones_like(data[:, :, 0]).astype(theano.config.floatX)
return [data, mask]
if is_two_d:
# list of lists
d0 = [s.shape[0] for s in sliced]
max_len = max(d0)
batch_size = len(sliced)
data = np.zeros((batch_size, max_len)).astype(sliced[0].dtype)
mask = np.zeros((batch_size, max_len)).astype(theano.config.floatX)
for n, s in enumerate(sliced):
data[n, :len(s)] = s
mask[n, :len(s)] = 1
else:
# list of arrays
d0 = [s.shape[0] for s in sliced]
d1 = [s.shape[1] for s in sliced]
max_len = max(d0)
batch_size = len(sliced)
dim = d1[0]
same_dim = all([d == dim for d in d1])
assert same_dim
data = np.zeros((max_len, batch_size, dim)).astype(theano.config.floatX)
mask = np.zeros((max_len, batch_size)).astype(theano.config.floatX)
for n, s in enumerate(sliced):
data[:len(s), n] = s
mask[:len(s), n] = 1
return [data, mask]
def make_embedding_minibatch(arg, slice_type):
if type(slice_type) is not slice:
raise ValueError("Text formatters for list of list can only use "
"slice objects")
sli = arg[slice_type]
lengths = [len(s) for s in sli]
maxlen = max(lengths)
mask = np.zeros((max(lengths), len(sli)), dtype=theano.config.floatX)
expanded = [np.zeros((maxlen,), dtype="int32") for s in sli]
for n, l in enumerate(lengths):
mask[:l, n] = 1.
expanded[n][:l] = sli[n]
return expanded, mask
def gen_make_one_hot_minibatch(n_targets):
""" returns function that returns list """
def make_one_hot_minibatch(arg, slice_or_indices_list):
non_one_hot_minibatch = make_minibatch(
arg, slice_or_indices_list)[0].squeeze()
return [convert_to_one_hot(non_one_hot_minibatch, n_targets)]
return make_one_hot_minibatch
def gen_make_masked_one_hot_minibatch(n_targets):
""" returns function that returns list """
def make_masked_one_hot_minibatch(arg, slice_or_indices_list):
non_one_hot_minibatch = make_minibatch(
arg, slice_or_indices_list)[0].squeeze()
max_len = max([len(i) for i in non_one_hot_minibatch])
mask = np.zeros((max_len, len(non_one_hot_minibatch))).astype(
theano.config.floatX)
for n, i in enumerate(non_one_hot_minibatch):
mask[:len(i), n] = 1.
return [convert_to_one_hot(non_one_hot_minibatch, n_targets), mask]
return make_masked_one_hot_minibatch
def gen_make_list_one_hot_minibatch(n_targets):
"""
Returns a function that will turn a list into a minibatch of one_hot form.
For use with iterate_function list_of_minibatch_functions argument.
Example:
n_chars = 84
text_minibatcher = gen_make_text_minibatch_func(n_chars)
valid_results = iterate_function(
cost_function, [X_clean_valid, y_clean_valid], minibatch_size,
list_of_output_names=["valid_cost"],
list_of_minibatch_functions=[text_minibatcher], n_epochs=1,
shuffle=False)
"""
def make_list_one_hot_minibatch(arg, slice_type):
if type(slice_type) is not slice:
raise ValueError("Text formatters for list of list can only use "
"slice objects")
sli = arg[slice_type]
expanded = convert_to_one_hot(sli, n_targets)
lengths = [len(s) for s in sli]
mask = np.zeros((max(lengths), len(sli)), dtype=theano.config.floatX)
for n, l in enumerate(lengths):
mask[np.arange(l), n] = 1.
return expanded, mask
return make_list_one_hot_minibatch
def make_minibatch_from_indices(indices, minibatch_size):
if len(indices) % minibatch_size != 0:
warnings.warn("WARNING:Length of dataset should be evenly divisible"
"by minibatch_size - slicing to match.", UserWarning)
indices = even_slice(indices,
len(indices) - len(indices) % minibatch_size)
assert(len(indices) % minibatch_size == 0)
minibatch_indices = [indices[i:i + minibatch_size]
for i in np.arange(0, len(indices), minibatch_size)]
# Check for contiguity to avoid unnecessary copies
minibatch_indices = [slice(mi[0], mi[-1] + 1, 1)
if np.all(
np.abs(
|
np.array(mi)
|
numpy.array
|
'''
6 April 2020
Python file for generating anomalies in sample conductivity distributions.
by <NAME> and <NAME>
in collaboration with <NAME> and <NAME>
from Solid State Physics Group
at the University of Manchester
'''
import numpy as np
#import numpy.random as rand
from random import SystemRandom
import numpy.linalg as la
rand = SystemRandom()
def multivariateGaussian(x, mu, sigma, normalised=False):
if normalised:
denominator = 1. / (2 * np.pi * np.sqrt(np.linalg.det(sigma)))
else:
denominator = 1.
x_centred = x - mu
#path = np.einsum_path('ij, jk, ki->i', x_centred, np.linalg.inv(sigma), x_centred.T, optimize='optimal')[0]
numerator = np.exp(-0.5 * np.einsum('ij, jk, ki->i', x_centred, np.linalg.inv(sigma), x_centred.T, optimize='optimal'))
return numerator / denominator
def generateContinuousConductivity(a, centre, number_of_gaussians, mu, sigma, npix, weightGauss=None, pts=None, tri=None):
# array to store permitivity in different square
if centre is None:
centre=[0, 0]
if (number_of_gaussians) == 0:
if pts is not None and tri is not None:
return np.ones((npix, npix)), np.ones(tri.shape[0])
else:
return np.ones((npix, npix)), None
# assumed that background permitivity is 1 (and therefore difference with uniform will be 0)
permSquares = np.zeros((int(npix), int(npix)), dtype='f4')
if pts is not None and tri is not None:
permTri = np.zeros(tri.shape[0], dtype='f4')
# initialises an array to store the coordinates of centres of squares (pixels)
centresSquares = np.empty((npix, npix, 2), dtype='f4')
# initialising the j vector to prepare for tiling
j = np.arange(npix)
# tiling j to itself npix times (makes array shape (npix, npix))
j = np.tile(j, (npix, 1))
# i and j are transposes of each other
i = j
j = j.T
# assigning values to C_sq
centresSquares[i, j, :] = np.transpose([a / 2 * ((2 * i + 1) / npix - 1) + centre[0], a / 2 * ((2 * j + 1) / npix - 1) + centre[1]])
if pts is not None and tri is not None:
centresTriangles = np.mean(pts[tri], axis=1)
centresSquares = centresSquares.reshape((npix * npix, 2))
if weightGauss is None:
weightGauss = rand.uniform(size=(number_of_gaussians,), low=0., high=0.1)
for i in range(number_of_gaussians):
if type(weightGauss) is np.ndarray:
weight = weightGauss[i]
elif type(weightGauss) is float:
weight = weightGauss
else:
raise TypeError("weight is not float or array of floats")
permSquares[:] += (weight/number_of_gaussians) * multivariateGaussian(centresSquares, mu[i], sigma[i]).reshape(npix, npix)
if pts is not None and tri is not None:
permTri[:] += (weight/number_of_gaussians) * multivariateGaussian(centresTriangles, mu[i], sigma[i])
if pts is not None and tri is not None:
if (np.abs(permSquares) < 5e-2).any():
a = np.random.randint(low = 4, high = 14) * 0.1
permSquares += a
permTri += a
'''
fig, ax = plt.subplots(figsize=(6, 4))
im = ax.imshow(np.real(permSquares) - np.ones((npix, npix)), interpolation='none', cmap=plt.cm.viridis, origin='lower', extent=[-1,1,-1,1])
fig.colorbar(im)
ax.axis('equal')
#plt.show
'''
if pts is not None and tri is not None:
return permSquares, permTri
else:
return permSquares, None
def randomiseGaussianParams(a, centre, npix):
if centre is None:
centre = [0, 0]
# randomise parameters of gaussians
number_of_gaussians = rand.randint(low=0, high=5)
if (number_of_gaussians) == 0:
return 0, 0, 0
mu = np.empty(shape=(number_of_gaussians, 2))
mu[:, 0] = rand.normal(size=(number_of_gaussians), loc=0, scale=0.5)
mu[:, 1] = rand.normal(size=(number_of_gaussians), loc=0, scale=0.5)
sigma = np.empty(shape=(number_of_gaussians, 2, 2))
sigma[:, 0, 0] = rand.uniform(size=(number_of_gaussians), low = 0.2, high = 5.)
sigma[:, 1, 1] = rand.uniform(size=(number_of_gaussians), low = 0.2, high = 5.)
sigma[:, 1, 0] = rand.uniform(size=(number_of_gaussians), low = -np.sqrt(sigma[:,0,0]*sigma[:,1,1]), high = np.sqrt(sigma[:,0,0]*sigma[:,1,1]))
sigma[:, 0, 1] = sigma[:, 1, 0]
return number_of_gaussians, mu, sigma
def randomiseGaussianParam(a=2., centre=None, npix=64):
if centre is None:
centre = [0, 0]
# randomise parameters of gaussians
mu = np.empty(shape=(1, 2))
mu[:, 0] = rand.uniform(-1, 1)
mu[:, 1] = rand.uniform(-1, 1)
#mu[:, 0] = rand.normal(size=(number_of_gaussians), loc=0, scale=0.5)
#mu[:, 1] = rand.normal(size=(number_of_gaussians), loc=0, scale=0.5)
sigma = np.empty(shape=(1, 2, 2))
sigma[:, 0, 0] = rand.uniform(0.08, 0.8)
sigma[:, 1, 1] = rand.uniform(0.08, 0.8)
sigma[:, 1, 0] = rand.uniform(-np.sqrt(sigma[:,0,0]*sigma[:,1,1]), np.sqrt(sigma[:,0,0]*sigma[:,1,1]))
sigma[:, 0, 1] = sigma[:, 1, 0]
return mu, sigma
def triangle_area(x, y):
'''
function that area given 2d coordinates of all vertices of triangle
takes:
x - array storing the x-coordinates of all vertices [3, 1] float
y - array storing the y-coordinates of all vertices [3, 1] float
returns:
area of the triangle
'''
return 0.5 * np.absolute(x[0] * (y[1] - y[2]) + x[1] * (y[2] - y[0]) + x[2] * (y[0] - y[1]))
def generate_examplary_output(a, npix, anomaly, centre=None):
'''
a function that generates true conductivity map to be used in training of U-net
takes:
a - side of square - float
npix - number of pixels along each axis - int
anomaly - dictionary of anomalies characteristics
centre - centre of coordinate system - array shape (2,)
returns:
true conductivity distribution - array shape (npix, npix)
'''
if centre is None:
centre = [0, 0]
# array to store permitivity in different square
# assumed that background permitivity is 1 (and therefore difference with uniform will be 0)
perm_sq = np.ones((npix, npix), dtype='f4')
# initialises an array to store the coordinates of centres of squares (pixels)
C_sq = np.empty((npix, npix, 2), dtype='f4')
# initialising the j vector to prepare for tiling
j = np.arange(npix)
# tiling j to itself npix times (makes array shape (npix, npix))
j = np.tile(j, (npix, 1))
# i and j are transposes of each other
i = j
j = j.T
# assigning values to C_sq
C_sq[i, j, :] = np.transpose([a / 2 * ((2 * i + 1) / npix - 1) + centre[0], a / 2 * ((2 * j + 1) / npix - 1) + centre[1]])
# return an empty array if there are no anomalies generated
if anomaly is None:
return perm_sq - 1
# putting anomalies on map one by one
for l in range(len(anomaly)):
if anomaly[l]['name'] == 'ellipse':
# check what squares have their centres inside the ellipse and set permittivity values
x = anomaly[l]['x']
y = anomaly[l]['y']
a_ = anomaly[l]['a']
b = anomaly[l]['b']
angle = anomaly[l]['angle']
# equation for a rotated ellipse in 2d cartesians
indices = np.sum(np.power([(np.cos(angle)*(C_sq[:, :, 0] - x) - np.sin(angle) * (C_sq[:, : , 1] - y))/a_,
(np.sin(angle)*(C_sq[:, :, 0] - x) + np.cos(angle) * (C_sq[:, : , 1] - y))/b], 2),
axis=0) < 1
# setting relative permittivity values
perm_sq[indices] = anomaly[l]['perm']
# check what squares are crossed by the line element and set their permittivity values to zero
elif anomaly[l]['name'] == 'line':
x = anomaly[l]['x'] # of centre
y = anomaly[l]['y']
theta = anomaly[l]['angle_line']
length = anomaly[l]['len']
# coordinates of endpoints of the line
p_start = np.array([x + (length * np.cos(theta))/2, y + (length * np.sin(theta))/2])
p_end = np.array([x - (length * np.cos(theta))/2, y - (length * np.sin(theta))/2])
# find min and max x and y for any coordinates, so we have lower left and upper right corners of rectangle, whose diagonal is our line
x_min_max = np.sort([x + (length * np.cos(theta))/2, x - (length * np.cos(theta))/2])
y_min_max = np.sort([y + (length * np.sin(theta))/2, y - (length * np.sin(theta))/2])
# checking whether pixel is in that rectangle by setting a limit on x and y of its centre
if abs(y_min_max[0] - y_min_max[1]) < a / (npix/4):
# the loop increases the allowed distances from the line if line is very close to horizontal
index_1 = (C_sq[:,:,0] > x_min_max[0]) * (C_sq[:,:,0] < x_min_max[1]) * (C_sq[:,:,1] > y_min_max[0] - a / (npix * np.sqrt(2))) * (C_sq[:,:,1] < y_min_max[1] + a / (npix * np.sqrt(2)))
elif abs(x_min_max[0] - x_min_max[1]) < a / (npix/4):
# the loop increases the allowed distances from the line if line is very close to vertical
index_1 = (C_sq[:,:,0] > x_min_max[0] - a / (npix/4)) * (C_sq[:,:,0] < x_min_max[1] + a / (npix/4)) * (C_sq[:,:,1] > y_min_max[0]) * (C_sq[:,:,1] < y_min_max[1])
else:
index_1 = (C_sq[:,:,0] > x_min_max[0]) * (C_sq[:,:,0] < x_min_max[1]) * (C_sq[:,:,1] > y_min_max[0]) * (C_sq[:,:,1] < y_min_max[1])
# checking whether distance from the centre to the line is smaller than the diagonal of the square
indices = (np.absolute(np.cross(p_end - p_start,
np.array([p_start[0] - C_sq[:, :, 0], p_start[1] - C_sq[:, :, 1]]).T)
/ la.norm(p_end - p_start))
< a / (npix * np.sqrt(2)))
indices = np.transpose(indices)
# combining the two conditions 1)square in rectangle with line as diagonal and 2) distance to line smaller than half diagonal of pixel
indices = np.multiply(indices, index_1)
# setting permittivity values (relative)
perm_sq[indices] = anomaly[l]['perm']
elif anomaly[l]['name'] == 'triangle':
#extracting the coordinatec of each of the vertices
A = anomaly[l]['A']
B = anomaly[l]['B']
C = anomaly[l]['C']
#for each point check whether the sum of the areas of the triangles formed by it and all combinations of
#two of the vertices of the triangle is approximately equal to the area of the triangle
index_tri = triangle_area([A[0], B[0], C_sq[:, :, 0]], [A[1], B[1], C_sq[:, :, 1]]) + triangle_area([B[0], C[0], C_sq[:, :, 0]], [B[1], C[1], C_sq[:, :, 1]]) + triangle_area([C[0], A[0], C_sq[:, :, 0]], [C[1], A[1], C_sq[:, :, 1]]) - triangle_area([A[0], B[0], C[0]], [A[1], B[1], C[1]]) < 0.01
#set permitivity of triangle equal to the permitivity of the anomaly
perm_sq[index_tri] = anomaly[l]['perm']
elif anomaly[l]['name'] == 'gaussian_mixture':
mu = anomaly[l]['mean']
sigma = anomaly[l]['covariance']
weightGauss = anomaly[l]['perm']
permGauss, _ = generateContinuousConductivity(2., None, 1, mu, sigma, npix, weightGauss)
perm_sq += permGauss
perm_sq[perm_sq < 0.005] = 0.005
perm_sq -= 1.
#check whether any anomalies are too close to each of the edges
indexx1 = (np.absolute(C_sq[:, :, 0] + a/2) < 0.15)
indexx2 = (np.absolute(C_sq[:, :, 0] - a/2) < 0.15)
indexy1 = (np.absolute(C_sq[:, :, 1] + a/2) < 0.15)
indexy2 = (np.absolute(C_sq[:, :, 1] - a/2) < 0.15)
#combine all edge conditions
index = (indexx1 + indexx2 + indexy1 + indexy2)
#check for permitivities close to 0
index_p = perm_sq < -0.9995
index = np.multiply(index_p, index)
index = index > 0
#set such conditions equal to the background to ensure existing solution to forward problem
perm_sq[index] = 0.
'''
#optional plot conductivity distribution as a check
plt.imshow(perm_sq, cmap=plt.cm.viridis, origin='lower', extent=[-1, 1, -1, 1])
plt.colorbar()
#plt.show()
'''
return perm_sq
def generate_anoms(a, b):
'''
a function that generates an array of a random number of dictionaries for the different anomalies;
also randomises the type and characteristics of the different anomalies
takes:
a - length of side on x axis - float
b - length of side on y axis - float
returns:
anoms - array of dictionaries with information about anomalies - array shape (number of anomalies); type(anoms[0]): object
'''
# random number of anomalies (between 0 and 2) with a given probability
#n_anom = int(np.round_(np.absolute(np.random.normal(1.3, 0.35))))
n_anom = int(np.random.choice([0,1,2,3], p=[0.07,0.45,0.38, 0.1]))
#print(n_anom)
# stop the function if n_anom == 0
if n_anom == 0:
return None
# initialises an empty array of objects(dictionaries) with length n_anom
anoms = np.empty((n_anom,), dtype='O')
# chooses types of anomalies, (ellipse ( == 0) with probability 0.5, line ( == 1 ) with probability 0.1 and triangle ( == 2) with probability 0.4)
names = np.random.choice([0, 1, 2, 3], n_anom, p=[0.4, 0.1, 0.4, 0.1])
#names = 3 * np.ones(n_anom)
# randomises characteristics of each anomaly and assigns dictionary to the anoms array
for i in range(n_anom):
if names[i] == 0:
# x, y from -a to a or -b to b
x = a * rand.random() - a/2
y = b * rand.random() - b/2
# a, b from 0 to a and 0 to b
a_ = a * rand.random()
b_ = b * rand.random()
# angle from 0 to PI
ang = np.pi * rand.random()
#modulus to ensure positive values 0.25 times a random number + number from [0,1] based of power law of 1.2 + 0.5 base offset to prevent conductivities too low
#main goal is to have a bias to higher conductivities since this is what we expect in real data
perm = np.absolute(0.25 * np.random.randn() + np.random.power(1.2) + 0.5)
# add anomaly to array
anoms[i] = {'name': 'ellipse', 'x': x, 'y': y, 'a': a_, 'b': b_ ,'angle': ang, 'perm': perm}
if names[i] == 1:
# x, y from -a to a or -b to b
x = a * rand.random() - a/2
y = b * rand.random() - b/2
# diagonal of the given line
l = 0.5 * np.sqrt(a ** 2 + b ** 2)
# total length of line anomaly ( with pdf proportional to 1.4) + constant length value
#prevents existence of lines too short and overfitting of CNN
length = l * (np.random.power(1.4) + 0.14)
# angle from 0 to PI
ang = np.pi * rand.random()
# add anomaly to array
anoms[i] = {'name': 'line', 'len': length, 'x': x, 'y': y, 'angle_line': ang, 'perm': 0.00001}
if names[i] == 2:
#two individual choices of triangles (one with random angles that are not too small with probability 70% and
#one with angles 120/60 deg to capture the symmetry of the graphene sample)
#tri_type = rand.choice([0, 1], p = [0.7, 0.3])
tri_type = rand.choice([0,0,0,0,0,0,0,1,1,1])
if tri_type == 0:
#initialise cosines to be one rad.
cosa = np.ones(3)
while (np.absolute(cosa) - 0.5).all() > 0.01 and (np.absolute(cosa) - np.sqrt(3)/2).all() > 0.01:
#initialise coordinates of two of the points
Ax = a * rand.random() - a/2
Ay = b * rand.random() - b/2
Bx = a * rand.random() - a/2
By = b * rand.random() - b/2
#randomise which root to take since two such triangles will be possible for a set of 2 points
sign = rand.choice([-1, 1])
#calculate length of line connecting A/B
l = np.sqrt(np.power(Ax - Bx, 2) + np.power(Ay - By, 2))
#randomise length of second side of triangle (constant factor added to ensure existence of this specific triangle)
l2 = np.sqrt(3) * l / 2 + rand.random()
#calculate differences of y's of A/B
diff = np.absolute(Ay - By)
#initialise angle of 60 deg
ang = 1/3 * np.pi
#calculate angle needed to determine y coord of C
beta = np.pi - np.arcsin(diff/l) - ang
#Calculate coordinates of C[x, y]
Cy = Ay - np.sin(beta)*l2
Cx = Ax - np.sqrt(np.power(l2, 2) - np.power(Ay - Cy, 2))
#iterate over created triangles to ensure desired result given lack of general formulation
a_sq = np.power(Ax - Bx, 2) + np.power(Ay - By, 2)
b_sq = np.power(Bx - Cx, 2) + np.power(By - Cy, 2)
c_sq = np.power(Cx - Ax, 2) + np.power(Cy - Ay, 2)
N1 = a_sq + b_sq - c_sq
D1 = 2 * np.sqrt(a_sq) * np.sqrt(b_sq)
N2 = b_sq + c_sq - a_sq
D2 = 2 * np.sqrt(b_sq) * np.sqrt(c_sq)
N3 = c_sq + a_sq - b_sq
D3 = 2 * np.sqrt(c_sq) * np.sqrt(a_sq)
cosa = ([np.true_divide(N1, D1), np.true_divide(N2, D2), np.true_divide(N3, D3)])
elif tri_type == 1:
#initialise cosine in order to enter loop
cosa = 1
#interate over created triangles to ensure no silver triangles
while np.absolute(cosa) > np.sqrt(2)/2:
#initialise coordinates randomly
Ax = a * rand.random() - a/2
Ay = b * rand.random() - b/2
Bx = a * rand.random() - a/2
By = b * rand.random() - b/2
Cx = a * rand.random() - a/2
Cy = b * rand.random() - b/2
#calculate length of each side
a_sq = np.power(Ax - Bx, 2) + np.power(Ay - By, 2)
b_sq = np.power(Bx - Cx, 2) + np.power(By - Cy, 2)
c_sq = np.power(Cx - Ax, 2) +
|
np.power(Cy - Ay, 2)
|
numpy.power
|
from functools import partial
from typing import Union, List
import numpy as np
from statannotations.utils import check_is_in
try:
from statsmodels.stats.multitest import multipletests
except ImportError:
multipletests = None
# For user convenience
methods_names = {'bonferroni': 'Bonferroni',
'bonf': 'Bonferroni',
'Bonferroni': 'Bonferroni',
'holm-bonferroni': 'Holm-Bonferroni',
'HB': 'Holm-Bonferroni',
'Holm-Bonferroni': 'Holm-Bonferroni',
'holm': 'Holm-Bonferroni',
'benjamini-hochberg': 'Benjamini-Hochberg',
'BH': 'Benjamini-Hochberg',
'fdr_bh': 'Benjamini-Hochberg',
'Benjamini-Hochberg': 'Benjamini-Hochberg',
'fdr_by': 'Benjamini-Yekutieli',
'Benjamini-Yekutieli': 'Benjamini-Yekutieli',
'BY': 'Benjamini-Yekutieli'
}
# methods_data represents function and method type:
# Type 0 means per-pvalue correction with modification
# Type 1 means correction of interpretation of set of pvalues
methods_data = {'Bonferroni': ["bonferroni", 0],
'Holm-Bonferroni': ["holm", 1],
'Benjamini-Hochberg': ["fdr_bh", 1],
'Benjamini-Yekutieli': ["fdr_by", 1]}
IMPLEMENTED_METHODS = [name for name in methods_names.keys()]
def get_validated_comparisons_correction(comparisons_correction):
if comparisons_correction is None:
return
if isinstance(comparisons_correction, str):
check_valid_correction_name(comparisons_correction)
try:
comparisons_correction = ComparisonsCorrection(
comparisons_correction)
except ImportError as e:
raise ImportError(f"{e} Please install statsmodels or pass "
f"`comparisons_correction=None`.")
if not (isinstance(comparisons_correction, ComparisonsCorrection)):
raise ValueError("comparisons_correction must be a statmodels "
"method name or a ComparisonCorrection instance")
return comparisons_correction
def get_correction_parameters(name):
if name is None:
return None
if name not in IMPLEMENTED_METHODS:
raise NotImplementedError(f"Correction method {str(name)} is not "
f"implemented.")
correction_method = methods_names[name]
return methods_data[correction_method]
def check_valid_correction_name(name):
check_is_in(name, IMPLEMENTED_METHODS + [None],
label='argument `comparisons_correction`')
def _get_correction_attributes(method: Union[str, callable], alpha, name,
method_type, corr_kwargs):
if isinstance(method, str):
if multipletests is None:
raise ImportError("The statsmodels package is required to use "
"one of the multiple comparisons correction "
"methods proposed in statannotations.")
name = name if name is not None else method
method, method_type = get_correction_parameters(method)
if corr_kwargs is None:
corr_kwargs = {}
func = partial(multipletests, alpha=alpha, method=method,
**corr_kwargs)
else:
if name is None:
raise ValueError("A method name must be provided if passing a "
"function")
if method_type is None:
raise ValueError("A method type must be provided if passing a "
"function")
func = method
method = None
if corr_kwargs is not None:
func = partial(func, **corr_kwargs)
return name, method, method_type, func
class ComparisonsCorrection(object):
def __init__(self, method: Union[str, callable], alpha: float = 0.05,
name: str = None, method_type: int = None,
statsmodels_api: bool = True, corr_kwargs: dict = None):
"""
Wrapper for a multiple testing correction method. All arguments must be
provided here so that it can be called only with the pvalues.
:param method:
str that matches one of statsmodel multipletests methods or a
callable
:param alpha:
If using statsmodel: FWER, family-wise error rate, else use
`corr_kwargs`
:param name: Necessary if `method` is a function, optional otherwise
:param method_type:
type 0: Per-pvalue correction with modification
type 1 function: Correction of interpretation of set of
(ordered) pvalues
:param statsmodels_api:
statsmodels multipletests returns reject and pvals_corrected as
first and second values, which correspond to our type 1 and 0
method_type. Set to False if the used method only returns
the correct array
:param corr_kwargs: additional parameters for correction method
"""
self.name, self.method, self.type, self.func = \
_get_correction_attributes(method, alpha, name, method_type,
corr_kwargs)
self.alpha = alpha
self.statsmodels_api = statsmodels_api
self.name = methods_names.get(self.name, self.name)
func = self.func
while isinstance(func, partial):
func = func.func
self.document(func)
def document(self, func):
self.__doc__ = (
f"ComparisonCorrection wrapper for the function "
f"'{func.__name__}', providing the attributes\n"
f" `name`: {self.name}\n"
f" `type`: {self.type} \n"
f" `alpha (FWER)`: {self.alpha} \n")
if self.method is not None:
self.__doc__ += f" `method`: {self.method} \n"
self.__doc__ += (
f"With\n"
f" type 0 function: Per-pvalue correction with modification\n"
f" type 1 function: Correction of interpretation of set of "
f"pvalues\n"
f"------ Original function documentation ------ \n"
f"{func.__doc__}")
def __call__(self, pvalues: Union[List[float], float],
num_comparisons=None):
try:
# Will raise TypeError if scalar value
n_vals = len(pvalues)
got_pvalues_in_array = True
except TypeError:
n_vals = 1
pvalues =
|
np.array([pvalues])
|
numpy.array
|
# coding=utf-8
import copy
import numpy as np
from numpy import sin, cos
from scipy.io import savemat, loadmat
from petsc4py import PETSc
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from src.support_class import *
import abc
from scipy.special import hyp2f1
from scipy import interpolate, integrate, optimize, sparse
from itertools import compress
from scipy.spatial.transform import Rotation as spR
from src.support_class import *
__all__ = ['base_geo', 'sphere_geo', 'ellipse_base_geo', 'ellipse_3d_geo',
'geoComposit',
'tunnel_geo', 'pipe_cover_geo', 'supHelix', 'FatHelix',
'lineOnFatHelix', 'ThickLine_base_geo',
'SelfRepeat_body_geo', 'SelfRepeat_FatHelix',
'infgeo_1d', 'infHelix', 'infPipe',
'slb_geo', 'slb_helix', 'Johnson_helix', 'expJohnson_helix', 'sphereEnd_helix',
'regularizeDisk', 'helicoid',
'_revolve_geo', 'revolve_pipe', 'revolve_ellipse',
'region', 'set_axes_equal']
class base_geo():
def __init__(self):
self._nodes = np.array([])
self._elems = np.array([])
self._elemtype = ' '
self._normal = np.array([]) # norm of surface at each point.
self._geo_norm = np.array((0, 0, 1)) # describing the aspect of the geo.
self._origin = np.array((0, 0, 0))
self._u = np.array([])
self._deltaLength = 0
self._dmda = None # dof management
self._stencil_width = 0 # --->>>if change in further version, deal with combine method.
self._glbIdx = np.array([]) # global indices
self._glbIdx_all = np.array([]) # global indices for all process.
self._selfIdx = np.array([]) # indices of _glbIdx in _glbIdx_all
self._dof = 3 # degrees of freedom pre node.
self._type = 'general_geo' # geo type
def __str__(self):
return "%s(%r)" % (self.get_type(), id(self))
def mat_nodes(self, filename: str = '..',
mat_handle: str = 'nodes'):
err_msg = 'wrong mat file name. '
assert filename != '..', err_msg
filename = check_file_extension(filename, '.mat')
mat_contents = loadmat(filename)
nodes = mat_contents[mat_handle].astype(np.float, order='F')
err_msg = 'nodes is a n*3 numpy array containing x, y and z coordinates. '
assert nodes.shape[1] == 3, err_msg
self._nodes = nodes
self._u = np.zeros(self._nodes.size)
self.set_dmda()
return True
def mat_elmes(self, filename: str = '..',
mat_handle: str = 'elmes',
elemtype: str = ' '):
err_msg = 'wrong mat file name. '
assert filename != '..', err_msg
mat_contents = loadmat(filename)
elems = mat_contents[mat_handle].astype(np.int, order='F')
elems = elems - elems.min()
self._elems = elems
self._elemtype = elemtype
return True
def text_nodes(self, filename: str = '..'):
err_msg = 'wrong mat file name. '
assert filename != '..', err_msg
nodes = np.loadtxt(filename)
err_msg = 'nodes is a n*3 numpy array containing x, y and z coordinates. '
assert nodes.shape[1] == 3, err_msg
self._nodes = np.asfortranarray(nodes)
self._u = np.zeros(self._nodes.size)
self.set_dmda()
return True
def mat_origin(self, filename: str = '..',
mat_handle: str = 'origin'):
err_msg = 'wrong mat file name. '
assert filename != '..', err_msg
mat_contents = loadmat(filename)
self._origin = mat_contents[mat_handle].astype(np.float)
return True
def mat_velocity(self, filename: str = '..',
mat_handle: str = 'U'):
err_msg = 'wrong mat file name. '
assert filename != '..', err_msg
mat_contents = loadmat(filename)
self._u = mat_contents[mat_handle].flatten()
return True
def node_rotation(self, norm=np.array([0, 0, 1]), theta=0, rotation_origin=None):
rotM = get_rot_matrix(norm, theta)
return self.node_rotM(rotM=rotM, rotation_origin=rotation_origin)
def node_rotM(self, rotM, rotation_origin=None):
# The rotation is counterclockwise
if rotation_origin is None:
rotation_origin = self.get_origin()
else:
rotation_origin = np.array(rotation_origin).reshape((3,))
self._nodes = np.dot(rotM, (self._nodes - rotation_origin).T).T + \
rotation_origin # The rotation is counterclockwise
self._origin = np.dot(rotM, (self._origin - rotation_origin)) + rotation_origin
self._geo_norm = np.dot(rotM, self._geo_norm) / np.linalg.norm(self._geo_norm)
return True
def coord_rotation(self, norm=np.array([0, 0, 1]), theta=0):
# TODO: check the direction.
assert 1 == 2
# theta = -theta # The rotation is counterclockwise
rotation = get_rot_matrix(norm, theta)
temp_u = self._u.reshape((3, -1), order='F')
self._u = rotation.dot(temp_u).T.flatten()
self._nodes = np.dot(rotation, self._nodes.T).T
self._origin = 000
self._geo_norm = 000
return True
def node_zoom(self, factor, zoom_origin=None):
if zoom_origin is None:
zoom_origin = self.get_origin()
self._nodes = (self._nodes - zoom_origin) * factor + zoom_origin
return True
def node_zoom_x(self, factor, zoom_origin=None):
if zoom_origin is None:
zoom_origin = self.get_origin()
self._nodes[:, 0] = (self._nodes[:, 0] - zoom_origin[0]) * factor + zoom_origin[0]
return True
def node_zoom_y(self, factor, zoom_origin=None):
if zoom_origin is None:
zoom_origin = self.get_origin()
self._nodes[:, 1] = (self._nodes[:, 1] - zoom_origin[1]) * factor + zoom_origin[1]
return True
def node_zoom_z(self, factor, zoom_origin=None):
if zoom_origin is None:
zoom_origin = self.get_origin()
self._nodes[:, 2] = (self._nodes[:, 2] - zoom_origin[2]) * factor + zoom_origin[2]
return True
def move(self, displacement: np.array):
displacement = np.array(displacement).reshape((3,))
self.set_nodes(self.get_nodes() + displacement, self.get_deltaLength())
self.set_origin(self.get_origin() + displacement)
return True
def mirrorImage(self, norm=np.array([0, 0, 1]), rotation_origin=None):
if rotation_origin is None:
rotation_origin = self.get_origin()
else:
rotation_origin = np.array(rotation_origin).reshape((3,))
norm = norm / np.linalg.norm(norm)
nodes = self.get_nodes()
dist = nodes - rotation_origin
parallel = np.einsum('i,j', np.einsum('ij,j', dist, norm), norm)
perpendicular = dist - parallel
dist2 = perpendicular + (-1 * parallel)
nodes2 = dist2 + rotation_origin
self.set_nodes(nodes2, self.get_deltaLength())
return True
def combine(self, geo_list, deltaLength=None, origin=None, geo_norm=None):
if len(geo_list) == 0:
return False
for geo1 in geo_list:
err_msg = 'some objects in geo_list are not geo object. %s' % str(type(geo1))
assert isinstance(geo1, base_geo), err_msg
err_msg = 'one or more objects not finished create yet. '
assert geo1.get_n_nodes() != 0, err_msg
if deltaLength is None:
deltaLength = geo_list[0].get_deltaLength()
if origin is None:
origin = geo_list[0].get_origin()
if geo_norm is None:
geo_norm = geo_list[0].get_geo_norm()
geo1 = geo_list.pop(0)
self.set_nodes(geo1.get_nodes(), deltalength=deltaLength)
self.set_velocity(geo1.get_velocity())
for geo1 in geo_list:
self.set_nodes(np.vstack((self.get_nodes(), geo1.get_nodes())), deltalength=deltaLength)
self.set_velocity(np.hstack((self.get_velocity(), geo1.get_velocity())))
self.set_dmda()
self._geo_norm = geo_norm
self.set_origin(origin)
return True
def get_nodes(self):
return self._nodes
def get_nodes_petsc(self):
nodes_petsc = self.get_dmda().createGlobalVector()
nodes_petsc[:] = self._nodes.reshape((3, -1))[:]
nodes_petsc.assemble()
return nodes_petsc
def set_nodes(self, nodes, deltalength, resetVelocity=False):
nodes = np.array(nodes).reshape((-1, 3), order='F')
self._nodes = nodes
self._deltaLength = deltalength
self.set_dmda()
if resetVelocity:
self._u = np.zeros(self._nodes.size)
return True
def get_nodes_x(self):
return self._nodes[:, 0]
def get_nodes_y(self):
return self._nodes[:, 1]
def get_nodes_z(self):
return self._nodes[:, 2]
def get_nodes_x_petsc(self):
x_petsc = self.get_dmda().createGlobalVector()
t_x = np.matlib.repmat(self._nodes[:, 0].reshape((-1, 1)), 1, 3).flatten()
x_petsc[:] = t_x[:]
x_petsc.assemble()
return x_petsc
def get_nodes_y_petsc(self):
y_petsc = self.get_dmda().createGlobalVector()
t_y = np.matlib.repmat(self._nodes[:, 1].reshape((-1, 1)), 1, 3).flatten()
y_petsc[:] = t_y[:]
y_petsc.assemble()
return y_petsc
def get_nodes_z_petsc(self):
z_petsc = self.get_dmda().createGlobalVector()
t_z = np.matlib.repmat(self._nodes[:, 2].reshape((-1, 1)), 1, 3).flatten()
z_petsc[:] = t_z[:]
z_petsc.assemble()
return z_petsc
def get_n_nodes(self):
return self._nodes.shape[0]
def get_n_velocity(self):
return self._u.size
def get_velocity(self):
return self._u.flatten()
def set_velocity(self, velocity):
err_msg = 'set nodes first. '
assert self._nodes.size != 0, err_msg
err_msg = 'velocity is a numpy array having a similar size of nodes. '
assert velocity.size == self._nodes.size, err_msg
self._u = velocity.flatten()
return True
def set_rigid_velocity(self, U=np.zeros(6), center=None):
"""
:type U: np.array
:param U: [u1, u2, u3, w1, w2, w3], velocity and angular velocity.
:type center: np.array
:param center: rotation center.
"""
if center is None:
center = self._origin
center = np.array(center)
err_msg = 'center is a np.array containing 3 scales. '
assert center.size == 3, err_msg
r = self._nodes - center
self._u = np.zeros(self._nodes.size)
self._u[0::3] = U[0] + U[4] * r[:, 2] - U[5] * r[:, 1]
self._u[1::3] = U[1] + U[5] * r[:, 0] - U[3] * r[:, 2]
self._u[2::3] = U[2] + U[3] * r[:, 1] - U[4] * r[:, 0]
return True
def get_velocity_x(self):
return self._u[0::3].flatten()
def get_velocity_y(self):
return self._u[1::3].flatten()
def get_velocity_z(self):
return self._u[2::3].flatten()
def get_polar_coord(self):
phi = np.arctan2(self.get_nodes_y(), self.get_nodes_x())
rho = np.sqrt(self.get_nodes_x() ** 2 + self.get_nodes_y() ** 2)
z = self.get_nodes_z()
return phi, rho, z
def get_normal(self):
return self._normal
def set_normal(self, normal):
self._normal = normal
return True
def get_geo_norm(self):
return self._geo_norm
def set_geo_norm(self, geo_norm):
geo_norm = np.array(geo_norm).ravel()
assert geo_norm.size == 3
self._geo_norm = geo_norm
return True
def get_origin(self):
return self._origin
def get_center(self):
return self.get_origin()
def set_origin(self, origin):
self._origin = np.array(origin).ravel()
assert self._origin.size == 3
return True
def set_center(self, origin):
return self.set_origin(origin=origin)
def get_deltaLength(self):
return self._deltaLength
def set_deltaLength(self, deltaLength):
self._deltaLength = deltaLength
return True
def copy(self) -> 'base_geo':
self.destroy_dmda()
geo2 = copy.deepcopy(self)
self.set_dmda()
geo2.set_dmda()
return geo2
def save_nodes(self, filename):
comm = PETSc.COMM_WORLD.tompi4py()
rank = comm.Get_rank()
filename = check_file_extension(filename, extension='.mat')
if rank == 0:
savemat(filename,
{'nodes': self.get_nodes()},
oned_as='column')
return True
def _show_velocity(self, length_factor=1, show_nodes=True):
comm = PETSc.COMM_WORLD.tompi4py()
rank = comm.Get_rank()
if rank == 0:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# ax.set_aspect('equal')
# Be careful. the axis using in matplotlib is a left-handed coordinate system
if show_nodes:
ax.plot(self.get_nodes_x(), self.get_nodes_y(), self.get_nodes_z(),
linestyle='None', c='b',
marker='o')
INDEX = np.zeros_like(self.get_nodes_z(), dtype=bool)
INDEX[:] = True
length = 1 / np.mean(self._deltaLength) * length_factor
ax.quiver(self.get_nodes_x()[INDEX], self.get_nodes_y()[INDEX],
self.get_nodes_z()[INDEX],
self.get_velocity_x()[INDEX], self.get_velocity_y()[INDEX],
self.get_velocity_z()[INDEX],
color='r', length=length)
# ax.quiver(self.get_nodes_x(), self.get_nodes_y(), self.get_nodes_z(),
# 0, 0, self.get_nodes_z(), length=self._deltaLength * 2)
X = np.hstack((self.get_nodes_x()))
Y = np.hstack((self.get_nodes_y()))
Z = np.hstack((self.get_nodes_z()))
max_range = np.array(
[X.max() - X.min(), Y.max() - Y.min(), Z.max() - Z.min()]).max() / 2.0
mid_x = (X.max() + X.min()) * 0.5
mid_y = (Y.max() + Y.min()) * 0.5
mid_z = (Z.max() + Z.min()) * 0.5
ax.set_xlim(mid_x - max_range, mid_x + max_range)
ax.set_ylim(mid_y - max_range, mid_y + max_range)
ax.set_zlim(mid_z - max_range, mid_z + max_range)
ax.set_xlabel('$x_1$', size='xx-large')
ax.set_ylabel('$x_2$', size='xx-large')
ax.set_zlabel('$x_3$', size='xx-large')
else:
fig = None
return fig
def show_velocity(self, length_factor=1, show_nodes=True):
comm = PETSc.COMM_WORLD.tompi4py()
rank = comm.Get_rank()
self._show_velocity(length_factor=length_factor, show_nodes=show_nodes)
if rank == 0:
plt.grid()
# plt.get_current_fig_manager().window.showMaximized()
plt.show()
return True
def core_show_nodes(self, linestyle='-', marker='.'):
comm = PETSc.COMM_WORLD.tompi4py()
rank = comm.Get_rank()
if rank == 0:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# ax.set_aspect('equal')
ax.plot(self.get_nodes_x(), self.get_nodes_y(), self.get_nodes_z(),
linestyle=linestyle,
color='b',
marker=marker)
X = np.hstack((self.get_nodes_x()))
Y = np.hstack((self.get_nodes_y()))
Z = np.hstack((self.get_nodes_z()))
max_range = np.array([X.max() - X.min(),
Y.max() - Y.min(),
Z.max() - Z.min()]).max() / 2.0
mid_x = (X.max() + X.min()) * 0.5
mid_y = (Y.max() + Y.min()) * 0.5
mid_z = (Z.max() + Z.min()) * 0.5
ax.set_xlim(mid_x - max_range, mid_x + max_range)
ax.set_ylim(mid_y - max_range, mid_y + max_range)
ax.set_zlim(mid_z - max_range, mid_z + max_range)
ax.set_xlabel('$x_1$', size='xx-large')
ax.set_ylabel('$x_2$', size='xx-large')
ax.set_zlabel('$x_3$', size='xx-large')
else:
fig = None
return fig
def show_nodes(self, linestyle='-', marker='.'):
comm = PETSc.COMM_WORLD.tompi4py()
rank = comm.Get_rank()
self.core_show_nodes(linestyle=linestyle, marker=marker)
if rank == 0:
plt.grid()
# plt.get_current_fig_manager().window.showMaximized()
plt.show()
return True
def png_nodes(self, finename, linestyle='-', marker='.'):
comm = PETSc.COMM_WORLD.tompi4py()
rank = comm.Get_rank()
finename = check_file_extension(finename, '.png')
fig = self.core_show_nodes(linestyle=linestyle, marker=marker)
if rank == 0:
fig.set_size_inches(18.5, 10.5)
fig.savefig(finename, dpi=100)
plt.close()
return True
def get_mesh(self):
return self._elems, self._elemtype
def get_dmda(self):
return self._dmda
def set_dmda(self):
if self.get_dmda() is not None:
self._dmda.destroy()
if not hasattr(self, '_dof'):
self._dof = 3
self._dmda = PETSc.DMDA().create(sizes=(self.get_n_nodes(),), dof=self._dof,
stencil_width=self._stencil_width, comm=PETSc.COMM_WORLD)
self._dmda.setFromOptions()
self._dmda.setUp()
# self._dmda.createGlobalVector()
return True
def destroy_dmda(self):
self._dmda.destroy()
self._dmda = None
return True
def get_dof(self):
return self._dof
def set_dof(self, dof):
self._dof = dof
return True
def set_glbIdx(self, indices):
comm = PETSc.COMM_WORLD.tompi4py()
self._glbIdx = indices
self._glbIdx_all = np.hstack(comm.allgather(indices))
self._selfIdx = np.searchsorted(self._glbIdx_all, self._glbIdx)
return True
def set_glbIdx_all(self, indices):
self._glbIdx = []
self._selfIdx = []
self._glbIdx_all = indices
return True
def get_glbIdx(self):
return self._glbIdx, self._glbIdx_all
def get_selfIdx(self):
return self._selfIdx
# def _heaviside(self, n, factor):
# f = lambda x: 1 / (1 + np.exp(-factor * x))
# x = np.linspace(-0.5, 0.5, n)
# return (f(x) - f(-0.5)) / (f(0.5) - f(-0.5))
def get_type(self):
return self._type
def print_info(self):
PETSc.Sys.Print(' %s: norm %s, center %s' %
(str(self), str(self.get_geo_norm()), str(self.get_center())))
return True
def pickmyself_prepare(self):
if not self._dmda is None:
self.destroy_dmda()
return True
class geoComposit(uniqueList):
def __init__(self, liste=[]):
acceptType = base_geo
super().__init__(acceptType=acceptType)
liste = list(tube_flatten((liste,)))
for geoi in liste:
self.append(geoi)
def core_show_nodes(self, linestyle='-', marker='.'):
color_list = ['b', 'g', 'r', 'c', 'm', 'y', 'k', ]
comm = PETSc.COMM_WORLD.tompi4py()
rank = comm.Get_rank()
if len(self) == 0:
return False
if rank == 0:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# ax.set_aspect('equal')
xlim_list = np.zeros((len(self), 2))
ylim_list = np.zeros((len(self), 2))
zlim_list = np.zeros((len(self), 2))
for i0, geo0 in enumerate(self):
if geo0.get_n_nodes() > 0:
ax.plot(geo0.get_nodes_x(), geo0.get_nodes_y(), geo0.get_nodes_z(),
linestyle=linestyle,
color=color_list[i0 % len(color_list)],
marker=marker)
X = np.hstack((geo0.get_nodes_x()))
Y = np.hstack((geo0.get_nodes_y()))
Z = np.hstack((geo0.get_nodes_z()))
max_range = np.array([X.max() - X.min(),
Y.max() - Y.min(),
Z.max() - Z.min()]).max() / 2.0
mid_x = (X.max() + X.min()) * 0.5
mid_y = (Y.max() + Y.min()) * 0.5
mid_z = (Z.max() + Z.min()) * 0.5
xlim_list[i0] = (mid_x - max_range, mid_x + max_range)
ylim_list[i0] = (mid_y - max_range, mid_y + max_range)
zlim_list[i0] = (mid_z - max_range, mid_z + max_range)
else:
xlim_list[i0] = (np.nan, np.nan)
ylim_list[i0] = (np.nan, np.nan)
zlim_list[i0] = (np.nan, np.nan)
ax.set_xlim(np.nanmin(xlim_list), np.nanmax(xlim_list))
ax.set_ylim(np.nanmin(ylim_list), np.nanmax(ylim_list))
ax.set_zlim(np.nanmin(zlim_list), np.nanmax(zlim_list))
ax.set_xlabel('$x_1$', size='xx-large')
ax.set_ylabel('$x_2$', size='xx-large')
ax.set_zlabel('$x_3$', size='xx-large')
set_axes_equal(ax)
else:
fig = None
return fig
def show_nodes(self, linestyle='-', marker='.'):
if len(self) == 0:
return False
comm = PETSc.COMM_WORLD.tompi4py()
rank = comm.Get_rank()
self.core_show_nodes(linestyle=linestyle, marker=marker)
if rank == 0:
plt.grid()
# plt.get_current_fig_manager().window.showMaximized()
plt.show()
return True
def move(self, displacement: np.array):
if len(self) == 0:
return False
else:
for sub_geo in self:
sub_geo.move(displacement=displacement)
return True
class ThickLine_base_geo(base_geo):
def __init__(self):
super().__init__()
self._r = 0 # radius of thick line itself, thick is a cycle.
self._dth = 0 # anglar between nodes in a cycle.
self._axisNodes = np.array([]).reshape((-1, 3))
self._frenetFrame = (np.array([]).reshape((-1, 3)),
np.array([]).reshape((-1, 3)),
np.array([]).reshape((-1, 3)))
self._iscover = [] # start: -1, body: 0, end: 1
self._with_cover = 0
self._factor = 1e-5
self._left_hand = False
self._check_epsilon = True
self._type = '_ThickLine_geo' # geo type
self._cover_strat_idx = np.array([])
self._body_idx_list = []
self._cover_end_idx = np.array([])
self._local_rot = True # special parameter for selfrepeat_geo
self._node_axisNode_idx = []
def set_check_epsilon(self, check_epsilon):
self._check_epsilon = check_epsilon
return True
def get_check_epsilon(self):
return self._check_epsilon
def _get_theta(self):
def eqr(dth, ds, r):
return (ds / (2 * r)) ^ 2 + np.sin(dth / 4) ** 2 - np.sin(dth / 2) ** 2
from scipy import optimize as sop
self._dth = sop.brentq(eqr, -1e-3 * np.pi, np.pi, args=(self.get_deltaLength(), self._r))
return self._dth
def _get_deltalength(self):
# dl = 2 * self._r * np.sqrt(np.sin(self._dth / 2) ** 2 - np.sin(self._dth / 4) ** 2)
dl = 2 * self._r * np.sin(self._dth / 2)
self.set_deltaLength(dl)
return dl
@abc.abstractmethod
def _get_axis(self):
return
@abc.abstractmethod
def _get_fgeo_axis(self, epsilon):
return
@abc.abstractmethod
def _body_pretreatment(self, nodes, **kwargs):
return
@abc.abstractmethod
def _strat_pretreatment(self, nodes, **kwargs):
return
@abc.abstractmethod
def _end_pretreatment(self, nodes, **kwargs):
return
def _create_deltatheta(self, dth: float, # delta theta of the cycle for the mesh
radius: float, # radius of the cycle
epsilon=0, with_cover=0, local_rot=True):
# the tunnel is along z axis
err_msg = 'dth must less than pi'
assert dth < np.pi, err_msg
self._dth = dth
self._r = radius
self._with_cover = with_cover
deltalength = self._get_deltalength()
nc = np.ceil(2 * np.pi / dth).astype(int)
angleCycle = np.linspace(0, 2 * np.pi, nc, endpoint=False)
axisNodes, T_frame, N_frame, B_frame = self._get_axis()
fgeo_axisNodes, fgeo_T_frame, fgeo_N_frame, fgeo_B_frame = self._get_fgeo_axis(epsilon)
iscover = []
vgeo_nodes = []
fgeo_nodes = []
epsilon = (radius + epsilon * deltalength) / radius
if self.get_check_epsilon():
err_msg = 'epsilon > %f. ' % (-radius / deltalength)
assert epsilon > 0, err_msg
ai_para = 0
t_node_idx = 0
local_rot = self._local_rot
self._node_axisNode_idx = []
self._body_idx_list = []
# cover at start
if with_cover == 1:
# old version, cover is a plate.
nc = np.ceil((radius - deltalength) / deltalength).astype(int)
ri = np.linspace(deltalength / 2, radius, nc, endpoint=False)
# self
tidx = 0
for i0 in np.arange(0, nc):
ai_para = ai_para + 1 if local_rot else 0
ni = np.ceil(2 * np.pi * ri[i0] / deltalength).astype(int)
ai = np.linspace(0, 2 * np.pi, ni, endpoint=False) + (-1) ** ai_para * dth / 4
iscover.append(np.ones_like(ai) * -1)
nodes_cycle = np.vstack(
(np.cos(ai) * ri[i0], np.sin(ai) * ri[i0], np.zeros_like(ai))).T
t_nodes = axisNodes[0] + np.dot(nodes_cycle,
np.vstack((N_frame[0], B_frame[0],
np.zeros_like(T_frame[0]))))
vgeo_nodes.append(t_nodes)
tidx = tidx + t_nodes.shape[0]
tf_nodes = fgeo_axisNodes[0] + np.dot(nodes_cycle * epsilon,
np.vstack((N_frame[0], B_frame[0],
np.zeros_like(T_frame[0]))))
fgeo_nodes.append(tf_nodes)
self._strat_pretreatment(t_nodes)
self._cover_strat_idx = np.arange(len(vgeo_nodes))
t_node_idx = self._cover_strat_idx[-1] + 1 if self._cover_strat_idx.size > 0 else 0
self._node_axisNode_idx.append(np.zeros(tidx))
elif with_cover == 2:
# 20170929, new version, cover is a hemisphere
vhsgeo = sphere_geo()
vhsgeo.create_half_delta(deltalength, radius)
vhsgeo.node_rotation((1, 0, 0), np.pi / 2 + ai_para)
t_nodes = axisNodes[0] + np.dot(vhsgeo.get_nodes(),
np.vstack((-T_frame[0], N_frame[0], B_frame[0])))
vgeo_nodes.append(t_nodes)
self._cover_strat_idx = np.arange(t_nodes.shape[0]) + t_node_idx
t_node_idx = self._cover_strat_idx[-1] + 1
fhsgeo = vhsgeo.copy()
# fhsgeo.show_nodes()
fhsgeo.node_zoom(epsilon)
# fhsgeo.show_nodes()
tf_nodes = fgeo_axisNodes[0] + np.dot(fhsgeo.get_nodes(),
np.vstack((-T_frame[0], N_frame[0], B_frame[0])))
fgeo_nodes.append(tf_nodes)
self._strat_pretreatment(t_nodes)
iscover.append(np.ones(vhsgeo.get_n_nodes()) * -1)
self._node_axisNode_idx.append(np.zeros(vhsgeo.get_n_nodes()))
# body
for i0, nodei_line in enumerate(axisNodes):
ai_para = ai_para + 1 if local_rot else 0
ai = angleCycle + (-1) ** ai_para * dth / 4
nodes_cycle = np.vstack((np.cos(ai) * radius, np.sin(ai) * radius, np.zeros_like(ai))).T
t_nodes = nodei_line + np.dot(nodes_cycle,
np.vstack((N_frame[i0], B_frame[i0],
np.zeros_like(T_frame[i0]))))
vgeo_nodes.append(t_nodes)
self._body_idx_list.append(np.arange(t_nodes.shape[0]) + t_node_idx)
t_node_idx = self._body_idx_list[-1][-1] + 1
iscover.append(np.zeros_like(ai))
nodes_cycle = np.vstack(
(np.cos(ai) * radius, np.sin(ai) * radius, np.zeros_like(ai))).T * epsilon
tf_nodes = fgeo_axisNodes[i0] + np.dot(nodes_cycle, np.vstack(
(fgeo_N_frame[i0], fgeo_B_frame[i0], np.zeros_like(fgeo_T_frame[i0]))))
fgeo_nodes.append(tf_nodes)
self._body_pretreatment(t_nodes)
self._node_axisNode_idx.append(np.ones(ai.size) * i0)
self._body_idx_list = np.array(self._body_idx_list)
# cover at end
if with_cover == 1:
# old version, cover is a plate.
nc = np.ceil((radius - deltalength) / deltalength).astype(int)
ri = np.linspace(deltalength / 2, radius, nc, endpoint=False)[-1::-1]
tidx = 0
for i0 in np.arange(0, nc):
ai_para = ai_para + 1 if local_rot else 0
ni = np.ceil(2 * np.pi * ri[i0] / deltalength).astype(int)
ai = np.linspace(0, 2 * np.pi, ni, endpoint=False) + (-1) ** ai_para * dth / 4
iscover.append(np.ones_like(ai))
nodes_cycle = np.vstack(
(np.cos(ai) * ri[i0], np.sin(ai) * ri[i0], np.zeros_like(ai))).T
t_nodes = axisNodes[-1] + np.dot(nodes_cycle,
np.vstack((N_frame[-1], B_frame[-1],
np.zeros_like(T_frame[-1]))))
vgeo_nodes.append(t_nodes)
tidx = tidx + t_nodes.shape[0]
tf_nodes = fgeo_axisNodes[-1] + np.dot(nodes_cycle * epsilon, np.vstack(
(fgeo_N_frame[-1], fgeo_B_frame[-1], np.zeros_like(fgeo_T_frame[-1]))))
fgeo_nodes.append(tf_nodes)
self._end_pretreatment(t_nodes)
self._cover_end_idx = np.arange(len(vgeo_nodes) - t_node_idx) + t_node_idx
self._node_axisNode_idx.append(np.ones(tidx) * (axisNodes.shape[0] - 1))
elif with_cover == 2:
# 20170929, new version, cover is a hemisphere
vhsgeo = sphere_geo()
vhsgeo.create_half_delta(deltalength, radius)
vhsgeo.node_rotation((1, 0, 0), -np.pi / 2 - ai_para)
t_nodes = axisNodes[-1] + np.dot(vhsgeo.get_nodes(),
np.vstack((T_frame[-1], N_frame[-1], B_frame[-1])))
vgeo_nodes.append(np.flipud(t_nodes))
self._cover_end_idx = np.arange(t_nodes.shape[0]) + t_node_idx
fhsgeo = vhsgeo.copy()
fhsgeo.node_zoom(epsilon)
tf_nodes = fgeo_axisNodes[-1] + np.dot(fhsgeo.get_nodes(),
np.vstack(
(T_frame[-1], N_frame[-1], B_frame[-1])))
fgeo_nodes.append(np.flipud(tf_nodes))
self._end_pretreatment(t_nodes)
iscover.append(np.ones(vhsgeo.get_n_nodes()))
self._node_axisNode_idx.append(np.ones(vhsgeo.get_n_nodes()) * (axisNodes.shape[0] - 1))
self._iscover = np.hstack(iscover)
self._nodes = np.asfortranarray(np.vstack(vgeo_nodes))
self.set_dmda()
self._u = np.zeros(self._nodes.size)
self._normal = np.zeros((self._nodes.shape[0], 2), order='F')
self._node_axisNode_idx = np.hstack(self._node_axisNode_idx).astype('int')
fgeo = self.copy()
# fgeo.set_dof(self.get_dof())
fgeo.set_nodes(np.asfortranarray(np.vstack(fgeo_nodes)), deltalength=deltalength * epsilon,
resetVelocity=True)
return fgeo
def get_iscover(self):
return self._iscover
def _factor_fun(self, n, factor):
err_msg = 'factor must positive'
assert factor > 0, err_msg
if np.abs(factor - 1) < 0.01:
y = np.linspace(0, 1, n)
else:
f1 = lambda x: (np.exp(x * factor) - 1) / (2 * (np.exp(0.5 * factor) - 1))
f2 = lambda x: np.log(2 * (np.exp(0.5 / factor) - 1) * x + 1) * factor
x = np.linspace(-0.5, 0.5, n)
y1 = np.sign(x) * f1(np.abs(x)) + 0.5
y2 = np.sign(x) * f2(np.abs(x)) + 0.5
y = (y1 * factor + y2 / factor) / (y1[-1] * factor + y2[-1] / factor)
return y
@property
def axisNodes(self):
return self._axisNodes
@property
def frenetFrame(self):
return self._frenetFrame
@property
def cover_strat_idx(self):
return self._cover_strat_idx
@property
def body_idx_list(self):
return self._body_idx_list
@property
def cover_end_idx(self):
return self._cover_end_idx
@property
def with_cover(self):
return self._with_cover
@property
def cover_start_nodes(self):
return self.get_nodes()[self.cover_strat_idx]
@property
def body_nodes_list(self):
return [self.get_nodes()[tidx] for tidx in self.body_idx_list]
@property
def cover_end_nodes(self):
return self.get_nodes()[self.cover_end_idx]
@property
def node_axisNode_idx(self):
return self._node_axisNode_idx
@property
def left_hand(self):
return self.left_hand
# def node_rotation(self, norm=np.array([0, 0, 1]), theta=0, rotation_origin=None):
# # The rotation is counterclockwise
# super().node_rotation(norm, theta, rotation_origin)
#
# if rotation_origin is None:
# rotation_origin = self.get_origin()
# else:
# rotation_origin = np.array(rotation_origin).reshape((3,))
#
# rotation = get_rot_matrix(norm, theta)
# t_axisNodes = self._axisNodes
# self._axisNodes = np.dot(rotation, (self._axisNodes - rotation_origin).T).T + \
# rotation_origin # The rotation is counterclockwise
# t0 = []
# for i0 in range(3):
# t1 = []
# for t2, taxis0, taxis in zip(self._frenetFrame[i0], t_axisNodes, self._axisNodes):
# t2 = np.dot(rotation, (t2 + taxis0 - rotation_origin)) \
# + rotation_origin - taxis
# t2 = t2 / np.linalg.norm(t2)
# t1.append(t2)
# t0.append(np.vstack(t1))
# self._frenetFrame = t0
# return True
def node_rotM(self, rotM, rotation_origin=None):
# The rotation is counterclockwise
super().node_rotM(rotM, rotation_origin)
if rotation_origin is None:
rotation_origin = self.get_origin()
else:
rotation_origin = np.array(rotation_origin).reshape((3,))
t_axisNodes = self._axisNodes
self._axisNodes = np.dot(rotM, (self._axisNodes - rotation_origin).T).T + \
rotation_origin # The rotation is counterclockwise
t0 = []
for i0 in range(3):
t1 = []
for t2, taxis0, taxis in zip(self._frenetFrame[i0], t_axisNodes, self._axisNodes):
t2 = np.dot(rotM, (t2 + taxis0 - rotation_origin)) \
+ rotation_origin - taxis
t2 = t2 / np.linalg.norm(t2)
t1.append(t2)
t0.append(np.vstack(t1))
self._frenetFrame = t0
return True
def move(self, displacement: np.array):
super().move(displacement)
displacement = np.array(displacement).reshape((3,))
self._axisNodes = self._axisNodes + displacement
return True
def nodes_local_coord(self, nodes, axis_idx):
tnode_line = self.axisNodes[axis_idx]
tT = self.frenetFrame[0][axis_idx]
tN = self.frenetFrame[1][axis_idx]
tB = self.frenetFrame[2][axis_idx]
tfnodes_local = np.dot((nodes - tnode_line), np.vstack((tN, tB, tT)).T)
return tfnodes_local
def selfnodes_local_coord(self, axis_idx):
nodes = self.get_nodes()[self.body_idx_list[axis_idx]]
return self.nodes_local_coord(nodes, axis_idx)
def force_local_coord(self, force, axis_idx):
tT = self.frenetFrame[0][axis_idx]
tN = self.frenetFrame[1][axis_idx]
tB = self.frenetFrame[2][axis_idx]
tfi_local = np.dot(force, np.vstack((tN, tB, tT)).T)
return tfi_local
def frenetFrame_local(self, axis_idx):
tT = self.frenetFrame[0][axis_idx]
tN = self.frenetFrame[1][axis_idx]
tB = self.frenetFrame[2][axis_idx]
return tT, tN, tB
class ellipse_base_geo(base_geo):
def __init__(self):
super().__init__()
self._type = 'ellipse_geo' # geo type
def create_n(self, n: int, # number of nodes.
headA: float, # major axis = 2*headA
headC: float): # minor axis = 2*headC
err_msg = 'both major and minor axises should positive. '
assert headA > 0 and headC > 0, err_msg
jj = np.arange(n)
xlocH = -1 + 2 * jj / (n - 1)
numf = 0.5
prefac = 3.6 * np.sqrt(headC / headA)
spherePhi = np.ones(n)
for i0 in range(0, n):
if i0 == 0 or i0 == n - 1:
spherePhi[i0] = 0
else:
tr = np.sqrt(1 - xlocH[i0] ** 2)
wgt = prefac * (1 - numf * (1 - tr)) / tr
spherePhi[i0] = (spherePhi[i0 - 1] + wgt / np.sqrt(n)) % (2 * np.pi)
tsin = np.sqrt(1 - xlocH ** 2)
self._nodes = np.zeros((n, 3), order='F')
self._nodes[:, 0] = headC * xlocH
self._nodes[:, 1] = headA * tsin * np.cos(spherePhi)
self._nodes[:, 2] = headA * tsin * np.sin(spherePhi)
self.set_dmda()
self._u = np.zeros(self._nodes.size)
self._normal = np.zeros((n, 2), order='F')
return True
def create_delta(self, ds: float, # length of the mesh
a: float, # axis1 = 2*a
b: float): # axis2 = 2*b
err_msg = 'both major and minor axises should positive. '
assert a > 0 and b > 0, err_msg
self._deltaLength = ds
# fit arc length as function F of theta using 2-degree pylonomial
from scipy.special import ellipeinc
from scipy.optimize import curve_fit
func = lambda theta, a, b: a * theta ** 2 + b * theta
theta = np.linspace(0, np.pi / 2, 100)
arcl = b * ellipeinc(theta, 1 - (a / b) ** 2)
popt, _ = curve_fit(func, theta, arcl)
# # dbg
# plt.plot(theta, arcl, '.')
# plt.plot(theta, func(theta, popt[0], popt[1]))
# plt.show()
# assert 1 == 2
# divided arc length equally, and get theta using F^-1.
n = np.ceil(arcl[-1] / ds).astype(int)
t_arcl = np.linspace(0, arcl[-1], n, endpoint=False) + ds / 2
# do something to correct the fitting error.
while t_arcl[-1] > arcl[-1]:
t_arcl = t_arcl[:-1]
t_theta1 = (-popt[1] + np.sqrt(popt[1] ** 2 + 4 * popt[0] * t_arcl)) / (2 * popt[0])
t_theta2 = (-popt[1] - np.sqrt(popt[1] ** 2 + 4 * popt[0] * t_arcl)) / (2 * popt[0])
b_theta1 = [a and b for a, b in zip(t_theta1 > 0, t_theta1 < np.pi / 2)]
b_theta2 = [a and b for a, b in zip(t_theta2 > 0, t_theta2 < np.pi / 2)]
err_msg = 'something is wrong, theta of ellipse is uncertain. '
assert all([a != b for a, b in zip(b_theta1, b_theta2)]), err_msg
t_theta0 = t_theta1 * b_theta1 + t_theta2 * b_theta2
t_theta = np.hstack((t_theta0, np.pi / 2, np.pi - t_theta0[::-1]))
t_x = a * np.cos(t_theta)
t_y = b * np.sin(t_theta)
# generate nodes.
x = []
y = []
z = []
ai_para = 0
for xi, yi in zip(t_x, t_y):
ai_para = ai_para + 1
ni = np.ceil(2 * np.pi * yi / ds).astype(int)
ai, da = np.linspace(0, 2 * np.pi, ni, endpoint=False, retstep=True)
ai = ai + (-1) ** ai_para * da / 4 + np.sign(xi) * np.pi / 2
x.append(xi * np.ones_like(ai))
y.append(np.sign(xi) * yi * np.cos(ai))
z.append(np.sign(xi) * yi * np.sin(ai))
self._nodes = np.vstack((np.hstack(x), np.hstack(y), np.hstack(z))).T
self.set_dmda()
self._u = np.zeros(self._nodes.size)
self._normal = np.zeros((self._nodes.shape[0], 2), order='F')
self._geo_norm = np.array((1, 0, 0))
return True
def create_half_delta(self, ds: float, # length of the mesh
a: float, # axis1 = 2*a
b: float): # axis2 = 2*b
err_msg = 'both major and minor axises should positive. '
assert a > 0 and b > 0, err_msg
self._deltaLength = ds
# fit arc length as function F of theta using 2-degree pylonomial
from scipy.special import ellipeinc
from scipy.optimize import curve_fit
func = lambda theta, a, b: a * theta ** 2 + b * theta
theta = np.linspace(0, np.pi / 2, 100)
arcl = b * ellipeinc(theta, 1 - (a / b) ** 2)
popt, _ = curve_fit(func, theta, arcl)
# # dbg
# plt.plot(theta, arcl, '.')
# plt.plot(theta, func(theta, popt[0], popt[1]))
# plt.show()
# assert 1 == 2
# divided arc length equally, and get theta using F^-1.
n = np.ceil(arcl[-1] / ds).astype(int)
t_arcl = np.linspace(0, arcl[-1], n, endpoint=False) + ds / 2
# do something to correct the fitting error.
while t_arcl[-1] > arcl[-1]:
t_arcl = t_arcl[:-1]
t_theta1 = (-popt[1] + np.sqrt(popt[1] ** 2 + 4 * popt[0] * t_arcl)) / (2 * popt[0])
t_theta2 = (-popt[1] - np.sqrt(popt[1] ** 2 + 4 * popt[0] * t_arcl)) / (2 * popt[0])
b_theta1 = [a and b for a, b in zip(t_theta1 > 0, t_theta1 < np.pi / 2)]
b_theta2 = [a and b for a, b in zip(t_theta2 > 0, t_theta2 < np.pi / 2)]
err_msg = 'something is wrong, theta of ellipse is uncertain. '
assert all([a != b for a, b in zip(b_theta1, b_theta2)]), err_msg
t_theta0 = t_theta1 * b_theta1 + t_theta2 * b_theta2
t_x = a * np.cos(t_theta0)
t_y = b * np.sin(t_theta0)
# generate nodes.
x = []
y = []
z = []
ai_para = 0
for xi, yi in zip(t_x, t_y):
ai_para = ai_para + 1
ni = np.ceil(2 * np.pi * yi / ds).astype(int)
ai, da = np.linspace(0, 2 * np.pi, ni, endpoint=False, retstep=True)
ai = ai + (-1) ** ai_para * da / 4 + np.sign(xi) * np.pi / 2
x.append(xi * np.ones_like(ai))
y.append(np.sign(xi) * yi * np.cos(ai))
z.append(np.sign(xi) * yi * np.sin(ai))
self._nodes = np.vstack((np.hstack(x), np.hstack(y), np.hstack(z))).T
self.set_dmda()
self._u = np.zeros(self._nodes.size)
self._normal = np.zeros((self._nodes.shape[0], 2), order='F')
return True
class ellipse_3d_geo(base_geo):
def __init__(self):
super().__init__()
self._type = 'ellipse_3d_geo' # geo type
def create_delta(self, ds: float, # length of the mesh
a: float, # axis1 = 2*a
b1: float, b2: float): # axis2 = 2*b
tgeo = ellipse_base_geo()
tgeo.create_delta(ds, a, b1)
tnode = tgeo.get_nodes()
tnode[:, 2] = tnode[:, 2] / b1 * b2
self._deltaLength = ds
self._nodes = tnode
self.set_dmda()
self._u = np.zeros(self._nodes.size)
self._normal = np.zeros((self._nodes.shape[0], 2), order='F')
self._geo_norm = np.array((1, 0, 0))
return True
class sphere_geo(ellipse_base_geo):
def __init__(self):
super().__init__()
self._type = 'sphere_geo' # geo type
def create_n(self, n: int, # number of nodes.
radius: float, *args): # radius
err_msg = 'additional parameters are useless. '
assert not args, err_msg
self._deltaLength = np.sqrt(4 * np.pi * radius * radius / n)
return super().create_n(n, radius, radius)
def create_delta(self, deltaLength: float, # length of the mesh
radius: float, *args): # radius
err_msg = 'additional parameters are useless. '
assert not args, err_msg
return super().create_delta(deltaLength, radius, radius)
def create_half_delta(self, ds: float, # length of the mesh
a: float, *args):
err_msg = 'additional parameters are useless. '
assert not args, err_msg
return super().create_half_delta(ds, a, a)
def normal(self):
self._normal = np.zeros((self._nodes.shape[0],
2)) # {Sin[a] Sin[b], -Cos[a] Sin[b], Cos[b]} = {n1, n2, n3} is the normal vector
normal_vector = self._nodes / np.sqrt(
self._nodes[:, 0] ** 2 + self._nodes[:, 1] ** 2 + self._nodes[:, 2] ** 2).reshape(
self._nodes.shape[0],
1)
self._normal[:, 1] = np.arccos(normal_vector[:, 2]) # b
self._normal[:, 0] = np.arcsin(normal_vector[:, 0] / np.sin(self._normal[:, 1])) # a
return True
# noinspection PyUnresolvedReferences
class tunnel_geo(ThickLine_base_geo):
def __init__(self):
super().__init__()
self._length = 0
self._cover_strat_list = []
self._cover_end_list = []
self._type = 'tunnel_geo' # geo type
def create_n(self, n: int, # number of nodes.
length: float, # length of the tunnel
radius: float): # radius of the tunnel
deltaLength = np.sqrt(2 * np.pi * radius * length / n)
self._deltaLength = deltaLength
deltaTheta = deltaLength / radius
# the geo is symmetrical
if n % 2: # if n is odd
n_half = int((n - 1) / 2)
theta = np.arange(-n_half, n_half + 1) * deltaTheta
else: # if n is even
n_half = int(n / 2)
theta = np.arange(-n_half, n_half) * deltaTheta + deltaTheta / 2
self._nodes = np.zeros((n, 3), order='F')
self._nodes[:, 0] = deltaLength * theta / 2 / np.pi
self._nodes[:, 1] = radius * np.sin(theta)
self._nodes[:, 2] = radius * np.cos(theta)
self.set_dmda()
self._u = np.zeros(self._nodes.size)
self._normal = np.zeros((n, 2), order='F')
self._geo_norm = np.array((1, 0, 0))
return True
def create_deltalength(self, deltaLength: float, # length of the mesh
length: float, # length of the tunnel
radius: float): # radius of the tunnel
# the tunnel is along z axis
self._deltaLength = deltaLength
a = np.arange(0, 2 * np.pi - deltaLength / radius / 2, deltaLength / radius)
x, y = np.cos(a) * radius, np.sin(a) * radius
z = np.linspace(-length / 2, length / 2, num=np.ceil((length / deltaLength)).astype(int))
n_a, n_z = a.size, z.size
self._nodes = np.zeros((n_a * n_z, 3), order='F')
self._nodes[:, 0] = np.tile(z, n_a).reshape(n_a, -1).flatten(order='F')
self._nodes[:, 1] = np.tile(x, (n_z, 1)).reshape(-1, 1).flatten(order='F')
self._nodes[:, 2] = np.tile(y, (n_z, 1)).reshape(-1, 1).flatten(order='F')
self.set_dmda()
self._u = np.zeros(self._nodes.size)
self._normal = np.zeros((self._nodes.shape[0], 2), order='F')
self._geo_norm = np.array((0, 0, 1))
return True
def create_deltatheta(self, dth: float, # delta theta of the cycle for the mesh
radius: float,
length: float,
epsilon=0,
with_cover=0,
factor=1,
left_hand=False):
self._length = length
self._factor = factor
self._left_hand = left_hand
self._geo_norm = np.array((0, 0, 1))
return self._create_deltatheta(dth, radius, epsilon, with_cover)
def _get_axis(self):
length = self._length
factor = self._factor
left_hand = self._left_hand
ds = self.get_deltaLength()
nl = np.ceil(length / ds).astype(int)
z = self._factor_fun(nl, factor) * length - length / 2
self._axisNodes = np.vstack((np.zeros_like(z), np.zeros_like(z), z)).T
if left_hand:
T_frame = np.vstack((np.zeros(nl), np.zeros(nl), np.ones(nl))).T # (0, 0, 1)
N_frame = np.vstack((np.ones(nl), np.zeros(nl), np.zeros(nl))).T # (1, 0, 0)
B_frame = np.vstack((np.zeros(nl), np.ones(nl), np.zeros(nl))).T # (0, 1, 0)
else:
T_frame = np.vstack((np.zeros(nl), np.zeros(nl), np.ones(nl))).T # (0, 0, 1)
N_frame = np.vstack((np.zeros(nl), np.ones(nl), np.zeros(nl))).T # (0, 1, 0)
B_frame = np.vstack((np.ones(nl), np.zeros(nl), np.zeros(nl))).T # (1, 0, 0)
self._frenetFrame = (T_frame, N_frame, B_frame)
return self._axisNodes, self._frenetFrame[0], self._frenetFrame[1], self._frenetFrame[2]
def _get_fgeo_axis(self, epsilon):
length = self._length
factor = self._factor
nl = self._axisNodes.shape[0]
ds = -self.get_deltaLength() * epsilon / 4
z = self._factor_fun(nl, factor) * (length - ds * 2) - length / 2 + ds
axisNodes = np.vstack((np.zeros_like(z), np.zeros_like(z), z)).T
return axisNodes, self._frenetFrame[0], self._frenetFrame[1], self._frenetFrame[2]
def _strat_pretreatment(self, nodes, **kwargs):
def cart2pol(x, y):
rho = np.sqrt(x ** 2 + y ** 2)
phi = np.arctan2(y, x)
return rho, phi
r, ai = cart2pol(nodes[:, 0], nodes[:, 1])
self._cover_strat_list.append((np.mean(r), ai, np.mean(nodes[:, 2])))
return True
def _end_pretreatment(self, nodes, **kwargs):
def cart2pol(x, y):
rho = np.sqrt(x ** 2 + y ** 2)
phi = np.arctan2(y, x)
return (rho, phi)
r, ai = cart2pol(nodes[:, 0], nodes[:, 1])
self._cover_end_list.append((np.mean(r), ai, np.mean(nodes[:, 2])))
return True
def get_cover_start_list(self):
return self._cover_strat_list
def get_cover_end_list(self):
return self._cover_end_list
def normal(self):
self._normal = np.zeros((self._nodes.shape[0],
2)) # {Sin[a] Sin[b], -Cos[a] Sin[b], Cos[b]} = {n1, n2, n3} is the normal vector
normal_vector = -1 * self._nodes / np.sqrt(
self._nodes[:, 1] ** 2 + self._nodes[:, 2] ** 2).reshape(
self._nodes.shape[0], 1) # -1 means swap direction
self._normal[:, 1] = np.arccos(normal_vector[:, 2]) # b
self._normal[:, 0] = 0 # a
return True
def node_zoom_radius(self, factor):
def cart2pol(x, y):
rho = np.sqrt(x ** 2 + y ** 2)
phi = np.arctan2(y, x)
return rho, phi
def pol2cart(rho, phi):
x = rho * np.cos(phi)
y = rho * np.sin(phi)
return x, y
# zooming geo along radius of tunnel, keep longitude axis.
# 1. copy
temp_geo = base_geo()
temp_nodes = self.get_nodes() - self.get_origin()
temp_geo.set_nodes(temp_nodes, self.get_deltaLength())
# temp_geo.show_nodes()
# 2. rotation, tunnel center line along x axis.
temp_norm = self._geo_norm
rotation_norm = np.cross(temp_norm, [1, 0, 0])
temp_theta = -np.arccos(temp_norm[0] / np.linalg.norm(temp_norm))
doRotation = (not np.array_equal(rotation_norm, np.array((0, 0, 0)))) and temp_theta != 0.
if doRotation:
temp_geo.node_rotation(rotation_norm, temp_theta)
# 3. zooming
temp_nodes = temp_geo.get_nodes()
temp_R, temp_phi = cart2pol(temp_nodes[:, 1], temp_nodes[:, 2])
temp_R = temp_R * factor
X1 = np.min(temp_nodes[:, 0])
X2 = np.max(temp_nodes[:, 0])
factor = (factor - 1) / 2 + 1
temp_nodes[:, 0] = (temp_nodes[:, 0] - (X1 + X2) / 2) * factor + (X1 + X2) / 2
temp_nodes[:, 1], temp_nodes[:, 2] = pol2cart(temp_R, temp_phi)
temp_geo.set_nodes(temp_nodes, self.get_deltaLength())
# 4. rotation back
if doRotation:
temp_geo.node_rotation(rotation_norm, -temp_theta)
# 5. set
# temp_geo.show_nodes()
self.set_nodes(temp_geo.get_nodes() + self.get_origin(), self.get_deltaLength())
return True
class _revolve_geo(base_geo):
def __init__(self):
super().__init__()
def create_full_geo(self, n_c):
# rotate alone z axis
def rot_nodes(nodes):
r = nodes[:, 0]
z = nodes[:, 2]
theta = np.linspace(0, 2 * np.pi, n_c, endpoint=False)
x = np.outer(r, np.cos(theta)).flatten()
y = np.outer(r, np.sin(theta)).flatten()
z = np.outer(z, np.ones_like(theta)).flatten()
nodes = np.vstack((x, y, z)).T
return nodes
self.set_nodes(rot_nodes(self.get_nodes()), self.get_deltaLength(), resetVelocity=True)
return True
class revolve_ellipse(_revolve_geo):
def __init__(self):
super().__init__()
self._length = 0
self._radius = 0
self._type = 'revolve_ellipse'
def create_deltaz(self, ds: float, # length of the mesh
a: float, # axis1 = 2*a
b: float): # axis2 = 2*b
epsilon1 = 1 / 3
epsilon2 = 0.3
err_msg = 'both major and minor axises should positive. '
assert a > 0 and b > 0, err_msg
self._deltaLength = ds
n_2 = np.ceil(a / 2 / ds).astype(int)
dz = a / n_2
z0 = np.linspace(a - dz / 2, dz / 2, n_2)
z1 = np.hstack([z0, np.flipud(z0) * -1])
x1 = np.sqrt(b ** 2 * (1 - (z1 / a) ** 2))
# generate nodes.
self._nodes = np.zeros((x1.size, 3), order='F')
self._nodes[:, 0] = x1.flatten(order='F')
self._nodes[:, 2] = z1.flatten(order='F')
self.set_dmda()
self._u = np.zeros(self._nodes.size)
self._normal = np.zeros((self._nodes.shape[0], 2), order='F')
self._geo_norm = np.array((0, 0, 1))
# associated force geo
move_delta = dz * epsilon1
z0 = z0 - move_delta
z1 = np.hstack([z0, np.flipud(z0) * -1])
dx = x1 / b * dz * epsilon2
x1 = x1 - dx
f_geo = self.copy()
fnodes = np.vstack((x1, np.zeros_like(x1), z1)).T
f_geo.set_nodes(fnodes, 1)
return f_geo
def create_half_deltaz(self, ds: float, # length of the mesh
a: float, # axis1 = 2*a
b: float): # axis2 = 2*b
epsilon1 = 1 / 3
epsilon2 = 0.3
err_msg = 'both major and minor axises should positive. '
assert a > 0 and b > 0, err_msg
self._deltaLength = ds
n_2 = np.ceil(a / 2 / ds).astype(int)
dz = a / n_2
z1 = np.linspace(a - dz / 2, dz / 2, n_2)
x1 = np.sqrt(b ** 2 * (1 - (z1 / a) ** 2))
# generate nodes.
self._nodes = np.zeros((x1.size, 3), order='F')
self._nodes[:, 0] = x1.flatten(order='F')
self._nodes[:, 2] = z1.flatten(order='F')
self.set_dmda()
self._u = np.zeros(self._nodes.size)
self._normal = np.zeros((self._nodes.shape[0], 2), order='F')
self._geo_norm = np.array((0, 0, 1))
# associated force geo
move_delta = dz * epsilon1
z1 = z1 - move_delta
dx = x1 / b * dz * epsilon2
x1 = x1 - dx
f_geo = self.copy()
fnodes = np.vstack((x1, np.zeros_like(x1), z1)).T
f_geo.set_nodes(fnodes, 1)
return f_geo
def create_delta(self, ds: float, # length of the mesh
a: float, # axis1 = 2*a
b: float, # axis2 = 2*b
epsilon):
err_msg = 'both major and minor axises should positive. '
assert a > 0 and b > 0, err_msg
self._deltaLength = ds
# fit arc length as function F of theta using 2-degree pylonomial
from scipy.special import ellipeinc
from scipy.optimize import curve_fit
func = lambda theta, a, b: a * theta ** 2 + b * theta
theta = np.linspace(0, np.pi / 2, 100)
arcl = b * ellipeinc(theta, 1 - (a / b) ** 2)
popt, _ = curve_fit(func, theta, arcl)
# divided arc length equally, and get theta using F^-1.
n = np.ceil(arcl[-1] / ds).astype(int)
t_arcl = np.linspace(0, arcl[-1], n, endpoint=False) + ds / 2
# do something to correct the fitting error.
while t_arcl[-1] > arcl[-1]:
t_arcl = t_arcl[:-1]
t_theta1 = (-popt[1] + np.sqrt(popt[1] ** 2 + 4 * popt[0] * t_arcl)) / (2 * popt[0])
t_theta2 = (-popt[1] - np.sqrt(popt[1] ** 2 + 4 * popt[0] * t_arcl)) / (2 * popt[0])
b_theta1 = [a and b for a, b in zip(t_theta1 > 0, t_theta1 < np.pi / 2)]
b_theta2 = [a and b for a, b in zip(t_theta2 > 0, t_theta2 < np.pi / 2)]
err_msg = 'something is wrong, theta of ellipse is uncertain. '
assert all([a != b for a, b in zip(b_theta1, b_theta2)]), err_msg
t_theta0 = t_theta1 * b_theta1 + t_theta2 * b_theta2
t_theta = np.hstack((t_theta0, np.pi / 2, np.pi - t_theta0[::-1]))
t_x = a * np.cos(t_theta)
t_y = b * np.sin(t_theta)
self._nodes = np.vstack((t_y, np.zeros_like(t_y), np.hstack(t_x))).T
self.set_dmda()
self._u = np.zeros(self._nodes.size)
self._normal = np.zeros((self._nodes.shape[0], 2), order='F')
self._geo_norm = np.array((0, 0, 1))
# force geo
tfct = (a + epsilon * ds) / a
t_x = a * tfct * np.cos(t_theta)
t_y = b * tfct * np.sin(t_theta)
fnodes = np.vstack((t_y, np.zeros_like(t_y), np.hstack(t_x))).T
f_geo = self.copy()
f_geo.set_nodes(fnodes, 1)
return f_geo
def create_half_delta(self, ds: float, # length of the mesh
a: float, # axis1 = 2*a
b: float, # axis2 = 2*b
epsilon):
err_msg = 'both major and minor axises should positive. '
assert a > 0 and b > 0, err_msg
self._deltaLength = ds
# fit arc length as function F of theta using 2-degree pylonomial
from scipy.special import ellipeinc
from scipy.optimize import curve_fit
func = lambda theta, a, b: a * theta ** 2 + b * theta
theta = np.linspace(0, np.pi / 2, 100)
arcl = b * ellipeinc(theta, 1 - (a / b) ** 2)
popt, _ = curve_fit(func, theta, arcl)
# divided arc length equally, and get theta using F^-1.
n = np.ceil(arcl[-1] / ds).astype(int)
t_arcl = np.linspace(0, arcl[-1], n, endpoint=False) + ds / 2
# do something to correct the fitting error.
while t_arcl[-1] > arcl[-1]:
t_arcl = t_arcl[:-1]
t_theta1 = (-popt[1] + np.sqrt(popt[1] ** 2 + 4 * popt[0] * t_arcl)) / (2 * popt[0])
t_theta2 = (-popt[1] - np.sqrt(popt[1] ** 2 + 4 * popt[0] * t_arcl)) / (2 * popt[0])
b_theta1 = [a and b for a, b in zip(t_theta1 > 0, t_theta1 < np.pi / 2)]
b_theta2 = [a and b for a, b in zip(t_theta2 > 0, t_theta2 < np.pi / 2)]
err_msg = 'something is wrong, theta of ellipse is uncertain. '
assert all([a != b for a, b in zip(b_theta1, b_theta2)]), err_msg
t_theta0 = t_theta1 * b_theta1 + t_theta2 * b_theta2
t_x = a * np.cos(t_theta0)
t_y = b * np.sin(t_theta0)
self._nodes = np.vstack((t_y, np.zeros_like(t_y), np.hstack(t_x))).T
self.set_dmda()
self._u = np.zeros(self._nodes.size)
self._normal = np.zeros((self._nodes.shape[0], 2), order='F')
self._geo_norm = np.array((0, 0, 1))
# force geo
tfct = (a + epsilon * ds) / a
t_x = a * tfct * np.cos(t_theta0)
t_y = b * tfct * np.sin(t_theta0)
fnodes = np.vstack((t_y, np.zeros_like(t_y), np.hstack(t_x))).T
f_geo = self.copy()
f_geo.set_nodes(fnodes, 1)
return f_geo
class revolve_pipe(_revolve_geo):
def __init__(self):
super().__init__()
self._length = 0
self._radius = 0
self._type = 'revolve_pipe'
def create_deltaz(self, ds: float, # length of the mesh
length: float, # length of the tunnel
radius: float): # radius of the tunnel
epsilon_x = 1 / 2
epsilon_z = 1 / 3
cover_fct = 2
self._deltaLength = ds
self._length = length
self._radius = radius
# the tunnel is along z axis
# due to the symmetry of pipe, generate the first part and get the image as the other part.
z0 = np.linspace((length - ds) / 2, 0,
num=np.ceil((length / ds / 2)).astype(int))[1:]
z0 = z0 + ds / 2
x0 = np.ones_like(z0) * radius
# cover 1
x1 = np.linspace(0, radius, num=cover_fct * np.ceil((radius / ds)).astype(int))
z1 = np.ones_like(x1) * length / 2
# half pard
xi = np.hstack((x1, x0))
zi = np.hstack((z1, z0))
# all
x = np.hstack((xi, np.flipud(xi)))
z = np.hstack((zi, np.flipud(zi) * -1))
self._nodes = np.zeros((x.size, 3), order='F')
self._nodes[:, 0] = x.flatten(order='F')
self._nodes[:, 1] = np.zeros_like(x).flatten(order='F')
self._nodes[:, 2] = z.flatten(order='F')
self.set_dmda()
self._u = np.zeros(self._nodes.size)
self._normal = np.zeros((self._nodes.shape[0], 2), order='F')
self._geo_norm = np.array((0, 0, 1))
# associated force geo
f_geo = self.copy()
epsilon_x = epsilon_x / cover_fct
a = (radius - ds * epsilon_x * 2) / radius
b = ds * epsilon_x
z0 = z0 - ds * epsilon_z
x0 = a * x0 + b
x1 = a * x1 + b
z1 = np.ones_like(x1) * length / 2 - ds * epsilon_z
# half pard
xi = np.hstack((x1, x0))
zi = np.hstack((z1, z0))
# all
x = np.hstack((xi, np.flipud(xi)))
z = np.hstack((zi, np.flipud(zi) * -1))
fnodes = np.vstack((x, np.zeros_like(x), z)).T
f_geo.set_nodes(fnodes, 1)
return f_geo
def create_half_deltaz(self, ds: float, # length of the mesh
length: float, # length of the tunnel
radius: float): # radius of the tunnel
epsilon_x = 1 / 2
epsilon_z = 1 / 2
cover_fct = 1.5
self._deltaLength = ds
self._length = length
self._radius = radius
# the tunnel is along z axis
z0 = np.linspace(length / 2, ds / 2, num=np.ceil(length / ds / 2).astype(int))[1:]
x0 = np.ones_like(z0) * radius
# cover
x1 = np.linspace(0, radius, num=np.ceil(cover_fct * radius / ds).astype(int))
z1 = np.ones_like(x1) * length / 2
# half part
xi = np.hstack((x1, x0))
zi = np.hstack((z1, z0))
self._nodes = np.zeros((xi.size, 3), order='F')
self._nodes[:, 0] = xi.flatten(order='F')
self._nodes[:, 1] = np.zeros_like(xi).flatten(order='F')
self._nodes[:, 2] = zi.flatten(order='F')
self.set_dmda()
self._u = np.zeros(self._nodes.size)
self._normal = np.zeros((self._nodes.shape[0], 2), order='F')
self._geo_norm = np.array((0, 0, 1))
# associated force geo
f_geo = self.copy()
epsilon_x = epsilon_x / cover_fct
a = (radius - ds * epsilon_x * 2) / radius
b = ds * epsilon_x
z0 = z0 - ds * epsilon_z
x0 = a * x0 + b
x1 = a * x1 + b
z1 = np.ones_like(x1) * length / 2 - ds * epsilon_z
# half part
xi = np.hstack((x1, x0))
zi = np.hstack((z1, z0))
fnodes = np.vstack((xi, np.zeros_like(xi), zi)).T
f_geo.set_nodes(fnodes, 1)
return f_geo
def create_half_deltaz_v2(self, ds: float, # length of the mesh
length: float, # length of the tunnel
radius: float): # radius of the tunnel
epsilon_x = 1 / 2
epsilon_z = 1 / 2
epsilon_3 = 1 / 5 # radio between radii of tangent curve and pipe.
cover_fct = 1
tc_fct = 5
self._deltaLength = ds
self._length = length
self._radius = radius
# the tunnel is along z axis
z0 = np.linspace(length / 2, ds / 2, num=np.ceil(length / ds / 2).astype(int))[1:]
x0 = np.ones_like(z0) * radius
# Tangent curve
tnz = np.ceil(epsilon_3 * radius / ds).astype(int)
r_cv = ds * tnz
z1 = np.flipud(np.arange(tnz) * ds + length / 2)
x1 = (r_cv ** tc_fct - (z1 - length / 2) ** tc_fct) ** (1 / tc_fct) + radius - r_cv
# cover
num = np.ceil(cover_fct * x1[0] / ds).astype(int)
x2 = np.linspace(0, x1[0], num=num)[:np.ceil(-2 * cover_fct).astype(int)]
z2 = np.ones_like(x2) * z1[0]
# half part
xi = np.hstack((x2, x1, x0))
zi = np.hstack((z2, z1, z0))
self._nodes = np.zeros((xi.size, 3), order='F')
self._nodes[:, 0] = xi.flatten(order='F')
self._nodes[:, 1] = np.zeros_like(xi).flatten(order='F')
self._nodes[:, 2] = zi.flatten(order='F')
self.set_dmda()
self._u = np.zeros(self._nodes.size)
self._normal = np.zeros((self._nodes.shape[0], 2), order='F')
self._geo_norm = np.array((0, 0, 1))
# associated force geo
f_geo = self.copy()
epsilon_x = epsilon_x / cover_fct
a = (radius - ds * epsilon_x * 2) / radius
b = ds * epsilon_x
x0 = a * x0 + b
z0 = z0 - ds * epsilon_z
x1 = a * x1 + b
z1 = z1 - ds * epsilon_z
x2 = a * x2 + b
z2 = np.ones_like(x2) * length / 2 - ds * epsilon_z + r_cv
# half part
xi = np.hstack((x2, x1, x0))
zi = np.hstack((z2, z1, z0))
fnodes = np.vstack((xi, np.zeros_like(xi), zi)).T
f_geo.set_nodes(fnodes, 1)
return f_geo
def create_half_deltaz_v3(self, ds: float, # length of the mesh
length: float, # length of the tunnel
radius: float): # radius of the tunnel
epsilon_x = 1 / 2
epsilon_z = 1 / 2
epsilon_3 = 1 / 1 # radio between radii of tangent curve and pipe.
cover_fct = 1.5
tc_fct = 2
self._deltaLength = ds
self._length = length
self._radius = radius
# the tunnel is along z axis
z0 = np.linspace(length / 2, ds / 2, num=np.ceil(length / ds / 2).astype(int))[1:]
x0 = np.ones_like(z0) * radius
# Tangent curve
tnz = np.ceil(epsilon_3 * radius / ds).astype(int)
r_cv = ds * tnz
z1 = np.flipud(np.arange(tnz) * ds + length / 2)
x1 = (r_cv ** tc_fct - (z1 - length / 2) ** tc_fct) ** (1 / tc_fct) + radius - r_cv
# cover
num = np.ceil(cover_fct * x1[0] / ds).astype(int)
x2 = np.linspace(0, x1[0], num=num)[:np.ceil(-2 * cover_fct).astype(int)]
z2 = np.ones_like(x2) * length / 2 + r_cv
# half part
xi = np.hstack((x2, x1, x0))
zi = np.hstack((z2, z1, z0))
self._nodes = np.zeros((xi.size, 3), order='F')
self._nodes[:, 0] = xi.flatten(order='F')
self._nodes[:, 1] = np.zeros_like(xi).flatten(order='F')
self._nodes[:, 2] = zi.flatten(order='F')
self.set_dmda()
self._u = np.zeros(self._nodes.size)
self._normal = np.zeros((self._nodes.shape[0], 2), order='F')
self._geo_norm = np.array((0, 0, 1))
# associated force geo
f_geo = self.copy()
epsilon_x = epsilon_x / cover_fct
a = (radius - ds * epsilon_x * 2) / radius
b = ds * epsilon_x
x0 = a * x0 + b
z0 = z0 - ds * epsilon_z
x1 = a * x1 + b
z1 = z1 - ds * epsilon_z
x2 = a * x2 + b
z2 = np.ones_like(x2) * length / 2 - ds * epsilon_z + r_cv
# half part
xi = np.hstack((x2, x1, x0))
zi = np.hstack((z2, z1, z0))
fnodes = np.vstack((xi, np.zeros_like(xi), zi)).T
f_geo.set_nodes(fnodes, 1)
return f_geo
class pipe_cover_geo(tunnel_geo):
def __init__(self):
super().__init__()
self._cover_node_list = uniqueList()
self._type = 'pipe_cover_geo' # geo type
def create_with_cover(self, deltaLength: float, # length of the mesh
length: float, # length of the tunnel
radius: float, # radius of the tunnel
a_factor=1e-6,
z_factor=1e-6):
# the tunnel is along z axis.
self._deltaLength = deltaLength
# pipe
na = np.ceil(2 * np.pi * radius / deltaLength).astype(int)
a = np.linspace(-1, 1, na, endpoint=False)
a = (1 / (1 + np.exp(-a_factor * a)) - 1 / (1 + np.exp(a_factor))) / (
1 / (1 + np.exp(-a_factor)) - 1 / (1 + np.exp(a_factor))) * 2 * np.pi
nz = np.ceil(length / deltaLength).astype(int)
nodes_z = np.linspace(1, -1, nz)
nodes_z = np.sign(nodes_z) * (np.exp(np.abs(nodes_z) * z_factor) - 1) / (
np.exp(z_factor) - 1) * length / 2
a, nodes_z = np.meshgrid(a, nodes_z)
a = a.flatten()
nodes_z = nodes_z.flatten()
nodes_x = np.cos(a) * radius
nodes_y = np.sin(a) * radius
iscover = np.ones_like(nodes_z, dtype=bool)
iscover[:] = False
# cover
nc =
|
np.ceil((radius - deltaLength) / deltaLength)
|
numpy.ceil
|
__author__ = '<NAME>'
__email__ = '<EMAIL>'
# todo: Clean this up! Make it into a real module
import os, sys, itertools
import networkx as nx
import pandas as pd
from statsmodels.tsa.stattools import ccf
import matplotlib.pyplot as plt
import numpy as np
from collections import Counter
import matplotlib as mpl
mpl.rcParams['pdf.fonttype'] = 42
mpl.rcParams['font.sans-serif'] = 'Arial'
from scipy.stats import pearsonr
from sklearn.metrics.cluster import entropy
from sklearn.metrics.cluster import expected_mutual_information
from sklearn.utils.validation import check_array
from math import log
from Swing.util.Evaluator import Evaluator
def get_experiment_list(filename, timepoints=None, perturbs=None, time_col='Time'):
# load files
timecourse = pd.read_csv(filename, sep="\t")
if timepoints is None:
timepoints = len(set(timecourse[time_col]))
if perturbs is None:
perturbs = len(timecourse)/timepoints
if perturbs.is_integer():
perturbs = int(perturbs)
else:
raise ValueError("Uneven number of timepoints between perturbation experiments")
# divide into list of dataframes
experiments = []
for i in range(0, timepoints * perturbs - timepoints + 1, timepoints):
experiments.append(timecourse.ix[i:i + timepoints - 1])
# reformat
for idx, exp in enumerate(experiments):
exp = exp.set_index(time_col)
experiments[idx] = exp
return experiments
def xcorr_experiments(experiments, gene_axis=1):
"""
Cross correlate the g
:param experiments: list
list of dataframes
:param gene_axis: int
axis corresponding to each gene. 0 for rows, 1 for columns
:return:
"""
return np.array([cc_experiment(experiment.values.T) if gene_axis == 1 else cc_experiment(experiment.values)
for experiment in experiments])
def cc_experiment(experiment):
"""
For one experiment.
x should be n rows (genes) by m columns (timepoints)
:param experiment:
:return:
"""
ccf_array = np.zeros((experiment.shape[0], experiment.shape[0], experiment.shape[1]))
for ii, static in enumerate(experiment):
for jj, moving in enumerate(experiment):
if ii == jj:
unbiased = True
else:
unbiased = False
ccf_array[ii][jj] = ccf(static, moving, unbiased=unbiased)
return ccf_array
def get_xcorr_indices(diff_ts, lag, tolerance):
pair_list = []
# get all pairs
targets = np.array(np.where((diff_ts >= lag-tolerance ) & (diff_ts <= lag+tolerance)))
n_ind = targets.shape[1]
pair_list = [tuple(targets[:,x]) for x in range(n_ind)]
# only keep tuples where the parent index is greater than the child
if lag != 0:
pair_list = [ x for x in pair_list if x[1] < x[2]]
p_pair_list = [(x[0],x[1]) for x in pair_list]
c_pair_list = [(x[0],x[2]) for x in pair_list]
return(p_pair_list,c_pair_list)
def get_pairwise_xcorr(parent,child,experiment,time_map,lag,tolerance,rc):
ts_shape = time_map.shape[1]-1
ts = time_map.iloc[:,:ts_shape]
ts = ts.values
all_ps_values = np.zeros(rc)
all_cs_values = np.zeros(rc)
# make an array of differences
diff_ts = np.abs(ts[:,:,None] - ts[:,None,:])
# get all indices with the same difference
ps_values = np.zeros(rc)
cs_values = np.zeros(rc)
ps = [x[parent].values for x in experiment]
cs = [x[child].values for x in experiment]
all_ps_values = np.vstack(ps)
all_cs_values = np.vstack(cs)
p_idx,c_idx = get_xcorr_indices(diff_ts, lag, tolerance)
ps_values = [all_ps_values[x] for x in p_idx]
cs_values = [all_cs_values[x] for x in c_idx]
rsq, pval = pearsonr(ps_values,cs_values)
#c_xy = np.histogram2d(ps_values, cs_values, 10)[0]
#n_samples = len(ps_values)
#mi = my_mutual_info_score(n_samples, x_val = ps_values, y_val = cs_values, labels_true=None, labels_pred=None, contingency=c_xy)
#print(mi, parent, child, lag)
return(rsq,pval)
def my_mutual_info_score(n_samples, x_val, y_val, labels_true, labels_pred, contingency=None):
"""Mutual Information between two clusterings.
The Mutual Information is a measure of the similarity between two labels of
the same data. Where :math:`P(i)` is the probability of a random sample
occurring in cluster :math:`U_i` and :math:`P'(j)` is the probability of a
random sample occurring in cluster :math:`V_j`, the Mutual Information
between clusterings :math:`U` and :math:`V` is given as:
.. math::
MI(U,V)=\sum_{i=1}^R \sum_{j=1}^C P(i,j)\log\\frac{P(i,j)}{P(i)P'(j)}
This is equal to the Kullback-Leibler divergence of the joint distribution
with the product distribution of the marginals.
This metric is independent of the absolute values of the labels:
a permutation of the class or cluster label values won't change the
score value in any way.
This metric is furthermore symmetric: switching ``label_true`` with
``label_pred`` will return the same score value. This can be useful to
measure the agreement of two independent label assignments strategies
on the same dataset when the real ground truth is not known.
Read more in the :ref:`User Guide <mutual_info_score>`.
Parameters
----------
labels_true : int array, shape = [n_samples]
A clustering of the data into disjoint subsets.
labels_pred : array, shape = [n_samples]
A clustering of the data into disjoint subsets.
contingency : {None, array, sparse matrix},
shape = [n_classes_true, n_classes_pred]
A contingency matrix given by the :func:`contingency_matrix` function.
If value is ``None``, it will be computed, otherwise the given value is
used, with ``labels_true`` and ``labels_pred`` ignored.
Returns
-------
mi : float
Mutual information, a non-negative value
See also
--------
adjusted_mutual_info_score: Adjusted against chance Mutual Information
normalized_mutual_info_score: Normalized Mutual Information
"""
if contingency is None:
labels_true, labels_pred = check_clusterings(labels_true, labels_pred)
contingency = contingency_matrix(labels_true, labels_pred, sparse=True)
else:
contingency = check_array(contingency,
accept_sparse=['csr', 'csc', 'coo'],
dtype=[int, np.int32, np.int64])
if isinstance(contingency, np.ndarray):
# For an array
nzx, nzy = np.nonzero(contingency)
nz_val = contingency[nzx, nzy]
elif sp.issparse(contingency):
# For a sparse matrix
nzx, nzy, nz_val = sp.find(contingency)
else:
raise ValueError("Unsupported type for 'contingency': %s" %
type(contingency))
contingency_sum = contingency.sum()
pi = np.ravel(contingency.sum(axis=1))
pj = np.ravel(contingency.sum(axis=0))
log_contingency_nm = np.log(nz_val)
contingency_nm = nz_val / contingency_sum
# Don't need to calculate the full outer product, just for non-zeroes
outer = pi.take(nzx) * pj.take(nzy)
log_outer = -np.log(outer) + log(pi.sum()) + log(pj.sum())
mi = (contingency_nm * (log_contingency_nm - log(contingency_sum)) +
contingency_nm * log_outer)
mi = mi.sum()
emi = expected_mutual_information(contingency, n_samples)
# Calculate entropy for each labeling
h_true, h_pred = entropy(x_val), entropy(y_val)
ami = (mi - emi) / (max(h_true, h_pred) - emi)
return ami
def calc_edge_lag2(experiments,genes, signed_edge_list=None, tolerance = 8, rc = (23,6), mode=None):
# load the interval file
edges = signed_edge_list['regulator-target']
#initialize dataframe to return
col, row = np.meshgrid(range(len(genes)), range(len(genes)))
edge_lag = pd.DataFrame()
edge_lag['parent'] = np.array(genes)[row.flatten()]
edge_lag['child'] = np.array(genes)[col.flatten()]
edge_lag['Edge'] = list(zip(edge_lag['parent'], edge_lag['child']))
lag_results = []
if mode is 'marbach':
time_map = pd.read_csv('../../data/invitro/marbach_timesteps.tsv', sep='\t')
rc = (23,6)
lags = [0,5,10,20,30,40]
tolerance = 3
else:
time_map = pd.read_csv('../../data/invitro/omranian_timesteps.tsv', sep='\t')
lags = [0,10,20,30,60,90]
time_steps = time_map['Timestep'].tolist()
for edge in edges:
# Ignore self edges
if edge[0] == edge[1]:
continue
tolerance = 8
c_list = []
for lag in lags:
r,p = get_pairwise_xcorr(edge[0],edge[1],experiments,time_map,lag,tolerance,rc)
c_list.append((lag,r,p))
sign = signed_edge_list[signed_edge_list['regulator-target'] == edge]['signs'].tolist()
best_lag = min(c_list, key = lambda x: x[2])
if best_lag[2] > 0.05/len(edges):
true_lag = np.nan
else:
true_lag = best_lag[0]
lag_results.append({'Edge':edge, 'Lag':true_lag, 'Sign': sign, 'Lag_list': c_list})
lag_results = pd.DataFrame(lag_results)
edge_lag = pd.merge(edge_lag, lag_results, how='outer', on='Edge')
lag_results['parent'] = [x[0] for x in lag_results['Edge'].tolist()]
lag_results['child'] = [x[1] for x in lag_results['Edge'].tolist()]
return(lag_results, edge_lag)
def calc_edge_lag(xcorr, genes, sc_frac=0.1, min_ccf=0.5, timestep=1, signed_edge_list=None, flat=True, return_raw=False):
"""
:param xcorr: 4d array
4 axes in order: experiments, parent, child, time
:param genes: list
:param sc_frac: float
related filtering. see filter_ccfs
:param min_ccf: float
minimum cross correlation needed to call a lag
:param timestep: int
:param signed: dataframe
can be a list of signed edges or none (default)
maximize either negative or positive correlation depending on prior information
:param flat: boolean
true: return the mean lag for each edge
false: return the list of all lags (for each exp) for each edge
:return:
"""
e, p, c, t = xcorr.shape
if signed_edge_list is not None:
edges = signed_edge_list['regulator-target']
else:
edges = itertools.product(genes, genes)
lag_estimate = np.zeros((p,c))
sc_thresh = sc_frac * t
#initialize dataframe to return
col, row = np.meshgrid(range(len(genes)), range(len(genes)))
edge_lag = pd.DataFrame()
edge_lag['Parent'] = np.array(genes)[row.flatten()]
edge_lag['Child'] = np.array(genes)[col.flatten()]
edge_lag['Edge'] = list(zip(edge_lag['Parent'], edge_lag['Child']))
lag_results = []
for edge in edges:
# Ignore self edges
if edge[0] == edge[1]:
continue
p_idx = genes.index(edge[0])
c_idx = genes.index(edge[1])
if signed_edge_list is not None:
sign = signed_edge_list[signed_edge_list['regulator-target'] == edge]['signs'].tolist()[0]
# The ccf keeps the parent static and moves the child. Therefore the reversed xcorr would show the true lag
reverse = xcorr[:, c_idx, p_idx]
filtered = filter_ccfs(reverse, sc_thresh, min_ccf)
if filtered.shape[0] > 0:
# f, axarr = plt.subplots(1,2)
# axarr[0].plot(reverse.T)
# axarr[1].plot(filtered.T)
# plt.show()
# default setting
if flat:
if signed_edge_list is None:
lag_estimate[p_idx, c_idx] = float(np.mean(np.argmax(np.abs(filtered), axis=1)))*timestep
elif sign == '+':
lag_estimate[p_idx, c_idx] = float(np.mean(np.argmax(filtered, axis=1)))*timestep
elif sign == '-':
lag_estimate[p_idx, c_idx] = float(np.mean(np.argmin(filtered, axis=1)))*timestep
elif sign == '+-':
lag_estimate[p_idx, c_idx] = float(np.mean(np.argmax(
|
np.abs(filtered)
|
numpy.abs
|
"""
Sample code for
Convolutional Neural Networks for Sentence Classification
http://arxiv.org/pdf/1408.5882v2.pdf
Much of the code is modified from
- deeplearning.net (for ConvNet classes)
- https://github.com/mdenil/dropout (for dropout)
- https://groups.google.com/forum/#!topic/pylearn-dev/3QbKtCumAW4 (for Adadelta)
"""
# from conv_net_classes import LeNetConvPoolLayer, MLPDropout
# import _pickle as cPickle
import cPickle
import numpy as np
from collections import defaultdict, OrderedDict
import theano
import theano.tensor as T
from theano.ifelse import ifelse
import os
import warnings
import sys
import time
import getpass
import csv
from conv_net_classes_gpu import LeNetConvPoolLayer, MLPDropout
warnings.filterwarnings("ignore")
# different non-linearities
def ReLU(x):
y = T.maximum(0.0, x)
return (y)
def Sigmoid(x):
y = T.nnet.sigmoid(x)
return (y)
def Tanh(x):
y = T.tanh(x)
return (y)
def Iden(x):
y = x
return (y)
def train_conv_net(datasets,
U,
ofile,
cv=0,
attr=0,
img_w=300,
filter_hs=[3, 4, 5],
hidden_units=[100, 2],
dropout_rate=[0.5],
shuffle_batch=True,
n_epochs=25,
batch_size=50,
lr_decay=0.95,
conv_non_linear="relu",
activations=[Iden],
sqr_norm_lim=9,
non_static=True):
"""
Train a simple conv net
img_h = sentence length (padded where necessary)
img_w = word vector length (300 for word2vec)
filter_hs = filter window sizes
hidden_units = [x,y] x is the number of feature maps (per filter window), and y is the penultimate layer
sqr_norm_lim = s^2 in the paper
lr_decay = adadelta decay parameter
"""
rng = np.random.RandomState(3435)
img_h = len(datasets[0][0][0])
filter_w = img_w
feature_maps = hidden_units[0]
filter_shapes = []
pool_sizes = []
for filter_h in filter_hs:
filter_shapes.append((feature_maps, 1, filter_h, filter_w))
pool_sizes.append((img_h - filter_h + 1, img_w - filter_w + 1))
parameters = [("image shape", img_h, img_w), ("filter shape", filter_shapes), ("hidden_units", hidden_units),
("dropout", dropout_rate), ("batch_size", batch_size), ("non_static", non_static),
("learn_decay", lr_decay), ("conv_non_linear", conv_non_linear), ("non_static", non_static)
, ("sqr_norm_lim", sqr_norm_lim), ("shuffle_batch", shuffle_batch)]
print(parameters)
# define model architecture
index = T.iscalar()
x = T.tensor3('x', dtype=theano.config.floatX)
y = T.ivector('y')
mair = T.matrix('mair')
Words = theano.shared(value=U, name="Words")
zero_vec_tensor = T.vector(dtype=theano.config.floatX)
zero_vec = np.zeros(img_w, dtype=theano.config.floatX)
set_zero = theano.function([zero_vec_tensor], updates=[(Words, T.set_subtensor(Words[0, :], zero_vec_tensor))],
allow_input_downcast=True)
conv_layers = []
for i in range(len(filter_hs)):
filter_shape = filter_shapes[i]
pool_size = pool_sizes[i]
conv_layer = LeNetConvPoolLayer(rng, image_shape=None,
filter_shape=filter_shape, poolsize=pool_size, non_linear=conv_non_linear)
conv_layers.append(conv_layer)
layer0_input = Words[T.cast(x.flatten(), dtype="int32")].reshape(
(x.shape[0], x.shape[1], x.shape[2], Words.shape[1]))
def convolve_user_statuses(statuses):
layer1_inputs = []
def sum_mat(mat, out):
z = ifelse(T.neq(T.sum(mat, dtype=theano.config.floatX), T.constant(0, dtype=theano.config.floatX)),
T.constant(1, dtype=theano.config.floatX), T.constant(0, dtype=theano.config.floatX))
return out + z, theano.scan_module.until(T.eq(z, T.constant(0, dtype=theano.config.floatX)))
status_count, _ = theano.scan(fn=sum_mat, sequences=statuses,
outputs_info=T.constant(0, dtype=theano.config.floatX))
# Slice-out dummy (zeroed) sentences
relv_input = statuses[:T.cast(status_count[-1], dtype='int32')].dimshuffle(0, 'x', 1, 2)
for conv_layer in conv_layers:
layer1_inputs.append(conv_layer.set_input(input=relv_input).flatten(2))
features = T.concatenate(layer1_inputs, axis=1)
avg_feat = T.max(features, axis=0)
return avg_feat
conv_feats, _ = theano.scan(fn=convolve_user_statuses, sequences=layer0_input)
# Add Mairesse features
layer1_input = T.concatenate([conv_feats, mair], axis=1) ##mairesse_change
hidden_units[0] = feature_maps * len(filter_hs) + datasets[4].shape[1] ##mairesse_change
classifier = MLPDropout(rng, input=layer1_input, layer_sizes=hidden_units, activations=activations,
dropout_rates=dropout_rate)
svm_data = T.concatenate([classifier.layers[0].output, y.dimshuffle(0, 'x')], axis=1)
# define parameters of the model and update functions using adadelta
params = classifier.params
for conv_layer in conv_layers:
params += conv_layer.params
if non_static:
# if word vectors are allowed to change, add them as model parameters
params += [Words]
cost = classifier.negative_log_likelihood(y)
dropout_cost = classifier.dropout_negative_log_likelihood(y)
grad_updates = sgd_updates_adadelta(params, dropout_cost, lr_decay, 1e-6, sqr_norm_lim)
# shuffle dataset and assign to mini batches. if dataset size is not a multiple of mini batches, replicate
# extra data (at random)
np.random.seed(3435)
if datasets[0].shape[0] % batch_size > 0:
extra_data_num = batch_size - datasets[0].shape[0] % batch_size
rand_perm = np.random.permutation(range(len(datasets[0])))
train_set_x = datasets[0][rand_perm]
train_set_y = datasets[1][rand_perm]
train_set_m = datasets[4][rand_perm]
extra_data_x = train_set_x[:extra_data_num]
extra_data_y = train_set_y[:extra_data_num]
extra_data_m = train_set_m[:extra_data_num]
new_data_x = np.append(datasets[0], extra_data_x, axis=0)
new_data_y = np.append(datasets[1], extra_data_y, axis=0)
new_data_m = np.append(datasets[4], extra_data_m, axis=0)
else:
new_data_x = datasets[0]
new_data_y = datasets[1]
new_data_m = datasets[4]
rand_perm = np.random.permutation(range(len(new_data_x)))
new_data_x = new_data_x[rand_perm]
new_data_y = new_data_y[rand_perm]
new_data_m = new_data_m[rand_perm]
n_batches = new_data_x.shape[0] / batch_size
n_train_batches = int(np.round(n_batches * 0.9))
# divide train set into train/val sets
test_set_x = datasets[2]
test_set_y = np.asarray(datasets[3], "int32")
test_set_m = datasets[5]
train_set_x, train_set_y, train_set_m = shared_dataset((new_data_x[:n_train_batches * batch_size],
new_data_y[:n_train_batches * batch_size],
new_data_m[:n_train_batches * batch_size]))
val_set_x, val_set_y, val_set_m = shared_dataset((new_data_x[n_train_batches * batch_size:],
new_data_y[n_train_batches * batch_size:],
new_data_m[n_train_batches * batch_size:]))
n_val_batches = n_batches - n_train_batches
val_model = theano.function([index], classifier.errors(y),
givens={
x: val_set_x[index * batch_size: (index + 1) * batch_size],
y: val_set_y[index * batch_size: (index + 1) * batch_size],
mair: val_set_m[index * batch_size: (index + 1) * batch_size]}, ##mairesse_change
allow_input_downcast=False)
# compile theano functions to get train/val/test errors
test_model = theano.function([index], [classifier.errors(y), svm_data],
givens={
x: train_set_x[index * batch_size: (index + 1) * batch_size],
y: train_set_y[index * batch_size: (index + 1) * batch_size],
mair: train_set_m[index * batch_size: (index + 1) * batch_size]},
##mairesse_change
allow_input_downcast=True)
train_model = theano.function([index], cost, updates=grad_updates,
givens={
x: train_set_x[index * batch_size:(index + 1) * batch_size],
y: train_set_y[index * batch_size:(index + 1) * batch_size],
mair: train_set_m[index * batch_size: (index + 1) * batch_size]},
##mairesse_change
allow_input_downcast=True)
test_y_pred = classifier.predict(layer1_input)
test_error = T.sum(T.neq(test_y_pred, y), dtype=theano.config.floatX)
true_p = T.sum(test_y_pred * y, dtype=theano.config.floatX)
false_p = T.sum(test_y_pred * T.mod(y + T.ones_like(y, dtype=theano.config.floatX), T.constant(2, dtype='int32')))
false_n = T.sum(y * T.mod(test_y_pred + T.ones_like(y, dtype=theano.config.floatX), T.constant(2, dtype='int32')))
test_model_all = theano.function([x, y,
mair ##mairesse_change
]
, [test_error, true_p, false_p, false_n, svm_data], allow_input_downcast=True)
test_batches = test_set_x.shape[0] / batch_size;
# start training over mini-batches
print('... training')
epoch = 0
best_val_perf = 0
val_perf = 0
test_perf = 0
fscore = 0
cost_epoch = 0
while (epoch < n_epochs):
start_time = time.time()
epoch = epoch + 1
if shuffle_batch:
for minibatch_index in np.random.permutation(range(n_train_batches)):
cost_epoch = train_model(minibatch_index)
set_zero(zero_vec)
else:
for minibatch_index in range(n_train_batches):
cost_epoch = train_model(minibatch_index)
set_zero(zero_vec)
train_losses = [test_model(i) for i in range(n_train_batches)]
train_perf = 1 - np.mean([loss[0] for loss in train_losses])
val_losses = [val_model(i) for i in range(n_val_batches)]
val_perf = 1 - np.mean(val_losses)
epoch_perf = 'epoch: %i, training time: %.2f secs, train perf: %.2f %%, val perf: %.2f %%' % (
epoch, time.time() - start_time, train_perf * 100., val_perf * 100.)
print(epoch_perf)
ofile.write(epoch_perf + "\n")
ofile.flush()
if val_perf >= best_val_perf:
best_val_perf = val_perf
test_loss_list = [test_model_all(test_set_x[idx * batch_size:(idx + 1) * batch_size],
test_set_y[idx * batch_size:(idx + 1) * batch_size],
test_set_m[idx * batch_size:(idx + 1) * batch_size] ##mairesse_change
) for idx in range(test_batches)]
if test_set_x.shape[0] > test_batches * batch_size:
test_loss_list.append(
test_model_all(test_set_x[test_batches * batch_size:], test_set_y[test_batches * batch_size:],
test_set_m[test_batches * batch_size:] ##mairesse_change
))
test_loss_list_temp = test_loss_list
test_loss_list = np.asarray([t[:-1] for t in test_loss_list])
test_loss = np.sum(test_loss_list[:, 0]) / float(test_set_x.shape[0])
test_perf = 1 - test_loss
tp = np.sum(test_loss_list[:, 1])
fp = np.sum(test_loss_list[:, 2])
fn =
|
np.sum(test_loss_list[:, 3])
|
numpy.sum
|
"""
Tests for deepreg/model/layer_util.py in
pytest style
"""
from test.unit.util import is_equal_tf
from typing import Tuple, Union
import numpy as np
import pytest
import tensorflow as tf
import deepreg.model.layer_util as layer_util
def test_get_reference_grid():
"""
Test get_reference_grid by confirming that it generates
a sample grid test case to is_equal_tf's tolerance level.
"""
want = tf.constant(
np.array(
[[[[0, 0, 0], [0, 0, 1], [0, 0, 2]], [[0, 1, 0], [0, 1, 1], [0, 1, 2]]]],
dtype=np.float32,
)
)
get = layer_util.get_reference_grid(grid_size=[1, 2, 3])
assert is_equal_tf(want, get)
def test_get_n_bits_combinations():
"""
Test get_n_bits_combinations by confirming that it generates
appropriate solutions for 1D, 2D, and 3D cases.
"""
# Check n=1 - Pass
assert layer_util.get_n_bits_combinations(1) == [[0], [1]]
# Check n=2 - Pass
assert layer_util.get_n_bits_combinations(2) == [[0, 0], [0, 1], [1, 0], [1, 1]]
# Check n=3 - Pass
assert layer_util.get_n_bits_combinations(3) == [
[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1],
]
class TestPyramidCombination:
def test_1d(self):
weights = tf.constant(np.array([[0.2]], dtype=np.float32))
values = tf.constant(np.array([[1], [2]], dtype=np.float32))
# expected = 1 * 0.2 + 2 * 2
expected = tf.constant(np.array([1.8], dtype=np.float32))
got = layer_util.pyramid_combination(
values=values, weight_floor=weights, weight_ceil=1 - weights
)
assert is_equal_tf(got, expected)
def test_2d(self):
weights = tf.constant(np.array([[0.2], [0.3]], dtype=np.float32))
values = tf.constant(
np.array(
[
[1], # value at corner (0, 0), weight = 0.2 * 0.3
[2], # value at corner (0, 1), weight = 0.2 * 0.7
[3], # value at corner (1, 0), weight = 0.8 * 0.3
[4], # value at corner (1, 1), weight = 0.8 * 0.7
],
dtype=np.float32,
)
)
# expected = 1 * 0.2 * 0.3
# + 2 * 0.2 * 0.7
# + 3 * 0.8 * 0.3
# + 4 * 0.8 * 0.7
expected = tf.constant(np.array([3.3], dtype=np.float32))
got = layer_util.pyramid_combination(
values=values, weight_floor=weights, weight_ceil=1 - weights
)
assert is_equal_tf(got, expected)
def test_error_dim(self):
weights = tf.constant(np.array([[[0.2]], [[0.2]]], dtype=np.float32))
values = tf.constant(np.array([[1], [2]], dtype=np.float32))
with pytest.raises(ValueError) as err_info:
layer_util.pyramid_combination(
values=values, weight_floor=weights, weight_ceil=1 - weights
)
assert (
"In pyramid_combination, elements of values, weight_floor, "
"and weight_ceil should have same dimension" in str(err_info.value)
)
def test_error_len(self):
weights = tf.constant(np.array([[0.2]], dtype=np.float32))
values = tf.constant(np.array([[1]], dtype=np.float32))
with pytest.raises(ValueError) as err_info:
layer_util.pyramid_combination(
values=values, weight_floor=weights, weight_ceil=1 - weights
)
assert (
"In pyramid_combination, num_dim = len(weight_floor), "
"len(values) must be 2 ** num_dim" in str(err_info.value)
)
class TestLinearResample:
x_min, x_max = 0, 2
y_min, y_max = 0, 2
# vol are values on grid [0,2]x[0,2]
# values on each point is 3x+y
# shape = (1,3,3)
vol = tf.constant(np.array([[[0, 1, 2], [3, 4, 5], [6, 7, 8]]]), dtype=tf.float32)
# loc are some points, especially
# shape = (1,4,3,2)
loc = tf.constant(
np.array(
[
[
[[0, 0], [0, 1], [1, 2]], # boundary corners
[[0.4, 0], [0.5, 2], [2, 1.7]], # boundary edge
[[-0.4, 0.7], [0, 3], [2, 3]], # outside boundary
[[0.4, 0.7], [1, 1], [0.6, 0.3]], # internal
]
]
),
dtype=tf.float32,
)
@pytest.mark.parametrize("channel", [0, 1, 2])
def test_repeat_extrapolation(self, channel):
x = self.loc[..., 0]
y = self.loc[..., 1]
x = tf.clip_by_value(x, self.x_min, self.x_max)
y = tf.clip_by_value(y, self.y_min, self.y_max)
expected = 3 * x + y
vol = self.vol
if channel > 0:
vol = tf.repeat(vol[..., None], channel, axis=-1)
expected = tf.repeat(expected[..., None], channel, axis=-1)
got = layer_util.resample(vol=vol, loc=self.loc, zero_boundary=False)
assert is_equal_tf(expected, got)
@pytest.mark.parametrize("channel", [0, 1, 2])
def test_repeat_zero_bound(self, channel):
x = self.loc[..., 0]
y = self.loc[..., 1]
expected = 3 * x + y
expected = (
expected
* tf.cast(x > self.x_min, tf.float32)
* tf.cast(x <= self.x_max, tf.float32)
)
expected = (
expected
* tf.cast(y > self.y_min, tf.float32)
* tf.cast(y <= self.y_max, tf.float32)
)
vol = self.vol
if channel > 0:
vol = tf.repeat(vol[..., None], channel, axis=-1)
expected = tf.repeat(expected[..., None], channel, axis=-1)
got = layer_util.resample(vol=vol, loc=self.loc, zero_boundary=True)
assert is_equal_tf(expected, got)
def test_shape_error(self):
vol = tf.constant(np.array([[0]], dtype=np.float32)) # shape = [1,1]
loc = tf.constant(np.array([[0, 0], [0, 0]], dtype=np.float32)) # shape = [2,2]
with pytest.raises(ValueError) as err_info:
layer_util.resample(vol=vol, loc=loc)
assert "vol shape inconsistent with loc" in str(err_info.value)
def test_interpolation_error(self):
interpolation = "nearest"
vol = tf.constant(np.array([[0]], dtype=np.float32)) # shape = [1,1]
loc = tf.constant(
|
np.array([[0, 0], [0, 0]], dtype=np.float32)
|
numpy.array
|
import abc
import logging
from typing import Union, Dict, Tuple, List, Set, Callable
import pandas as pd
import warnings
import numpy as np
import scipy.sparse
import xarray as xr
import patsy
try:
import anndata
except ImportError:
anndata = None
import batchglm.data as data_utils
from batchglm.xarray_sparse import SparseXArrayDataArray, SparseXArrayDataSet
from batchglm.models.glm_nb import Model as GeneralizedLinearModel
from ..stats import stats
from . import correction
from ..models.batch_bfgs.optim import Estim_BFGS
from diffxpy import pkg_constants
logger = logging.getLogger(__name__)
def _dmat_unique(dmat, sample_description):
dmat, idx = np.unique(dmat, axis=0, return_index=True)
sample_description = sample_description.iloc[idx].reset_index(drop=True)
return dmat, sample_description
class _Estimation(GeneralizedLinearModel, metaclass=abc.ABCMeta):
"""
Dummy class specifying all needed methods / parameters necessary for a model
fitted for DifferentialExpressionTest.
Useful for type hinting.
"""
@property
@abc.abstractmethod
def X(self) -> np.ndarray:
pass
@property
@abc.abstractmethod
def design_loc(self) -> np.ndarray:
pass
@property
@abc.abstractmethod
def design_scale(self) -> np.ndarray:
pass
@property
@abc.abstractmethod
def constraints_loc(self) -> np.ndarray:
pass
@property
@abc.abstractmethod
def constraints_scale(self) -> np.ndarray:
pass
@property
@abc.abstractmethod
def num_observations(self) -> int:
pass
@property
@abc.abstractmethod
def num_features(self) -> int:
pass
@property
@abc.abstractmethod
def features(self) -> np.ndarray:
pass
@property
@abc.abstractmethod
def observations(self) -> np.ndarray:
pass
@property
@abc.abstractmethod
def log_likelihood(self, **kwargs) -> np.ndarray:
pass
@property
@abc.abstractmethod
def loss(self, **kwargs) -> np.ndarray:
pass
@property
@abc.abstractmethod
def gradients(self, **kwargs) -> np.ndarray:
pass
@property
@abc.abstractmethod
def hessians(self, **kwargs) -> np.ndarray:
pass
@property
@abc.abstractmethod
def fisher_inv(self, **kwargs) -> np.ndarray:
pass
class _DifferentialExpressionTest(metaclass=abc.ABCMeta):
"""
Dummy class specifying all needed methods / parameters necessary for DifferentialExpressionTest.
Useful for type hinting. Structure:
Methods which are called by constructor and which compute (corrected) p-values:
_test()
_correction()
Accessor methods for important metrics which have to be extracted from estimated models:
log_fold_change()
reduced_model_gradient()
full_model_gradient()
Interface method which provides summary of results:
results()
plot()
"""
def __init__(self):
self._pval = None
self._qval = None
self._mean = None
self._log_likelihood = None
@property
@abc.abstractmethod
def gene_ids(self) -> np.ndarray:
pass
@property
@abc.abstractmethod
def X(self):
pass
@abc.abstractmethod
def log_fold_change(self, base=np.e, **kwargs):
pass
def log2_fold_change(self, **kwargs):
"""
Calculates the pairwise log_2 fold change(s) for this DifferentialExpressionTest.
"""
return self.log_fold_change(base=2, **kwargs)
def log10_fold_change(self, **kwargs):
"""
Calculates the log_10 fold change(s) for this DifferentialExpressionTest.
"""
return self.log_fold_change(base=10, **kwargs)
def _test(self, **kwargs) -> np.ndarray:
pass
def _correction(self, method) -> np.ndarray:
"""
Performs multiple testing corrections available in statsmodels.stats.multitest.multipletests()
on self.pval.
:param method: Multiple testing correction method.
Browse available methods in the annotation of statsmodels.stats.multitest.multipletests().
"""
if np.all(np.isnan(self.pval)):
return self.pval
else:
return correction.correct(pvals=self.pval, method=method)
def _ave(self):
"""
Returns a xr.DataArray containing the mean expression by gene
:return: xr.DataArray
"""
pass
@property
def log_likelihood(self):
if self._log_likelihood is None:
self._log_likelihood = self._ll().compute()
return self._log_likelihood
@property
def mean(self):
if self._mean is None:
self._mean = self._ave()
if isinstance(self._mean, xr.DataArray): # Could also be np.ndarray coming out of XArraySparseDataArray
self._mean = self._mean.compute()
return self._mean
@property
def pval(self):
if self._pval is None:
self._pval = self._test().copy()
return self._pval
@property
def qval(self, method="fdr_bh"):
if self._qval is None:
self._qval = self._correction(method=method).copy()
return self._qval
def log10_pval_clean(self, log10_threshold=-30):
"""
Return log10 transformed and cleaned p-values.
NaN p-values are set to one and p-values below log10_threshold
in log10 space are set to log10_threshold.
:param log10_threshold: minimal log10 p-value to return.
:return: Cleaned log10 transformed p-values.
"""
pvals = np.reshape(self.pval, -1)
pvals = np.nextafter(0, 1, out=pvals, where=pvals == 0)
log10_pval_clean = np.log(pvals) / np.log(10)
log10_pval_clean[np.isnan(log10_pval_clean)] = 1
log10_pval_clean = np.clip(log10_pval_clean, log10_threshold, 0, log10_pval_clean)
return log10_pval_clean
def log10_qval_clean(self, log10_threshold=-30):
"""
Return log10 transformed and cleaned q-values.
NaN p-values are set to one and q-values below log10_threshold
in log10 space are set to log10_threshold.
:param log10_threshold: minimal log10 q-value to return.
:return: Cleaned log10 transformed q-values.
"""
qvals = np.reshape(self.qval, -1)
qvals = np.nextafter(0, 1, out=qvals, where=qvals == 0)
log10_qval_clean = np.log(qvals) / np.log(10)
log10_qval_clean[np.isnan(log10_qval_clean)] = 1
log10_qval_clean = np.clip(log10_qval_clean, log10_threshold, 0, log10_qval_clean)
return log10_qval_clean
@abc.abstractmethod
def summary(self, **kwargs) -> pd.DataFrame:
pass
def _threshold_summary(self, res, qval_thres=None,
fc_upper_thres=None, fc_lower_thres=None, mean_thres=None) -> pd.DataFrame:
"""
Reduce differential expression results into an output table with desired thresholds.
"""
if qval_thres is not None:
res = res.iloc[res['qval'].values <= qval_thres, :]
if fc_upper_thres is not None and fc_lower_thres is None:
res = res.iloc[res['log2fc'].values >= np.log(fc_upper_thres) / np.log(2), :]
elif fc_upper_thres is None and fc_lower_thres is not None:
res = res.iloc[res['log2fc'].values <= np.log(fc_lower_thres) / np.log(2), :]
elif fc_upper_thres is not None and fc_lower_thres is not None:
res = res.iloc[np.logical_or(
res['log2fc'].values <= np.log(fc_lower_thres) / np.log(2),
res['log2fc'].values >= np.log(fc_upper_thres) / np.log(2)), :]
if mean_thres is not None:
res = res.iloc[res['mean'].values >= mean_thres, :]
return res
def plot_volcano(
self,
corrected_pval=True,
log10_p_threshold=-30,
log2_fc_threshold=10,
alpha=0.05,
min_fc=1,
size=20,
highlight_ids: List = [],
highlight_size: float = 30,
highlight_col: str = "red",
show: bool = True,
save: Union[str, None] = None,
suffix: str = "_volcano.png"
):
"""
Returns a volcano plot of p-value vs. log fold change
:param corrected_pval: Whether to use multiple testing corrected
or raw p-values.
:param log10_p_threshold: lower bound of log10 p-values displayed in plot.
:param log2_fc_threshold: Negative lower and upper bound of
log2 fold change displayed in plot.
:param alpha: p/q-value lower bound at which a test is considered
non-significant. The corresponding points are colored in grey.
:param min_fc: Fold-change lower bound for visualization,
the points below the threshold are colored in grey.
:param size: Size of points.
:param highlight_ids: Genes to highlight in volcano plot.
:param highlight_ids: Size of points of genes to highlight in volcano plot.
:param highlight_ids: Color of points of genes to highlight in volcano plot.
:param show: Whether (if save is not None) and where (save indicates dir and file stem) to display plot.
:param save: Path+file name stem to save plots to.
File will be save+suffix. Does not save if save is None.
:param suffix: Suffix for file name to save plot to. Also use this to set the file type.
:return: Tuple of matplotlib (figure, axis)
"""
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import gridspec
from matplotlib import rcParams
plt.ioff()
if corrected_pval == True:
neg_log_pvals = - self.log10_qval_clean(log10_threshold=log10_p_threshold)
else:
neg_log_pvals = - self.log10_pval_clean(log10_threshold=log10_p_threshold)
logfc = np.reshape(self.log2_fold_change(), -1)
# Clipping throws errors if not performed in actual data format (ndarray or DataArray):
if isinstance(logfc, xr.DataArray):
logfc = logfc.clip(-log2_fc_threshold, log2_fc_threshold)
else:
logfc = np.clip(logfc, -log2_fc_threshold, log2_fc_threshold, logfc)
fig, ax = plt.subplots()
is_significant = np.logical_and(
neg_log_pvals >= - np.log(alpha) / np.log(10),
np.abs(logfc) >= np.log(min_fc) / np.log(2)
)
sns.scatterplot(y=neg_log_pvals, x=logfc, hue=is_significant, ax=ax,
legend=False, s=size,
palette={True: "orange", False: "black"})
highlight_ids_found = np.array([x in self.gene_ids for x in highlight_ids])
highlight_ids_clean = [highlight_ids[i] for i in np.where(highlight_ids_found == True)[0]]
highlight_ids_not_found = [highlight_ids[i] for i in np.where(highlight_ids_found == False)[0]]
if len(highlight_ids_not_found) > 0:
logger.warning("not all highlight_ids were found in data set: ", ", ".join(highlight_ids_not_found))
if len(highlight_ids_clean) > 0:
neg_log_pvals_highlights = np.zeros([len(highlight_ids_clean)])
logfc_highlights = np.zeros([len(highlight_ids_clean)])
is_highlight = np.zeros([len(highlight_ids_clean)])
for i,id in enumerate(highlight_ids_clean):
idx = np.where(self.gene_ids == id)[0]
neg_log_pvals_highlights[i] = neg_log_pvals[idx]
logfc_highlights[i] = logfc[idx]
sns.scatterplot(y=neg_log_pvals_highlights, x=logfc_highlights,
hue=is_highlight, ax=ax,
legend=False, s=highlight_size,
palette={0: highlight_col})
if corrected_pval == True:
ax.set(xlabel="log2FC", ylabel='-log10(corrected p-value)')
else:
ax.set(xlabel="log2FC", ylabel='-log10(p-value)')
# Save, show and return figure.
if save is not None:
plt.savefig(save + suffix)
if show:
plt.show()
plt.close(fig)
return ax
def plot_ma(
self,
corrected_pval=True,
log2_fc_threshold=10,
alpha=0.05,
size=20,
highlight_ids: List = [],
highlight_size: float = 30,
highlight_col: str = "red",
show: bool = True,
save: Union[str, None] = None,
suffix: str = "_my_plot.png"
):
"""
Returns an MA plot of mean expression vs. log fold change with significance
super-imposed.
:param corrected_pval: Whether to use multiple testing corrected
or raw p-values.
:param log2_fc_threshold: Negative lower and upper bound of
log2 fold change displayed in plot.
:param alpha: p/q-value lower bound at which a test is considered
non-significant. The corresponding points are colored in grey.
:param size: Size of points.
:param highlight_ids: Genes to highlight in volcano plot.
:param highlight_ids: Size of points of genes to highlight in volcano plot.
:param highlight_ids: Color of points of genes to highlight in volcano plot.
:param show: Whether (if save is not None) and where (save indicates dir and file stem) to display plot.
:param save: Path+file name stem to save plots to.
File will be save+suffix. Does not save if save is None.
:param suffix: Suffix for file name to save plot to. Also use this to set the file type.
:return: Tuple of matplotlib (figure, axis)
"""
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import gridspec
from matplotlib import rcParams
plt.ioff()
ave = np.log(self.mean + 1e-08)
logfc = np.reshape(self.log2_fold_change(), -1)
# Clipping throws errors if not performed in actual data format (ndarray or DataArray):
if isinstance(logfc, xr.DataArray):
logfc = logfc.clip(-log2_fc_threshold, log2_fc_threshold)
else:
logfc = np.clip(logfc, -log2_fc_threshold, log2_fc_threshold, logfc)
fig, ax = plt.subplots()
if corrected_pval:
is_significant = self.pval < alpha
else:
is_significant = self.qval < alpha
sns.scatterplot(y=logfc, x=ave, hue=is_significant, ax=ax,
legend=False, s=size,
palette={True: "orange", False: "black"})
highlight_ids_found = np.array([x in self.gene_ids for x in highlight_ids])
highlight_ids_clean = [highlight_ids[i] for i in np.where(highlight_ids_found == True)[0]]
highlight_ids_not_found = [highlight_ids[i] for i in np.where(highlight_ids_found == False)[0]]
if len(highlight_ids_not_found) > 0:
logger.warning("not all highlight_ids were found in data set: ", ", ".join(highlight_ids_not_found))
if len(highlight_ids_clean) > 0:
ave_highlights = np.zeros([len(highlight_ids_clean)])
logfc_highlights = np.zeros([len(highlight_ids_clean)])
is_highlight = np.zeros([len(highlight_ids_clean)])
for i,id in enumerate(highlight_ids_clean):
idx = np.where(self.gene_ids == id)[0]
ave_highlights[i] = ave[idx]
logfc_highlights[i] = logfc[idx]
sns.scatterplot(y=logfc_highlights, x=ave_highlights,
hue=is_highlight, ax=ax,
legend=False, s=highlight_size,
palette={0: highlight_col})
ax.set(xlabel="log2FC", ylabel='log mean expression')
# Save, show and return figure.
if save is not None:
plt.savefig(save + suffix)
if show:
plt.show()
plt.close(fig)
return ax
def plot_diagnostics(self):
"""
Directly plots a set of diagnostic diagrams
"""
import matplotlib.pyplot as plt
volcano = self.plot_volcano()
plt.show()
class _DifferentialExpressionTestSingle(_DifferentialExpressionTest, metaclass=abc.ABCMeta):
"""
_DifferentialExpressionTest for unit_test with a single test per gene.
The individual test object inherit directly from this class.
All implementations of this class should return one p-value and one fold change per gene.
"""
def summary(
self,
qval_thres=None,
fc_upper_thres=None,
fc_lower_thres=None,
mean_thres=None,
**kwargs
) -> pd.DataFrame:
"""
Summarize differential expression results into an output table.
"""
assert self.gene_ids is not None
res = pd.DataFrame({
"gene": self.gene_ids,
"pval": self.pval,
"qval": self.qval,
"log2fc": self.log2_fold_change(),
"mean": self.mean
})
return res
class DifferentialExpressionTestLRT(_DifferentialExpressionTestSingle):
"""
Single log-likelihood ratio test per gene.
"""
sample_description: pd.DataFrame
full_design_loc_info: patsy.design_info
full_estim: _Estimation
reduced_design_loc_info: patsy.design_info
reduced_estim: _Estimation
def __init__(
self,
sample_description: pd.DataFrame,
full_design_loc_info: patsy.design_info,
full_estim,
reduced_design_loc_info: patsy.design_info,
reduced_estim
):
super().__init__()
self.sample_description = sample_description
self.full_design_loc_info = full_design_loc_info
self.full_estim = full_estim
self.reduced_design_loc_info = reduced_design_loc_info
self.reduced_estim = reduced_estim
@property
def gene_ids(self) -> np.ndarray:
return np.asarray(self.full_estim.features)
@property
def X(self):
return self.full_estim.X
@property
def reduced_model_gradient(self):
return self.reduced_estim.gradients
@property
def full_model_gradient(self):
return self.full_estim.gradients
def _test(self):
if np.any(self.full_estim.log_likelihood < self.reduced_estim.log_likelihood):
logger.warning("Test assumption failed: full model is (partially) less probable than reduced model")
return stats.likelihood_ratio_test(
ll_full=self.full_estim.log_likelihood,
ll_reduced=self.reduced_estim.log_likelihood,
df_full=self.full_estim.constraints_loc.shape[1] + self.full_estim.constraints_scale.shape[1],
df_reduced=self.reduced_estim.constraints_loc.shape[1] + self.reduced_estim.constraints_scale.shape[1],
)
def _ave(self):
"""
Returns a xr.DataArray containing the mean expression by gene
:return: xr.DataArray
"""
return np.mean(self.full_estim.X, axis=0)
def _log_fold_change(self, factors: Union[Dict, Tuple, Set, List], base=np.e):
"""
Returns a xr.DataArray containing the locations for the different categories of the factors
:param factors: the factors to select.
E.g. `condition` or `batch` if formula would be `~ 1 + batch + condition`
:param base: the log base to use; default is the natural logarithm
:return: xr.DataArray
"""
if not (isinstance(factors, list) or isinstance(factors, tuple) or isinstance(factors, set)):
factors = {factors}
if not isinstance(factors, set):
factors = set(factors)
di = self.full_design_loc_info
sample_description = self.sample_description[[f.name() for f in di.subset(factors).factor_infos]]
dmat = self.full_estim.design_loc
# make rows unique
dmat, sample_description = _dmat_unique(dmat, sample_description)
# factors = factors.intersection(di.term_names)
# select the columns of the factors
cols = np.arange(len(di.column_names))
sel = np.concatenate([cols[di.slice(f)] for f in factors], axis=0)
neg_sel =
|
np.ones_like(cols)
|
numpy.ones_like
|
import datetime as dt
from unittest import SkipTest
from nose.plugins.attrib import attr
import numpy as np
from holoviews import Dimension, Image, Curve, RGB, HSV, Dataset, Table
from holoviews.element.comparison import ComparisonTestCase
from holoviews.core.util import date_range
from holoviews.core.data.interface import DataError
from .testdataset import DatatypeContext
class ImageInterfaceTest(ComparisonTestCase):
datatype = 'image'
def setUp(self):
self.eltype = Image
self.restore_datatype = self.eltype.datatype
self.eltype.datatype = [self.datatype]
self.init_data()
def init_data(self):
self.array = np.arange(10) * np.arange(10)[:, np.newaxis]
self.image = Image(np.flipud(self.array), bounds=(-10, 0, 10, 10))
def tearDown(self):
self.eltype.datatype = self.restore_datatype
def test_init_data_tuple(self):
xs = np.arange(5)
ys = np.arange(10)
array = xs * ys[:, np.newaxis]
Image((xs, ys, array))
def test_init_data_tuple_error(self):
xs = np.arange(5)
ys = np.arange(10)
array = xs * ys[:, np.newaxis]
with self.assertRaises(DataError):
Image((ys, xs, array))
def test_init_data_datetime_xaxis(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
Image(np.flipud(self.array), bounds=(start, 0, end, 10))
def test_init_data_datetime_yaxis(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
Image(np.flipud(self.array), bounds=(-10, start, 10, end))
def test_init_bounds(self):
self.assertEqual(self.image.bounds.lbrt(), (-10, 0, 10, 10))
def test_init_bounds_datetime_xaxis(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
bounds = (start, 0, end, 10)
image = Image(np.flipud(self.array), bounds=bounds)
self.assertEqual(image.bounds.lbrt(), bounds)
def test_init_bounds_datetime_yaxis(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
bounds = (-10, start, 10, end)
image = Image(np.flipud(self.array), bounds=bounds)
self.assertEqual(image.bounds.lbrt(), bounds)
def test_init_densities(self):
self.assertEqual(self.image.xdensity, 0.5)
self.assertEqual(self.image.ydensity, 1)
def test_init_densities_datetime_xaxis(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
bounds = (start, 0, end, 10)
image = Image(np.flipud(self.array), bounds=bounds)
self.assertEqual(image.xdensity, 1e-5)
self.assertEqual(image.ydensity, 1)
def test_init_densities_datetime_yaxis(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
bounds = (-10, start, 10, end)
image = Image(np.flipud(self.array), bounds=bounds)
self.assertEqual(image.xdensity, 0.5)
self.assertEqual(image.ydensity, 1e-5)
def test_dimension_values_xs(self):
self.assertEqual(self.image.dimension_values(0, expanded=False),
np.linspace(-9, 9, 10))
def test_dimension_values_ys(self):
self.assertEqual(self.image.dimension_values(1, expanded=False),
np.linspace(0.5, 9.5, 10))
def test_dimension_values_vdim(self):
self.assertEqual(self.image.dimension_values(2, flat=False),
self.array)
def test_index_single_coordinate(self):
self.assertEqual(self.image[0.3, 5.1], 25)
def test_slice_xaxis(self):
sliced = self.image[0.3:5.2]
self.assertEqual(sliced.bounds.lbrt(), (0, 0, 6, 10))
self.assertEqual(sliced.xdensity, 0.5)
self.assertEqual(sliced.ydensity, 1)
self.assertEqual(sliced.dimension_values(2, flat=False),
self.array[:, 5:8])
def test_slice_datetime_xaxis(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
bounds = (start, 0, end, 10)
image = Image(np.flipud(self.array), bounds=bounds)
sliced = image[start+np.timedelta64(530, 'ms'): start+np.timedelta64(770, 'ms')]
self.assertEqual(sliced.dimension_values(2, flat=False),
self.array[:, 5:8])
def test_slice_yaxis(self):
sliced = self.image[:, 1.2:5.2]
self.assertEqual(sliced.bounds.lbrt(), (-10, 1., 10, 5))
self.assertEqual(sliced.xdensity, 0.5)
self.assertEqual(sliced.ydensity, 1)
self.assertEqual(sliced.dimension_values(2, flat=False),
self.array[1:5, :])
def test_slice_datetime_yaxis(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
bounds = (-10, start, 10, end)
image = Image(np.flipud(self.array), bounds=bounds)
sliced = image[:, start+np.timedelta64(120, 'ms'): start+np.timedelta64(520, 'ms')]
self.assertEqual(sliced.dimension_values(2, flat=False),
self.array[1:5, :])
def test_slice_both_axes(self):
sliced = self.image[0.3:5.2, 1.2:5.2]
self.assertEqual(sliced.bounds.lbrt(), (0, 1., 6, 5))
self.assertEqual(sliced.xdensity, 0.5)
self.assertEqual(sliced.ydensity, 1)
self.assertEqual(sliced.dimension_values(2, flat=False),
self.array[1:5, 5:8])
def test_slice_x_index_y(self):
sliced = self.image[0.3:5.2, 5.2]
self.assertEqual(sliced.bounds.lbrt(), (0, 5.0, 6.0, 6.0))
self.assertEqual(sliced.xdensity, 0.5)
self.assertEqual(sliced.ydensity, 1)
self.assertEqual(sliced.dimension_values(2, flat=False),
self.array[5:6, 5:8])
def test_index_x_slice_y(self):
sliced = self.image[3.2, 1.2:5.2]
self.assertEqual(sliced.bounds.lbrt(), (2.0, 1.0, 4.0, 5.0))
self.assertEqual(sliced.xdensity, 0.5)
self.assertEqual(sliced.ydensity, 1)
self.assertEqual(sliced.dimension_values(2, flat=False),
self.array[1:5, 6:7])
def test_range_xdim(self):
self.assertEqual(self.image.range(0), (-10, 10))
def test_range_datetime_xdim(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
bounds = (start, 0, end, 10)
image = Image(np.flipud(self.array), bounds=bounds)
self.assertEqual(image.range(0), (start, end))
def test_range_ydim(self):
self.assertEqual(self.image.range(1), (0, 10))
def test_range_datetime_ydim(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
bounds = (-10, start, 10, end)
image = Image(np.flipud(self.array), bounds=bounds)
self.assertEqual(image.range(1), (start, end))
def test_range_vdim(self):
self.assertEqual(self.image.range(2), (0, 81))
def test_dimension_values_xcoords(self):
self.assertEqual(self.image.dimension_values(0, expanded=False),
np.linspace(-9, 9, 10))
def test_dimension_values_datetime_xcoords(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
bounds = (start, 0, end, 10)
image = Image(np.flipud(self.array), bounds=bounds)
self.assertEqual(image.dimension_values(0, expanded=False),
date_range(start, end, 10))
def test_dimension_values_ycoords(self):
self.assertEqual(self.image.dimension_values(1, expanded=False),
np.linspace(0.5, 9.5, 10))
def test_sample_xcoord(self):
ys = np.linspace(0.5, 9.5, 10)
zs = [0, 7, 14, 21, 28, 35, 42, 49, 56, 63]
with DatatypeContext([self.datatype, 'dictionary' , 'dataframe'], self.image):
self.assertEqual(self.image.sample(x=5),
Curve((ys, zs), kdims=['y'], vdims=['z']))
def test_sample_ycoord(self):
xs = np.linspace(-9, 9, 10)
zs = [0, 4, 8, 12, 16, 20, 24, 28, 32, 36]
with DatatypeContext([self.datatype, 'dictionary' , 'dataframe'], self.image):
self.assertEqual(self.image.sample(y=5),
Curve((xs, zs), kdims=['x'], vdims=['z']))
def test_sample_coords(self):
arr = np.arange(10)*np.arange(5)[np.newaxis].T
xs = np.linspace(0.12, 0.81, 10)
ys = np.linspace(0.12, 0.391, 5)
img = Image((xs, ys, arr), kdims=['x', 'y'], vdims=['z'], datatype=[self.datatype])
sampled = img.sample([(0.15, 0.15), (0.15, 0.4), (0.8, 0.4), (0.8, 0.15)])
self.assertIsInstance(sampled, Table)
yidx = [0, 4, 4, 0]
xidx = [0, 0, 9, 9]
table = Table((xs[xidx], ys[yidx], arr[yidx, xidx]), kdims=['x', 'y'], vdims=['z'])
self.assertEqual(sampled, table)
def test_reduce_to_scalar(self):
self.assertEqual(self.image.reduce(['x', 'y'], function=np.mean),
20.25)
def test_reduce_x_dimension(self):
ys = np.linspace(0.5, 9.5, 10)
zs = [0., 4.5, 9., 13.5, 18., 22.5, 27., 31.5, 36., 40.5]
with DatatypeContext([self.datatype, 'dictionary' , 'dataframe'], Image):
self.assertEqual(self.image.reduce(x=np.mean),
Curve((ys, zs), kdims=['y'], vdims=['z']))
def test_reduce_y_dimension(self):
xs = np.linspace(-9, 9, 10)
zs = [0., 4.5, 9., 13.5, 18., 22.5, 27., 31.5, 36., 40.5]
with DatatypeContext([self.datatype, 'dictionary' , 'dataframe'], Image):
self.assertEqual(self.image.reduce(y=np.mean),
Curve((xs, zs), kdims=['x'], vdims=['z']))
def test_dataset_reindex_constant(self):
selected = Dataset(self.image.select(x=0))
reindexed = selected.reindex(['y'])
data = Dataset(selected.columns(['y', 'z']),
kdims=['y'], vdims=['z'])
self.assertEqual(reindexed, data)
def test_dataset_reindex_non_constant(self):
ds = Dataset(self.image)
reindexed = ds.reindex(['y'])
data = Dataset(ds.columns(['y', 'z']),
kdims=['y'], vdims=['z'])
self.assertEqual(reindexed, data)
def test_aggregate_with_spreadfn(self):
with DatatypeContext([self.datatype, 'dictionary' , 'dataframe'], self.image):
agg = self.image.aggregate('x', np.mean, np.std)
xs = self.image.dimension_values('x', expanded=False)
mean = self.array.mean(axis=0)
std = self.array.std(axis=0)
self.assertEqual(agg, Curve((xs, mean, std), kdims=['x'],
vdims=['z', 'z_std']))
class ImageGridInterfaceTest(ImageInterfaceTest):
datatype = 'grid'
def init_data(self):
self.xs = np.linspace(-9, 9, 10)
self.ys = np.linspace(0.5, 9.5, 10)
self.array = np.arange(10) * np.arange(10)[:, np.newaxis]
self.image = Image((self.xs, self.ys, self.array))
self.image_inv = Image((self.xs[::-1], self.ys[::-1], self.array[::-1, ::-1]))
def test_init_data_datetime_xaxis(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
xs = date_range(start, end, 10)
Image((xs, self.ys, self.array))
def test_init_data_datetime_yaxis(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
ys = date_range(start, end, 10)
Image((self.xs, ys, self.array))
def test_init_bounds_datetime_xaxis(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
xs = date_range(start, end, 10)
image = Image((xs, self.ys, self.array))
self.assertEqual(image.bounds.lbrt(), (start, 0, end, 10))
def test_init_bounds_datetime_yaxis(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
ys = date_range(start, end, 10)
image = Image((self.xs, ys, self.array))
self.assertEqual(image.bounds.lbrt(), (-10, start, 10, end))
def test_init_densities_datetime_xaxis(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
xs = date_range(start, end, 10)
image = Image((xs, self.ys, self.array))
self.assertEqual(image.xdensity, 1e-5)
self.assertEqual(image.ydensity, 1)
def test_init_densities_datetime_yaxis(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
ys = date_range(start, end, 10)
image = Image((self.xs, ys, self.array))
self.assertEqual(image.xdensity, 0.5)
self.assertEqual(image.ydensity, 1e-5)
def test_sample_datetime_xaxis(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
xs = date_range(start, end, 10)
image = Image((xs, self.ys, self.array))
curve = image.sample(x=xs[3])
self.assertEqual(curve, Curve((self.ys, self.array[:, 3]), 'y', 'z'))
def test_sample_datetime_yaxis(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
ys = date_range(start, end, 10)
image = Image((self.xs, ys, self.array))
curve = image.sample(y=ys[3])
self.assertEqual(curve, Curve((self.xs, self.array[3]), 'x', 'z'))
def test_range_datetime_xdim(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
xs = date_range(start, end, 10)
image = Image((xs, self.ys, self.array))
self.assertEqual(image.range(0), (start, end))
def test_range_datetime_ydim(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
ys = date_range(start, end, 10)
image = Image((self.xs, ys, self.array))
self.assertEqual(image.range(1), (start, end))
def test_dimension_values_datetime_xcoords(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
xs = date_range(start, end, 10)
image = Image((xs, self.ys, self.array))
self.assertEqual(image.dimension_values(0, expanded=False), xs)
def test_dimension_values_datetime_ycoords(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
ys = date_range(start, end, 10)
image = Image((self.xs, ys, self.array))
self.assertEqual(image.dimension_values(1, expanded=False), ys)
def test_slice_datetime_xaxis(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
xs = date_range(start, end, 10)
image = Image((xs, self.ys, self.array))
sliced = image[start+np.timedelta64(530, 'ms'): start+np.timedelta64(770, 'ms')]
self.assertEqual(sliced.dimension_values(2, flat=False),
self.array[:, 5:8])
def test_slice_datetime_yaxis(self):
start = np.datetime64(dt.datetime.today())
end = start+np.timedelta64(1, 's')
ys = date_range(start, end, 10)
image = Image((self.xs, ys, self.array))
sliced = image[:, start+np.timedelta64(120, 'ms'): start+np.timedelta64(520, 'ms')]
self.assertEqual(sliced.dimension_values(2, flat=False),
self.array[1:5, :])
def test_slice_xaxis_inv(self):
sliced = self.image_inv[0.3:5.2]
self.assertEqual(sliced.bounds.lbrt(), (0, 0, 6, 10))
self.assertEqual(sliced.xdensity, 0.5)
self.assertEqual(sliced.ydensity, 1)
self.assertEqual(sliced.dimension_values(2, flat=False),
self.array[:, 5:8])
def test_slice_yaxis_inv(self):
sliced = self.image_inv[:, 1.2:5.2]
self.assertEqual(sliced.bounds.lbrt(), (-10, 1., 10, 5))
self.assertEqual(sliced.xdensity, 0.5)
self.assertEqual(sliced.ydensity, 1)
self.assertEqual(sliced.dimension_values(2, flat=False),
self.array[1:5, :])
def test_slice_both_axes_inv(self):
sliced = self.image_inv[0.3:5.2, 1.2:5.2]
self.assertEqual(sliced.bounds.lbrt(), (0, 1., 6, 5))
self.assertEqual(sliced.xdensity, 0.5)
self.assertEqual(sliced.ydensity, 1)
self.assertEqual(sliced.dimension_values(2, flat=False),
self.array[1:5, 5:8])
def test_slice_x_index_y_inv(self):
sliced = self.image_inv[0.3:5.2, 5.2]
self.assertEqual(sliced.bounds.lbrt(), (0, 5.0, 6.0, 6.0))
self.assertEqual(sliced.xdensity, 0.5)
self.assertEqual(sliced.ydensity, 1)
self.assertEqual(sliced.dimension_values(2, flat=False),
self.array[5:6, 5:8])
def test_index_x_slice_y_inv(self):
sliced = self.image_inv[3.2, 1.2:5.2]
self.assertEqual(sliced.bounds.lbrt(), (2.0, 1.0, 4.0, 5.0))
self.assertEqual(sliced.xdensity, 0.5)
self.assertEqual(sliced.ydensity, 1)
self.assertEqual(sliced.dimension_values(2, flat=False),
self.array[1:5, 6:7])
@attr(optional=1)
class ImageXArrayInterfaceTest(ImageGridInterfaceTest):
datatype = 'xarray'
def setUp(self):
try:
import xarray as xr # noqa
except:
raise SkipTest('Test requires xarray')
super(ImageXArrayInterfaceTest, self).setUp()
def test_dataarray_dimension_order(self):
import xarray as xr
x = np.linspace(-3, 7, 53)
y = np.linspace(-5, 8, 89)
z = np.exp(-1*(x**2 + y[:, np.newaxis]**2))
array = xr.DataArray(z, coords=[y, x], dims=['x', 'y'])
img = Image(array)
self.assertEqual(img.kdims, [Dimension('x'), Dimension('y')])
def test_dataarray_shape(self):
import xarray as xr
x = np.linspace(-3, 7, 53)
y = np.linspace(-5, 8, 89)
z = np.exp(-1*(x**2 + y[:, np.newaxis]**2))
array = xr.DataArray(z, coords=[y, x], dims=['x', 'y'])
img = Image(array, ['x', 'y'])
self.assertEqual(img.interface.shape(img, gridded=True), (53, 89))
def test_dataarray_shape_transposed(self):
import xarray as xr
x = np.linspace(-3, 7, 53)
y = np.linspace(-5, 8, 89)
z = np.exp(-1*(x**2 + y[:, np.newaxis]**2))
array = xr.DataArray(z, coords=[y, x], dims=['x', 'y'])
img = Image(array, ['y', 'x'])
self.assertEqual(img.interface.shape(img, gridded=True), (89, 53))
def test_select_on_transposed_dataarray(self):
import xarray as xr
x = np.linspace(-3, 7, 53)
y = np.linspace(-5, 8, 89)
z = np.exp(-1*(x**2 + y[:, np.newaxis]**2))
array = xr.DataArray(z, coords=[y, x], dims=['x', 'y'])
img = Image(array)[1:3]
self.assertEqual(img['z'], Image(array.sel(x=slice(1, 3)))['z'])
@attr(optional=1)
class ImageIrisInterfaceTest(ImageGridInterfaceTest):
datatype = 'cube'
def init_data(self):
xs =
|
np.linspace(-9, 9, 10)
|
numpy.linspace
|
import numpy as np
import pandas as pd
import xarray as xr
def get_summary_stats_for_date(tick_quotes: np.ndarray) -> xr.Dataset:
specs = tick_quotes['index'][['expiry', 'strike', 'payoff']]
specs_uniq = np.concatenate([specs[:1], specs[1:][specs[1:] != specs[:-1]]])
np.testing.assert_equal(specs_uniq, np.unique(specs_uniq))
expiries, n_options =
|
np.unique(specs_uniq['expiry'], return_counts=True)
|
numpy.unique
|
# -*- coding: utf-8 -*-
"""
Function to ensure external sorting for contiguity
'across adjacent sublaminates'
Created on Mon Jan 29 12:00:18 2018
@author: <NAME>
"""
import numpy as np
def external_contig(angle, n_plies_group, constraints, ss_before, angle2 = None):
'''
returns only the stacking sequences that satisfy constraints concerning
contiguity at the junction with an adjacent group of plies, but not within the
group of plies
OUTPUTS
- angle: the selected sublaminate stacking sequences line by
line
- angle2: the selected sublaminate stacking sequences line by
line if a second sublaminate is given as input for angle2
INPUTS
- angle: the first sublaminate stacking sequences
- angle:2 matrix storing the second sublaminate stacking sequences
- ss_before is the stacking sequence of the sublaminate adjacent to the first
sublaminate
'''
if angle.ndim == 1:
angle = angle.reshape((1, angle.size))
ss_beforeLength = ss_before.size
# CHECK FOR CORRECT INPUTS SIZE
if n_plies_group > angle.shape[1]:
raise Exception('The input set of angles have fewer elements that what is asked to be checked')
if angle2 is None:
# TO ENSURE CONTIGUITY
if constraints.contig:
# To ensure the contiguity constraint at the junction of ply groups
if ss_beforeLength>=1:
if constraints.n_contig ==2:
if n_plies_group>1:
a = angle.shape[0]
for ii in range(a)[::-1]:
if angle[ii, 0] == ss_before[-1] \
and angle[ii, 1] == ss_before[-1]:
angle = np.delete(angle, np.s_[ii], axis=0)
continue
elif constraints.n_contig == 3:
if n_plies_group>2:
a = angle.shape[0]
for ii in range(a)[::-1]:
if angle[ii, 0] == ss_before[-1] \
and angle[ii, 1] == ss_before[-1] \
and angle[ii, 2] == ss_before[-1]:
angle = np.delete(angle, np.s_[ii], axis=0)
continue
elif constraints.n_contig == 4:
if n_plies_group>3:
a = angle.shape[0]
for ii in range(a)[::-1]:
if angle[ii, 0] == ss_before[-1] \
and angle[ii, 1] == ss_before[-1] \
and angle[ii, 2] == ss_before[-1] \
and angle[ii, 3] == ss_before[-1]:
angle = np.delete(angle, np.s_[ii], axis=0)
continue
elif constraints.n_contig == 5:
if n_plies_group>4:
a = angle.shape[0]
for ii in range(a)[::-1]:
if angle[ii, 0] == ss_before[-1] \
and angle[ii, 1] == ss_before[-1] \
and angle[ii, 2] == ss_before[-1] \
and angle[ii, 3] == ss_before[-1]\
and angle[ii, 4] == ss_before[-1]:
angle = np.delete(angle, np.s_[ii], axis=0)
continue
elif constraints.n_contig == 6:
if n_plies_group>5:
a = angle.shape[0]
for ii in range(a)[::-1]:
if angle[ii, 0] == ss_before[-1] \
and angle[ii, 1] == ss_before[-1] \
and angle[ii, 2] == ss_before[-1] \
and angle[ii, 3] == ss_before[-1] \
and angle[ii, 4] == ss_before[-1] \
and angle[ii, 5] == ss_before[-1]:
angle = np.delete(angle, np.s_[ii], axis=0)
continue
else:
raise Exception(
'constraints.n_contig must be 2, 3, 4 or 5')
if ss_beforeLength>=2:
if constraints.n_contig ==2:
a = angle.shape[0]
for ii in range(a)[::-1]:
if angle[ii, 0] == ss_before[-1] \
and angle[ii, 0] == ss_before[-2]:
angle = np.delete(angle, np.s_[ii], axis=0)
continue
elif constraints.n_contig == 3:
if n_plies_group>1:
a = angle.shape[0]
for ii in range(a)[::-1]:
if angle[ii, 0] == ss_before[-1] \
and angle[ii, 1] == ss_before[-1] \
and ss_before[-2] == ss_before[-1]:
angle = np.delete(angle, np.s_[ii], axis=0)
continue
elif constraints.n_contig == 4:
if n_plies_group>2:
a = angle.shape[0]
for ii in range(a)[::-1]:
if angle[ii, 0] == ss_before[-1] \
and angle[ii, 1] == ss_before[-1] \
and angle[ii, 2] == ss_before[-1] \
and ss_before[-2] == ss_before[-1]:
angle = np.delete(angle, np.s_[ii], axis=0)
continue
elif constraints.n_contig == 5:
if n_plies_group>3:
a = angle.shape[0]
for ii in range(a)[::-1]:
if angle[ii, 0] == ss_before[-1] \
and angle[ii, 1] == ss_before[-1] \
and angle[ii, 2] == ss_before[-1] \
and ss_before[-2] == ss_before[-1] \
and angle[ii, 3] == ss_before[-1]:
angle = np.delete(angle, np.s_[ii], axis=0)
continue
elif constraints.n_contig == 6:
if n_plies_group>4:
a = angle.shape[0]
for ii in range(a)[::-1]:
if angle[ii, 0] == ss_before[-1] \
and angle[ii, 1] == ss_before[-1] \
and angle[ii, 2] == ss_before[-1] \
and ss_before[-2] == ss_before[-1] \
and angle[ii, 3] == ss_before[-1] \
and angle[ii, 4] == ss_before[-1]:
angle = np.delete(angle, np.s_[ii], axis=0)
continue
else:
raise Exception(
'constraints.n_contig must be 2, 3, 4 or 5')
if ss_beforeLength>=3:
if constraints.n_contig == 2:
pass
elif constraints.n_contig == 3:
a = angle.shape[0]
for ii in range(a)[::-1]:
if angle[ii, 0] == ss_before[-1] \
and ss_before[-3] == ss_before[-1] \
and ss_before[-2] == ss_before[-1]:
angle = np.delete(angle, np.s_[ii], axis=0)
continue
elif constraints.n_contig == 4:
if n_plies_group>1:
a = angle.shape[0]
for ii in range(a)[::-1]:
if angle[ii, 0] == ss_before[-1] \
and angle[ii, 1] == ss_before[-1] \
and ss_before[-3] == ss_before[-1] \
and ss_before[-2] == ss_before[-1]:
angle = np.delete(angle, np.s_[ii], axis=0)
continue
elif constraints.n_contig == 5:
if n_plies_group>2:
a = angle.shape[0]
for ii in range(a)[::-1]:
if angle[ii, 0] == ss_before[-1] \
and angle[ii, 1] == ss_before[-1] \
and ss_before[-3] == ss_before[-1] \
and ss_before[-2] == ss_before[-1] \
and angle[ii, 2] == ss_before[-1]:
angle = np.delete(angle, np.s_[ii], axis=0)
continue
elif constraints.n_contig == 6:
if n_plies_group>3:
a = angle.shape[0]
for ii in range(a)[::-1]:
if angle[ii, 0] == ss_before[-1] \
and angle[ii, 1] == ss_before[-1] \
and ss_before[-3] == ss_before[-1] \
and ss_before[-2] == ss_before[-1] \
and angle[ii, 2] == ss_before[-1] \
and angle[ii, 3] == ss_before[-1]:
angle = np.delete(angle, np.s_[ii], axis=0)
continue
else:
raise Exception(
'constraints.n_contig must be 2, 3, 4 or 5')
if ss_beforeLength>=4:
if constraints.n_contig ==2:
pass
elif constraints.n_contig == 3:
pass
elif constraints.n_contig == 4:
a = angle.shape[0]
for ii in range(a)[::-1]:
if angle[ii, 0] == ss_before[-1] \
and ss_before[-4] == ss_before[-1] \
and ss_before[-3] == ss_before[-1] \
and ss_before[-2] == ss_before[-1]:
angle = np.delete(angle, np.s_[ii], axis=0)
continue
elif constraints.n_contig == 5:
if n_plies_group>1:
a = angle.shape[0]
for ii in range(a)[::-1]:
if angle[ii, 0] == ss_before[-1] \
and ss_before[-4] == ss_before[-1] \
and ss_before[-3] == ss_before[-1] \
and ss_before[-2] == ss_before[-1] \
and angle[ii, 1] == ss_before[-1]:
angle = np.delete(angle, np.s_[ii], axis=0)
continue
elif constraints.n_contig == 6:
if n_plies_group>2:
a = angle.shape[0]
for ii in range(a)[::-1]:
if angle[ii, 0] == ss_before[-1] \
and ss_before[-4] == ss_before[-1] \
and ss_before[-3] == ss_before[-1] \
and ss_before[-2] == ss_before[-1] \
and angle[ii, 1] == ss_before[-1] \
and angle[ii, 2] == ss_before[-1]:
angle = np.delete(angle, np.s_[ii], axis=0)
continue
else:
raise Exception(
'constraints.n_contig must be 2, 3, 4 or 5')
if ss_beforeLength>=5:
if constraints.n_contig ==2:
pass
elif constraints.n_contig == 3:
pass
elif constraints.n_contig == 4:
pass
elif constraints.n_contig == 5:
a = angle.shape[0]
for ii in range(a)[::-1]:
if angle[ii, 0] == ss_before[-1] \
and ss_before[-4] == ss_before[-1] \
and ss_before[-3] == ss_before[-1] \
and ss_before[-2] == ss_before[-1] \
and angle[ii, 0] == ss_before[-5]:
angle = np.delete(angle, np.s_[ii], axis=0)
continue
elif constraints.n_contig == 6:
if n_plies_group>1:
a = angle.shape[0]
for ii in range(a)[::-1]:
if angle[ii, 0] == ss_before[-1] \
and ss_before[-4] == ss_before[-1] \
and ss_before[-3] == ss_before[-1] \
and ss_before[-2] == ss_before[-1] \
and angle[ii, 0] == ss_before[-5] \
and angle[ii, 1] == ss_before[-5]:
angle =
|
np.delete(angle, np.s_[ii], axis=0)
|
numpy.delete
|
# Author: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# License: BSD (3-clause)
import os
import os.path as op
import pytest
import numpy as np
from scipy.io import savemat
from copy import deepcopy
from functools import partial
from string import ascii_lowercase
from numpy.testing import (assert_array_equal, assert_almost_equal,
assert_allclose, assert_array_almost_equal,
assert_array_less, assert_equal)
from mne import create_info, EvokedArray, read_evokeds, __file__ as _mne_file
from mne.channels import (Montage, read_montage, read_dig_montage,
get_builtin_montages, DigMontage,
read_dig_egi, read_dig_captrack, read_dig_fif)
from mne.channels.montage import _set_montage, make_dig_montage
from mne.channels.montage import transform_to_head
from mne.channels import read_polhemus_fastscan, read_dig_polhemus_isotrak
from mne.channels import compute_dev_head_t
from mne.channels._dig_montage_utils import _transform_to_head_call
from mne.channels._dig_montage_utils import _fix_data_fiducials
from mne.utils import (_TempDir, run_tests_if_main, assert_dig_allclose,
object_diff, Bunch)
from mne.bem import _fit_sphere
from mne.transforms import apply_trans, get_ras_to_neuromag_trans
from mne.io.constants import FIFF
from mne._digitization import Digitization
from mne._digitization._utils import _read_dig_points, _format_dig_points
from mne._digitization._utils import _get_fid_coords
from mne._digitization.base import _get_dig_eeg, _count_points_by_type
from mne.viz._3d import _fiducial_coords
from mne.io.kit import read_mrk
from mne.io import (read_raw_brainvision, read_raw_egi, read_raw_fif,
read_raw_cnt, read_raw_edf, read_raw_nicolet, read_raw_bdf,
read_raw_eeglab, read_fiducials, __file__ as _mne_io_file)
from mne.datasets import testing
data_path = testing.data_path(download=False)
fif_dig_montage_fname = op.join(data_path, 'montage', 'eeganes07.fif')
egi_dig_montage_fname = op.join(data_path, 'montage', 'coordinates.xml')
egi_raw_fname = op.join(data_path, 'montage', 'egi_dig_test.raw')
egi_fif_fname = op.join(data_path, 'montage', 'egi_dig_raw.fif')
bvct_dig_montage_fname = op.join(data_path, 'montage', 'captrak_coords.bvct')
bv_raw_fname = op.join(data_path, 'montage', 'bv_dig_test.vhdr')
bv_fif_fname = op.join(data_path, 'montage', 'bv_dig_raw.fif')
locs_montage_fname = op.join(data_path, 'EEGLAB', 'test_chans.locs')
evoked_fname = op.join(data_path, 'montage', 'level2_raw-ave.fif')
eeglab_fname = op.join(data_path, 'EEGLAB', 'test_raw.set')
bdf_fname1 = op.join(data_path, 'BDF', 'test_generator_2.bdf')
bdf_fname2 = op.join(data_path, 'BDF', 'test_bdf_stim_channel.bdf')
egi_fname1 = op.join(data_path, 'EGI', 'test_egi.mff')
cnt_fname = op.join(data_path, 'CNT', 'scan41_short.cnt')
io_dir = op.dirname(_mne_io_file)
kit_dir = op.join(io_dir, 'kit', 'tests', 'data')
elp = op.join(kit_dir, 'test_elp.txt')
hsp = op.join(kit_dir, 'test_hsp.txt')
hpi = op.join(kit_dir, 'test_mrk.sqd')
bv_fname = op.join(io_dir, 'brainvision', 'tests', 'data', 'test.vhdr')
fif_fname = op.join(io_dir, 'tests', 'data', 'test_raw.fif')
edf_path = op.join(io_dir, 'edf', 'tests', 'data', 'test.edf')
bdf_path = op.join(io_dir, 'edf', 'tests', 'data', 'test_bdf_eeglab.mat')
egi_fname2 = op.join(io_dir, 'egi', 'tests', 'data', 'test_egi.raw')
vhdr_path = op.join(io_dir, 'brainvision', 'tests', 'data', 'test.vhdr')
ctf_fif_fname = op.join(io_dir, 'tests', 'data', 'test_ctf_comp_raw.fif')
nicolet_fname = op.join(io_dir, 'nicolet', 'tests', 'data',
'test_nicolet_raw.data')
def test_fiducials():
"""Test handling of fiducials."""
# Eventually the code used here should be unified with montage.py, but for
# now it uses code in odd places
for fname in (fif_fname, ctf_fif_fname):
fids, coord_frame = read_fiducials(fname)
points = _fiducial_coords(fids, coord_frame)
assert points.shape == (3, 3)
# Fids
assert_allclose(points[:, 2], 0., atol=1e-6)
assert_allclose(points[::2, 1], 0., atol=1e-6)
assert points[2, 0] > 0 # RPA
assert points[0, 0] < 0 # LPA
# Nasion
assert_allclose(points[1, 0], 0., atol=1e-6)
assert points[1, 1] > 0
def test_documented():
"""Test that montages are documented."""
docs = read_montage.__doc__
lines = [line[4:] for line in docs.splitlines()]
start = stop = None
for li, line in enumerate(lines):
if line.startswith('====') and li < len(lines) - 2 and \
lines[li + 1].startswith('Kind') and\
lines[li + 2].startswith('===='):
start = li + 3
elif start is not None and li > start and line.startswith('===='):
stop = li
break
assert (start is not None)
assert (stop is not None)
kinds = [line.split(' ')[0] for line in lines[start:stop]]
kinds = [kind for kind in kinds if kind != '']
montages = os.listdir(op.join(op.dirname(_mne_file), 'channels', 'data',
'montages'))
montages = sorted(op.splitext(m)[0] for m in montages)
assert_equal(len(set(montages)), len(montages))
assert_equal(len(set(kinds)), len(kinds), err_msg=str(sorted(kinds)))
assert_equal(set(montages), set(kinds))
def test_montage():
"""Test making montages."""
tempdir = _TempDir()
inputs = dict(
sfp='FidNz 0 9.071585155 -2.359754454\n'
'FidT9 -6.711765 0.040402876 -3.251600355\n'
'very_very_very_long_name -5.831241498 -4.494821698 4.955347697\n'
'Cz 0 0 8.899186843',
csd='// MatLab Sphere coordinates [degrees] Cartesian coordinates\n' # noqa: E501
'// Label Theta Phi Radius X Y Z off sphere surface\n' # noqa: E501
'E1 37.700 -14.000 1.000 0.7677 0.5934 -0.2419 -0.00000000000000011\n' # noqa: E501
'E3 51.700 11.000 1.000 0.6084 0.7704 0.1908 0.00000000000000000\n' # noqa: E501
'E31 90.000 -11.000 1.000 0.0000 0.9816 -0.1908 0.00000000000000000\n' # noqa: E501
'E61 158.000 -17.200 1.000 -0.8857 0.3579 -0.2957 -0.00000000000000022', # noqa: E501
mm_elc='# ASA electrode file\nReferenceLabel avg\nUnitPosition mm\n' # noqa:E501
'NumberPositions= 68\n'
'Positions\n'
'-86.0761 -19.9897 -47.9860\n'
'85.7939 -20.0093 -48.0310\n'
'0.0083 86.8110 -39.9830\n'
'-86.0761 -24.9897 -67.9860\n'
'Labels\nLPA\nRPA\nNz\nDummy\n',
m_elc='# ASA electrode file\nReferenceLabel avg\nUnitPosition m\n'
'NumberPositions= 68\nPositions\n-.0860761 -.0199897 -.0479860\n' # noqa:E501
'.0857939 -.0200093 -.0480310\n.0000083 .00868110 -.0399830\n'
'.08 -.02 -.04\n'
'Labels\nLPA\nRPA\nNz\nDummy\n',
txt='Site Theta Phi\n'
'Fp1 -92 -72\n'
'Fp2 92 72\n'
'very_very_very_long_name -92 72\n'
'O2 92 -90\n',
elp='346\n'
'EEG\t F3\t -62.027\t -50.053\t 85\n'
'EEG\t Fz\t 45.608\t 90\t 85\n'
'EEG\t F4\t 62.01\t 50.103\t 85\n'
'EEG\t FCz\t 68.01\t 58.103\t 85\n',
hpts='eeg Fp1 -95.0 -3. -3.\n'
'eeg AF7 -1 -1 -3\n'
'eeg A3 -2 -2 2\n'
'eeg A 0 0 0',
bvef='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
'<!-- Generated by EasyCap Configurator 19.05.2014 -->\n'
'<Electrodes defaults="false">\n'
' <Electrode>\n'
' <Name>Fp1</Name>\n'
' <Theta>-90</Theta>\n'
' <Phi>-72</Phi>\n'
' <Radius>1</Radius>\n'
' <Number>1</Number>\n'
' </Electrode>\n'
' <Electrode>\n'
' <Name>Fz</Name>\n'
' <Theta>45</Theta>\n'
' <Phi>90</Phi>\n'
' <Radius>1</Radius>\n'
' <Number>2</Number>\n'
' </Electrode>\n'
' <Electrode>\n'
' <Name>F3</Name>\n'
' <Theta>-60</Theta>\n'
' <Phi>-51</Phi>\n'
' <Radius>1</Radius>\n'
' <Number>3</Number>\n'
' </Electrode>\n'
' <Electrode>\n'
' <Name>F7</Name>\n'
' <Theta>-90</Theta>\n'
' <Phi>-36</Phi>\n'
' <Radius>1</Radius>\n'
' <Number>4</Number>\n'
' </Electrode>\n'
'</Electrodes>',
)
# Get actual positions and save them for checking
# csd comes from the string above, all others come from commit 2fa35d4
poss = dict(
sfp=[[0.0, 9.07159, -2.35975], [-6.71176, 0.0404, -3.2516],
[-5.83124, -4.49482, 4.95535], [0.0, 0.0, 8.89919]],
mm_elc=[[-0.08608, -0.01999, -0.04799], [0.08579, -0.02001, -0.04803],
[1e-05, 0.08681, -0.03998], [-0.08608, -0.02499, -0.06799]],
m_elc=[[-0.08608, -0.01999, -0.04799], [0.08579, -0.02001, -0.04803],
[1e-05, 0.00868, -0.03998], [0.08, -0.02, -0.04]],
txt=[[-26.25044, 80.79056, -2.96646], [26.25044, 80.79056, -2.96646],
[-26.25044, -80.79056, -2.96646], [0.0, -84.94822, -2.96646]],
elp=[[-48.20043, 57.55106, 39.86971], [0.0, 60.73848, 59.4629],
[48.1426, 57.58403, 39.89198], [41.64599, 66.91489, 31.8278]],
hpts=[[-95, -3, -3], [-1, -1., -3.], [-2, -2, 2.], [0, 0, 0]],
bvef=[[-2.62664445e-02, 8.08398039e-02, 5.20474890e-18],
[3.68031324e-18, 6.01040764e-02, 6.01040764e-02],
[-4.63256329e-02, 5.72073923e-02, 4.25000000e-02],
[-6.87664445e-02, 4.99617464e-02, 5.20474890e-18]],
)
for key, text in inputs.items():
kind = key.split('_')[-1]
fname = op.join(tempdir, 'test.' + kind)
with open(fname, 'w') as fid:
fid.write(text)
unit = 'mm' if kind == 'bvef' else 'm'
montage = read_montage(fname, unit=unit)
if kind in ('sfp', 'txt'):
assert ('very_very_very_long_name' in montage.ch_names)
assert_equal(len(montage.ch_names), 4)
assert_equal(len(montage.ch_names), len(montage.pos))
assert_equal(montage.pos.shape, (4, 3))
assert_equal(montage.kind, 'test')
if kind == 'csd':
dtype = [('label', 'S4'), ('theta', 'f8'), ('phi', 'f8'),
('radius', 'f8'), ('x', 'f8'), ('y', 'f8'), ('z', 'f8'),
('off_sph', 'f8')]
try:
table = np.loadtxt(fname, skip_header=2, dtype=dtype)
except TypeError:
table = np.loadtxt(fname, skiprows=2, dtype=dtype)
poss['csd'] = np.c_[table['x'], table['y'], table['z']]
if kind == 'elc':
# Make sure points are reasonable distance from geometric centroid
centroid = np.sum(montage.pos, axis=0) / montage.pos.shape[0]
distance_from_centroid = np.apply_along_axis(
np.linalg.norm, 1,
montage.pos - centroid)
assert_array_less(distance_from_centroid, 0.2)
assert_array_less(0.01, distance_from_centroid)
assert_array_almost_equal(poss[key], montage.pos, 4, err_msg=key)
# Bvef is either auto or mm in terms of "units"
with pytest.raises(ValueError, match='be "auto" or "mm" for .bvef files.'):
bvef_file = op.join(tempdir, 'test.' + 'bvef')
read_montage(bvef_file, unit='m')
# Test reading in different letter case.
ch_names = ["F3", "FZ", "F4", "FC3", "FCz", "FC4", "C3", "CZ", "C4", "CP3",
"CPZ", "CP4", "P3", "PZ", "P4", "O1", "OZ", "O2"]
montage = read_montage('standard_1020', ch_names=ch_names)
assert_array_equal(ch_names, montage.ch_names)
# test transform
input_strs = ["""
eeg Fp1 -95.0 -31.0 -3.0
eeg AF7 -81 -59 -3
eeg AF3 -87 -41 28
cardinal 2 -91 0 -42
cardinal 1 0 -91 -42
cardinal 3 0 91 -42
""", """
Fp1 -95.0 -31.0 -3.0
AF7 -81 -59 -3
AF3 -87 -41 28
FidNz -91 0 -42
FidT9 0 -91 -42
FidT10 0 91 -42
"""]
# sfp files seem to have Nz, T9, and T10 as fiducials:
# https://github.com/mne-tools/mne-python/pull/4482#issuecomment-321980611
kinds = ['test_fid.hpts', 'test_fid.sfp']
for kind, input_str in zip(kinds, input_strs):
fname = op.join(tempdir, kind)
with open(fname, 'w') as fid:
fid.write(input_str)
montage = read_montage(op.join(tempdir, kind), transform=True)
# check coordinate transformation
pos = np.array([-95.0, -31.0, -3.0])
nasion = np.array([-91, 0, -42])
lpa = np.array([0, -91, -42])
rpa = np.array([0, 91, -42])
fids = np.vstack((nasion, lpa, rpa))
trans = get_ras_to_neuromag_trans(fids[0], fids[1], fids[2])
pos = apply_trans(trans, pos)
assert_array_equal(montage.pos[0], pos)
assert_array_equal(montage.nasion[[0, 2]], [0, 0])
assert_array_equal(montage.lpa[[1, 2]], [0, 0])
assert_array_equal(montage.rpa[[1, 2]], [0, 0])
pos = np.array([-95.0, -31.0, -3.0])
montage_fname = op.join(tempdir, kind)
montage = read_montage(montage_fname, unit='mm')
assert_array_equal(montage.pos[0], pos * 1e-3)
# test with last
info = create_info(montage.ch_names, 1e3,
['eeg'] * len(montage.ch_names))
_set_montage(info, montage)
pos2 = np.array([c['loc'][:3] for c in info['chs']])
assert_array_equal(pos2, montage.pos)
assert_equal(montage.ch_names, info['ch_names'])
info = create_info(
montage.ch_names, 1e3, ['eeg'] * len(montage.ch_names))
evoked = EvokedArray(
data=np.zeros((len(montage.ch_names), 1)), info=info, tmin=0)
# test return type as well as set montage
assert (isinstance(evoked.set_montage(montage), type(evoked)))
pos3 = np.array([c['loc'][:3] for c in evoked.info['chs']])
assert_array_equal(pos3, montage.pos)
assert_equal(montage.ch_names, evoked.info['ch_names'])
# Warning should be raised when some EEG are not specified in montage
info = create_info(montage.ch_names + ['foo', 'bar'], 1e3,
['eeg'] * (len(montage.ch_names) + 2))
with pytest.warns(RuntimeWarning, match='position specified'):
_set_montage(info, montage)
# Channel names can be treated case insensitive
info = create_info(['FP1', 'af7', 'AF3'], 1e3, ['eeg'] * 3)
_set_montage(info, montage)
# Unless there is a collision in names
info = create_info(['FP1', 'Fp1', 'AF3'], 1e3, ['eeg'] * 3)
assert (info['dig'] is None)
with pytest.warns(RuntimeWarning, match='position specified'):
_set_montage(info, montage)
assert len(info['dig']) == 5 # 2 EEG w/pos, 3 fiducials
montage.ch_names = ['FP1', 'Fp1', 'AF3']
info = create_info(['fp1', 'AF3'], 1e3, ['eeg', 'eeg'])
assert (info['dig'] is None)
with pytest.warns(RuntimeWarning, match='position specified'):
_set_montage(info, montage, set_dig=False)
assert (info['dig'] is None)
# test get_pos2d method
montage = read_montage("standard_1020")
c3 = montage.get_pos2d()[montage.ch_names.index("C3")]
c4 = montage.get_pos2d()[montage.ch_names.index("C4")]
fz = montage.get_pos2d()[montage.ch_names.index("Fz")]
oz = montage.get_pos2d()[montage.ch_names.index("Oz")]
f1 = montage.get_pos2d()[montage.ch_names.index("F1")]
assert (c3[0] < 0) # left hemisphere
assert (c4[0] > 0) # right hemisphere
assert (fz[1] > 0) # frontal
assert (oz[1] < 0) # occipital
assert_allclose(fz[0], 0, atol=1e-2) # midline
assert_allclose(oz[0], 0, atol=1e-2) # midline
assert (f1[0] < 0 and f1[1] > 0) # left frontal
# test get_builtin_montages function
montages = get_builtin_montages()
assert (len(montages) > 0) # MNE should always ship with montages
assert ("standard_1020" in montages) # 10/20 montage
assert ("standard_1005" in montages) # 10/05 montage
@testing.requires_testing_data
def test_read_locs():
"""Test reading EEGLAB locs."""
pos = read_montage(locs_montage_fname).pos
expected = [[0., 9.99779165e-01, -2.10157875e-02],
[3.08738197e-01, 7.27341573e-01, -6.12907052e-01],
[-5.67059636e-01, 6.77066318e-01, 4.69067752e-01],
[0., 7.14575231e-01, 6.99558616e-01]]
assert_allclose(pos[:4], expected, atol=1e-7)
def test_read_dig_montage():
"""Test read_dig_montage."""
names = ['nasion', 'lpa', 'rpa', '1', '2', '3', '4', '5']
montage = read_dig_montage(hsp, hpi, elp, names, transform=False)
elp_points = _read_dig_points(elp)
hsp_points = _read_dig_points(hsp)
hpi_points = read_mrk(hpi)
with pytest.deprecated_call():
assert_equal(montage.point_names, names)
assert_array_equal(montage.elp, elp_points)
assert_array_equal(montage.hsp, hsp_points)
assert (montage.dev_head_t is None)
montage = read_dig_montage(hsp, hpi, elp, names,
transform=True, dev_head_t=True)
# check coordinate transformation
# nasion
with pytest.deprecated_call():
assert_almost_equal(montage.nasion[0], 0)
assert_almost_equal(montage.nasion[2], 0)
# lpa and rpa
with pytest.deprecated_call():
assert_allclose(montage.lpa[1:], 0, atol=1e-16)
assert_allclose(montage.rpa[1:], 0, atol=1e-16)
# device head transform
EXPECTED_DEV_HEAD_T = np.array(
[[-3.72201691e-02, -9.98212167e-01, -4.67667497e-02, -7.31583414e-04],
[8.98064989e-01, -5.39382685e-02, 4.36543170e-01, 1.60134431e-02],
[-4.38285221e-01, -2.57513699e-02, 8.98466990e-01, 6.13035748e-02],
[0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]]
)
|
assert_allclose(montage.dev_head_t, EXPECTED_DEV_HEAD_T, atol=1e-7)
|
numpy.testing.assert_allclose
|
import numpy as np
import streamlit as st
@st.cache
def get_xor():
X = np.zeros((200, 2))
X[:50] = np.random.random((50, 2)) / 2 + 0.5
X[50:100] = np.random.random((50, 2)) / 2
X[100:150] =
|
np.random.random((50, 2))
|
numpy.random.random
|
# --*-- coding: utf-8 --*--
# Copyright (c) 2020 Guangzhou fermion Technology Co.,Ltd. All rights reserved.
# create by Ben 2020/3/13 上午9:40
from sklearn.metrics import accuracy_score, roc_auc_score, recall_score, precision_score, f1_score, \
mean_absolute_error, precision_recall_curve, auc, mean_squared_error, r2_score
import numpy as np
try:
import tensorflow as tf
except:
pass
def maskNan(yPred, yMask, logger=None):
if logger and np.sum(np.isnan(yPred)) > 0:
logger.warn('yPred existed nan,mask')
yMask = np.clip(yMask - np.isnan(yPred), 0, 1)
return yMask
def prc_auc_score(yTrue, yPred):
precision, recall, _ = precision_recall_curve(yTrue, yPred)
prc_auc = auc(recall, precision)
return prc_auc
def root_mean_squared_error(yTrue, yPred):
rmse = mean_squared_error(yTrue, yPred) ** 0.5
return rmse
def fn_roc_auc(yTrue, yPred, yMask):
yTrue = np.array(yTrue, dtype=np.int64)
yPred = np.array(yPred, dtype=np.float64)
yMask = np.array(yMask, dtype=np.int64)
# =====================================
roc_auc_list = []
for i in range(yTrue.shape[1]):
yMask_i = yMask[:, i]
if np.mean(yMask_i) > 0.0:
yTrue_i = yTrue[:, i][yMask_i != 0]
yPred_i = yPred[:, i][yMask_i != 0]
# ----------------------------------------
yTrue_mean = np.mean(yTrue_i)
if yTrue_mean > 0.0 and yTrue_mean < 1.0:
roc_auc_list.append(roc_auc_score(yTrue_i, yPred_i))
if len(roc_auc_list) > 0:
roc_auc = np.mean(roc_auc_list)
else:
roc_auc = 0.0
return roc_auc
def fn_accuracy(yTrue, yPred, yMask):
yTrue = np.array(yTrue, dtype=np.int64)
yPred = np.array(yPred, dtype=np.float64)
yPred_int = np.int64(yPred > 0.5)
yMask = np.array(yMask, dtype=np.int64)
# =====================================
accuracy_list = []
for i in range(yTrue.shape[1]):
yMask_i = yMask[:, i]
if np.mean(yMask_i) > 0.0:
yTrue_i = yTrue[:, i][yMask_i != 0]
yPred_int_i = yPred_int[:, i][yMask_i != 0]
accuracy_list.append(accuracy_score(yTrue_i, yPred_int_i))
if len(accuracy_list) > 0:
accuracy = np.mean(accuracy_list)
else:
accuracy = 0.0
return accuracy
def fn_prc_auc(yTrue, yPred, yMask):
yTrue = np.array(yTrue, dtype=np.int64)
yPred = np.array(yPred, dtype=np.float64)
yMask = np.array(yMask, dtype=np.int64)
# =====================================
prc_auc_list = []
for i in range(yTrue.shape[1]):
yMask_i = yMask[:, i]
if np.mean(yMask_i) > 0.0:
yTrue_i = yTrue[:, i][yMask_i != 0]
yPred_i = yPred[:, i][yMask_i != 0]
yTrue_mean = np.mean(yTrue_i)
if yTrue_mean > 0.0 and yTrue_mean < 1.0:
prc_auc_list.append(prc_auc_score(yTrue_i, yPred_i))
# =====================================
if len(prc_auc_list) > 0:
prc_auc = np.mean(prc_auc_list)
else:
prc_auc = 0.0
return prc_auc
def fn_recall(yTrue, yPred, yMask):
yTrue = np.array(yTrue, dtype=np.int64)
yPred = np.array(yPred, dtype=np.float64)
yPred_int = np.int64(yPred > 0.5)
yMask = np.array(yMask, dtype=np.int64)
# =====================================
recall_list = []
for i in range(yTrue.shape[1]):
yMask_i = yMask[:, i]
if np.mean(yMask_i) > 0.0:
yTrue_i = yTrue[:, i][yMask_i != 0]
yPred_int_i = yPred_int[:, i][yMask_i != 0]
# ----------------------------------------
recall_list.append(recall_score(yTrue_i, yPred_int_i))
if len(recall_list) > 0:
recall = np.mean(recall_list)
else:
recall = 0.0
return recall
def fn_precision(yTrue, yPred, yMask):
yTrue = np.array(yTrue, dtype=np.int64)
yPred = np.array(yPred, dtype=np.float64)
yPred_int =
|
np.int64(yPred > 0.5)
|
numpy.int64
|
"""
QTNM base field module.
Provides the abstract classes, QtnmBaseField and QtnmBaseSolver.
New concrete implementations of this class should be compatible with
other python code within the Electron-Tracking package.
"""
from abc import ABC, abstractmethod
import numpy as np
import matplotlib.pyplot as plt
from scipy.constants import electron_mass as me, elementary_charge as qe
from scipy.integrate import solve_ivp
from utils import calculate_omega
class QtnmBaseSolver(ABC):
def __init__(self, charge=-qe, mass=me, b_field=1.0, calc_b_field=None):
self.mass = mass
self.charge = charge
self.b_field = b_field
self.calc_b_field = calc_b_field
if calc_b_field is not None:
# Handle cases where calc_b_field returns a single component
if np.size(calc_b_field(0, 0, 0)) == 1:
self.calc_b_field = lambda x, y, z: \
np.array([0.0, 0.0, calc_b_field(x, y, z)])
# If calc_b_field not provided, assume constant field, and store omega
if calc_b_field is None:
omega0 = calculate_omega(b_field, mass=mass, charge=charge)
if np.size(omega0) == 3:
self.omega0 = omega0
elif np.size(omega0) == 1:
self.omega0 =
|
np.array([0, 0, omega0], dtype=float)
|
numpy.array
|
import os
import tqdm
import random
import numpy as np
from os import listdir
from os.path import join
import event_representations as er
from numpy.lib import recfunctions as rfn
from dataloader.prophesee import dat_events_tools
from dataloader.prophesee import npy_events_tools
from dataloader.dataloader_mnist import NMNIST
from dataloader.dataloader_pilotney import PilotNet
import pickle
def random_shift_events(events, max_shift=20, resolution=(180, 240), bounding_box=None):
H, W = resolution
if bounding_box is not None:
x_shift = np.random.randint(-min(bounding_box[0, 0], max_shift),
min(W - bounding_box[2, 0], max_shift), size=(1,))
y_shift = np.random.randint(-min(bounding_box[0, 1], max_shift),
min(H - bounding_box[2, 1], max_shift), size=(1,))
bounding_box[:, 0] += x_shift
bounding_box[:, 1] += y_shift
else:
x_shift, y_shift = np.random.randint(-max_shift, max_shift+1, size=(2,))
events[:, 0] += x_shift
events[:, 1] += y_shift
valid_events = (events[:, 0] >= 0) & (events[:, 0] < W) & (events[:, 1] >= 0) & (events[:, 1] < H)
events = events[valid_events]
if bounding_box is None:
return events
return events, bounding_box
def random_flip_events_along_x(events, resolution=(180, 240), p=0.5, bounding_box=None):
H, W = resolution
flipped = False
if np.random.random() < p:
events[:, 0] = W - 1 - events[:, 0]
flipped = True
if bounding_box is None:
return events
if flipped:
bounding_box[:, 0] = W - 1 - bounding_box[:, 0]
bounding_box = bounding_box[[1, 0, 3, 2]]
return events, bounding_box
def getDataloader(name):
dataset_dict = {'NCaltech101': NCaltech101,
'NCaltech101_ObjectDetection': NCaltech101_ObjectDetection,
'Prophesee': Prophesee,
'NCars': NCars,
'NMNIST': NMNIST,
'PilotNet': PilotNet
}
dl = dataset_dict.get(name)
dl.dataset_name = name
return dl
# class NMNIST:
# def __init__(self, root, object_classes, height, width, nr_events_window=-1, augmentation=False, mode='training',
# event_representation='histogram', shuffle=True):
# root = os.path.join(root, mode)
# class PilotNet:
# def __init__(self, root, object_classes, height, width, nr_events_window=-1, augmentation=False, mode='training',
# event_representation='histogram', shuffle=True):
# root = os.path.join(root, mode)
class NCaltech101:
def __init__(self, root, object_classes, height, width, nr_events_window=-1, augmentation=False, mode='training',
event_representation='histogram', shuffle=True,proc_rate=1250):
"""
Creates an iterator over the N_Caltech101 dataset.
:param root: path to dataset root
:param object_classes: list of string containing objects or 'all' for all classes
:param height: height of dataset image
:param width: width of dataset image
:param nr_events_window: number of events in a sliding window histogram, -1 corresponds to all events
:param augmentation: flip, shift and random window start for training
:param mode: 'training', 'testing' or 'validation'
:param event_representation: 'histogram' or 'event_queue'
"""
root = os.path.join(root, mode)
if object_classes == 'all':
self.object_classes = listdir(root)
else:
self.object_classes = object_classes
self.width = width
self.height = height
self.augmentation = augmentation
self.nr_events_window = nr_events_window
self.nr_classes = len(self.object_classes)
self.event_representation = event_representation
self.files = []
self.labels = []
for i, object_class in enumerate(self.object_classes):
new_files = [join(root, object_class, f) for f in listdir(join(root, object_class))]
self.files += new_files
self.labels += [i] * len(new_files)
self.nr_samples = len(self.labels)
if shuffle:
zipped_lists = list(zip(self.files, self.labels))
# random.seed(7)
random.shuffle(zipped_lists)
self.files, self.labels = zip(*zipped_lists)
self.proc_rate = proc_rate
def __len__(self):
return len(self.files)
def __getitem__(self, idx):
"""
returns events and label, loading events from aedat
:param idx:
:return: x,y,t,p, label
"""
label = self.labels[idx]
filename = self.files[idx]
events = np.load(filename).astype(np.float32)
nr_events = events.shape[0]
window_start0 = 0
window_start1 = min(nr_events,self.proc_rate)
window_end0 = nr_events
window_end1 = nr_events
if self.augmentation:
events = random_shift_events(events, max_shift=10,resolution=(self.height, self.width))
events = random_flip_events_along_x(events, resolution=(self.height, self.width))
window_start0 = random.randrange(0, max(1, nr_events - self.nr_events_window-self.proc_rate))
window_start1 = min(nr_events, window_start0+self.proc_rate)
if self.nr_events_window != -1:
# Catch case if number of events in batch is lower than number of events in window.
window_end0 = min(nr_events, window_start0 + self.nr_events_window)
window_end1 = min(nr_events, window_start1 + self.nr_events_window)
# First Events
events0 = events[window_start0:window_end0, :]
histogram0= self.generate_input_representation(events0, (self.height, self.width))
events1 = events[window_start1:window_end1, :]
histogram1= self.generate_input_representation(events1, (self.height, self.width))
if 0:
import matplotlib.pyplot as plt
plt.imshow(histogram0[:,:,0]/histogram0.max())
plt.savefig('histogram0_.png')
plt.imshow(histogram1[:,:,0]/histogram0.max())
plt.savefig('histogram1_.png')
return events0,events1, label, histogram0, histogram1
def generate_input_representation(self, events, shape):
"""
Events: N x 4, where cols are x, y, t, polarity, and polarity is in {0,1}. x and y correspond to image
coordinates u and v.
"""
if self.event_representation == 'histogram':
return self.generate_event_histogram(events, shape)
elif self.event_representation == 'event_queue':
return self.generate_event_queue(events, shape)
@staticmethod
def generate_event_histogram(events, shape, no_t=False):
"""
Events: N x 4, where cols are x, y, t, polarity, and polarity is in {0,1}. x and y correspond to image
coordinates u and v.
"""
H, W = shape
if no_t:
x, y, p = events.T
else:
x, y, t, p = events.T
x = x.astype(np.int)
y = y.astype(np.int)
img_pos = np.zeros((H * W,), dtype="float32")
img_neg = np.zeros((H * W,), dtype="float32")
np.add.at(img_pos, x[p == 1] + W * y[p == 1], 1)
np.add.at(img_neg, x[p == -1] + W * y[p == -1], 1)
histogram = np.stack([img_neg, img_pos], -1).reshape((H, W, 2))
return histogram
@staticmethod
def generate_event_queue(events, shape, K=15):
"""
Events: N x 4, where cols are x, y, t, polarity, and polarity is in {0,1}. x and y correspond to image
coordinates u and v.
"""
H, W = shape
events = events.astype(np.float32)
if events.shape[0] == 0:
return np.zeros([H, W, 2*K], dtype=np.float32)
# [2, K, height, width], [0, ...] time, [:, 0, :, :] newest events
four_d_tensor = er.event_queue_tensor(events, K, H, W, -1).astype(np.float32)
# Normalize
four_d_tensor[0, ...] = four_d_tensor[0, 0, None, :, :] - four_d_tensor[0, :, :, :]
max_timestep = np.amax(four_d_tensor[0, :, :, :], axis=0, keepdims=True)
# four_d_tensor[0, ...] = np.divide(four_d_tensor[0, ...], max_timestep, where=max_timestep.astype(np.bool))
four_d_tensor[0, ...] = four_d_tensor[0, ...] / (max_timestep + (max_timestep == 0).astype(np.float))
return four_d_tensor.reshape([2*K, H, W]).transpose(1, 2, 0)
class NCaltech101_ObjectDetection(NCaltech101):
def __init__(self, root, object_classes, height, width, nr_events_window=-1, augmentation=False, mode='training',
event_representation='histogram', shuffle=True):
"""
Creates an iterator over the N_Caltech101 object recognition dataset.
:param root: path to dataset root
:param object_classes: list of string containing objects or 'all' for all classes
:param height: height of dataset image
:param width: width of dataset image
:param nr_events_window: number of events in a sliding window histogram, -1 corresponds to all events
:param augmentation: flip, shift and random window start for training
:param mode: 'training', 'testing' or 'validation'
:param event_representation: 'histogram' or 'event_queue'
"""
if object_classes == 'all':
self.object_classes = listdir(os.path.join(root, 'Caltech101'))
else:
self.object_classes = object_classes
self.object_classes.sort()
self.root = root
self.mode = mode
self.width = width
self.height = height
self.augmentation = augmentation
self.nr_events_window = nr_events_window
self.nr_classes = len(self.object_classes)
self.event_representation = event_representation
self.files = []
self.class_labels = []
self.bounding_box_list = []
self.createDataset()
self.nr_samples = len(self.files)
if shuffle:
zipped_lists = list(zip(self.files, self.class_labels, self.bounding_box_list))
random.shuffle(zipped_lists)
self.files, self.class_labels, self.bounding_box_list = zip(*zipped_lists)
def createDataset(self):
"""Does a stratified training, testing, validation split"""
np_random_state = np.random.RandomState(42)
training_ratio = 0.7
testing_ratio = 0.2
# Validation Ratio will be 0.1
for i_class, object_class in enumerate(self.object_classes):
if object_class == 'BACKGROUND_Google':
continue
dir_path = os.path.join(self.root, 'Caltech101', object_class)
image_files = listdir(dir_path)
nr_samples = len(image_files)
random_permutation = np_random_state.permutation(nr_samples)
nr_samples_train = int(nr_samples*training_ratio)
nr_samples_test = int(nr_samples*testing_ratio)
if self.mode == 'training':
start_idx = 0
end_idx = nr_samples_train
elif self.mode == 'testing':
start_idx = nr_samples_train
end_idx = nr_samples_train + nr_samples_test
elif self.mode == 'validation':
start_idx = nr_samples_train + nr_samples_test
end_idx = nr_samples
for idx in random_permutation[start_idx:end_idx]:
self.files.append(os.path.join(self.root, 'Caltech101', object_class, image_files[idx]))
annotation_file = 'annotation' + image_files[idx][5:]
self.readBoundingBox(os.path.join(self.root, 'Caltech101_annotations', object_class, annotation_file))
self.class_labels.append(i_class)
def readBoundingBox(self, file_path):
f = open(file_path)
annotations = np.fromfile(f, dtype=np.int16)
f.close()
self.bounding_box_list.append(annotations[2:10])
def loadEventsFile(self, file_name):
f = open(file_name, 'rb')
raw_data = np.fromfile(f, dtype=np.uint8)
f.close()
raw_data = np.uint32(raw_data)
all_y = raw_data[1::5]
all_x = raw_data[0::5]
all_p = (raw_data[2::5] & 128) >> 7 # bit 7
all_ts = ((raw_data[2::5] & 127) << 16) | (raw_data[3::5] << 8) | (raw_data[4::5])
all_p = all_p.astype(np.float64)
all_p[all_p == 0] = -1
return np.column_stack((all_x, all_y, all_ts, all_p))
def __len__(self):
return len(self.files)
def __getitem__(self, idx):
"""
returns events and label, loading events from aedat
:param idx:
:return: x,y,t,p, label
"""
class_label = self.class_labels[idx]
bounding_box = self.bounding_box_list[idx]
bounding_box = bounding_box.reshape([4, 2])
# Set negative corners to zero
bounding_box = np.maximum(bounding_box,
|
np.zeros_like(bounding_box)
|
numpy.zeros_like
|
# -*- coding: utf-8 -*-
#
from __future__ import division
import numpy
import sympy
def _s3(symbolic):
frac = sympy.Rational if symbolic else lambda x, y: x / y
return numpy.full((1, 3), frac(1, 3))
def _s21(a):
a = numpy.array(a)
b = 1 - 2 * a
return numpy.array([[a, a, b], [a, b, a], [b, a, a]])
def _s111(a, b):
c = 1 - a - b
return numpy.array(
[[a, b, c], [c, a, b], [b, c, a], [b, a, c], [c, b, a], [a, c, b]]
)
def _s111ab(a, b):
c = 1 - a - b
out = numpy.array(
[[a, b, c], [c, a, b], [b, c, a], [b, a, c], [c, b, a], [a, c, b]]
)
out = numpy.swapaxes(out, 0, 1)
return out
def _rot_ab(a, b):
c = 1 - a - b
out = numpy.array([[a, b, c], [c, a, b], [b, c, a]])
out = numpy.swapaxes(out, 0, 1)
return out
def _collapse0(a):
"""Collapse all dimensions of `a` except the first.
"""
return a.reshape(a.shape[0], -1)
def untangle2(data, symbolic=False):
bary = []
weights = []
if "s3" in data:
d = numpy.array(data["s3"]).T
bary.append(_s3(symbolic).T)
weights.append(numpy.tile(d[0], 1))
if "s2" in data:
d = numpy.array(data["s2"]).T
s2_data = _s21(d[1])
bary.append(_collapse0(s2_data))
weights.append(numpy.tile(d[0], 3))
if "s1" in data:
d = numpy.array(data["s1"]).T
s1_data = _s111ab(*d[1:])
bary.append(_collapse0(s1_data))
weights.append(numpy.tile(d[0], 6))
if "rot" in data:
d =
|
numpy.array(data["rot"])
|
numpy.array
|
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.models import Sequential
from tensorflow.keras import Input
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import to_categorical
import numpy
import collections
import random
from typing import List, Union
from yahtzee import Player, Round
class State:
def __init__(self, data: List[int] = []) -> None:
self.data = data
self.num_fields = len(data)
def to_data(self) -> List[int]:
return numpy.asarray(self.data)
class Agent:
"""Deep Q-Network Agent"""
def __init__(
self,
weights_path: str,
input_size: int,
output_size: int,
epsilon: float = 1.0,
learning_rate: float = 0.0005,
first_layer_size: int = 50,
second_layer_size: int = 300,
third_layer_size: int = 50,
memory_size: int = 2500,
load_weights: bool = False,
) -> None:
self.gamma = 0.9
self.short_memory = numpy.array([])
self.learning_rate = learning_rate
self.epsilon = epsilon
self.first_layer = first_layer_size
self.second_layer = second_layer_size
self.third_layer = third_layer_size
self.input_size = input_size
self.output_size = output_size
self.memory = collections.deque(maxlen=memory_size)
self.weights = weights_path
self.load_weights = load_weights
self.model = self.network()
def network(self):
model = Sequential()
model.add(Input(shape=(self.input_size)))
model.add(Dense(self.first_layer, activation="relu"))
model.add(Dense(self.second_layer, activation="relu"))
model.add(Dense(self.third_layer, activation="relu"))
model.add(Dense(self.output_size, activation="softmax"))
opt = Adam(self.learning_rate)
model.compile(loss="mse", optimizer=opt)
if self.load_weights:
model.load_weights(self.weights)
return model
def get_state(self, player: Player, round: Round) -> State:
raise Exception("Not implemented")
def get_reward(self, player: Player, round: Round):
return player.total_score()
def remember(
self, state: State, action: int, reward: int, next_state: State, done: bool
):
self.memory.append(
(state.to_data(), action, reward, next_state.to_data(), done)
)
def replay_new(self, memory, batch_size):
if len(memory) > batch_size:
minibatch = random.sample(memory, batch_size)
else:
minibatch = memory
for state, action, reward, next_state, done in minibatch:
target = reward
if not done:
target = reward + self.gamma * numpy.amax(
self.model.predict(numpy.array([next_state]))[0]
)
target_f = self.model.predict(numpy.array([state]))
target_f[0][
|
numpy.argmax(action)
|
numpy.argmax
|
# test_basic.py: some basic tests of the code
import numpy
numpy.random.seed(2)
from extreme_deconvolution import extreme_deconvolution
def test_single_gauss_1d_nounc():
# Generate data from a single Gaussian, recover mean and variance
ndata= 3001
ydata= numpy.atleast_2d(numpy.random.normal(size=ndata)).T
ycovar= numpy.zeros_like(ydata)
# initialize fit
K= 1
initamp= numpy.ones(K)
initmean= numpy.atleast_2d(numpy.mean(ydata)+1.)
initcovar= numpy.atleast_3d(3.*numpy.var(ydata))
# Run XD
extreme_deconvolution(ydata,ycovar,initamp,initmean,initcovar)
# Test
tol= 10./numpy.sqrt(ndata)
assert numpy.fabs(initmean-0.) < tol, 'XD does not recover correct mean for single Gaussian w/o uncertainties'
assert numpy.fabs(initcovar-1.) < tol, 'XD does not recover correct variance for single Gaussian w/o uncertainties'
return None
def test_single_gauss_1d_constunc():
# Generate data from a single Gaussian, recover mean and variance
ndata= 3001
ydata= numpy.atleast_2d(numpy.random.normal(size=ndata)).T
ycovar= numpy.ones_like(ydata)*0.25
ydata+= numpy.atleast_2d(numpy.random.normal(size=ndata)).T\
*numpy.sqrt(ycovar)
# initialize fit
K= 1
initamp= numpy.ones(K)
initmean= numpy.atleast_2d(numpy.mean(ydata)+1.5)
initcovar= numpy.atleast_3d(3.*numpy.var(ydata))
# Run XD
extreme_deconvolution(ydata,ycovar,initamp,initmean,initcovar)
# Test
tol= 10./numpy.sqrt(ndata)
assert numpy.fabs(initmean-0.) < tol, 'XD does not recover correct mean for single Gaussian w/ constant uncertainties'
assert numpy.fabs(initcovar-1.) < tol, 'XD does not recover correct variance for single Gaussian w/ constant uncertainties'
return None
def test_single_gauss_1d_varunc():
# Generate data from a single Gaussian, recover mean and variance
ndata= 3001
ydata= numpy.atleast_2d(numpy.random.normal(size=ndata)).T
ycovar= numpy.ones_like(ydata)*\
numpy.atleast_2d(numpy.random.uniform(size=ndata)).T
ydata+= numpy.atleast_2d(numpy.random.normal(size=ndata)).T\
*numpy.sqrt(ycovar)
# initialize fit
K= 1
initamp= numpy.ones(K)
initmean= numpy.atleast_2d(numpy.mean(ydata)+numpy.std(ydata))
initcovar= numpy.atleast_3d(3.*numpy.var(ydata))
# Run XD
extreme_deconvolution(ydata,ycovar,initamp,initmean,initcovar)
# Test
tol= 10./numpy.sqrt(ndata)
assert numpy.fabs(initmean-0.) < tol, 'XD does not recover correct mean for single Gaussian w/ uncertainties'
assert numpy.fabs(initcovar-1.) < tol, 'XD does not recover correct variance for single Gaussian w/ uncertainties'
return None
def test_dual_gauss_1d_nounc():
# Generate data from two Gaussians, recover mean and variance
ndata= 3001
amp_true= 0.3
assign= numpy.random.binomial(1,1.-amp_true,ndata)
ydata= numpy.zeros((ndata,1))
ydata[assign==0,0]= numpy.random.normal(size=numpy.sum(assign==0))-2.
ydata[assign==1,0]= numpy.random.normal(size=numpy.sum(assign==1))*2.+1.
ycovar= numpy.zeros_like(ydata)
# initialize fit
K= 2
initamp= numpy.ones(K)/float(K)
initmean= numpy.array([[-1.],[2.]])
initcovar= numpy.zeros((K,1,1))
for kk in range(K):
initcovar[kk]= numpy.mean(3.*numpy.var(ydata))
# Run XD
extreme_deconvolution(ydata,ycovar,initamp,initmean,initcovar)
# Test
tol= 12./numpy.sqrt(ndata)
first= initamp < 0.5
assert numpy.fabs(initamp[first]-amp_true) < tol, 'XD does not recover correct amp for dual Gaussian w/o uncertainties'
assert numpy.fabs(initmean[first]--2.) < tol, 'XD does not recover correct mean for dual Gaussian w/o uncertainties'
assert numpy.fabs(initcovar[first]-1.) < tol, 'XD does not recover correct variance for dual Gaussian w/o uncertainties'
second= initamp >= 0.5
assert numpy.fabs(initamp[second]-(1.-amp_true)) < tol, 'XD does not recover correct amp for dual Gaussian w/o uncertainties'
assert numpy.fabs(initmean[second]-1.) < 2.*tol, 'XD does not recover correct mean for dual Gaussian w/o uncertainties'
assert numpy.fabs(initcovar[second]-4.) < 2.*tol, 'XD does not recover correct variance for dual Gaussian w/o uncertainties'
return None
def test_dual_gauss_1d_constunc():
# Generate data from two Gaussians, recover mean and variance
ndata= 3001
amp_true= 0.3
assign= numpy.random.binomial(1,1.-amp_true,ndata)
ydata= numpy.zeros((ndata,1))
ydata[assign==0,0]= numpy.random.normal(size=numpy.sum(assign==0))-2.
ydata[assign==1,0]= numpy.random.normal(size=numpy.sum(assign==1))*2.+1.
ycovar= numpy.ones_like(ydata)*0.25
ydata+= numpy.atleast_2d(numpy.random.normal(size=ndata)).T\
*numpy.sqrt(ycovar)
# initialize fit
K= 2
initamp= numpy.ones(K)/float(K)
initmean= numpy.array([[-1.],[0.]])
initcovar= numpy.zeros((K,1,1))
for kk in range(K):
initcovar[kk]= numpy.mean(3.*numpy.var(ydata))
# Run XD
extreme_deconvolution(ydata,ycovar,initamp,initmean,initcovar)
# Test
tol= 20./numpy.sqrt(ndata)
first= initamp < 0.5
assert
|
numpy.fabs(initamp[first]-amp_true)
|
numpy.fabs
|
"""
Zade-Mamdani fuzzy model
===============================================================================
"""
import matplotlib.pyplot as plt
import numpy as np
from .core import (
apply_modifiers,
plot_crisp_input,
plot_fuzzy_input,
plot_fuzzyvariable,
)
# #############################################################################
#
#
# Fuzzy Variable
#
#
# #############################################################################
class FuzzyVariable:
"""Creates a (fuzzy) linguistic variable.
Args:
name (string): variable name.
universe (list, numpy.array): list of points defining the universe of the variable.
sets (dict): dictionary where keys are the name of the sets, and the values correspond to the membership for each point of the universe.
Returns:
A fuzzy variable.
"""
def __init__(self, name, universe, sets=None):
self.name = name.replace(" ", "_")
self.universe = universe
if sets is None:
self.sets = {}
else:
self.sets = sets
for key in sets.keys():
self.sets[key] = np.array(self.sets[key])
def __getitem__(self, name):
"""Returns the membership function for the specified fuzzy set.
Args:
name (string): Fuzzy set name
Returns:
A numpy array.
"""
return self.sets[name]
def __setitem__(self, name, memberships):
"""Sets the membership function values for the specified fuzzy set.
Args:
name (string): Fuzzy set name.
memberships (list, numpy.array): membership values.
"""
self.sets[name] = np.array(memberships)
def plot(self, fmt="-", linewidth=2):
"""Plots the fuzzy sets defined for the variable.
Args:
figsize (tuple): figure size.
"""
plot_fuzzyvariable(
universe=self.universe,
memberships=[self.sets[k] for k in self.sets.keys()],
labels=list(self.sets.keys()),
title=self.name,
fmt=fmt,
linewidth=linewidth,
view_xaxis=True,
view_yaxis=True,
)
def plot_input(self, value, fuzzyset, view_xaxis=True, view_yaxis="left"):
if isinstance(value, (np.ndarray, list)):
plot_fuzzy_input(
value=value,
universe=self.universe,
membership=self.sets[fuzzyset],
name=self.name,
view_xaxis=view_xaxis,
view_yaxis=view_yaxis,
)
else:
plot_crisp_input(
value=value,
universe=self.universe,
membership=self.sets[fuzzyset],
name=self.name,
view_xaxis=view_xaxis,
view_yaxis=view_yaxis,
)
def apply_modifiers(self, fuzzyset, modifiers):
"""Computes a modified membership function.
Args:
fuzzyset (string): Identifier of the fuzzy set.
modifiers (list of string): {"very"|"somewhat"|"more_or_less"|"extremely"|"plus"|"intensify"|"slightly"|None}
Returns:
A numpy.array.
"""
if modifiers is None:
return self.sets[fuzzyset]
return apply_modifiers(membership=self.sets[fuzzyset], modifiers=modifiers)
def fuzzificate(self, value, fuzzyset, modifiers=None):
"""Computes the value of the membership function on a specifyied point of the universe for the fuzzy set.
Args:
value (float, numpy.array): point to evaluate the value of the membership function.
fuzzyset (string): name of the fuzzy set.
modifier (string): membership function modifier.
negation (bool): returns the negation?.
Returns:
A float number or numpy.array.
"""
membership = self.apply_modifiers(fuzzyset, modifiers)
return np.interp(
x=value,
xp=self.universe,
fp=membership,
)
# #############################################################################
#
#
# Operators over fuzzy sets
#
#
# #############################################################################
def defuzzificate(universe, membership, operator="cog"):
"""Computes a representative crisp value for the fuzzy set.
Args:
fuzzyset (string): Fuzzy set to defuzzify
operator (string): {"cog"|"bisection"|"mom"|"lom"|"som"}
Returns:
A float value.
"""
def cog():
start = np.min(universe)
stop = np.max(universe)
x = np.linspace(start, stop, num=200)
m = np.interp(x, xp=universe, fp=membership)
return np.sum(x * m) / sum(m)
def coa():
start = np.min(universe)
stop = np.max(universe)
x = np.linspace(start, stop, num=200)
m = np.interp(x, xp=universe, fp=membership)
area = np.sum(m)
cum_area = np.cumsum(m)
return np.interp(area / 2, xp=cum_area, fp=x)
def mom():
maximum = np.max(membership)
maximum = np.array([u for u, m in zip(universe, membership) if m == maximum])
return np.mean(maximum)
def lom():
maximum = np.max(membership)
maximum = np.array([u for u, m in zip(universe, membership) if m == maximum])
return np.max(maximum)
def som():
maximum = np.max(membership)
maximum = np.array([u for u, m in zip(universe, membership) if m == maximum])
return np.min(maximum)
if np.sum(membership) == 0.0:
return 0.0
return {
"cog": cog,
"coa": coa,
"mom": mom,
"lom": lom,
"som": som,
}[operator]()
def aggregate(memberships, operator):
"""Replace the fuzzy sets by a unique fuzzy set computed by the aggregation operator.
Args:
operator (string): {"max"|"sim"|"probor"} aggregation operator.
Returns:
A FuzzyVariable
"""
result = memberships[0]
if operator == "max":
for membership in memberships[1:]:
result = np.maximum(result, membership)
return result
if operator == "sum":
for membership in memberships[1:]:
result = result + membership
return np.minimum(1, result)
if operator == "probor":
for membership in memberships[1:]:
result = result + membership - result * membership
return np.maximum(1, np.minimum(1, result))
# #############################################################################
#
#
# Zadeh-Mamdani's Rule
#
#
# #############################################################################
class FuzzyRule:
"""Mamdani fuzzy rule.
Creates a Mamdani fuzzy fule.
Args:
antecedents (list of tuples): Fuzzy variables in the rule antecedent.
consequent (tuple): Fuzzy variable in the consequence.
is_and (bool): When True, membership values are combined using the specified AND operator; when False, the OR operator is used.
"""
def __init__(
self,
premises,
consequence,
):
self.premises = premises
self.consequence = consequence
#
def __repr__(self):
text = "IF "
space = " " * 4
for i_premise, premise in enumerate(self.premises):
if i_premise == 0:
text += premise[0].name + " IS"
for t in premise[1:]:
text += " " + t
text += "\n"
else:
text += space + premise[0] + " " + premise[1].name + " IS"
for t in premise[2:]:
text += " " + t
text += "\n"
text += "THEN\n"
text += space + self.consequence[0].name + " IS"
for t in self.consequence[1:]:
text += " " + t
return text
# #############################################################################
#
#
# Generic inference method
#
#
# #############################################################################
def probor(a, b):
return np.maximum(0, np.minimum(1, a + b - a * b))
class InferenceMethod:
def __init__(
self,
and_operator,
or_operator,
composition_operator,
production_link,
defuzzification_operator,
):
self.and_operator = and_operator
self.or_operator = or_operator
self.composition_operator = composition_operator
self.production_link = production_link
self.defuzzification_operator = defuzzification_operator
#
self.rules = []
def compute_modified_premise_memberships(self):
for rule in self.rules:
rule.modified_premise_memberships = {}
rule.universes = {}
for i_premise, premise in enumerate(rule.premises):
if i_premise == 0:
if len(premise) == 2:
fuzzyvar, fuzzyset = premise
modifiers = None
else:
fuzzyvar = premise[0]
fuzzyset = premise[-1]
modifiers = premise[1:-1]
else:
if len(premise) == 3:
_, fuzzyvar, fuzzyset = premise
modifiers = None
else:
fuzzyvar = premise[1]
fuzzyset = premise[-1]
modifiers = premise[2:-1]
rule.modified_premise_memberships[
fuzzyvar.name
] = fuzzyvar.apply_modifiers(fuzzyset, modifiers)
rule.universes[fuzzyvar.name] = fuzzyvar.universe
def compute_modified_consequence_membership(self):
for rule in self.rules:
if len(rule.consequence) == 2:
modifiers = None
else:
modifiers = rule.consequence[1:-1]
fuzzyset = rule.consequence[-1]
rule.modified_consequence_membership = rule.consequence[0].apply_modifiers(
fuzzyset, modifiers
)
def build_infered_consequence(self):
self.infered_consequence = FuzzyVariable(
name=self.rules[0].consequence[0].name,
universe=self.rules[0].consequence[0].universe,
)
for i_rule, rule in enumerate(self.rules):
self.infered_consequence["Rule-{}".format(i_rule)] = rule.infered_membership
def aggregate_productions(self):
"""Computes the output fuzzy set of the inference system."""
infered_membership = None
if self.production_link == "max":
for rule in self.rules:
if infered_membership is None:
infered_membership = rule.infered_membership
else:
infered_membership = np.maximum(
infered_membership, rule.infered_membership
)
self.infered_membership = infered_membership
def fuzzificate(self, **values):
"""Computes the memberships of the antecedents.
Args:
values: crisp values for the antecedentes in the rule.
"""
for rule in self.rules:
rule.fuzzificated_values = {}
for name in rule.modified_premise_memberships.keys():
crisp_value = values[name]
rule.fuzzificated_values[name] = np.interp(
x=crisp_value,
xp=rule.universes[name],
fp=rule.modified_premise_memberships[name],
)
def defuzzificate(self):
self.defuzzificated_infered_membership = defuzzificate(
universe=self.infered_consequence.universe,
membership=self.infered_membership,
operator=self.defuzzification_operator,
)
# #############################################################################
#
#
# Decompositional Inference Method
#
#
# #############################################################################
class DecompositionalInference(InferenceMethod):
def __init__(
self,
input_type,
and_operator,
or_operator,
implication_operator,
composition_operator,
production_link,
defuzzification_operator,
):
super().__init__(
and_operator=and_operator,
or_operator=or_operator,
composition_operator=composition_operator,
production_link=production_link,
defuzzification_operator=defuzzification_operator,
)
self.implication_operator = implication_operator
self.input_type = input_type
#
def __call__(self, rules, **values):
self.rules = rules
self.compute_modified_premise_memberships()
self.compute_modified_consequence_membership()
self.compute_fuzzy_implication()
if self.input_type == "crisp":
self.fuzzificate(**values)
else:
self.fuzzificated_values = values.copy()
self.compute_fuzzy_composition()
self.compute_aggregation()
self.build_infered_consequence()
self.aggregate_productions()
self.defuzzificate()
return self.defuzzificated_infered_membership
def compute_fuzzy_implication(self):
#
# Implication operators
# See Kasabov, pag. 185
#
Ra = lambda u, v: np.minimum(1, 1 - u + v)
Rm = lambda u, v: np.maximum(np.minimum(u, v), 1 - u)
Rc = lambda u, v: np.minimum(u, v)
Rb = lambda u, v:
|
np.maximum(1 - u, v)
|
numpy.maximum
|
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
cols_t=np.array(['M_star', 'v_disk', 'm_cold gas', 'sfr_ave100Myr']) # old columns
cols_t = np.array(['halo_index (long) (0)',
'birthhaloid (long long)(1)',
'roothaloid (long long)(2)',
'redshift(3)',
'sat_type 0= central(4)',
'mhalo total halo mass [1.0E09 Msun](5)',
'm_strip stripped mass [1.0E09 Msun](6)',
'rhalo halo virial radius [Mpc)](7)',
'mstar stellar mass [1.0E09 Msun](8)',
'mbulge stellar mass of bulge [1.0E09 Msun] (9)',
' mstar_merge stars entering via mergers] [1.0E09 Msun](10)',
' v_disk rotation velocity of disk [km/s] (11)',
' sigma_bulge velocity dispersion of bulge [km/s](12)',
' r_disk exponential scale radius of stars+gas disk [kpc] (13)',
' r_bulge 3D effective radius of bulge [kpc](14)',
' mcold cold gas mass in disk [1.0E09 Msun](15)',
' mHI cold gas mass [1.0E09 Msun](16)',
' mH2 cold gas mass [1.0E09 Msun](17)',
' mHII cold gas mass [1.0E09 Msun](18)',
' Metal_star metal mass in stars [Zsun*Msun](19)',
' Metal_cold metal mass in cold gas [Zsun*Msun] (20)',
' sfr instantaneous SFR [Msun/yr](21)',
' sfrave20myr SFR averaged over 20 Myr [Msun/yr](22)',
' sfrave100myr SFR averaged over 100 Myr [Msun/yr](23)',
' sfrave1gyr SFR averaged over 1 Gyr [Msun/yr](24)',
' mass_outflow_rate [Msun/yr](25)',
' metal_outflow_rate [Msun/yr](26)',
' mBH black hole mass [1.0E09 Msun](27)',
' maccdot accretion rate onto BH [Msun/yr](28)',
' maccdot_radio accretion rate in radio mode [Msun/yr](29)',
' tmerge time since last merger [Gyr] (30)',
' tmajmerge time since last major merger [Gyr](31)',
' mu_merge mass ratio of last merger [](32)',
' t_sat time since galaxy became a satellite in this halo [Gyr](33)',
' r_fric distance from halo center [Mpc](34)',
' x_position x coordinate [cMpc](35)',
' y_position y coordinate [cMpc](36)',
' z_position z coordinate [cMpc](37)',
' vx x component of velocity [km/s](38)',
' vy y component of velocity [km/s](39)',
' vz z component of velocity [km/s](40)'])
cols_t = [t.replace(' ','') for t in cols_t]
cols_t = [t.replace('/','') for t in cols_t]
cols_t = np.array(cols_t)
def SAM_base(ys, pred, xs, Mh):
''' Basic lotting scheme for an unspecified range of targets, xs/Mh keywords aren't used, left for dependency
ys/pred should be the same dimensionality'''
fig, ax =plt.subplots(figsize=(6,6))
ax.plot(ys,pred, 'ro', alpha=0.3)
ax.plot([min(ys),max(ys)],[min(ys),max(ys)], 'k--', label='Perfect correspondance')
ax.set(xlabel='SAM Truth',ylabel='GNN Prediction', title='True/predicted correlation')
yhat=r'$\hat{y}$'
ax.text(0.6,0.15, f'Bias (mean(y-{yhat})) : {np.mean(ys-pred):.3f}', transform=ax.transAxes)
ax.text(0.6,0.1, r'$\sigma$ : '+f'{np.std(ys-pred):.3f}', transform=ax.transAxes)
ax.legend()
return fig
def multi_base(ys, pred, xs, Mh, targets):
''' Plotting scheme for an unspecified range of targets, xs/Mh keywords aren't used, left for dependency
ys/pred should be the same dimensionality, targets should be numerical indexed, not boolean'''
n_t = len(targets)
figs=[]
for n in range(n_t):
fig, ax =plt.subplots(1,2, figsize=(12,6))
ax=ax.flatten()
ax[0].plot(ys[:,n],pred[:,n], 'ro', alpha=0.3)
ax[0].plot([min(ys[:,n]),max(ys[:,n])],[min(ys[:,n]),max(ys[:,n])], 'k--', label='Perfect correspondance')
ax[0].set(xlabel='SAM Truth',ylabel='GNN Prediction', title=cols_t[targets[n]])
yhat=r'$\hat{y}$'
ax[0].text(0.6,0.15, f'Bias (mean(y-{yhat})) : {np.mean(ys[:,n]-pred[:,n]):.3f}', transform=ax[0].transAxes)
ax[0].text(0.6,0.1, r'$\sigma$ : '+f'{np.std(ys[:,n]-pred[:,n]):.3f}', transform=ax[0].transAxes)
ax[0].legend()
vals, x, y, _ =ax[1].hist2d(ys[:,n],pred[:,n],bins=50, norm=mpl.colors.LogNorm(), cmap=mpl.cm.magma)
X, Y = np.meshgrid((x[1:]+x[:-1])/2, (y[1:]+y[:-1])/2)
ax[1].contour(X,Y,
|
np.log(vals.T+1)
|
numpy.log
|
from collections import OrderedDict
import copy
import getpass
import itertools
import numpy as np
from scipy import signal
import time
LOCAL_MODE = getpass.getuser() == 'tom'
CONFIG = {
'halite_config_setting_divisor': 1.0,
'collect_smoothed_multiplier': 0.0,
'collect_actual_multiplier': 5.0,
'collect_less_halite_ships_multiplier_base': 0.55,
'collect_base_nearest_distance_exponent': 0.2,
'return_base_multiplier': 8.0,
'return_base_less_halite_ships_multiplier_base': 0.85,
'early_game_return_base_additional_multiplier': 0.1,
'early_game_return_boost_step': 50,
'establish_base_smoothed_multiplier': 0.0,
'establish_first_base_smoothed_multiplier_correction': 2.0,
'establish_base_dm_exponent': 1.1,
'first_base_no_4_way_camping_spot_bonus': 300*0,
'start_camp_if_not_winning': 0,
'max_camper_ship_budget': 2*1,
'relative_step_start_camping': 0.15,
'establish_base_deposit_multiplier': 1.0,
'establish_base_less_halite_ships_multiplier_base': 1.0,
'max_attackers_per_base': 3*1,
'attack_base_multiplier': 300.0,
'attack_base_less_halite_ships_multiplier_base': 0.9,
'attack_base_halite_sum_multiplier': 2.0,
'attack_base_run_opponent_multiplier': 1.0,
'attack_base_catch_opponent_multiplier': 1.0,
'collect_run_opponent_multiplier': 10.0,
'return_base_run_opponent_multiplier': 2.5,
'establish_base_run_opponent_multiplier': 2.5,
'collect_catch_opponent_multiplier': 1.0,
'return_base_catch_opponent_multiplier': 1.0,
'establish_base_catch_opponent_multiplier': 0.5,
'two_step_avoid_boxed_opponent_multiplier_base': 0.7,
'n_step_avoid_boxed_opponent_multiplier_base': 0.45,
'min_consecutive_chase_extrapolate': 6,
'chase_return_base_exponential_bonus': 2.0,
'ignore_catch_prob': 0.3,
'max_initial_ships': 60,
'max_final_ships': 60,
'max_standard_ships_decided_end_pack_hunting': 2,
'nearby_ship_halite_spawn_constant': 3.0,
'nearby_halite_spawn_constant': 5.0,
'remaining_budget_spawn_constant': 0.2,
'spawn_score_threshold': 75.0,
'boxed_in_halite_convert_divisor': 1.0,
'n_step_avoid_min_die_prob_cutoff': 0.05,
'n_step_avoid_window_size': 7,
'influence_map_base_weight': 2.0,
'influence_map_min_ship_weight': 0.0,
'influence_weights_additional_multiplier': 2.0,
'influence_weights_exponent': 8.0,
'escape_influence_prob_divisor': 3.0,
'rescue_ships_in_trouble': 1,
'target_strategic_base_distance': 8.0,
'target_strategic_num_bases_ship_divisor': 9,
'target_strategic_triangle_weight': 20.0, # initially: 20
'target_strategic_independent_base_distance_multiplier': 8.0, # initially 8.0
'target_strategic_influence_desirability_multiplier': 1.0, # initially: 1.0
'target_strategic_potential_divisor': 15.0, # initially: 15.0
'max_spawn_relative_step_divisor': 12.0,
'no_spawn_near_base_ship_limit': 100,
'avoid_cycles': 1,
'max_risk_n_step_risky': 0.5,
'max_steps_n_step_risky': 70,
'log_near_base_distance': 2,
'max_recent_considered_relevant_zero_move_count': 120,
'near_base_2_step_risky_min_count': 50,
'relative_stand_still_collect_boost': 1.5,
'initial_collect_boost_away_from_base': 2.0,
'start_hunting_season_relative_step': 0.1875,
'end_hunting_season_relative_step': 0.75,
'early_hunting_season_less_collect_relative_step': 0.375,
'max_standard_ships_early_hunting_season': 2,
'late_hunting_season_more_collect_relative_step': 0.5,
'late_hunting_season_collect_max_n_step_risk': 0.2,
'after_hunting_season_collect_max_n_step_risk': 0.5,
'late_hunting_season_standard_min_fraction': 0.7,
'max_standard_ships_late_hunting_season': 15,
'collect_on_safe_return_relative_step': 0.075,
'min_halite_to_stop_early_hunt': 15000.0,
'early_best_opponent_relative_step': 0.5,
'surrounding_ships_cycle_extrapolate_step_count': 5,
'surrounding_ships_extended_cycle_extrapolate_step_count': 7,
}
NORTH = "NORTH"
SOUTH = "SOUTH"
EAST = "EAST"
WEST = "WEST"
CONVERT = "CONVERT"
SPAWN = "SPAWN"
NOT_NONE_DIRECTIONS = [NORTH, SOUTH, EAST, WEST]
MOVE_DIRECTIONS = [None, NORTH, SOUTH, EAST, WEST]
MOVE_DIRECTIONS_TO_ID = {None: 0, NORTH: 1, SOUTH: 2, EAST: 3, WEST: 4}
RELATIVE_DIR_MAPPING = {None: (0, 0), NORTH: (-1, 0), SOUTH: (1, 0),
EAST: (0, 1), WEST: (0, -1)}
RELATIVE_DIR_TO_DIRECTION_MAPPING = {
v: k for k, v in RELATIVE_DIR_MAPPING.items()}
OPPOSITE_MAPPING = {None: None, NORTH: SOUTH, SOUTH: NORTH, EAST: WEST,
WEST: EAST}
RELATIVE_DIRECTIONS = [(-1, 0), (1, 0), (0, -1), (0, 1), (0, 0)]
RELATIVE_NOT_NONE_DIRECTIONS = [(-1, 0), (1, 0), (0, -1), (0, 1)]
MOVE_GATHER_OPTIONS = [(-1, 0, False), (1, 0, False), (0, -1, False),
(0, 1, False), (0, 0, True)]
TWO_STEP_THREAT_DIRECTIONS = {
(-2, 0): [(-1, 0)],
(-1, -1): [(-1, 0), (0, -1)],
(-1, 0): [(-1, 0), (0, 0)],
(-1, 1): [(-1, 0), (0, 1)],
(0, -2): [(0, -1)],
(0, -1): [(0, -1), (0, 0)],
(0, 1): [(0, 1), (0, 0)],
(0, 2): [(0, 1)],
(1, -1): [(1, 0), (0, -1)],
(1, 0): [(1, 0), (0, 0)],
(1, 1): [(1, 0),(0, 1)],
(2, 0): [(1, 0)],
}
GAUSSIAN_2D_KERNELS = {}
for dim in range(3, 20, 2):
# Modified from https://scipy-lectures.org/intro/scipy/auto_examples/solutions/plot_image_blur.html
center_distance = np.floor(np.abs(np.arange(dim) - (dim-1)/2))
horiz_distance = np.tile(center_distance, [dim, 1])
vert_distance = np.tile(np.expand_dims(center_distance, 1), [1, dim])
manh_distance = horiz_distance + vert_distance
kernel = np.exp(-manh_distance/(dim/4))
kernel[manh_distance > dim/2] = 0
GAUSSIAN_2D_KERNELS[dim] = kernel
DISTANCES = {}
DISTANCE_MASKS = {}
HALF_PLANES_CATCH = {}
HALF_PLANES_RUN = {}
ROW_COL_DISTANCE_MASKS = {}
ROW_COL_MAX_DISTANCE_MASKS = {}
ROW_COL_BOX_MAX_DISTANCE_MASKS = {}
ROW_COL_BOX_DIR_MAX_DISTANCE_MASKS = {}
BOX_DIR_MAX_DISTANCE = 4
BOX_DIRECTION_MASKS = {}
ROW_MASK = {}
COLUMN_MASK = {}
DISTANCE_MASK_DIM = 21
half_distance_mask_dim = int(DISTANCE_MASK_DIM/2)
for row in range(DISTANCE_MASK_DIM):
row_mask = np.zeros((DISTANCE_MASK_DIM, DISTANCE_MASK_DIM), dtype=np.bool)
row_mask[row] = 1
col_mask = np.zeros((DISTANCE_MASK_DIM, DISTANCE_MASK_DIM), dtype=np.bool)
col_mask[:, row] = 1
ROW_MASK [row] = row_mask
COLUMN_MASK[row] = col_mask
for col in range(DISTANCE_MASK_DIM):
horiz_distance = np.minimum(
np.abs(np.arange(DISTANCE_MASK_DIM) - col),
np.abs(np.arange(DISTANCE_MASK_DIM) - col - DISTANCE_MASK_DIM))
horiz_distance = np.minimum(
horiz_distance,
np.abs(np.arange(DISTANCE_MASK_DIM) - col + DISTANCE_MASK_DIM))
vert_distance = np.minimum(
np.abs(np.arange(DISTANCE_MASK_DIM) - row),
np.abs(np.arange(DISTANCE_MASK_DIM) - row - DISTANCE_MASK_DIM))
vert_distance = np.minimum(
vert_distance,
np.abs(np.arange(DISTANCE_MASK_DIM) - row + DISTANCE_MASK_DIM))
horiz_distance = np.tile(horiz_distance, [DISTANCE_MASK_DIM, 1])
vert_distance = np.tile(np.expand_dims(vert_distance, 1),
[1, DISTANCE_MASK_DIM])
manh_distance = horiz_distance + vert_distance
kernel = np.exp(-manh_distance/(DISTANCE_MASK_DIM/4))
DISTANCE_MASKS[(row, col)] = kernel
DISTANCES[(row, col)] = manh_distance
catch_distance_masks = {}
run_distance_masks = {}
for d in MOVE_DIRECTIONS:
if d is None:
catch_rows = np.array([]).astype(np.int)
catch_cols = np.array([]).astype(np.int)
if d == NORTH:
catch_rows = np.mod(row - np.arange(half_distance_mask_dim) - 1,
DISTANCE_MASK_DIM)
catch_cols = np.arange(DISTANCE_MASK_DIM)
box_dir_rows = np.mod(row + np.arange(BOX_DIR_MAX_DISTANCE) + 1,
DISTANCE_MASK_DIM)
box_dir_cols = np.mod(col + np.arange(
2*(BOX_DIR_MAX_DISTANCE+1)-1) - BOX_DIR_MAX_DISTANCE,
DISTANCE_MASK_DIM)
if d == SOUTH:
catch_rows = np.mod(row + np.arange(half_distance_mask_dim) + 1,
DISTANCE_MASK_DIM)
catch_cols = np.arange(DISTANCE_MASK_DIM)
box_dir_rows = np.mod(row - np.arange(BOX_DIR_MAX_DISTANCE) - 1,
DISTANCE_MASK_DIM)
box_dir_cols = np.mod(col + np.arange(
2*(BOX_DIR_MAX_DISTANCE+1)-1) - BOX_DIR_MAX_DISTANCE,
DISTANCE_MASK_DIM)
if d == WEST:
catch_cols = np.mod(col - np.arange(half_distance_mask_dim) - 1,
DISTANCE_MASK_DIM)
catch_rows = np.arange(DISTANCE_MASK_DIM)
box_dir_cols = np.mod(col + np.arange(BOX_DIR_MAX_DISTANCE) + 1,
DISTANCE_MASK_DIM)
box_dir_rows = np.mod(row + np.arange(
2*(BOX_DIR_MAX_DISTANCE+1)-1) - BOX_DIR_MAX_DISTANCE,
DISTANCE_MASK_DIM)
if d == EAST:
catch_cols = np.mod(col + np.arange(half_distance_mask_dim) + 1,
DISTANCE_MASK_DIM)
catch_rows = np.arange(DISTANCE_MASK_DIM)
box_dir_cols = np.mod(col - np.arange(BOX_DIR_MAX_DISTANCE) - 1,
DISTANCE_MASK_DIM)
box_dir_rows = np.mod(row + np.arange(
2*(BOX_DIR_MAX_DISTANCE+1)-1) - BOX_DIR_MAX_DISTANCE,
DISTANCE_MASK_DIM)
catch_mask = np.zeros((DISTANCE_MASK_DIM, DISTANCE_MASK_DIM),
dtype=np.bool)
catch_mask[catch_rows[:, None], catch_cols] = 1
run_mask = np.copy(catch_mask)
run_mask[row, col] = 1
catch_distance_masks[d] = catch_mask
run_distance_masks[d] = run_mask
if d is not None:
box_dir_mask = np.zeros((DISTANCE_MASK_DIM, DISTANCE_MASK_DIM),
dtype=np.bool)
box_dir_mask[box_dir_rows[:, None], box_dir_cols] = 1
if d in [NORTH, SOUTH]:
box_dir_mask &= (horiz_distance <= vert_distance)
else:
box_dir_mask &= (horiz_distance >= vert_distance)
ROW_COL_BOX_DIR_MAX_DISTANCE_MASKS[(row, col, d)] = box_dir_mask
HALF_PLANES_CATCH[(row, col)] = catch_distance_masks
HALF_PLANES_RUN[(row, col)] = run_distance_masks
for d in range(1, DISTANCE_MASK_DIM):
ROW_COL_DISTANCE_MASKS[(row, col, d)] = manh_distance == d
for d in range(half_distance_mask_dim):
ROW_COL_MAX_DISTANCE_MASKS[(row, col, d)] = manh_distance <= d
ROW_COL_BOX_MAX_DISTANCE_MASKS[(row, col, d)] = np.logical_and(
horiz_distance <= d, vert_distance <= d)
for dist in range(2, half_distance_mask_dim+1):
dist_mask_dim = dist*2+1
row_pos = np.tile(np.expand_dims(np.arange(dist_mask_dim), 1),
[1, dist_mask_dim])
col_pos = np.tile(np.arange(dist_mask_dim), [dist_mask_dim, 1])
for direction in NOT_NONE_DIRECTIONS:
if direction == NORTH:
box_mask = (row_pos < dist) & (
np.abs(col_pos-dist) <= (dist-row_pos))
if direction == SOUTH:
box_mask = (row_pos > dist) & (
np.abs(col_pos-dist) <= (row_pos-dist))
if direction == WEST:
box_mask = (col_pos < dist) & (
np.abs(row_pos-dist) <= (dist-col_pos))
if direction == EAST:
box_mask = (col_pos > dist) & (
np.abs(row_pos-dist) <= (col_pos-dist))
BOX_DIRECTION_MASKS[(dist, direction)] = box_mask
CONSIDERED_OTHER_DISTANCES = [13]
OTHER_DISTANCES = {}
for other_distance in CONSIDERED_OTHER_DISTANCES:
for row in range(other_distance):
for col in range(other_distance):
horiz_distance = np.minimum(
np.abs(np.arange(other_distance) - col),
np.abs(np.arange(other_distance) - col - other_distance))
horiz_distance = np.minimum(
horiz_distance,
np.abs(np.arange(other_distance) - col + other_distance))
vert_distance = np.minimum(
np.abs(np.arange(other_distance) - row),
np.abs(np.arange(other_distance) - row - other_distance))
vert_distance = np.minimum(
vert_distance,
np.abs(np.arange(other_distance) - row + other_distance))
horiz_distance = np.tile(horiz_distance, [other_distance, 1])
vert_distance = np.tile(np.expand_dims(vert_distance, 1),
[1, other_distance])
manh_distance = horiz_distance + vert_distance
OTHER_DISTANCES[(row, col, other_distance)] = manh_distance
D2_ROW_COL_SHIFTS_DISTANCES = [
(-2, 0, 2),
(-1, -1, 2), (-1, 0, 1), (-1, 1, 2),
(0, -2, 2), (0, -1, 1), (0, 1, 1), (0, 2, 2),
(1, -1, 2), (1, 0, 1), (1, 1, 2),
(2, 0, 2),
]
def row_col_from_square_grid_pos(pos, size):
col = pos % size
row = pos // size
return row, col
def move_ship_row_col(row, col, direction, size):
if direction == "NORTH":
return (size-1 if row == 0 else row-1, col)
elif direction == "SOUTH":
return (row+1 if row < (size-1) else 0, col)
elif direction == "EAST":
return (row, col+1 if col < (size-1) else 0)
elif direction == "WEST":
return (row, size-1 if col == 0 else col-1)
elif direction is None:
return (row, col)
def get_directional_distance(r1, c1, r2, c2, size, d):
relative_pos = get_relative_position(r1, c1, r2, c2, size)
if d == NORTH:
directional_distance = -relative_pos[0]
elif d == SOUTH:
directional_distance = relative_pos[0]
elif d == EAST:
directional_distance = relative_pos[1]
elif d == WEST:
directional_distance = -relative_pos[1]
return directional_distance
def mirror_edges(observation, num_mirror_dim):
if num_mirror_dim > 0:
# observation = np.arange(225).reshape((15,15)) # Debugging test
assert len(observation.shape) == 2
grid_size = observation.shape[0]
new_grid_size = grid_size + 2*num_mirror_dim
mirrored_obs = np.full((new_grid_size, new_grid_size), np.nan)
# Fill in the original data
mirrored_obs[num_mirror_dim:(-num_mirror_dim),
num_mirror_dim:(-num_mirror_dim)] = observation
# Add top and bottom mirrored data
mirrored_obs[:num_mirror_dim, num_mirror_dim:(
-num_mirror_dim)] = observation[-num_mirror_dim:, :]
mirrored_obs[-num_mirror_dim:, num_mirror_dim:(
-num_mirror_dim)] = observation[:num_mirror_dim, :]
# Add left and right mirrored data
mirrored_obs[:, :num_mirror_dim] = mirrored_obs[
:, -(2*num_mirror_dim):(-num_mirror_dim)]
mirrored_obs[:, -num_mirror_dim:] = mirrored_obs[
:, num_mirror_dim:(2*num_mirror_dim)]
observation = mirrored_obs
return observation
def smooth2d(grid, smooth_kernel_dim=7, return_kernel=False):
edge_augmented = mirror_edges(grid, smooth_kernel_dim-1)
kernel = GAUSSIAN_2D_KERNELS[int(2*smooth_kernel_dim-1)]
convolved = signal.convolve2d(edge_augmented, kernel, mode="valid")
if return_kernel:
return convolved, kernel
else:
return convolved
def get_relative_position(row, col, other_row, other_col, size):
if row >= other_row:
if (other_row + size - row) < (row - other_row):
row_diff = (other_row + size - row)
else:
row_diff = -(row - other_row)
else:
if (row + size - other_row) < (other_row - row):
row_diff = -(row + size - other_row)
else:
row_diff = other_row - row
if col >= other_col:
if (other_col + size - col) < (col - other_col):
col_diff = (other_col + size - col)
else:
col_diff = -(col - other_col)
else:
if (col + size - other_col) < (other_col - col):
col_diff = -(col + size - other_col)
else:
col_diff = other_col - col
return (row_diff, col_diff)
def update_scores_opponent_ships(
config, collect_grid_scores, return_to_base_scores, establish_base_scores,
attack_base_scores, opponent_ships, opponent_bases, halite_ships, row, col,
grid_size, spawn_cost, drop_None_valid, obs_halite, collect_rate, np_rng,
opponent_ships_sensible_actions, opponent_ships_sensible_actions_no_risk,
ignore_bad_attack_directions, observation, ship_k, my_bases, my_ships,
steps_remaining, history, escape_influence_probs, player_ids, env_obs_ids,
env_observation, main_base_distances, nearest_base_distances,
end_game_base_return, camping_override_strategy,
attack_campers_override_strategy, boxed_in_attack_squares,
safe_to_collect, boxed_in_zero_halite_opponents, ignore_convert_positions,
avoid_attack_squares_zero_halite, n_step_avoid_min_die_prob_cutoff,
safe_to_return_halites, safe_to_return_base_halites,
my_nearest_base_distances):
direction_halite_diff_distance_raw = {
NORTH: [], SOUTH: [], EAST: [], WEST: []}
my_bases_or_ships = np.logical_or(my_bases, my_ships)
chase_details = history['chase_counter'][0].get(ship_k, None)
take_my_square_next_halite_diff = None
take_my_next_square_dir = None
wide_cycle_mask = ROW_COL_MAX_DISTANCE_MASKS[row, col, 3]
tight_cycle_mask = ROW_COL_MAX_DISTANCE_MASKS[row, col, 2]
opponents_in_cycle = np.any(opponent_ships[tight_cycle_mask]) and (
np.all(history['empty_or_cycled_positions'][wide_cycle_mask]) or (
np.all(history['empty_or_extended_cycled_positions'][tight_cycle_mask])))
if opponents_in_cycle:
print("EXTRAPOLATING OPPONENT CYCLIC BEHAVIOR", observation['step'], row,
col)
if len(camping_override_strategy) == 0:
navigation_zero_halite_risk_threshold = 0
else:
navigation_zero_halite_risk_threshold = camping_override_strategy[0]
if camping_override_strategy[1].max() >= 1e4:
collect_grid_scores = 1e-4*collect_grid_scores + (
camping_override_strategy[1])
else:
collect_grid_scores += camping_override_strategy[1]
attack_base_scores += camping_override_strategy[2]
if len(attack_campers_override_strategy) > 0:
ignore_opponent_row = attack_campers_override_strategy[0]
ignore_opponent_col = attack_campers_override_strategy[1]
ignore_opponent_distance = attack_campers_override_strategy[5]
collect_grid_scores[ignore_opponent_row, ignore_opponent_col] += (
attack_campers_override_strategy[2])
navigation_zero_halite_risk_threshold = max(
navigation_zero_halite_risk_threshold,
attack_campers_override_strategy[6])
else:
ignore_opponent_row = None
ignore_opponent_col = None
ignore_opponent_distance = None
# Identify directions where I can certainly reach the base in time and always
# mark them as valid
ship_halite = halite_ships[row, col]
safe_return_base_directions = []
if ship_halite < safe_to_return_halites[row, col]:
for base_safe_return_halite, base_location in safe_to_return_base_halites:
if ship_halite < base_safe_return_halite[row, col]:
for d in get_dir_from_target(
row, col, base_location[0], base_location[1], grid_size):
if not d is None and not d in safe_return_base_directions:
safe_return_base_directions.append(d)
# if observation['step'] == 131 and ship_k in ['63-1']:
# import pdb; pdb.set_trace()
can_stay_still_zero_halite = True
for row_shift, col_shift, distance in D2_ROW_COL_SHIFTS_DISTANCES:
considered_row = (row + row_shift) % grid_size
considered_col = (col + col_shift) % grid_size
if opponent_ships[considered_row, considered_col] and (
ignore_opponent_row is None or (((
considered_row != ignore_opponent_row) or (
considered_col != ignore_opponent_col)) and (
ignore_opponent_distance > 2))):
relevant_dirs = []
halite_diff = halite_ships[row, col] - halite_ships[
considered_row, considered_col]
assume_take_my_square_next = False
# if observation['step'] == 266 and row == 11 and col == 15:
# import pdb; pdb.set_trace()
# Extrapolate the opponent behavior if we have been chased for a
# while and chasing is likely to continue
if distance == 1 and chase_details is not None and (
chase_details[1] >= config[
'min_consecutive_chase_extrapolate']) and (
considered_row, considered_col) == (
chase_details[4], chase_details[5]):
chaser_row = chase_details[4]
chaser_col = chase_details[5]
to_opponent_dir = get_dir_from_target(
row, col, chaser_row, chaser_col, grid_size)[0]
opp_to_me_dir = OPPOSITE_MAPPING[to_opponent_dir]
rel_opp_to_me_dir = RELATIVE_DIR_MAPPING[opp_to_me_dir]
opp_can_move_to_me = rel_opp_to_me_dir in (
opponent_ships_sensible_actions_no_risk[chaser_row, chaser_col])
# There is a unique opponent id with the least amount of halite
# on the chaser square or the chaser has at least one friendly
# ship that can replace it
chaser_can_replace = None
chaser_is_chased_by_not_me = None
if opp_can_move_to_me:
chaser_id = player_ids[chaser_row, chaser_col]
near_chaser = ROW_COL_MAX_DISTANCE_MASKS[
chaser_row, chaser_col, 1]
near_halite = halite_ships[near_chaser]
near_chaser_friendly_halite = near_halite[
(near_halite >= 0) & (player_ids[near_chaser] == chaser_id)]
min_non_chaser_halite = near_halite[
(near_halite >= 0) & (
player_ids[near_chaser] != chaser_id)].min()
min_near_chaser_halite = near_halite[near_halite >= 0].min()
opponent_min_hal_ids = player_ids[np.logical_and(
near_chaser, halite_ships == min_near_chaser_halite)]
near_me = ROW_COL_MAX_DISTANCE_MASKS[row, col, 1]
near_me_threat_players = player_ids[np.logical_and(
near_me, (halite_ships >= 0) & (
halite_ships < halite_ships[row, col]))]
double_opp_chase = (near_me_threat_players.size > 1) and (
np.all(near_me_threat_players == chaser_id))
chaser_can_replace = ((opponent_min_hal_ids.size > 1) and (
np.all(opponent_min_hal_ids == chaser_id) or (
(opponent_min_hal_ids == chaser_id).sum() > 1)) or (
(near_chaser_friendly_halite <= (
min_non_chaser_halite)).sum() > 1)) or double_opp_chase
if opp_can_move_to_me and not chaser_can_replace:
chaser_players_index = env_obs_ids[chaser_id]
chaser_k = [k for k, v in env_observation.players[
chaser_players_index][2].items() if v[0] == (
chaser_row*grid_size + chaser_col)][0]
chaser_is_chased = chaser_k in history[
'chase_counter'][chaser_id]
chaser_is_chased_by_not_me = chaser_is_chased
if chaser_is_chased:
chaser_chaser = history['chase_counter'][chaser_id][chaser_k]
chaser_is_chased_by_not_me = (chaser_chaser[4] is None) or (
player_ids[chaser_chaser[4], chaser_chaser[5]] != 0)
if opp_can_move_to_me and not chaser_can_replace and not (
chaser_is_chased_by_not_me):
assume_take_my_square_next = True
take_my_square_next_halite_diff = halite_diff
take_my_next_square_dir = to_opponent_dir
# if observation['step'] == 96 and ship_k in ['80-1']:
# import pdb; pdb.set_trace()
can_ignore_ship = False
if (considered_row, considered_col) in boxed_in_zero_halite_opponents:
can_stay_still_zero_halite = can_stay_still_zero_halite and (
distance == 2)
else:
if halite_ships[row, col] == halite_ships[
considered_row, considered_col]:
opponent_id = player_ids[considered_row, considered_col]
# Note: use the opponent distance because the opponent model is
# learned using the opponent distance to the nearest base (with near
# base distance cutoff typically at 2)
is_near_base = nearest_base_distances[
considered_row, considered_col] <= config['log_near_base_distance']
risk_lookup_k = str(is_near_base) + '_' + str(distance)
if distance == 2:
can_ignore_ship = history['zero_halite_move_behavior'][
opponent_id][risk_lookup_k] <= (
navigation_zero_halite_risk_threshold)
else:
risk_lookup_k_dist_zero = str(is_near_base) + '_' + str(0)
d1_threat = history['zero_halite_move_behavior'][
opponent_id][risk_lookup_k] > (
navigation_zero_halite_risk_threshold)
d0_threat = history['zero_halite_move_behavior'][
opponent_id][risk_lookup_k_dist_zero] > (
navigation_zero_halite_risk_threshold)
can_stay_still_zero_halite = can_stay_still_zero_halite and (
not d0_threat)
# if is_near_base and history['zero_halite_move_behavior'][
# opponent_id][str(is_near_base) + '_' + str(0) + '_ever_risky']:
# import pdb; pdb.set_trace()
can_ignore_ship = not (d0_threat or d1_threat)
if not assume_take_my_square_next and not can_ignore_ship:
relevant_dirs += [] if row_shift >= 0 else [NORTH]
relevant_dirs += [] if row_shift <= 0 else [SOUTH]
relevant_dirs += [] if col_shift <= 0 else [EAST]
relevant_dirs += [] if col_shift >= 0 else [WEST]
# When the opponents are in a cycle: only consider the direction I
# expect my opponent to be at in the next step (if any)
if opponents_in_cycle:
relevant_dirs = []
opponent_ship_key = history['opponent_ship_pos_to_key'][(
considered_row, considered_col)]
opponent_id = player_ids[considered_row, considered_col]
likely_opponent_action = history['opponent_cycle_counters'][
opponent_id-1][opponent_ship_key][1][0]
likely_opponent_next_pos = move_ship_row_col(
considered_row, considered_col, likely_opponent_action, grid_size)
relative_other_pos = get_relative_position(
row, col, likely_opponent_next_pos[0], likely_opponent_next_pos[1],
grid_size)
current_opp_relative_dir = get_relative_position(
row, col, considered_row, considered_col, grid_size)
if np.abs(relative_other_pos[0]) + np.abs(
relative_other_pos[1]) <= 1:
# At distance 1 or 0
# import pdb; pdb.set_trace()
if relative_other_pos[0] == 0 and relative_other_pos[1] == 0:
relevant_dirs = [RELATIVE_DIR_TO_DIRECTION_MAPPING[
current_opp_relative_dir]]
elif relative_other_pos == (0, 0):
relevant_dirs = [RELATIVE_DIR_TO_DIRECTION_MAPPING[
relative_other_pos]]
# if observation['step'] == 215 and ship_k == '2-2':
# import pdb; pdb.set_trace()
for d in relevant_dirs:
direction_halite_diff_distance_raw[d].append(
(halite_diff, distance))
direction_halite_diff_distance = {}
for d in direction_halite_diff_distance_raw:
vals = np.array(direction_halite_diff_distance_raw[d])
if vals.size:
diffs = vals[:, 0]
distances = vals[:, 1]
max_diff = diffs.max()
if max_diff > 0:
if can_stay_still_zero_halite:
greater_min_distance = distances[diffs > 0].min()
else:
# My halite is > 0 and I have a threat at D1 of an aggressive equal
# halite ships and a threat of a less halite ship at D2
greater_min_distance = distances[diffs >= 0].min()
direction_halite_diff_distance[d] = (max_diff, greater_min_distance)
elif max_diff == 0:
equal_min_distance = distances[diffs == 0].min()
direction_halite_diff_distance[d] = (max_diff, equal_min_distance)
else:
min_diff = diffs.min()
min_diff_min_distance = distances[diffs == min_diff].min()
direction_halite_diff_distance[d] = (min_diff, min_diff_min_distance)
else:
direction_halite_diff_distance[d] = None
preferred_directions = []
strongly_preferred_directions = []
valid_directions = copy.copy(MOVE_DIRECTIONS)
one_step_valid_directions = copy.copy(MOVE_DIRECTIONS)
bad_directions = []
ignore_catch = np_rng.uniform() < config['ignore_catch_prob']
# if observation['step'] == 221 and ship_k == '54-1':
# import pdb; pdb.set_trace()
# x=1
for direction, halite_diff_dist in direction_halite_diff_distance.items():
if halite_diff_dist is not None:
move_row, move_col = move_ship_row_col(row, col, direction, grid_size)
no_escape_bonus = 0 if not (
boxed_in_attack_squares[move_row, move_col]) else 5e3
halite_diff = halite_diff_dist[0]
if halite_diff >= 0:
# I should avoid a collision
distance_multiplier = 1/halite_diff_dist[1]
mask_collect_return = np.copy(HALF_PLANES_RUN[(row, col)][direction])
valid_directions.remove(direction)
one_step_valid_directions.remove(direction)
bad_directions.append(direction)
if halite_diff_dist[1] == 1:
if halite_diff > 0 or not can_stay_still_zero_halite:
# Only suppress the stay still action if the opponent has something
# to gain.
# Exception: the opponent may aggressively attack my zero halite
# ships
if None in valid_directions:
valid_directions.remove(None)
one_step_valid_directions.remove(None)
bad_directions.append(None)
else:
mask_collect_return[row, col] = False
# I can safely mine halite at the current square if the opponent ship
# is >1 move away
if halite_diff_dist[1] > 1:
mask_collect_return[row, col] = False
collect_grid_scores -= mask_collect_return*(ship_halite+spawn_cost)*(
config['collect_run_opponent_multiplier'])*distance_multiplier
return_to_base_scores -= mask_collect_return*(ship_halite+spawn_cost)*(
config['return_base_run_opponent_multiplier'])
base_nearby_in_direction_mask = np.logical_and(
ROW_COL_MAX_DISTANCE_MASKS[(row, col, 2)], mask_collect_return)
base_nearby_in_direction = np.logical_and(
base_nearby_in_direction_mask, opponent_bases).sum() > 0
if not ignore_bad_attack_directions and not base_nearby_in_direction:
attack_base_scores -= mask_collect_return*(ship_halite+spawn_cost)*(
config['attack_base_run_opponent_multiplier'])
mask_establish = np.copy(mask_collect_return)
mask_establish[row, col] = False
establish_base_scores -= mask_establish*(ship_halite+spawn_cost)*(
config['establish_base_run_opponent_multiplier'])
elif halite_diff < 0 and (
not ignore_catch or no_escape_bonus > 0) and (not (
move_row, move_col) in ignore_convert_positions):
# I would like a collision unless if there is another opponent ship
# chasing me - risk avoiding policy for now: if there is at least
# one ship in a direction that has less halite, I should avoid it
if no_escape_bonus > 0:
halite_diff = max(-spawn_cost/2, halite_diff) - no_escape_bonus
else:
halite_diff = 0 # Dubious choice, likely not very important
# halite_diff = max(-spawn_cost/2, halite_diff) - no_escape_bonus
distance_multiplier = 1/halite_diff_dist[1]
mask_collect_return = np.copy(HALF_PLANES_CATCH[(row, col)][direction])
collect_grid_scores -= mask_collect_return*halite_diff*(
config['collect_catch_opponent_multiplier'])*distance_multiplier
return_to_base_scores -= mask_collect_return*halite_diff*(
config['return_base_catch_opponent_multiplier'])*distance_multiplier
attack_base_scores -= mask_collect_return*halite_diff*(
config['attack_base_catch_opponent_multiplier'])*distance_multiplier
mask_establish = np.copy(mask_collect_return)
mask_establish[row, col] = False
establish_base_scores -= mask_establish*halite_diff*(
config['establish_base_catch_opponent_multiplier'])*(
distance_multiplier)
if no_escape_bonus > 0:
strongly_preferred_directions.append(direction)
if boxed_in_attack_squares[row, col] and no_escape_bonus > 0 and (
ship_halite > 0 or obs_halite[row, col] == 0):
# Also incentivize the None action when it is a possible escape
# square of an opponent - divide by 2 to make the None action less
# dominant (likely check in several directions)
collect_grid_scores[row, col] += no_escape_bonus/2
if not None in strongly_preferred_directions:
strongly_preferred_directions.append(None)
preferred_directions.append(direction)
if take_my_square_next_halite_diff is not None and None in valid_directions:
valid_directions.remove(None)
one_step_valid_directions.remove(None)
bad_directions.append(None)
if drop_None_valid and None in valid_directions:
valid_directions.remove(None)
one_step_valid_directions.remove(None)
valid_non_base_directions = []
base_directions = []
for d in valid_directions:
move_row, move_col = move_ship_row_col(row, col, d, grid_size)
if not opponent_bases[move_row, move_col] :
valid_non_base_directions.append(d)
else:
base_directions.append(d)
# For the remaining valid non base directions: compute a score that resembles
# the probability of being boxed in during the next step
two_step_bad_directions = []
n_step_bad_directions = []
n_step_bad_directions_die_probs = {}
if steps_remaining > 1:
for d in valid_non_base_directions:
my_next_halite = halite_ships[row, col] if d != None else (
halite_ships[row, col] + int(collect_rate*obs_halite[row, col]))
move_row, move_col = move_ship_row_col(row, col, d, grid_size)
my_next_halite = 0 if my_bases[move_row, move_col] else my_next_halite
opponent_mask = ROW_COL_MAX_DISTANCE_MASKS[(move_row, move_col, 3)]
less_halite_threat_opponents = np.where(np.logical_and(
opponent_mask, np.logical_and(
opponent_ships, my_next_halite > halite_ships)))
num_threat_ships = less_halite_threat_opponents[0].size
if num_threat_ships > 1 and not d in safe_return_base_directions:
all_dir_threat_counter = {
(-1, 0): 0, (1, 0): 0, (0, -1): 0, (0, 1): 0, (0, 0): 0}
for i in range(num_threat_ships):
other_row = less_halite_threat_opponents[0][i]
other_col = less_halite_threat_opponents[1][i]
relative_other_pos = get_relative_position(
move_row, move_col, other_row, other_col, grid_size)
for diff_rel_row, diff_rel_col, other_gather in MOVE_GATHER_OPTIONS:
# Only consider sensible opponent actions
if (diff_rel_row, diff_rel_col) in opponent_ships_sensible_actions[
other_row, other_col]:
is_threat = (not other_gather) or (my_next_halite > (
halite_ships[other_row, other_col] + int(
collect_rate*obs_halite[other_row, other_col])))
if is_threat:
other_rel_row = relative_other_pos[0] + diff_rel_row
other_rel_col = relative_other_pos[1] + diff_rel_col
move_diff = np.abs(other_rel_row) + np.abs(other_rel_col)
if move_diff < 3 and move_diff > 0:
threat_dirs = TWO_STEP_THREAT_DIRECTIONS[
(other_rel_row, other_rel_col)]
for threat_row_diff, threat_col_diff in threat_dirs:
all_dir_threat_counter[
(threat_row_diff, threat_col_diff)] += 1
# if observation['step'] == 112 and ship_k == '76-1':
# import pdb; pdb.set_trace()
# Aggregate the threat count in all_dir_threat_counter
threat_counts = np.array(list(all_dir_threat_counter.values()))
threat_score = np.sqrt(threat_counts.prod())
if threat_score > 0:
# Disincentivize an action that can get me boxed in on the next step
mask_avoid_two_steps = np.copy(HALF_PLANES_RUN[(row, col)][d])
if d is not None:
mask_avoid_two_steps[row, col] = False
collect_grid_scores[mask_avoid_two_steps] *= ((
config['two_step_avoid_boxed_opponent_multiplier_base']) ** (
threat_score))
return_to_base_scores[mask_avoid_two_steps] *= ((
config['two_step_avoid_boxed_opponent_multiplier_base']) ** (
threat_score))
establish_base_scores[mask_avoid_two_steps] *= ((
config['two_step_avoid_boxed_opponent_multiplier_base']) ** (
threat_score))
two_step_bad_directions.append(d)
if d not in two_step_bad_directions and not end_game_base_return and (
my_next_halite > 0) and (not d in safe_return_base_directions) and (
d is not None or not safe_to_collect[row, col]):
# For the remaining valid directions: compute a score that resembles
# the probability of being boxed in sometime in the future
opponent_mask_lt = ROW_COL_MAX_DISTANCE_MASKS[
(move_row, move_col, min(
steps_remaining, config['n_step_avoid_window_size']))]
less_halite_threat_opponents_lt = np.where(np.logical_and(
opponent_mask_lt, np.logical_and(
opponent_ships, my_next_halite > halite_ships)))
num_threat_ships_lt = less_halite_threat_opponents_lt[0].size
# Ignore the box in threat if I have a base and at least one zero
# halite ship one step from the move square
ignore_threat = my_bases[
ROW_COL_DISTANCE_MASKS[(move_row, move_col, 1)]].sum() > 0 and ((
halite_ships[np.logical_and(
my_ships,
ROW_COL_DISTANCE_MASKS[move_row, move_col, 1])] == 0).sum() > 0)
# if observation['step'] == 359 and ship_k == '67-1':
# import pdb; pdb.set_trace()
if not ignore_threat:
lt_catch_prob = {k: [] for k in RELATIVE_NOT_NONE_DIRECTIONS}
for i in range(num_threat_ships_lt):
other_row = less_halite_threat_opponents_lt[0][i]
other_col = less_halite_threat_opponents_lt[1][i]
other_sensible_actions = opponent_ships_sensible_actions[
other_row, other_col]
relative_other_pos = get_relative_position(
move_row, move_col, other_row, other_col, grid_size)
# Give less weight to the other ship if there is a base of mine or
# a/multiple less halite ships in between
# FUTURE WORK: Also give additional move leeway if I have nearby
# bases? Especially relevant for None (collect) actions
distance_move_other = np.abs(relative_other_pos).sum()
mask_between_move_and_threat = np.logical_and(
DISTANCES[(move_row, move_col)] < distance_move_other,
DISTANCES[(other_row, other_col)] < distance_move_other)
less_halite_ship_base_count = np.logical_and(
np.logical_and(my_bases_or_ships, mask_between_move_and_threat),
halite_ships <= halite_ships[other_row, other_col]).sum() + 0*(
my_bases[ROW_COL_MAX_DISTANCE_MASKS[
move_row, move_col, 2]].sum())
my_material_defense_multiplier = 2**less_halite_ship_base_count
for threat_dir in RELATIVE_NOT_NONE_DIRECTIONS:
nz_dim = int(threat_dir[0] == 0)
dir_offset = relative_other_pos[nz_dim]*threat_dir[nz_dim]
other_dir_abs_offset = np.abs(relative_other_pos[1-nz_dim])
# if observation['step'] == 155 and ship_k == '63-2':
# import pdb; pdb.set_trace()
if dir_offset >= 0 and (other_dir_abs_offset-1) <= dir_offset:
# Ignore the threat if the ship is on the diagonal and can not
# move in the direction of the threat dir
if (other_dir_abs_offset-1) == dir_offset and len(
other_sensible_actions) < len(MOVE_DIRECTIONS):
if nz_dim == 0:
threat_other_dir = (
0, 1 if relative_other_pos[1-nz_dim] < 0 else -1)
else:
threat_other_dir = (
1 if relative_other_pos[1-nz_dim] < 0 else -1, 0)
threat_other_dirs = [threat_other_dir, threat_dir]
threats_actionable = np.array([
t in other_sensible_actions for t in threat_other_dirs])
consider_this_threat = np.any(threats_actionable)
if threats_actionable[1] and not threats_actionable[0]:
# Lower the threat weight - the opponent can not directly
# attack the considered threat direction and can only move
# along the threat direction
other_dir_abs_offset += 2
else:
consider_this_threat = True
if other_dir_abs_offset == 0 and dir_offset == 0:
# The scenario where a one step threat is ignored due to
# being chased for a while and moving to the threat is
# currently considered.
# This avoids division by zero but is overridden later anyway
other_dir_abs_offset = 2
if consider_this_threat:
lt_catch_prob[threat_dir].append(max(2,
other_dir_abs_offset+dir_offset)*(
my_material_defense_multiplier))
# Add a "bootstrapped" catch probability using the density of the
# players towards the edge of the threat direction
# Only add it if the next halite is > 0 (otherwise assume I can
# always escape)
# Also factor in the distance to my nearest non abandoned base
if my_next_halite > 0:
current_nearest_base_distance = my_nearest_base_distances[row, col]
moved_nearest_base_distance = my_nearest_base_distances[
move_row, move_col]
move_distance_difference = current_nearest_base_distance - (
moved_nearest_base_distance)
for threat_dir in RELATIVE_NOT_NONE_DIRECTIONS:
dens_threat_rows = np.mod(move_row + threat_dir[0]*(
np.arange(config['n_step_avoid_window_size']//2,
config['n_step_avoid_window_size'])), grid_size)
dens_threat_cols = np.mod(move_col + threat_dir[1]*(
1+np.arange(config['n_step_avoid_window_size']//2,
config['n_step_avoid_window_size'])), grid_size)
escape_probs = escape_influence_probs[
dens_threat_rows, dens_threat_cols]
mean_escape_prob = escape_probs.mean()
if escape_probs[:2].min() < 1:
if move_distance_difference > 0:
# When in trouble, it is typically better to move towards one
# of my bases. The move closer distance is of course 1.
mean_escape_prob *= 1.25
if mean_escape_prob < 1:
lt_catch_prob[threat_dir].append(1/(1-mean_escape_prob+1e-9))
# if observation['step'] == 75 and ship_k == '64-1' and d in [
# EAST, WEST]:
# import pdb; pdb.set_trace()
# if observation['step'] == 112 and ship_k == '76-1':
# import pdb; pdb.set_trace()
if np.all([len(v) > 0 for v in lt_catch_prob.values()]):
# Interpretation: for a threat at distance d, I have a probability
# of surviving it of (d-1)/d. The probability of surviving all
# threat is the product of all individual threats
survive_probs = np.array([
(np.maximum(0.2, (np.array(lt_catch_prob[k])-1)/np.array(
lt_catch_prob[k]))).prod() for k in lt_catch_prob])
min_die_prob = 1-survive_probs.max()
if main_base_distances.max() > 0:
if main_base_distances[move_row, move_col] <= 2:
min_die_prob = 0
else:
min_die_prob = max(
0, min_die_prob-0.33**main_base_distances[
move_row, move_col])
# if observation['step'] == 155 and ship_k in ['63-2', '63-1']:
# import pdb; pdb.set_trace()
# Disincentivize an action that can get me boxed in during the next
# N steps
mask_avoid_n_steps = np.copy(HALF_PLANES_RUN[(row, col)][d])
if d is not None:
mask_avoid_n_steps[row, col] = False
collect_grid_scores[mask_avoid_n_steps] *= ((
config['n_step_avoid_boxed_opponent_multiplier_base']) ** (
min_die_prob))
return_to_base_scores[mask_avoid_n_steps] *= (
config['n_step_avoid_boxed_opponent_multiplier_base']) ** (
min_die_prob)
establish_base_scores[mask_avoid_n_steps] *= (
config['n_step_avoid_boxed_opponent_multiplier_base']) ** (
min_die_prob)
n_step_bad_directions_die_probs[d] = min_die_prob
# Correction to act with more risk towards the end of the game
die_prob_cutoff = (n_step_avoid_min_die_prob_cutoff + 0.01*max(
0, 50-steps_remaining))
if d is None:
if observation['relative_step'] > config[
'end_hunting_season_relative_step']:
die_prob_cutoff = max(die_prob_cutoff, config[
'after_hunting_season_collect_max_n_step_risk'])
elif observation['relative_step'] > config[
'late_hunting_season_more_collect_relative_step']:
die_prob_cutoff = max(die_prob_cutoff, config[
'late_hunting_season_collect_max_n_step_risk'])
# print(observation['step'], die_prob_cutoff)
if min_die_prob > die_prob_cutoff:
n_step_bad_directions.append(d)
# if observation['step'] == 215 and ship_k == '2-2':
# import pdb; pdb.set_trace()
# Corner case: if I have a zero halite ship that is boxed in by other zero
# halite ships on a zero halite square: compute the risk for all available
# actions and only retain the actions with the lowest collision risks
if halite_ships[row, col] == 0 and len(valid_directions) == 0 and (
obs_halite[row, col] == 0):
risk_scores = np.zeros(len(MOVE_DIRECTIONS))
for risk_id, d in enumerate(MOVE_DIRECTIONS):
move_row, move_col = move_ship_row_col(row, col, d, grid_size)
for potential_threat_dir in MOVE_DIRECTIONS:
threat_row, threat_col = move_ship_row_col(
move_row, move_col, potential_threat_dir, grid_size)
if opponent_ships[threat_row, threat_col] and halite_ships[
threat_row, threat_col] == 0:
opponent_id = player_ids[threat_row, threat_col]
is_near_base = nearest_base_distances[
threat_row, threat_col] <= config['log_near_base_distance']
distance = int(d is not None) + int(potential_threat_dir is not None)
risk_lookup_k = str(is_near_base) + '_' + str(distance)
risk_scores[risk_id] = max(
risk_scores[risk_id], history['zero_halite_move_behavior'][
opponent_id][risk_lookup_k])
best_risk_score = risk_scores.min()
if best_risk_score < 0.05:
valid_directions = [d for d_id, d in enumerate(
MOVE_DIRECTIONS) if risk_scores[d_id] == best_risk_score]
else:
valid_directions = [None]
one_step_valid_directions = copy.copy(valid_directions)
bad_directions = list(set(MOVE_DIRECTIONS) - set(valid_directions))
# if observation['step'] == 169 and ship_k == '65-2':
# import pdb; pdb.set_trace()
# Corner case: if I have a zero halite ship that is boxed in by other zero
# halite ships on a non-zero halite square: prefer moving in directions where
# there is a lower risk of losing the ship as a function of opponent zero
# halite behavior
if halite_ships[row, col] == 0 and obs_halite[row, col] > 0 and (
(len(valid_directions) == 1 and (valid_directions[0] is None)) or (
len(valid_directions) == 0)):
risk_scores = np.zeros(len(MOVE_DIRECTIONS))
risk_scores[0] = 1 # Definitely don't stand still
for risk_id, d in enumerate(MOVE_DIRECTIONS):
move_row, move_col = move_ship_row_col(row, col, d, grid_size)
for potential_threat_dir in MOVE_DIRECTIONS:
threat_row, threat_col = move_ship_row_col(
move_row, move_col, potential_threat_dir, grid_size)
if opponent_ships[threat_row, threat_col] and halite_ships[
threat_row, threat_col] == 0:
opponent_id = player_ids[threat_row, threat_col]
is_near_base = nearest_base_distances[
threat_row, threat_col] <= config['log_near_base_distance']
distance = int(d is not None) + int(potential_threat_dir is not None)
risk_lookup_k = str(is_near_base) + '_' + str(distance)
risk_scores[risk_id] = max(
risk_scores[risk_id], history['zero_halite_move_behavior'][
opponent_id][risk_lookup_k])
best_risk_score = risk_scores.min()
valid_directions = [d for d_id, d in enumerate(
MOVE_DIRECTIONS) if risk_scores[d_id] == best_risk_score]
one_step_valid_directions = copy.copy(valid_directions)
bad_directions = list(set(MOVE_DIRECTIONS) - set(valid_directions))
# Treat attack squares I should avoid with a zero halite ship as N-step bad
# directions, if that leaves us with options
if np.any(avoid_attack_squares_zero_halite) and halite_ships[
row, col] == 0 and steps_remaining > 1:
avoid_attack_directions = []
for d in valid_non_base_directions:
move_row, move_col = move_ship_row_col(row, col, d, grid_size)
if avoid_attack_squares_zero_halite[move_row, move_col]:
avoid_attack_directions.append(d)
if len(avoid_attack_directions):
all_bad_dirs = set(bad_directions + (
two_step_bad_directions + n_step_bad_directions))
updated_bad_dirs = all_bad_dirs.union(set(avoid_attack_directions))
if len(updated_bad_dirs) > len(all_bad_dirs) and len(
updated_bad_dirs) < len(MOVE_DIRECTIONS):
new_bad_directions = list(updated_bad_dirs.difference(all_bad_dirs))
# import pdb; pdb.set_trace()
n_step_bad_directions.extend(new_bad_directions)
for new_bad_dir in new_bad_directions:
if not new_bad_dir in n_step_bad_directions_die_probs:
n_step_bad_directions_die_probs[new_bad_dir] = 0
# Corner case: if I can replace a chaser position and there are only very
# bad two step escape directions left: replace the chaser
if take_my_next_square_dir is not None and (
take_my_next_square_dir in two_step_bad_directions):
make_chase_replace_n_bad = True
for d in NOT_NONE_DIRECTIONS:
if not d == take_my_next_square_dir:
if d in n_step_bad_directions:
if n_step_bad_directions_die_probs[d] < 0.6:
make_chase_replace_n_bad = False
break
elif d in valid_directions:
make_chase_replace_n_bad = False
break
if make_chase_replace_n_bad:
print("CHASE: turning two step bad into n step bad", observation['step'],
row, col)
two_step_bad_directions.remove(take_my_next_square_dir)
# Treat the chasing - replace chaser position as an n-step bad action.
# Otherwise, we can get trapped in a loop of dumb behavior.
if take_my_next_square_dir is not None and not take_my_next_square_dir in (
two_step_bad_directions) and not take_my_next_square_dir in (
n_step_bad_directions):
n_step_bad_directions.append(take_my_next_square_dir)
n_step_bad_directions_die_probs[take_my_next_square_dir] = 1/4
# If all valid non base directions are n step bad actions: drop n step bad
# actions (call them 2 step bad) that are significantly worse than other n
# step bad actions
all_original_n_step_bad_directions = copy.copy(n_step_bad_directions)
all_n_step_bad_directions_die_probs = copy.copy(
n_step_bad_directions_die_probs)
if len(n_step_bad_directions) > 1 and len(
n_step_bad_directions) == len(valid_non_base_directions) and np.all(
np.array([d in n_step_bad_directions for d in (
valid_non_base_directions)])):
die_probs = np.array(list(n_step_bad_directions_die_probs.values()))
max_die_prob = min(die_probs.min()*2, die_probs.min()+0.1)
delete_from_n_step_bad = []
for d in n_step_bad_directions:
if n_step_bad_directions_die_probs[d] > max_die_prob and (
not d in safe_return_base_directions):
delete_from_n_step_bad.append(d)
for d in delete_from_n_step_bad:
two_step_bad_directions.append(d)
n_step_bad_directions.remove(d)
del n_step_bad_directions_die_probs[d]
if valid_non_base_directions:
valid_not_preferred_dirs = list(set(
two_step_bad_directions + n_step_bad_directions))
if valid_not_preferred_dirs and (
len(valid_non_base_directions) - len(valid_not_preferred_dirs)) > 0:
# Drop 2 and n step bad directions if that leaves us with valid options
bad_directions.extend(valid_not_preferred_dirs)
bad_directions = list(set(bad_directions))
valid_directions = list(
set(valid_directions) - set(valid_not_preferred_dirs))
else:
# Drop 2 step bad directions if that leaves us with valid options
valid_not_preferred_dirs = set(two_step_bad_directions)
if valid_not_preferred_dirs and (
len(valid_non_base_directions) - len(valid_not_preferred_dirs)) > 0:
bad_directions.extend(valid_not_preferred_dirs)
valid_directions = list(
set(valid_directions) - set(valid_not_preferred_dirs))
# Only keep the strongly preferred directions if there are any
if len(strongly_preferred_directions) > 0:
preferred_directions = strongly_preferred_directions
# Drop repetitive actions if that leaves us with valid options
if ship_k in history['avoid_cycle_actions']:
repetitive_action = history['avoid_cycle_actions'][ship_k]
if repetitive_action in valid_directions and len(valid_directions) > 1:
valid_directions.remove(repetitive_action)
if repetitive_action in preferred_directions:
preferred_directions.remove(repetitive_action)
if repetitive_action in one_step_valid_directions:
one_step_valid_directions.remove(repetitive_action)
bad_directions.append(repetitive_action)
# if observation['step'] == 180 and ship_k == '10-2':
# import pdb; pdb.set_trace()
return (collect_grid_scores, return_to_base_scores, establish_base_scores,
attack_base_scores, preferred_directions, valid_directions,
len(bad_directions) == len(MOVE_DIRECTIONS), two_step_bad_directions,
n_step_bad_directions, one_step_valid_directions,
n_step_bad_directions_die_probs, all_original_n_step_bad_directions,
all_n_step_bad_directions_die_probs)
# Update the scores as a function of blocking opponent bases
def update_scores_blockers(
collect_grid_scores, return_to_base_scores, establish_base_scores,
attack_base_scores, row, col, grid_size, blockers,
blocker_max_distances_to_consider, valid_directions,
one_step_valid_directions, early_base_direct_dir=None,
blocker_max_distance=half_distance_mask_dim, update_attack_base=True):
one_step_bad_directions = []
for d in NOT_NONE_DIRECTIONS:
if d == NORTH:
rows = np.mod(row - (1 + np.arange(blocker_max_distance)), grid_size)
cols = np.repeat(col, blocker_max_distance)
considered_vals = blockers[rows, col]
considered_max_distances = blocker_max_distances_to_consider[rows, col]
elif d == SOUTH:
rows = np.mod(row + (1 + np.arange(blocker_max_distance)), grid_size)
cols = np.repeat(col, blocker_max_distance)
considered_vals = blockers[rows, col]
considered_max_distances = blocker_max_distances_to_consider[rows, col]
elif d == WEST:
rows = np.repeat(row, blocker_max_distance)
cols = np.mod(col - (1 + np.arange(blocker_max_distance)), grid_size)
considered_vals = blockers[row, cols]
considered_max_distances = blocker_max_distances_to_consider[row, cols]
elif d == EAST:
rows = np.repeat(row, blocker_max_distance)
cols = np.mod(col + (1 + np.arange(blocker_max_distance)), grid_size)
considered_vals = blockers[row, cols]
considered_max_distances = blocker_max_distances_to_consider[row, cols]
if d == early_base_direct_dir:
considered_vals[0] = 1
is_blocking = np.logical_and(considered_vals, np.arange(
blocker_max_distance) < considered_max_distances)
if np.any(is_blocking):
first_blocking_id = np.where(is_blocking)[0][0]
mask_rows = rows[first_blocking_id:]
mask_cols = cols[first_blocking_id:]
collect_grid_scores[mask_rows, mask_cols] = -1e12
return_to_base_scores[mask_rows, mask_cols] = -1e12
establish_base_scores[mask_rows, mask_cols] = -1e12
if update_attack_base:
attack_base_scores[mask_rows, mask_cols] = -1e12
if first_blocking_id == 0:
one_step_bad_directions.append(d)
if d in valid_directions:
valid_directions.remove(d)
if d in one_step_valid_directions:
one_step_valid_directions.remove(d)
# Lower the score for entire quadrants when the two quadrant directions are
# blocking the movement
num_bad_one_directions = len(one_step_bad_directions)
if num_bad_one_directions > 1:
for i in range(num_bad_one_directions-1):
bad_direction_1 = one_step_bad_directions[i]
for j in range(i+1, num_bad_one_directions):
bad_direction_2 = one_step_bad_directions[j]
if (bad_direction_1 in [NORTH, SOUTH]) != (
bad_direction_2 in [NORTH, SOUTH]):
bad_quadrant_mask = np.logical_and(
HALF_PLANES_CATCH[row, col][bad_direction_1],
HALF_PLANES_CATCH[row, col][bad_direction_2])
collect_grid_scores[bad_quadrant_mask] = -1e12
return_to_base_scores[bad_quadrant_mask] = -1e12
establish_base_scores[bad_quadrant_mask] = -1e12
if update_attack_base:
attack_base_scores[bad_quadrant_mask] = -1e12
# Additional logic for the use of avoiding collisions when there is only a
# single escape direction
if blockers[row, col]:
collect_grid_scores[row, col] = -1e12
return_to_base_scores[row, col] = -1e12
establish_base_scores[row, col] = -1e12
attack_base_scores[row, col] = -1e12
if None in valid_directions:
valid_directions.remove(None)
if None in one_step_valid_directions:
one_step_valid_directions.remove(None)
return (collect_grid_scores, return_to_base_scores, establish_base_scores,
attack_base_scores, valid_directions, one_step_valid_directions,
one_step_bad_directions)
def set_scores_single_nearby_zero(scores, nearby, size, ship_row, ship_col,
nearby_distance=1):
nearby_pos = np.where(nearby)
row = nearby_pos[0][0]
col = nearby_pos[1][0]
next_nearby_pos = None
drop_None_valid = False
for i in range(-nearby_distance, nearby_distance+1):
near_row = (row + i) % size
for j in range(-nearby_distance, nearby_distance+1):
near_col = (col + j) % size
if i != 0 or j != 0:
# Don't gather near the base and don't move on top of it
scores[near_row, near_col] = -1e7
if near_row == ship_row and near_col == ship_col:
next_nearby_pos = get_dir_from_target(
ship_row, ship_col, row, col, size)[0]
else:
if near_row == ship_row and near_col == ship_col:
# Don't stay on top of the base
drop_None_valid = True
return scores, next_nearby_pos, drop_None_valid
def grid_distance(r1, c1, r2, c2, size):
horiz_diff = c2-c1
horiz_distance = min(np.abs(horiz_diff),
min(np.abs(horiz_diff-size), np.abs(horiz_diff+size)))
vert_diff = r2-r1
vert_distance = min(np.abs(vert_diff),
min(np.abs(vert_diff-size), np.abs(vert_diff+size)))
return horiz_distance+vert_distance
def override_early_return_base_scores(
base_return_grid_multiplier, my_bases, ship_row, ship_col, my_ship_count):
base_pos = np.where(my_bases)
base_row = base_pos[0][0]
base_col = base_pos[1][0]
dist_to_base = DISTANCES[base_row, base_col][ship_row, ship_col]
# Remember the rule that blocks spawning when a ship is about to return
if dist_to_base <= 10-my_ship_count:
base_return_grid_multiplier[base_row, base_col] = 0
return base_return_grid_multiplier
def get_nearest_base_distances(grid_size, ignore_abandoned, observation):
base_dms = []
base_distances = []
# for b in player_obs[1]:
# row, col = row_col_from_square_grid_pos(player_obs[1][b], grid_size)
# if not (row, col) in ignore_abandoned:
# base_dms.append(DISTANCE_MASKS[(row, col)])
# base_distances.append(DISTANCES[(row, col)])
my_bases = np.copy(observation['rewards_bases_ships'][0][1])
for r, c in ignore_abandoned:
my_bases[r, c] = 0
num_my_bases = my_bases.sum()
if num_my_bases > 0:
my_base_positions = np.where(my_bases)
for base_id in range(num_my_bases):
base_row = my_base_positions[0][base_id]
base_col = my_base_positions[1][base_id]
base_dms.append(DISTANCE_MASKS[(base_row, base_col)])
base_distances.append(DISTANCES[(base_row, base_col)])
if base_dms:
base_nearest_distance_scores = np.stack(base_dms).max(0)
all_base_distances = np.stack(base_distances)
else:
base_nearest_distance_scores = np.ones((grid_size, grid_size))
all_base_distances = 99*np.ones((1, grid_size, grid_size))
nearest_base_distances = np.min(all_base_distances, 0)
return (base_nearest_distance_scores, all_base_distances,
nearest_base_distances)
def get_valid_opponent_ship_actions(
config, rewards_bases_ships, halite_ships, size, history,
nearest_base_distances, observation, env_config):
opponent_ships_sensible_actions = {}
opponent_ships_sensible_actions_no_risk = {}
boxed_in_zero_halite_opponents = []
likely_convert_opponent_positions = []
possible_convert_opponent_positions = []
num_agents = len(rewards_bases_ships)
convert_cost = env_config.convertCost
stacked_bases = np.stack([rbs[1] for rbs in rewards_bases_ships])
stacked_ships = np.stack([rbs[2] for rbs in rewards_bases_ships])
num_players = stacked_ships.shape[0]
grid_size = stacked_ships.shape[1]
player_base_ids = -1*np.ones((grid_size, grid_size))
boxed_in_attack_squares = np.zeros((grid_size, grid_size), dtype=np.bool)
boxed_in_opponent_ids = -1*np.ones((grid_size, grid_size), dtype=np.int)
opponent_single_escape_pos = np.zeros(
(grid_size, grid_size), dtype=np.bool)
single_escape_mapping = {}
for i in range(num_players):
player_base_ids[stacked_bases[i]] = i
for i in range(1, num_agents):
opponent_ships = stacked_ships[i]
enemy_ships = np.delete(stacked_ships, (i), axis=0).sum(0)
ship_pos = np.where(opponent_ships)
num_ships = ship_pos[0].size
for j in range(num_ships):
valid_rel_directions = copy.copy(RELATIVE_DIRECTIONS)
valid_rel_directions_no_move_risk = copy.copy(RELATIVE_DIRECTIONS)
row = ship_pos[0][j]
col = ship_pos[1][j]
ship_halite = halite_ships[row, col]
for row_diff in range(-2, 3):
for col_diff in range(-2, 3):
distance = (np.abs(row_diff) + np.abs(col_diff))
if distance == 1 or distance == 2:
other_row = (row + row_diff) % size
other_col = (col + col_diff) % size
if enemy_ships[other_row, other_col]:
hal_diff = halite_ships[other_row, other_col] - ship_halite
# if observation['step'] == 189 and row == 14 and col == 2:
# import pdb; pdb.set_trace()
ignores_move_collision = False
risky_stay_still_collision = False
if halite_ships[row, col] == halite_ships[
other_row, other_col]:
# Note: use the opponent distance because the opponent model is
# learned using the opponent distance to the nearest base (with
# near base distance cutoff typically at 2)
is_near_base = nearest_base_distances[
other_row, other_col] <= config['log_near_base_distance']
risk_lookup_k = str(is_near_base) + '_' + str(distance) + (
'_ever_risky')
if distance == 2:
ignores_move_collision = history[
'zero_halite_move_behavior'][i][risk_lookup_k]
else:
risk_lookup_k_dist_zero = str(is_near_base) + '_' + str(
0) + '_ever_risky'
risky_stay_still_collision = history[
'zero_halite_move_behavior'][i][risk_lookup_k]
ignores_move_collision = history[
'zero_halite_move_behavior'][i][risk_lookup_k_dist_zero]
# if ignores_move_collision and distance == 1:
# import pdb; pdb.set_trace()
# x=1
rem_dirs = []
if risky_stay_still_collision:
rem_dirs += [(0, 0)] if distance == 1 and hal_diff <= 0 else []
else:
rem_dirs += [(0, 0)] if distance == 1 and hal_diff < 0 else []
if not ignores_move_collision:
rem_dirs += [(-1, 0)] if row_diff < 0 and hal_diff <= 0 else []
rem_dirs += [(1, 0)] if row_diff > 0 and hal_diff <= 0 else []
rem_dirs += [(0, -1)] if col_diff < 0 and hal_diff <= 0 else []
rem_dirs += [(0, 1)] if col_diff > 0 and hal_diff <= 0 else []
for d in rem_dirs:
if d in valid_rel_directions:
valid_rel_directions.remove(d)
# if observation['step'] == 146 and row == 13 and col == 13:
# import pdb; pdb.set_trace()
# Don't check for risky opponent zero halite behavior
rem_dirs = []
if risky_stay_still_collision:
rem_dirs += [(0, 0)] if distance == 1 and hal_diff <= 0 else []
else:
rem_dirs += [(0, 0)] if distance == 1 and hal_diff < 0 else []
rem_dirs += [(-1, 0)] if row_diff < 0 and hal_diff <= 0 else []
rem_dirs += [(1, 0)] if row_diff > 0 and hal_diff <= 0 else []
rem_dirs += [(0, -1)] if col_diff < 0 and hal_diff <= 0 else []
rem_dirs += [(0, 1)] if col_diff > 0 and hal_diff <= 0 else []
for d in rem_dirs:
if d in valid_rel_directions_no_move_risk:
valid_rel_directions_no_move_risk.remove(d)
# Prune for opponent base positions
rem_dirs = []
for rel_dir in valid_rel_directions:
d = RELATIVE_DIR_TO_DIRECTION_MAPPING[rel_dir]
move_row, move_col = move_ship_row_col(row, col, d, grid_size)
move_base_id = player_base_ids[move_row, move_col]
if move_base_id >= 0 and move_base_id != i:
rem_dirs.append(rel_dir)
for d in rem_dirs:
valid_rel_directions.remove(d)
# if observation['step'] == 146 and row == 14 and col == 13:
# import pdb; pdb.set_trace()
rem_dirs = []
for rel_dir in valid_rel_directions_no_move_risk:
d = RELATIVE_DIR_TO_DIRECTION_MAPPING[rel_dir]
move_row, move_col = move_ship_row_col(row, col, d, grid_size)
move_base_id = player_base_ids[move_row, move_col]
if move_base_id >= 0 and move_base_id != i:
rem_dirs.append(rel_dir)
for d in rem_dirs:
valid_rel_directions_no_move_risk.remove(d)
if len(valid_rel_directions) == 0:
player_halite_budget = observation['rewards_bases_ships'][i][0]
if ((ship_halite + player_halite_budget) >= convert_cost):
if ship_halite >= history['inferred_boxed_in_conv_threshold'][i][1]:
likely_convert_opponent_positions.append((row, col))
if ship_halite >= history['inferred_boxed_in_conv_threshold'][i][0]:
possible_convert_opponent_positions.append((row, col))
if ship_halite > 0:
for d in MOVE_DIRECTIONS:
move_row, move_col = move_ship_row_col(row, col, d, grid_size)
boxed_in_attack_squares[move_row, move_col] = True
boxed_in_opponent_ids[move_row, move_col] = i
if ship_halite == 0 and len(valid_rel_directions_no_move_risk) == 1 and (
valid_rel_directions_no_move_risk[0] == (0, 0)):
boxed_in_zero_halite_opponents.append((row, col))
if len(valid_rel_directions_no_move_risk) == 1:
escape_dir = RELATIVE_DIR_TO_DIRECTION_MAPPING[
valid_rel_directions_no_move_risk[0]]
escape_square = move_ship_row_col(row, col, escape_dir, grid_size)
opponent_single_escape_pos[escape_square] = 1
single_escape_mapping[(row, col)] = escape_square
opponent_ships_sensible_actions[(row, col)] = valid_rel_directions
opponent_ships_sensible_actions_no_risk[(row, col)] = (
valid_rel_directions_no_move_risk)
# if observation['step'] == 146:
# import pdb; pdb.set_trace()
# Do another pass over the zero halite ships to figure if they are boxed in
# by the escape squares of their own non zero halite ships - these ships
# will very likely take risky actions and should therefore be avoided
if np.any(opponent_single_escape_pos):
for j in range(num_ships):
row = ship_pos[0][j]
col = ship_pos[1][j]
ship_halite = halite_ships[row, col]
if ship_halite == 0:
valid_rel_directions = opponent_ships_sensible_actions[(row, col)]
valid_rel_directions_no_move_risk = (
opponent_ships_sensible_actions_no_risk[row, col])
# if observation['step'] == 146 and row == 15 and col == 12:
# import pdb; pdb.set_trace()
# if observation['step'] == 146 and row == 14 and col == 13:
# import pdb; pdb.set_trace()
for d in NOT_NONE_DIRECTIONS:
move_row, move_col = move_ship_row_col(row, col, d, grid_size)
if opponent_single_escape_pos[move_row, move_col]:
my_escape_square = False
if (row, col) in single_escape_mapping:
my_escape_square = (move_row, move_col) == (
single_escape_mapping[row, col])
if my_escape_square:
# Still treat it as a bad direction if there is another ship
# that has my escape square as it's only escape square
num_escape_count = np.array(
[v == (move_row, move_col) for v in (
single_escape_mapping.values())]).sum()
my_escape_square = num_escape_count == 1
if not my_escape_square:
avoid_rel_direction = RELATIVE_DIR_MAPPING[d]
if avoid_rel_direction in valid_rel_directions:
valid_rel_directions.remove(avoid_rel_direction)
if avoid_rel_direction in valid_rel_directions_no_move_risk:
valid_rel_directions_no_move_risk.remove(avoid_rel_direction)
if (len(valid_rel_directions_no_move_risk) == 0 or (
len(valid_rel_directions_no_move_risk) == 1 and (
valid_rel_directions_no_move_risk[0] == (0, 0)))) and (
not (row, col) in boxed_in_zero_halite_opponents):
# print("AVOIDING chained zero halite collision",
# observation['step'], row, col)
boxed_in_zero_halite_opponents.append((row, col))
opponent_ships_sensible_actions[(row, col)] = valid_rel_directions
opponent_ships_sensible_actions_no_risk[(row, col)] = (
valid_rel_directions_no_move_risk)
return (opponent_ships_sensible_actions,
opponent_ships_sensible_actions_no_risk, boxed_in_attack_squares,
boxed_in_opponent_ids, boxed_in_zero_halite_opponents,
likely_convert_opponent_positions,
possible_convert_opponent_positions)
def scale_attack_scores_bases_ships(
config, observation, player_obs, spawn_cost, non_abandoned_base_distances,
weighted_base_mask, steps_remaining, obs_halite, halite_ships, history,
smoothed_halite, player_influence_maps,
nearest_base_distances_with_my_excluded, player_ids,
laplace_smoother_rel_ship_count=4, initial_normalize_ship_diff=10,
final_normalize_ship_diff=3):
stacked_bases = np.stack([rbs[1] for rbs in observation[
'rewards_bases_ships']])
my_bases = stacked_bases[0]
# Exclude bases that are persistently camped by opponents
for base_pos in history['my_base_not_attacked_positions']:
my_bases[base_pos] = 0
stacked_opponent_bases = stacked_bases[1:]
stacked_ships = np.stack([rbs[2] for rbs in observation[
'rewards_bases_ships']])
stacked_opponent_ships = stacked_ships[1:]
base_counts = stacked_opponent_bases.sum((1, 2))
my_ship_count = len(player_obs[2])
ship_counts = stacked_opponent_ships.sum((1, 2))
grid_size = stacked_opponent_bases.shape[1]
approximate_scores = history['current_scores']
num_players = stacked_bases.shape[0]
player_ranks = np.zeros(num_players)
for i in range(num_players):
player_ranks[i] = (approximate_scores >= approximate_scores[i]).sum()
# print(approximate_scores)
# Factor 1: an opponent with less bases is more attractive to attack
base_count_multiplier = np.where(base_counts == 0, 0, 1/(base_counts+1e-9))
# Factor 2: an opponent that is closer in score is more attractive to attack
spawn_diffs = (approximate_scores[0] - approximate_scores[1:])/spawn_cost
abs_spawn_diffs = np.abs(spawn_diffs)
currently_winning = approximate_scores[0] >= approximate_scores[1:]
approximate_score_diff = approximate_scores[0] - approximate_scores[1:]
normalize_diff = initial_normalize_ship_diff - observation['relative_step']*(
initial_normalize_ship_diff-final_normalize_ship_diff)
abs_rel_normalized_diff = np.maximum(
0, (normalize_diff-abs_spawn_diffs)/normalize_diff)
rel_score_max_y = initial_normalize_ship_diff/normalize_diff
rel_score_multiplier = abs_rel_normalized_diff*rel_score_max_y
# Factor 3: an opponent with less ships is more attractive to attack since it
# is harder for them to defend the base
rel_ship_count_multiplier = (my_ship_count+laplace_smoother_rel_ship_count)/(
ship_counts+laplace_smoother_rel_ship_count)
# Additional term: attack bases nearby my main base
opponent_bases = stacked_opponent_bases.sum(0).astype(np.bool)
if opponent_bases.sum() > 0 and non_abandoned_base_distances.max() > 0:
additive_nearby_main_base = 3/max(0.15, observation['relative_step'])/(
1.5**non_abandoned_base_distances)/(
weighted_base_mask[my_bases].sum())
additive_nearby_main_base[~opponent_bases] = 0
else:
additive_nearby_main_base = 0
attack_multipliers = base_count_multiplier*rel_score_multiplier*(
rel_ship_count_multiplier)
tiled_multipliers = np.tile(attack_multipliers.reshape((-1, 1, 1)),
[1, grid_size, grid_size])
# if observation['step'] == 391:
# import pdb; pdb.set_trace()
opponent_bases_scaled = (stacked_opponent_bases*tiled_multipliers).sum(0) + (
additive_nearby_main_base)
# Compute the priority of attacking the ships of opponents
opponent_ships_scaled = np.maximum(0, 1 - np.abs(
approximate_scores[0]-approximate_scores[1:])/steps_remaining/10)
# print(observation['step'], opponent_ships_scaled, approximate_scores)
# if observation['step'] == 300:
# import pdb; pdb.set_trace()
# If I am winning by a considerable margin before the game is over, and the
# number three is far behind the number two: go ballistic on the number two
# Prefer opponent bases that are close to my bases and halite, and where the
# opponent has a relatively low density
# Make sure to guarantee some continuity with a start and stop mode
# Ballistic scenarios:
# - I am well ahead of all opponents: target the initial best agent
# - I am winning with a solid margin and the number three is far behind
# the number two: target the number two
# - I am in a close fight with the number two/one and the number three is
# very far behind: target the number two
winning_massively = np.all(spawn_diffs >= (
18-9*observation['relative_step']))
if not winning_massively:
history['ballistic_early_best_target_mode'] = False
winning_very_clearly = np.all(spawn_diffs >= (
14-7*observation['relative_step']))
winning_clearly = np.all(spawn_diffs >= (8-4*observation['relative_step']))
winning_considerably = np.all(spawn_diffs >= (
6-4*observation['relative_step'] + int(history[
'ballistic_early_best_target_mode'])))
winning_massively_near_end_game = winning_massively and observation[
'relative_step'] > 0.75
winning_massively_before_end_game = winning_massively and not (
winning_massively_near_end_game)
first_opp_id = np.argsort(spawn_diffs)[0]
second_opp_id = np.argsort(spawn_diffs)[1]
second_third_spawn_diff = spawn_diffs[second_opp_id] - spawn_diffs[
first_opp_id]
very_tight_fight_for_first = np.abs(spawn_diffs[first_opp_id]) < 1 and (
spawn_diffs[second_opp_id] >= (12-8*observation['relative_step']))
tight_fight_for_first = np.abs(spawn_diffs[first_opp_id]) < 3 and (
spawn_diffs[second_opp_id] >= (8-6*observation['relative_step']))
prev_ballistic_mode = history['ballistic_mode']
should_start_ballistic = (not winning_massively_before_end_game) and (
winning_clearly and second_third_spawn_diff > (
7-2*observation['relative_step']) or very_tight_fight_for_first or (
winning_massively_near_end_game)) and (
my_ship_count >= 15-max(0, 40*(observation['relative_step']-0.8)))
should_continue_ballistic = not (
winning_massively_before_end_game) and (winning_very_clearly or (
winning_clearly and (second_third_spawn_diff > 1)) or (
winning_considerably and (
second_third_spawn_diff > (2-observation['relative_step']))) or (
tight_fight_for_first)
) and (my_ship_count >= 10-max(0, 20*(observation['relative_step']-0.8)))
ballistic_mode = should_start_ballistic or (
prev_ballistic_mode and should_continue_ballistic)
# Select the next target in line if the opponent has no bases and no ships
if history['ballistic_early_best_targets_sorted'] is not None:
for opponent_id in history['ballistic_early_best_targets_sorted']:
ballistic_early_best_target_mode_target = opponent_id
num_opponent_bases = stacked_bases[opponent_id+1].sum()
num_opponent_ships = stacked_ships[opponent_id+1].sum()
if num_opponent_bases > 0 or num_opponent_ships > 0:
break
else:
ballistic_early_best_target_mode_target = first_opp_id
# print(observation['step'], ballistic_early_best_target_mode_target)
# if observation['step'] == 146:
# import pdb; pdb.set_trace()
# Ballistic early best target mode override of the opponent id: prefer to
# attack opponents that have a base which is close to one of my non
# abandoned bases
opponent_base_positions = np.where(stacked_opponent_bases.sum(0) > 0)
opponent_near_my_base_distances = nearest_base_distances_with_my_excluded[
opponent_base_positions]
targeted_base_override = None
if np.any(opponent_base_positions) and winning_very_clearly and (
opponent_near_my_base_distances.min() < 6):
prev_ballistic_target_override = history['prev_ballistic_target_override']
if history['prev_ballistic_target_override'] is not None and (
opponent_bases[prev_ballistic_target_override]):
targeted_base_override = prev_ballistic_target_override
else:
# Sort annoying bases by score: prefer to attack opponent bases that
# belong to the best opponent
smoothed_halite = smooth2d(observation['halite'])
opponent_near_my_base_scores = opponent_near_my_base_distances + 0.6*(
player_ranks[player_ids[opponent_base_positions]-1]) - 1e-9*(
smoothed_halite[opponent_base_positions])
target_base_id = np.argmin(opponent_near_my_base_scores)
targeted_base_override = (
opponent_base_positions[0][target_base_id],
opponent_base_positions[1][target_base_id])
history['prev_ballistic_target_override'] = targeted_base_override
if ballistic_mode and not prev_ballistic_mode and (
winning_massively_near_end_game):
# Switch to early best target mode - override of the target id
print(observation['step'], "Start attack on early best target",
ballistic_early_best_target_mode_target+1)
ballistic_early_best_target_mode = True
ballistic_target_id = ballistic_early_best_target_mode_target
elif ballistic_mode:
ballistic_early_best_target_mode = history[
'ballistic_early_best_target_mode'] and winning_very_clearly
if ballistic_early_best_target_mode or winning_massively_near_end_game:
# Early best target mode
ballistic_target_id = ballistic_early_best_target_mode_target
else:
# Standard ballistic mode
ballistic_target_id = first_opp_id
# print(observation['step'], "Winning massively near end?",
# winning_massively_near_end_game, ballistic_target_id)
else:
ballistic_early_best_target_mode = False
# Consider going ballistic on the nearest contender for the second place
# when the first place no longer seems possible
first_out_of_reach = spawn_diffs.min() <= (
-40+36*observation['relative_step']) # This should be conservative
if first_out_of_reach and np.abs(spawn_diffs[first_opp_id]) > np.abs(
spawn_diffs[second_opp_id]):
ballistic_target_id = second_opp_id
third_opp_id = np.argsort(spawn_diffs)[2]
spawn_diffs_not_best = np.array([spawn_diffs[i] for i in range(3) if (
not i == first_opp_id)])
winning_clearly_second = np.all(
spawn_diffs_not_best >= (8-4*observation['relative_step']))
winning_considerably_second = np.all(spawn_diffs_not_best >= (
6-4*observation['relative_step']))
third_fourth_spawn_diff = spawn_diffs[third_opp_id] - (
spawn_diffs[second_opp_id])
very_tight_fight_for_second = (
np.abs(spawn_diffs[second_opp_id]) < np.abs(
spawn_diffs[third_opp_id])/2) and (
spawn_diffs[third_opp_id] >= (12-8*observation['relative_step']))
tight_fight_for_second = (
np.abs(spawn_diffs[second_opp_id]) < np.abs(
spawn_diffs[third_opp_id])) and (
spawn_diffs[third_opp_id] >= (10-7*observation['relative_step']))
should_start_ballistic = (
winning_clearly_second and third_fourth_spawn_diff > (
4-2*observation['relative_step']) or (
very_tight_fight_for_second)) and (
my_ship_count >= 15-max(0, 40*(observation['relative_step']-0.8)))
should_continue_ballistic = ((
winning_clearly_second and (third_fourth_spawn_diff > 1)) or (
winning_considerably_second and (
third_fourth_spawn_diff > (2-observation['relative_step']))) or (
tight_fight_for_second)
) and (my_ship_count >= 10-max(
0, 20*(observation['relative_step']-0.8)))
ballistic_mode = should_start_ballistic or (
prev_ballistic_mode and should_continue_ballistic)
# if observation['step'] == 363:
# import pdb; pdb.set_trace()
# if ballistic_mode:
# print("SECOND BALLISTIC MODE", observation['step'],
# ballistic_target_id)
if not ballistic_mode:
ballistic_target_id = 0 # This could be 1 or 2 as well
history['ballistic_early_best_target_mode'] = (
ballistic_early_best_target_mode)
if not ballistic_mode and targeted_base_override is not None:
print("Go ballistic on nearby base", observation['step'],
targeted_base_override)
ballistic_mode = True
ballistic_target_id = np.argmax(base_counts)
num_target_bases = base_counts[ballistic_target_id]
ballistic_attack_base_targets = []
if ballistic_mode and num_target_bases > 0:
target_bases = stacked_opponent_bases[ballistic_target_id]
target_base_locations = np.where(target_bases)
attack_target_base_scores = np.zeros(num_target_bases)
my_base_density = smooth2d(my_bases, 10)
for base_id in range(num_target_bases):
base_row = target_base_locations[0][base_id]
base_col = target_base_locations[1][base_id]
attack_target_base_scores[base_id] = 5e-4*smoothed_halite[
base_row, base_col] + player_influence_maps[0, base_row, base_col] - (
player_influence_maps[ballistic_target_id+1, base_row, base_col]) + (
100*int((base_row, base_col) in history['prev_step'][
'ballistic_attack_base_targets'])) + 10*my_base_density[
base_row, base_col]
# import pdb; pdb.set_trace()
ordered_base_ids = np.argsort(-attack_target_base_scores)
num_attacked_bases = 1 # 1 is plenty of aggression for the world
for attack_id in range(num_attacked_bases):
if attack_id == 0 and targeted_base_override is not None:
# print("Targeted base override", observation['step'],
# targeted_base_override)
base_row, base_col = targeted_base_override
else:
base_id = ordered_base_ids[attack_id]
base_row = target_base_locations[0][base_id]
base_col = target_base_locations[1][base_id]
opponent_bases_scaled[base_row, base_col] = 1e4
ballistic_attack_base_targets.append((base_row, base_col))
del_keys = []
for k in history['camping_ships_strategy']:
if history['camping_ships_strategy'][k][5] in (
ballistic_attack_base_targets):
del_keys.append(k)
for k in del_keys:
del history['camping_ships_strategy'][k]
# print(observation['step'], ballistic_mode, ballistic_attack_base_targets)
history['ballistic_mode'] = ballistic_mode
return (opponent_bases_scaled, opponent_ships_scaled,
abs_rel_normalized_diff, currently_winning, approximate_score_diff,
history, ballistic_attack_base_targets)
def get_influence_map(config, stacked_bases, stacked_ships, halite_ships,
observation, player_obs, smooth_kernel_dim=7):
# FUTURE WORK: incorporate the number of ships in computing the base weights
# Reasoning: a base without ships is not really a threat
all_ships = stacked_ships.sum(0).astype(np.bool)
my_ships = stacked_ships[0].astype(np.bool)
if my_ships.sum() == 0:
return None, None, None, None, None, None
num_players = stacked_ships.shape[0]
grid_size = my_ships.shape[0]
ship_range = 1-config['influence_map_min_ship_weight']
all_ships_halite = halite_ships[all_ships]
unique_vals, unique_counts = np.unique(
all_ships_halite, return_counts=True)
assert np.all(np.diff(unique_vals) > 0)
unique_halite_vals = np.sort(unique_vals).astype(np.int).tolist()
num_ships = all_ships_halite.size
halite_ranks = [np.array(
[unique_halite_vals.index(hs) for hs in halite_ships[
stacked_ships[i]]]) for i in range(num_players)]
less_rank_cum_counts = np.cumsum(unique_counts)
num_unique = unique_counts.size
halite_rank_counts = [np.array(
[less_rank_cum_counts[r-1] if r > 0 else 0 for r in (
halite_ranks[i])]) for i in range(num_players)]
ship_weights = [1 - r/(num_ships-1+1e-9)*ship_range for r in (
halite_rank_counts)]
raw_influence_maps = np.zeros((num_players, grid_size, grid_size))
raw_influence_maps_unweighted = np.zeros((num_players, grid_size, grid_size))
influence_maps = np.zeros((num_players, grid_size, grid_size))
influence_maps_unweighted = np.zeros((num_players, grid_size, grid_size))
for i in range(num_players):
raw_influence_maps[i][stacked_ships[i]] += ship_weights[i]
raw_influence_maps[i][stacked_bases[i]] += config[
'influence_map_base_weight']
raw_influence_maps_unweighted[i][stacked_ships[i]] += 1
raw_influence_maps_unweighted[i][stacked_bases[i]] += 1
influence_maps[i] = smooth2d(raw_influence_maps[i],
smooth_kernel_dim=smooth_kernel_dim)
influence_maps_unweighted[i] = smooth2d(
raw_influence_maps_unweighted[i], smooth_kernel_dim=smooth_kernel_dim)
my_influence = influence_maps[0]
max_other_influence = influence_maps[1:].max(0)
influence_map = my_influence - max_other_influence
influence_map_unweighted = influence_maps_unweighted[0] - (
influence_maps_unweighted[1:].sum(0))
# Define the escape influence map
rem_other_influence = influence_maps[1:].sum(0) - max_other_influence
escape_influence_map = 3*my_influence-(
2*max_other_influence+rem_other_influence)
escape_influence_probs = np.exp(np.minimum(0, escape_influence_map)/config[
'escape_influence_prob_divisor'])
# Derive the priority scores based on the influence map
priority_scores = 1/(1+np.abs(influence_map))
# Extract a dict of my ship weights
ship_priority_weights = {}
for ship_k in player_obs[2]:
row, col = row_col_from_square_grid_pos(
player_obs[2][ship_k][0], grid_size)
ship_halite = halite_ships[row, col]
halite_rank = unique_halite_vals.index(ship_halite)
ship_priority_weights[ship_k] = 1 - halite_rank/(
num_unique-1+1e-9)*ship_range
return (influence_map, influence_map_unweighted, influence_maps,
priority_scores, ship_priority_weights, escape_influence_probs)
# Compute the weighted base mask - the base with value one represents the
# main base and the values are used as a multiplier in the return to base
# scores.
def get_weighted_base_mask(stacked_bases, stacked_ships, observation,
history, consistent_main_base_bonus=3):
my_bases = stacked_bases[0]
# Exclude bases that are persistently camped by opponents
for base_pos in history['my_base_not_attacked_positions']:
my_bases[base_pos] = 0
num_bases = my_bases.sum()
my_base_locations = np.where(my_bases)
grid_size = stacked_bases.shape[1]
ship_diff_smoothed = smooth2d(stacked_ships[0] - stacked_ships[1:].sum(0))
if num_bases == 0:
base_mask = np.ones((grid_size, grid_size))
main_base_distances = -1*np.ones((grid_size, grid_size))
non_abandoned_base_distances = -1*np.ones((grid_size, grid_size))
elif num_bases >= 1:
all_non_abandoned_base_distances = []
for base_id in range(num_bases):
base_row = my_base_locations[0][base_id]
base_col = my_base_locations[1][base_id]
all_non_abandoned_base_distances.append(DISTANCES[
base_row, base_col])
non_abandoned_base_distances = np.stack(
all_non_abandoned_base_distances).min(0)
# Add a bonus to identify the main base id, but don't include the bonus
# in the base scaling
ship_diff_smoothed_with_bonus = np.copy(ship_diff_smoothed)
prev_main_base_location = history['prev_step']['my_main_base_location']
# print(observation['step'], prev_main_base_location, num_bases)
if prev_main_base_location[0] >= 0:
ship_diff_smoothed_with_bonus[prev_main_base_location] += (
consistent_main_base_bonus)
base_densities = ship_diff_smoothed[my_base_locations]
base_densities_with_bonus = ship_diff_smoothed_with_bonus[
my_base_locations]
highest_base_density_with_bonus = base_densities_with_bonus.max()
best_ids = np.where(
base_densities_with_bonus == highest_base_density_with_bonus)[0]
highest_base_density = base_densities[best_ids[0]]
# Subtract some small value of the non max densities to break rare ties
main_base_row = my_base_locations[0][best_ids[0]]
main_base_col = my_base_locations[1][best_ids[0]]
main_base_distances = DISTANCES[main_base_row, main_base_col]
all_densities = np.minimum(ship_diff_smoothed, highest_base_density-1e-5)
all_densities[main_base_row, main_base_col] += 1e-5
# Linearly compute the weighted base mask: 1 is my best base and 0 is the
# lowest ship_diff_smoothed value
all_densities -= all_densities.min()
base_mask = all_densities/all_densities.max()
return (base_mask, main_base_distances, non_abandoned_base_distances,
ship_diff_smoothed)
# Force returning to a base when the episode is almost over
def force_return_base_end_episode(
my_bases, base_return_grid_multiplier, main_base_distances, row, col,
steps_remaining, opponent_less_halite_ships, weighted_base_mask,
safe_to_collect):
num_bases = my_bases.sum()
base_positions = np.where(my_bases)
# List the bases I *can* return to
can_return_scores = np.zeros(num_bases)
for i in range(num_bases):
base_row = base_positions[0][i]
base_col = base_positions[1][i]
base_distance = DISTANCES[row, col][base_row, base_col]
threat_mask = np.logical_and(
DISTANCES[(row, col)] <= base_distance,
DISTANCES[(base_row, base_col)] <= base_distance)
if base_distance > 1:
threat_mask[row, col] = 0
threat_mask[base_row, base_col] = 0
threat_ships_mask = opponent_less_halite_ships[threat_mask]
can_return_scores[i] = (base_distance <= steps_remaining)*(10+
max(int(safe_to_collect[row, col]),
weighted_base_mask[base_row, base_col]) - 5*(
threat_ships_mask.mean()) - base_distance/30)
# if observation['step'] == 384 and row == 8 and col == 11:
# import pdb; pdb.set_trace()
# Force an emergency return if the best return scores demand an urgent
# return in order to bring the halite home before the episode is over
end_game_base_return = False
if num_bases > 0:
best_return_id = np.argmax(can_return_scores)
best_base_row = base_positions[0][best_return_id]
best_base_col = base_positions[1][best_return_id]
best_base_distance = DISTANCES[row, col][best_base_row, best_base_col]
end_game_base_return = best_base_distance in [
steps_remaining-1, steps_remaining]
if end_game_base_return:
base_return_grid_multiplier[best_base_row, best_base_col] += 1e15
return base_return_grid_multiplier, end_game_base_return
def edge_aware_square_subset_mask(data, row, col, window, box, grid_size):
# Figure out how many rows to roll the data and box to end up with a
# contiguous subset
min_row = row - window
max_row = row + window
if min_row < 0:
data = np.roll(data, -min_row, axis=0)
box = np.roll(box, -min_row, axis=0)
elif max_row >= grid_size:
data = np.roll(data, grid_size-max_row-1, axis=0)
box = np.roll(box, grid_size-max_row-1, axis=0)
# Figure out how many columns to roll the data and box to end up with a
# contiguous subset
min_col = col - window
max_col = col + window
if min_col < 0:
data = np.roll(data, -min_col, axis=1)
box = np.roll(box, -min_col, axis=1)
elif max_col >= grid_size:
data = np.roll(data, grid_size-max_col-1, axis=1)
box = np.roll(box, grid_size-max_col-1, axis=1)
return data[box]
def update_scores_opponent_boxing_in(
all_ship_scores, stacked_ships, observation, env_config,
opponent_ships_sensible_actions, halite_ships, steps_remaining, player_obs,
np_rng, opponent_ships_scaled, collect_rate, obs_halite,
main_base_distances, history, on_rescue_mission,
my_defend_base_ship_positions, env_observation, player_influence_maps,
override_move_squares_taken, ignore_convert_positions,
convert_unavailable_positions, always_attack_opponent_id,
num_non_abandoned_bases, likely_convert_opponent_positions,
possible_convert_opponent_positions, my_current_base_distances,
box_in_window=3, min_attackers_to_box=4):
# Loop over the opponent ships and derive if I can box them in
# For now this is just greedy. We should probably consider decoupling finding
# targets from actually boxing in.
# FUTURE WORK: proper handling of opponent bases
opponent_positions = np.where(stacked_ships[1:].sum(0) > 0)
opponent_bases = np.stack([rbs[1] for rbs in observation[
'rewards_bases_ships']])[1:].sum(0)
num_opponent_ships = opponent_positions[0].size
double_window = box_in_window*2
dist_mask_dim = 2*double_window+1
nearby_rows = np.tile(np.expand_dims(np.arange(dist_mask_dim), 1),
[1, dist_mask_dim])
nearby_cols = np.tile(np.arange(dist_mask_dim), [dist_mask_dim, 1])
ships_available = np.copy(stacked_ships[0]) & (~on_rescue_mission) & (
~my_defend_base_ship_positions) & (~convert_unavailable_positions)
boxing_in = np.zeros_like(on_rescue_mission)
grid_size = stacked_ships.shape[1]
# ship_pos_to_key = {v[0]: k for k, v in player_obs[2].items()}
prev_step_boxing_in_ships = history['prev_step_boxing_in_ships']
num_players = stacked_ships.shape[0]
spawn_cost = env_config.spawnCost
ship_pos_to_key = {}
for i in range(num_players):
ship_pos_to_key.update({
v[0]: k for k, v in env_observation.players[i][2].items()})
# Loop over the camping ships and exclude the ones from the available mask
# that have flagged they are not available for boxing in
camping_ships_strategy = history['camping_ships_strategy']
for ship_k in camping_ships_strategy:
if not camping_ships_strategy[ship_k][3]:
camping_row, camping_col = row_col_from_square_grid_pos(
player_obs[2][ship_k][0], grid_size)
ships_available[camping_row, camping_col] = 0
# Loop over the ships that attack opponent camplers and exclude them from the
# available mask
attack_opponent_campers = history['attack_opponent_campers']
for ship_k in attack_opponent_campers:
attacking_camper_row, attacking_camper_col = row_col_from_square_grid_pos(
player_obs[2][ship_k][0], grid_size)
ships_available[attacking_camper_row, attacking_camper_col] = 0
# Loop over the ships that are stuck in a loop and mark them as unavailable
for ship_k in history['avoid_cycle_actions']:
cycle_row, cycle_col = row_col_from_square_grid_pos(
player_obs[2][ship_k][0], grid_size)
ships_available[cycle_row, cycle_col] = 0
original_ships_available = np.copy(ships_available)
my_ship_density = smooth2d(ships_available, smooth_kernel_dim=2)
# Compute the priorities of attacking each ship
# Compute the minimum opponent halite in the neighborhood of each square
# by looping over all opponent ships
attack_ship_priorities = np.zeros(num_opponent_ships)
near_opponent_min_halite = np.ones((grid_size, grid_size))*1e6
near_opponent_2_min_halite = np.ones((grid_size, grid_size))*1e6
near_opponent_specific_2_min_halite = [
np.ones((grid_size, grid_size))*1e6 for _ in range(num_players)]
should_attack = np.zeros(num_opponent_ships, dtype=np.bool)
for i in range(num_opponent_ships):
row = opponent_positions[0][i]
col = opponent_positions[1][i]
opponent_ship_k = ship_pos_to_key[row*grid_size+col]
boxing_in_prev_step = opponent_ship_k in prev_step_boxing_in_ships
opponent_halite = halite_ships[row, col]
clipped_opponent_halite = min(spawn_cost, opponent_halite)
opponent_id = np.where(stacked_ships[:, row, col])[0][0]
attack_ship_priorities[i] = 1e5*boxing_in_prev_step + (
clipped_opponent_halite) + 1000*(
opponent_ships_scaled[opponent_id-1]) + 1000*my_ship_density[row, col]
near_opp_mask = ROW_COL_MAX_DISTANCE_MASKS[(row, col, box_in_window)]
near_opp_2_mask = ROW_COL_MAX_DISTANCE_MASKS[(row, col, 2)]
near_opponent_min_halite[near_opp_mask] = np.minimum(
opponent_halite, near_opponent_min_halite[near_opp_mask])
near_opponent_2_min_halite[near_opp_2_mask] = np.minimum(
opponent_halite, near_opponent_2_min_halite[near_opp_2_mask])
near_opponent_specific_2_min_halite[opponent_id][near_opp_2_mask] = (
np.minimum(opponent_halite,
near_opponent_specific_2_min_halite[opponent_id][
near_opp_2_mask]))
# if observation['step'] == 163 and row == 2:
# import pdb; pdb.set_trace()
should_attack[i] = (main_base_distances[row, col] >= (9-(
observation['relative_step']*6 + 3*num_non_abandoned_bases)) or (
opponent_halite < history[
'inferred_boxed_in_conv_threshold'][opponent_id][0]) or (
always_attack_opponent_id == opponent_id)) and not (
(row, col) in ignore_convert_positions)
box_opponent_positions = []
boxing_in_ships = []
ships_on_box_mission = {}
opponent_ship_order = np.argsort(-attack_ship_priorities)
for i in range(num_opponent_ships):
opponent_ship_id = opponent_ship_order[i]
row = opponent_positions[0][opponent_ship_id]
col = opponent_positions[1][opponent_ship_id]
opponent_id = np.where(stacked_ships[:, row, col])[0][0]
opponent_ship_k = ship_pos_to_key[row*grid_size+col]
sensible_target_actions = opponent_ships_sensible_actions[row, col]
target_halite = halite_ships[row, col]
my_less_halite_mask = np.logical_and(
halite_ships < target_halite, ships_available)
# if observation['step'] == 210 and row == 1 and col == 8:
# import pdb; pdb.set_trace()
# Drop non zero halite ships towards the end of a game (they should return)
my_less_halite_mask = np.logical_and(
my_less_halite_mask, np.logical_or(
halite_ships == 0, steps_remaining > 20))
max_dist_mask = ROW_COL_MAX_DISTANCE_MASKS[(row, col, double_window)]
my_less_halite_mask &= max_dist_mask
box_pos = ROW_COL_BOX_MAX_DISTANCE_MASKS[row, col, double_window]
# if observation['step'] == 157 and row == 13 and col == 1:
# import pdb; pdb.set_trace()
if my_less_halite_mask.sum() >= min_attackers_to_box and should_attack[
opponent_ship_id]:
# Look up the near opponent min halite in the square which is in the
# middle between my attackers and the target - don't attack when there is
# a less halite ship near that ship or if there is an equal halite ship
# near that square and close to the opponent
my_considered_pos = np.where(my_less_halite_mask)
if my_considered_pos[0].size:
considered_rows = my_considered_pos[0]
considered_cols = my_considered_pos[1]
mid_rows = np.where(
np.abs(considered_rows-row) <= (grid_size // 2),
np.round((considered_rows*(1-1e-9)+row*(1+1e-9))/2),
np.where(considered_rows*(1-1e-9)+row*(1+1e-9) >= grid_size,
np.round(
(considered_rows*(1-1e-9)+row*(1+1e-9)-grid_size)/2),
np.mod(np.round(
(considered_rows*(1-1e-9)+row*(1+1e-9)+grid_size)/2),
grid_size))
).astype(np.int)
mid_cols = np.where(
np.abs(considered_cols-col) <= (grid_size // 2),
np.round((considered_cols*(1-1e-9)+col*(1+1e-9))/2),
np.where(considered_cols*(1-1e-9)+col*(1+1e-9) >= grid_size,
np.round(
(considered_cols*(1-1e-9)+col*(1+1e-9)-grid_size)/2),
np.mod(np.round(
(considered_cols*(1-1e-9)+col*(1+1e-9)+grid_size)/2),
grid_size))
).astype(np.int)
# Only box in with ships that can safely do so without becoming a
# target themselves. Take more risk when the halite on board is
# equal to that of other target surrounding ships (typically 0 halite)
considered_to_target_distances = DISTANCES[(row, col)][
(considered_rows, considered_cols)]
considered_min_halite_limits = np.where(
considered_to_target_distances < 3, near_opponent_2_min_halite[
(mid_rows, mid_cols)], near_opponent_min_halite[
(mid_rows, mid_cols)])
drop_ids = (considered_min_halite_limits < (
halite_ships[(considered_rows, considered_cols)])) | (
(considered_min_halite_limits == (
halite_ships[(considered_rows, considered_cols)])) & (
near_opponent_specific_2_min_halite[opponent_id][
(row, col)] <= (
halite_ships[(considered_rows, considered_cols)])))
if np.any(drop_ids):
drop_row_ids = considered_rows[drop_ids]
drop_col_ids = considered_cols[drop_ids]
my_less_halite_mask[(drop_row_ids, drop_col_ids)] = 0
my_less_halite_mask_box = edge_aware_square_subset_mask(
my_less_halite_mask, row, col, double_window, box_pos,
grid_size)
nearby_less_halite_mask = my_less_halite_mask_box.reshape(
(dist_mask_dim, dist_mask_dim))
# if observation['step'] == 32:
# import pdb; pdb.set_trace()
my_num_nearby = nearby_less_halite_mask.sum()
else:
my_num_nearby = 0
if my_num_nearby >= min_attackers_to_box:
# Check all directions to make sure I can box the opponent in
can_box_in = True
box_in_mask_dirs = np.zeros(
(4, dist_mask_dim, dist_mask_dim), dtype=np.bool)
for dim_id, d in enumerate(NOT_NONE_DIRECTIONS):
dir_and_ships = BOX_DIRECTION_MASKS[(double_window, d)] & (
nearby_less_halite_mask)
if not np.any(dir_and_ships):
can_box_in = False
break
else:
box_in_mask_dirs[dim_id] = dir_and_ships
if can_box_in:
# Sketch out the escape squares for the target ship
opponent_distances = np.abs(nearby_rows-double_window) + np.abs(
nearby_cols-double_window)
opponent_euclid_distances = np.sqrt(
(nearby_rows-double_window)**2 + (
nearby_cols-double_window)**2)
nearby_mask_pos = np.where(nearby_less_halite_mask)
my_nearest_distances = np.stack([np.abs(
nearby_rows-nearby_mask_pos[0][j]) + np.abs(
nearby_cols-nearby_mask_pos[1][j]) for j in range(
my_num_nearby)])
my_nearest_euclid_distances = np.stack([np.sqrt((
nearby_rows-nearby_mask_pos[0][j])**2 + (
nearby_cols-nearby_mask_pos[1][j])**2) for j in range(
my_num_nearby)])
# No boxing in if the opponent has a base in one of the escape squares
escape_squares = opponent_distances <= my_nearest_distances.min(0)
cropped_distances = OTHER_DISTANCES[
(double_window, double_window, dist_mask_dim)]
for dim_id, d in enumerate(NOT_NONE_DIRECTIONS):
box_dir_mask = BOX_DIRECTION_MASKS[(double_window, d)]
closest_dim_distance = cropped_distances[
box_in_mask_dirs[dim_id]].min()
escape_squares[box_dir_mask] &= (
cropped_distances[box_dir_mask] <= closest_dim_distance)
if not np.any(observation['rewards_bases_ships'][opponent_id][1][
box_pos][escape_squares.flatten()]):
# Let's box the opponent in!
# We should move towards the opponent if we can do so without opening
# up an escape direction
# if observation['step'] == 32:
# import pdb; pdb.set_trace()
# Order the planning by priority of direction and distance to the
# opponent
# Reasoning: mid-distance ships plan first since that allows fast
# boxing in - the nearby ships then just have to cover the remaining
# directions.
# Ships which cover hard to cover directions plan later.
box_in_mask_dirs_sum = box_in_mask_dirs.sum((1, 2))
ship_priorities = np.zeros(my_num_nearby)
must_attack_converting_square = ((row, col) in (
likely_convert_opponent_positions)) and not (
(row, col) in ignore_convert_positions) and ((
always_attack_opponent_id == opponent_id) or (
my_current_base_distances[:, row, col].min() < 5))
threatened_one_step = set()
for j in range(my_num_nearby):
my_row = nearby_mask_pos[0][j]
my_col = nearby_mask_pos[1][j]
box_directions = box_in_mask_dirs[:, my_row, my_col]
opponent_distance = np.abs(my_row-double_window) + np.abs(
my_col-double_window)
ship_priorities[j] = 20/(
box_in_mask_dirs_sum[box_directions].prod())+np.abs(
opponent_distance**0.9-box_in_window**0.9)
if opponent_distance == 2 and box_directions.sum() == 2 and np.all(
box_in_mask_dirs_sum[box_directions] == 1):
two_step_dirs = [MOVE_DIRECTIONS[move_id+1] for move_id in (
np.where(box_directions)[0])]
threatened_one_step.update(two_step_dirs)
# I can always attack all escape squares if I have at least 5 ships
# at a maximum distance of two with at least one attacker on each
# half plane
vert_diff = double_window-nearby_mask_pos[0]
horiz_diff = double_window-nearby_mask_pos[1]
distances = np.abs(vert_diff) + np.abs(horiz_diff)
is_near = distances <= 2
near_vert_diff = vert_diff[is_near]
near_horiz_diff = horiz_diff[is_near]
i_can_attack_all_escape_squares = distances.min() == 1 and (
is_near.sum() >= 5) and np.sign(near_vert_diff).ptp() == 2 and (
np.sign(near_horiz_diff).ptp() == 2)
if i_can_attack_all_escape_squares and (distances == 1).sum() == 1:
# I can only attack all escape squares if my attacker can be
# replaced
one_step_diff_id = np.argmin(distances)
single_attack_row = nearby_mask_pos[0][one_step_diff_id]
single_attack_col = nearby_mask_pos[1][one_step_diff_id]
can_replace = False
for row_offset in [-1, 1]:
for col_offset in [-1, 1]:
if nearby_less_halite_mask[single_attack_row + row_offset,
single_attack_col + col_offset]:
can_replace = True
break
i_can_attack_all_escape_squares = can_replace
# DISCERN if we are just chasing or actually attacking the ship in
# the next move - dummy rule to have at least K neighboring ships
# for us to attack the position of the targeted ship - this makes it
# hard to guess the escape direction
ship_target_1_distances = my_nearest_distances[
:, double_window, double_window] == 1
next_step_attack = (len(sensible_target_actions) == 0 and (
ship_target_1_distances.sum() > 2)) or (
i_can_attack_all_escape_squares) or (
must_attack_converting_square and np.any(
ship_target_1_distances))
# if next_step_attack and not (
# (len(sensible_target_actions) == 0 and (
# ship_target_1_distances.sum() > 2)) or (
# i_can_attack_all_escape_squares)):
# import pdb; pdb.set_trace()
opponent_boxed_bases = edge_aware_square_subset_mask(
opponent_bases, row, col, double_window, box_pos,
grid_size).reshape((dist_mask_dim, dist_mask_dim))
pos_taken = np.copy(opponent_boxed_bases)
box_override_assignment_not_next_attack = {}
if next_step_attack:
# If there is a ship that can take the position of my attacker:
# attack with that ship and replace its position.
# Otherwise pick a random attacker and keep the others in place.
# Initial approach: don't move with ships at distance 1.
ship_target_2_distance_ids = np.where(my_nearest_distances[
:, double_window, double_window] == 2)[0].tolist()
move_ids_directions_next_attack = {}
# Reorder ship_target_2_distance_ids so that the ones that can
# replace a 1 step threat are considered last, except when there is
# only a single 1 step threat (it would always move to the target).
# Also prefer to consider ships that only have a single option
# to move to the target first
two_step_distance_scores = np.zeros(
len(ship_target_2_distance_ids))
for two_step_id, two_step_diff_id in enumerate(
ship_target_2_distance_ids):
my_row = nearby_mask_pos[0][two_step_diff_id]
my_col = nearby_mask_pos[1][two_step_diff_id]
mask_between = get_mask_between_exclude_ends(
my_row, my_col, double_window, double_window, dist_mask_dim)
two_step_distance_scores[two_step_id] = mask_between.sum() + 10*(
nearby_less_halite_mask[mask_between].sum())*(
ship_target_1_distances.sum() > 1)
# if observation['step'] == 134:
# import pdb; pdb.set_trace()
ship_target_2_distance_ids = np.array(
ship_target_2_distance_ids)[
np.argsort(two_step_distance_scores)].tolist()
# Add the positions of the one step attackers
for one_step_diff_id in np.where(ship_target_1_distances)[0]:
my_row = nearby_mask_pos[0][one_step_diff_id]
my_col = nearby_mask_pos[1][one_step_diff_id]
# If I only have one ship that can attack the target: attack with
# that ship!
if ship_target_1_distances.sum() == 1:
attack_direction = get_dir_from_target(
my_row, my_col, double_window, double_window,
grid_size=1000)[0]
pos_taken[double_window, double_window] = True
move_ids_directions_next_attack[one_step_diff_id] = (
attack_direction)
else:
pos_taken[my_row, my_col] = 1
# if observation['step'] == 176:
# import pdb; pdb.set_trace()
two_step_pos_taken = []
while ship_target_2_distance_ids:
two_step_diff_id = ship_target_2_distance_ids.pop(0)
my_row = nearby_mask_pos[0][two_step_diff_id]
my_col = nearby_mask_pos[1][two_step_diff_id]
# Consider the shortest directions towards the target
shortest_directions = get_dir_from_target(
my_row, my_col, double_window, double_window, grid_size=1000)
has_selected_action = False
for d in shortest_directions:
# Prefer empty 1-step to target spaces over replacing a one
# step threat
move_row, move_col = move_ship_row_col(
my_row, my_col, d, size=1000)
if not pos_taken[move_row, move_col] and (not (
(move_row, move_col) in two_step_pos_taken)):
two_step_pos_taken.append((move_row, move_col))
move_ids_directions_next_attack[two_step_diff_id] = d
has_selected_action = True
break
if not has_selected_action:
# Replace a 1-step threatening ship
for d in shortest_directions:
move_row, move_col = move_ship_row_col(
my_row, my_col, d, size=1000)
if pos_taken[move_row, move_col] and not pos_taken[
double_window, double_window] and not opponent_boxed_bases[
move_row, move_col]:
move_ids_directions_next_attack[two_step_diff_id] = d
# Find the ids of the 1-step ship and make sure that ship
# attacks
replaced_id = np.where(my_nearest_distances[
:, move_row, move_col] == 0)[0][0]
one_step_attack_dir = get_dir_from_target(
move_row, move_col, double_window, double_window,
grid_size=1000)[0]
move_ids_directions_next_attack[replaced_id] = (
one_step_attack_dir)
pos_taken[double_window, double_window] = True
# Recompute the priority of the remaining two step ships
# Prefer ships with the lowest pos_taken shortest actions
two_step_distance_scores = np.zeros(
len(ship_target_2_distance_ids))
for two_step_id, two_step_diff_id in enumerate(
ship_target_2_distance_ids):
my_row = nearby_mask_pos[0][two_step_diff_id]
my_col = nearby_mask_pos[1][two_step_diff_id]
shortest_directions = get_dir_from_target(
my_row, my_col, double_window, double_window,
grid_size=1000)
for d in shortest_directions:
move_row, move_col = move_ship_row_col(
my_row, my_col, d, size=1000)
two_step_distance_scores[two_step_id] += int(
not (pos_taken[move_row, move_col] or (
(move_row, move_col) in two_step_pos_taken)))
ship_target_2_distance_ids = np.array(
ship_target_2_distance_ids)[
np.argsort(two_step_distance_scores)].tolist()
one_step_diff_ids = np.where(ship_target_1_distances)[0]
if pos_taken[double_window, double_window]:
# Add the remaining one step attackers with stay in place actions
for one_step_diff_id in one_step_diff_ids:
if not one_step_diff_id in move_ids_directions_next_attack:
move_ids_directions_next_attack[one_step_diff_id] = None
else:
# Prefer to avoid stay in place actions with zero halite ships
real_mask_pos = (
np.mod(nearby_mask_pos[0]+row-double_window, grid_size),
np.mod(nearby_mask_pos[1]+col-double_window, grid_size)
)
one_step_halite_on_board = halite_ships[real_mask_pos][
one_step_diff_ids]
one_step_halite_on_square = obs_halite[real_mask_pos][
one_step_diff_ids]
prefers_box_in = (one_step_halite_on_board == 0) & (
one_step_halite_on_square > 0)
if np.all(~prefers_box_in):
one_step_diff_ids_attack = one_step_diff_ids
else:
one_step_diff_ids_attack = one_step_diff_ids[
prefers_box_in]
# Of the remaining attack options: prefer an attacker from the
# direction where we have the highest influence, relative to the
# targeted opponent
# one_step_attacker_id = np_rng.choice(one_step_diff_ids_attack)
my_influences = player_influence_maps[0][real_mask_pos][
one_step_diff_ids_attack]
opponent_influences = player_influence_maps[opponent_id][
real_mask_pos][one_step_diff_ids_attack]
influence_differences = my_influences - opponent_influences
one_step_attacker_id = one_step_diff_ids_attack[
np.argmax(influence_differences)]
# Pick a random one step attacker to attack the target and make
# sure the remaining 1-step ships stay in place
for one_step_diff_id in one_step_diff_ids:
if one_step_diff_id == one_step_attacker_id:
my_row = nearby_mask_pos[0][one_step_diff_id]
my_col = nearby_mask_pos[1][one_step_diff_id]
attack_dir = get_dir_from_target(
my_row, my_col, double_window, double_window,
grid_size=1000)[0]
else:
attack_dir = None
move_ids_directions_next_attack[one_step_diff_id] = attack_dir
elif len(sensible_target_actions) == 0 or (
len(sensible_target_actions) == 1 and (
sensible_target_actions[0] == (0, 0))):
# Inspect what directions I can move right next to when the
# opponent has no valid escape actions. Use a greedy search to
# determine the action selection order
can_box_immediately = []
can_box_immediately_counts = np.zeros(4)
for j in range(my_num_nearby):
my_row = nearby_mask_pos[0][j]
my_col = nearby_mask_pos[1][j]
box_directions = box_in_mask_dirs[:, my_row, my_col]
opponent_distance = np.abs(my_row-double_window) + np.abs(
my_col-double_window)
if opponent_distance <= 2:
immediate_box_dirs = np.where(box_directions)[0]
can_box_immediately.append((
j, immediate_box_dirs, box_directions, my_row, my_col))
can_box_immediately_counts[box_directions] += 1
can_box_progress = [list(cb) for cb in can_box_immediately]
can_box_immediately_counts_progress = np.copy(
can_box_immediately_counts)
not_boxed_dirs = np.ones(4, dtype=np.bool)
# if observation['step'] == 97:
# import pdb; pdb.set_trace()
# Iteratively look for directions where I can box in in one step
# when I have others that can box in the remaining directions
# and nobody else can box that direction in
box_in_mask_rem_dirs_sum = np.copy(box_in_mask_dirs_sum)
while len(can_box_progress) > 0 and np.any(not_boxed_dirs) and (
can_box_immediately_counts_progress.sum() > 0):
considered_dir = np.argmin(
can_box_immediately_counts_progress + 100*(
can_box_immediately_counts_progress <= 0) + 1e-2*(
box_in_mask_rem_dirs_sum))
considered_dir_ids = [(
j, cb[0], box_in_mask_rem_dirs_sum[cb[1]], cb[1], cb[3],
cb[4]) for j, cb in enumerate(can_box_progress) if (
considered_dir in cb[1] and np.all(
box_in_mask_rem_dirs_sum[cb[1]] >= 1))]
num_considered_dir_ids = len(considered_dir_ids)
if num_considered_dir_ids > 0:
# Tie breaker: the one with the most ships in the other dir
# support
if num_considered_dir_ids > 1:
scores = np.zeros(num_considered_dir_ids)
for k in range(num_considered_dir_ids):
scores[k] = 100*len(considered_dir_ids[k][2]) - (
considered_dir_ids[k][2].sum())
picked_dir_id = np.argmin(scores)
else:
picked_dir_id = 0
picked = considered_dir_ids[picked_dir_id]
box_override_assignment_not_next_attack[picked[1]] = (
considered_dir, picked[4], picked[5])
# If I move closer with a diagonal ship: subtract the
# immediate box counter for the other direction
picked_other_immediate_box_dirs = picked[3][
picked[3] != considered_dir]
can_box_immediately_counts_progress[considered_dir] = 0
can_box_immediately_counts_progress[
picked_other_immediate_box_dirs] -= 1
not_boxed_dirs[considered_dir] = 0
box_in_mask_rem_dirs_sum[picked[3]] -= 1
ship_priorities[picked[1]] -= 1e6
del can_box_progress[picked[0]]
else:
break
num_covered_directions = np.zeros(4, dtype=np.int)
num_one_step_from_covered = np.zeros(4, dtype=np.bool)
ship_order = np.argsort(ship_priorities)
box_in_mask_rem_dirs_sum = np.copy(box_in_mask_dirs_sum)
update_ship_scores = []
one_square_threats = []
almost_covered_dirs = []
for j in range(my_num_nearby):
attack_id = ship_order[j]
my_row = nearby_mask_pos[0][attack_id]
my_col = nearby_mask_pos[1][attack_id]
my_abs_row = (row+my_row-double_window) % grid_size
my_abs_col = (col+my_col-double_window) % grid_size
ship_pos = my_abs_row*grid_size+my_abs_col
ship_k = ship_pos_to_key[ship_pos]
box_directions = box_in_mask_dirs[:, my_row, my_col]
opponent_distance = np.abs(my_row-double_window) + np.abs(
my_col-double_window)
box_in_mask_rem_dirs_sum[box_directions] -= 1
# if observation['step'] == 341:
# import pdb; pdb.set_trace()
if next_step_attack:
# Increase the ship scores for the planned actions
if attack_id in move_ids_directions_next_attack:
move_dir = move_ids_directions_next_attack[attack_id]
move_row, move_col = move_ship_row_col(
my_abs_row, my_abs_col, move_dir, grid_size)
# if observation['step'] == 204:
# import pdb; pdb.set_trace()
update_ship_scores.append(
(ship_k, move_row, move_col, 2e6, opponent_distance, None,
my_abs_row, my_abs_col))
else:
# Figure out if we should use this ship to attack the target -
# there is no point in using too many ships!
# if observation['step'] == 201 and my_row == 6 and my_col == 7:
# import pdb; pdb.set_trace()
if (opponent_distance > 2) and (
(num_covered_directions[box_directions] + 0.5*(
box_in_mask_rem_dirs_sum[box_directions])).min() >= 2 and (
np.all(num_covered_directions[box_directions] > 0)) or (
box_in_mask_rem_dirs_sum[box_directions].min() > 2) and (
opponent_distance > box_in_window)):
# print("Dropping ship", my_abs_row, my_abs_col, "from attack")
continue
rel_pos_diff = (my_row-double_window, my_col-double_window)
num_covered_attacker = num_covered_directions[box_directions]
# Logic to cover a direction that is almost covered
almost_covered_override = False
if np.all((num_covered_attacker > 0) | (
box_in_mask_rem_dirs_sum[box_directions] >= 1)) & np.any(
num_one_step_from_covered) and (
box_directions.sum() == 1) and len(
threatened_one_step) > 0 and ((
np.abs(my_row - my_col) == 1) or (my_row + my_col in [
double_window-1, double_window+1])):
move_dir = None
if my_row-my_col == -1:
if WEST in threatened_one_step and my_row < double_window:
almost_covered_dir = WEST
move_dir = SOUTH
elif SOUTH in threatened_one_step and my_row > double_window:
almost_covered_dir = SOUTH
move_dir = WEST
elif my_row-my_col == 1:
if NORTH in threatened_one_step and my_row < double_window:
almost_covered_dir = NORTH
move_dir = EAST
elif EAST in threatened_one_step and my_row > double_window:
almost_covered_dir = EAST
move_dir = NORTH
elif my_row+my_col == double_window-1:
if EAST in threatened_one_step and my_row < double_window:
almost_covered_dir = EAST
move_dir = SOUTH
elif SOUTH in threatened_one_step and my_row > double_window:
almost_covered_dir = SOUTH
move_dir = EAST
elif my_row+my_col == double_window+1:
if NORTH in threatened_one_step and my_row < double_window:
almost_covered_dir = NORTH
move_dir = WEST
elif WEST in threatened_one_step and my_row > double_window:
almost_covered_dir = WEST
move_dir = NORTH
if move_dir is not None:
move_row, move_col = move_ship_row_col(
my_row, my_col, move_dir, grid_size)
if not pos_taken[move_row, move_col]:
# Override: when we are next to the target: expect opponent
# to move
almost_covered_override = True
if opponent_distance == 1:
threat_dir = OPPOSITE_MAPPING[get_dir_from_target(
my_row, my_col, double_window, double_window, 1000)[0]]
one_square_threats.append(threat_dir)
move_dir = None
else:
# Make sure that the square we want to move to is
# available
almost_covered_dirs.append(almost_covered_dir)
if not almost_covered_override:
if attack_id in box_override_assignment_not_next_attack:
attack_move_id = box_override_assignment_not_next_attack[
attack_id][0]
assert box_directions[attack_move_id]
else:
attack_dir_scores = num_covered_attacker + 0.1*(
box_in_mask_rem_dirs_sum[box_directions])
attack_dir_id = np.argmin(attack_dir_scores)
attack_move_id = np.where(box_directions)[0][attack_dir_id]
rel_pos_diff = (my_row-double_window, my_col-double_window)
attack_cover_dir = np.array(NOT_NONE_DIRECTIONS)[
attack_move_id]
one_hot_cover_dirs = np.zeros(4, dtype=bool)
one_hot_cover_dirs[attack_move_id] = 1
other_dirs_covered = one_hot_cover_dirs | (
num_covered_directions > 0) | (box_in_mask_rem_dirs_sum >= 1)
wait_reinforcements = not np.all(other_dirs_covered) or (
opponent_distance == 1)
# if observation['step'] == 357:
# import pdb; pdb.set_trace()
# print(my_row, my_col, threatened_one_step,
# num_covered_directions, num_one_step_from_covered)
if wait_reinforcements:
# Move away from the target if staying would mean having more
# halite than the target
my_next_halite = halite_ships[my_abs_row, my_abs_col] + int(
collect_rate*obs_halite[my_abs_row, my_abs_col])
if my_next_halite > target_halite:
move_away_dirs = get_dir_from_target(
double_window, double_window, my_row, my_col,
grid_size=1000)
# import pdb; pdb.set_trace()
move_dir = np_rng.choice(move_away_dirs)
else:
move_dir = None
else:
if num_covered_directions[attack_move_id] > 0:
# Move towards the target on the diagonal (empowerment)
move_penalties = 0.001*opponent_euclid_distances**4 + (
my_nearest_euclid_distances[attack_id]**4) + 1e3*(
pos_taken)
move_penalties[my_row, my_col] += 1e3
best_penalty_pos = np.where(
move_penalties == move_penalties.min())
target_move_row = best_penalty_pos[0][0]
target_move_col = best_penalty_pos[1][0]
move_dir = get_dir_from_target(
my_row, my_col, target_move_row, target_move_col,
grid_size=1000)[0]
if attack_cover_dir == NORTH:
if np.abs(rel_pos_diff[1]) < (np.abs(rel_pos_diff[0])-1):
move_dir = SOUTH
elif rel_pos_diff[1] < 0:
move_dir = EAST
else:
move_dir = WEST
elif attack_cover_dir == SOUTH:
if np.abs(rel_pos_diff[1]) < (np.abs(rel_pos_diff[0])-1):
move_dir = NORTH
elif rel_pos_diff[1] < 0:
move_dir = EAST
else:
move_dir = WEST
elif attack_cover_dir == EAST:
if np.abs(rel_pos_diff[0]) < (np.abs(rel_pos_diff[1])-1):
move_dir = WEST
elif rel_pos_diff[0] < 0:
move_dir = SOUTH
else:
move_dir = NORTH
elif attack_cover_dir == WEST:
if np.abs(rel_pos_diff[0]) < (np.abs(rel_pos_diff[1])-1):
move_dir = EAST
elif rel_pos_diff[0] < 0:
move_dir = SOUTH
else:
move_dir = NORTH
# Increase the ship scores for the planned actions
moved_rel_dir = RELATIVE_DIR_MAPPING[move_dir]
new_rel_pos = (rel_pos_diff[0] + moved_rel_dir[0],
rel_pos_diff[1] + moved_rel_dir[1])
new_grid_pos = (double_window + new_rel_pos[0],
double_window + new_rel_pos[1])
if new_grid_pos[0] < 0 or new_grid_pos[1] < 0 or new_grid_pos[
0] > 2*double_window or new_grid_pos[1] > 2*double_window:
new_rel_pos = (rel_pos_diff[0], rel_pos_diff[1])
new_grid_pos = (double_window + new_rel_pos[0],
double_window + new_rel_pos[1])
if pos_taken[new_grid_pos] and opponent_distance == 2:
# Override - if I can move right next to the target: do it.
shortest_directions = get_dir_from_target(
my_row, my_col, double_window, double_window, grid_size=1000)
for move_dir in shortest_directions:
moved_rel_dir = RELATIVE_DIR_MAPPING[move_dir]
new_rel_pos = (rel_pos_diff[0] + moved_rel_dir[0],
rel_pos_diff[1] + moved_rel_dir[1])
new_grid_pos = (double_window + new_rel_pos[0],
double_window + new_rel_pos[1])
if not pos_taken[new_grid_pos]:
break
move_row, move_col = move_ship_row_col(
my_abs_row, my_abs_col, move_dir, grid_size)
if not pos_taken[new_grid_pos] and not new_rel_pos == (0, 0):
# Update the covered attack directions
ship_covered_directions = np.zeros(4, dtype=np.bool)
ship_one_step_from_covered_directions = np.zeros(
4, dtype=np.bool)
for threat_dir in RELATIVE_NOT_NONE_DIRECTIONS:
nz_dim = int(threat_dir[0] == 0)
dir_offset = new_rel_pos[nz_dim]*threat_dir[nz_dim]
other_dir_abs_offset = np.abs(new_rel_pos[1-nz_dim])
if dir_offset > 0 and other_dir_abs_offset <= dir_offset:
covered_id = np.where(
RELATIVE_DIR_TO_DIRECTION_MAPPING[threat_dir] == (
np.array(NOT_NONE_DIRECTIONS)))[0][0]
ship_one_step_from_covered_directions[covered_id] = 1
if other_dir_abs_offset < dir_offset:
ship_covered_directions[covered_id] = 1
# if observation['step'] == 210 and row == 1 and col == 8:
# import pdb; pdb.set_trace()
# Join the attack - add actions to the list
num_covered_directions[ship_covered_directions] += 1
num_one_step_from_covered[
ship_one_step_from_covered_directions] = 1
update_ship_scores.append(
(ship_k, move_row, move_col, 2e6, opponent_distance,
np.where(ship_covered_directions)[0], my_abs_row,
my_abs_col))
pos_taken[new_grid_pos] = 1
# We can almost box the opponent in and rely on the opponent not
# taking risky actions to escape
almost_attack_nearby_blockers = False
if len(threatened_one_step) > 0 and (
len(one_square_threats+almost_covered_dirs) > 0) and not np.all(
num_covered_directions > 0) and not next_step_attack:
not_covered_dirs = [MOVE_DIRECTIONS[i+1] for i in np.where(
num_covered_directions == 0)[0]]
if len(one_square_threats) > 0 and np.all(
[d in threatened_one_step for d in not_covered_dirs]):
almost_attack_nearby_blockers = True
else:
almost_attack_nearby_blockers = len(
threatened_one_step.intersection(almost_covered_dirs)) > 0
# if observation['step'] == 87:
# import pdb; pdb.set_trace()
if next_step_attack or np.all(num_covered_directions > 0) or (
almost_attack_nearby_blockers and np.any(
num_covered_directions > 0)):
# Prune the attackers: only keep the closest two in each direction
if not next_step_attack:
drop_rows = []
distance_dir = np.array([[u[4], u[5][0]] for u in (
update_ship_scores) if u[5].size > 0])
for d_id in np.arange(4):
if (distance_dir[:, 1] == d_id).sum() > 2:
dir_rows = np.where(distance_dir[:, 1] == d_id)[0]
drop_ids = np.argsort(distance_dir[dir_rows, 0])[2:]
drop_rows.extend(dir_rows[drop_ids].tolist())
for dr in np.sort(drop_rows)[::-1]:
del update_ship_scores[dr]
# if observation['step'] == 237:
# import pdb; pdb.set_trace()
box_opponent_positions.append((row, col))
boxing_in_ships.append(opponent_ship_k)
for (ship_k, move_row, move_col, new_collect_score,
distance_to_target, _, my_abs_row, my_abs_col) in (
update_ship_scores):
# Only update the ship scores if the box in action is in my one
# step valid actions
box_dir = get_dir_from_target(
my_abs_row, my_abs_col, move_row, move_col, grid_size)[0]
if box_dir in all_ship_scores[ship_k][9]:
all_ship_scores[ship_k][0][move_row, move_col] = (
new_collect_score)
# Flag the boxing in ships as unavailable for other hunts
ships_available[my_abs_row, my_abs_col] = 0
boxing_in[my_abs_row, my_abs_col] = 1
ships_on_box_mission[ship_k] = distance_to_target
override_move_squares_taken[move_row, move_col] = 1
# Make sure that I attack all squares where an opponent is converting that
# I can not allow to happen
for (row, col) in possible_convert_opponent_positions:
if not (row, col) in ignore_convert_positions:
my_base_distances = my_current_base_distances[:, row, col]
must_attack_converting_square = my_base_distances.min() < (3.5 - (
observation['relative_step']))
if must_attack_converting_square and not override_move_squares_taken[
row, col]:
# Look for nearby ships of mine that can attack the converting ship
for d in NOT_NONE_DIRECTIONS:
my_row, my_col = move_ship_row_col(row, col, d, grid_size)
if original_ships_available[my_row, my_col] or (
my_defend_base_ship_positions[my_row, my_col]):
to_target_dir = OPPOSITE_MAPPING[d]
ship_pos = my_row*grid_size+my_col
ship_k = ship_pos_to_key[ship_pos]
if to_target_dir in all_ship_scores[ship_k][6]:
all_ship_scores[ship_k][0][row, col] = 1e9
boxing_in[my_row, my_col] = 1
print("ATTACKING POSSIBLY CONVERTING SHIP", observation['step'],
row, col, my_row, my_col)
break
history['prev_step_boxing_in_ships'] = boxing_in_ships
return (all_ship_scores, boxing_in, box_opponent_positions,
override_move_squares_taken, ships_on_box_mission)
def update_scores_pack_hunt(
all_ship_scores, config, stacked_ships, observation,
opponent_ships_sensible_actions, halite_ships, steps_remaining,
player_obs, np_rng, opponent_ships_scaled, collect_rate, obs_halite,
main_base_distances, history, on_rescue_mission, boxing_in_mission,
my_defend_base_ship_positions, env_observation, box_opponent_positions,
override_move_squares_taken, player_influence_maps,
ignore_convert_positions, convert_unavailable_positions,
early_hunting_season, late_hunting_season, safe_collect_margin, spawn_cost,
change_standard_consecutive_steps=5):
available_pack_hunt_ships = np.copy(stacked_ships[0])
grid_size = available_pack_hunt_ships.shape[0]
hunting_season_started = history['hunting_season_started']
prev_standard_ships = history['hunting_season_standard_ships']
# # FUTURE WORK: Make the number of standard ships a function of the hunt
# # success?
# # FUTURE WORK: Make the number of standard ships a function of ship losses?
if early_hunting_season:
max_standard_ships_hunting_season = config[
'max_standard_ships_early_hunting_season']
elif late_hunting_season:
max_standard_ships_hunting_season = max(config[
'max_standard_ships_late_hunting_season'], int(len(player_obs[2])*(
config['late_hunting_season_standard_min_fraction'])))
else:
max_standard_ships_hunting_season = max(10, int(len(player_obs[2])/2.5))
# print(observation['step'], len(player_obs[2]),
# max_standard_ships_hunting_season)
# print(observation['step'], opponent_hunt_fraction, num_my_ships,
# my_target_standard_ships, max_standard_ships_hunting_season)
# Determine if I should preferably target a specific opponent.
# In games where there is a clear difference between the top two agents and
# my agent, where I am one of those two: mostly harrass/hoard the other top
# agent
current_scores = history['current_scores']
spawn_diffs = (current_scores[0] - current_scores[1:])/spawn_cost
first_opponent_id = np.argsort(spawn_diffs)[0]
second_opponent_id = np.argsort(spawn_diffs)[1]
my_agent_in_top_two = (spawn_diffs < 0).sum() <= 1
spawn_diff_first = np.abs(spawn_diffs[first_opponent_id])
spawn_diff_second = np.abs(spawn_diffs[second_opponent_id])
prev_targeted_hoard_mode = history['targeted_hoard_mode']
should_start_targeted_hoard_mode = my_agent_in_top_two and (
spawn_diff_second > 2*spawn_diff_first) and (spawn_diff_second > 6)
should_continue_targeted_hoard_mode = my_agent_in_top_two and (
spawn_diff_second > spawn_diff_first) and (spawn_diff_second > 4)
targeted_hoard_mode = should_start_targeted_hoard_mode or (
prev_targeted_hoard_mode and should_continue_targeted_hoard_mode)
history['targeted_hoard_mode'] = targeted_hoard_mode
preferred_victim = None
if targeted_hoard_mode:
preferred_victim = first_opponent_id+1
if should_start_targeted_hoard_mode and not prev_targeted_hoard_mode:
print(observation['step'], "Start selective hoarding of opponent",
preferred_victim)
prev_step_opponent_ship_moves = history['prev_step_opponent_ship_moves']
num_players = stacked_ships.shape[0]
ship_pos_to_key = {}
for i in range(num_players):
ship_pos_to_key.update({
v[0]: k for k, v in env_observation.players[i][2].items()})
ship_key_to_pos = {v: k for k, v in ship_pos_to_key.items()}
player_ids = -1*np.ones((grid_size, grid_size), dtype=np.int)
for i in range(stacked_ships.shape[0]):
player_ids[stacked_ships[i]] = i
not_available_due_to_camping = np.zeros_like(available_pack_hunt_ships)
# Loop over the camping ships and exclude the ones from the available mask
# that have flagged they are not available for boxing in
camping_ships_strategy = history['camping_ships_strategy']
for ship_k in camping_ships_strategy:
if not camping_ships_strategy[ship_k][3]:
camping_row, camping_col = row_col_from_square_grid_pos(
player_obs[2][ship_k][0], grid_size)
not_available_due_to_camping[camping_row, camping_col] = 1
# Loop over the ships that attack opponent camplers and exclude them from the
# available mask
attack_opponent_campers = history['attack_opponent_campers']
for ship_k in attack_opponent_campers:
attacking_camper_row, attacking_camper_col = row_col_from_square_grid_pos(
player_obs[2][ship_k][0], grid_size)
not_available_due_to_camping[
attacking_camper_row, attacking_camper_col] = 1
# Loop over the ships that are stuck in a loop and mark them as unavailable
not_available_due_to_cycle = np.zeros_like(available_pack_hunt_ships)
for ship_k in history['avoid_cycle_actions']:
cycle_row, cycle_col = row_col_from_square_grid_pos(
player_obs[2][ship_k][0], grid_size)
not_available_due_to_cycle[cycle_row, cycle_col] = 1
# Loop over the ships that are temporarily assigned a collect task
not_available_due_to_temp_collect = np.zeros_like(available_pack_hunt_ships)
delete_keys = []
for ship_k in history['temporary_hoarding_collect_ships']:
if ship_k in player_obs[2]:
collect_row, collect_col = row_col_from_square_grid_pos(
player_obs[2][ship_k][0], grid_size)
not_available_due_to_temp_collect[collect_row, collect_col] = 1
else:
delete_keys.append(ship_k)
for k in delete_keys:
history['temporary_hoarding_collect_ships'].remove(k)
# List the ships that are definitely not available for the pack hunt
# In this group:
# - Opponent base camping
# - Attack opponent base campers
# - Ships that are are on a rescue mission (rescuer and rescued)
# - Base defense emergency ships
# - Boxing in other ships
available_pack_hunt_ships &= (~not_available_due_to_camping)
available_pack_hunt_ships &= (~on_rescue_mission)
available_pack_hunt_ships &= (~my_defend_base_ship_positions)
available_pack_hunt_ships &= (~boxing_in_mission)
available_pack_hunt_ships &= (~convert_unavailable_positions)
available_pack_hunt_ships &= (~not_available_due_to_cycle)
available_pack_hunt_ships &= (~not_available_due_to_temp_collect)
# Of the remaining list: identify 'max_standard_ships_hunting_season' ships
# that are available to gather halite/attack bases.
# Preferably select ships that were also selected for these modes in the
# previous step and have halite on board.
# Only change the gather/attack ships if one of my gatherers was destroyed
# Assign a new gatherer if my gatherer is assigned to the base camping
# attack or defense (These ships tend to be indefinitely unavailable), or if
# the ship was destroyed.
# Prefer non-zero halite ships for the initial gathering ships.
my_ship_pos_to_k = {v[0]: k for k, v in player_obs[2].items()}
available_positions = np.where(available_pack_hunt_ships)
num_available_ships = available_pack_hunt_ships.sum()
standard_ships = []
if num_available_ships > 0:
best_standard_scores = np.zeros(num_available_ships)
pos_keys = []
for i in range(num_available_ships):
row = available_positions[0][i]
col = available_positions[1][i]
pos_key = my_ship_pos_to_k[row*grid_size+col]
best_standard_scores[i] = all_ship_scores[pos_key][0].max() - 1e6*(
halite_ships[row, col] == 0)
pos_keys.append(pos_key)
if hunting_season_started:
already_included_ids = np.zeros(num_available_ships, dtype=np.bool)
for ship_k in prev_standard_ships:
if ship_k in player_obs[2]:
# The ship still exists and was a standard ship in the previous step
row, col = row_col_from_square_grid_pos(
player_obs[2][ship_k][0], grid_size)
if my_defend_base_ship_positions[row, col] or boxing_in_mission[
row, col] or on_rescue_mission[row, col] or (
not_available_due_to_cycle[row, col]):
# We can use the ship for collecting soon (now it is rescuing or
# boxing in or defending the base)
standard_ships.append(ship_k)
elif available_pack_hunt_ships[row, col]:
# The ship is available now. Flag it for exclusion so it doesn't
# get added twice
standard_ships.append(ship_k)
match_id = np.where((available_positions[0] == row) & (
available_positions[1] == col))[0][0]
already_included_ids[match_id] = True
else:
# The ship is now used for base camping or base conversion or
# additional collection
# Exclude it from the standard ships group
assert not_available_due_to_camping[row, col] or (
convert_unavailable_positions[row, col]) or (
not_available_due_to_temp_collect[row, col])
best_standard_scores = best_standard_scores[~already_included_ids]
available_positions = (available_positions[0][~already_included_ids],
available_positions[1][~already_included_ids])
pos_keys = np.array(pos_keys)[~already_included_ids].tolist()
num_unassigned = max_standard_ships_hunting_season - len(standard_ships)
# if num_unassigned > 0:
# import pdb; pdb.set_trace()
num_to_assign = min(num_unassigned, num_available_ships)
num_to_assign_phase_1 = max(0, num_to_assign - config[
'max_standard_ships_decided_end_pack_hunting'])
num_to_assign_phase_2 = num_to_assign-num_to_assign_phase_1
num_available_ships = best_standard_scores.size
else:
num_to_assign = max_standard_ships_hunting_season
num_to_assign_phase_1 = min(num_to_assign, num_available_ships)
num_to_assign_phase_2 = 0
# Assign the remaining standard ships
# Assign the available ships with the highest collect score for collecting
# (preferably non zero halite ships)
best_standard_ids = np.argsort(-best_standard_scores)[
:num_to_assign_phase_1]
for standard_id in best_standard_ids:
standard_row = available_positions[0][standard_id]
standard_col = available_positions[1][standard_id]
standard_key = pos_keys[standard_id]
assert not standard_key in standard_ships
standard_ships.append(standard_key)
# Mark the standard ships as unavailable for pack hunting
for standard_key in standard_ships:
standard_row, standard_col = row_col_from_square_grid_pos(
player_obs[2][standard_key][0], grid_size)
available_pack_hunt_ships[standard_row, standard_col] = 0
# The remaining ships are considered for pack hunting. Send the ones with
# halite on board to a base.
considered_hunting_ships_pos = np.where(available_pack_hunt_ships)
num_available_ships = available_pack_hunt_ships.sum()
for i in range(num_available_ships):
row = considered_hunting_ships_pos[0][i]
col = considered_hunting_ships_pos[1][i]
if halite_ships[row, col] > 0:
available_pack_hunt_ships[row, col] = 0
ship_k = my_ship_pos_to_k[row*grid_size+col]
# Let the ship collect at will (but prefer to go to a base sooner rather
# than later) before joining the pack hunt (after touching base)
for j in [2, 3]:
all_ship_scores[ship_k][j][:] = -1e6
# Let a hoarding ship gather when it is safe to do so
if (obs_halite[row, col] < 100 or safe_collect_margin[
row, col] <= 0) and (
not ship_k in history['temporary_hoarding_collect_ships']):
# FUTURE WORK: Make the multiplier a function of the opponent
# aggression level?
all_ship_scores[ship_k][1][:] *= 4
elif not ship_k in history['temporary_hoarding_collect_ships'] and (
safe_collect_margin[row, col] > 0):
history['temporary_hoarding_collect_ships'].append(ship_k)
# print(observation['step'], row, col, ship_k,
# "Temporarily collecting")
# Ignore ships for hunting that are already being boxed in with my box-in
# ships
box_opponent_mask = np.zeros((grid_size, grid_size), dtype=np.bool)
for boxed_target_row, boxed_target_col in box_opponent_positions:
box_opponent_mask[boxed_target_row, boxed_target_col] = 1
# Consider what to do with the zero halite ships that are available for
# hunting.
# First attempt: do something similar as mzotkiew
# Main idea: move to the nearest non zero halite opponent if that direction
# is valid.
opponent_ships = stacked_ships[1:].sum(0) > 0
potential_targets = opponent_ships & (halite_ships > 0) & (
~box_opponent_mask)
hunting_ships_pos = np.where(available_pack_hunt_ships)
num_hunting_ships = available_pack_hunt_ships.sum()
# Exclude targets that I am willfully letting convert
for (ignore_convert_row, ignore_convert_col) in ignore_convert_positions:
potential_targets[ignore_convert_row, ignore_convert_col] = 0
# Exclude targets that have a safe path to one of their bases
if num_hunting_ships > 0:
stacked_bases = np.stack(
[rbs[1] for rbs in observation['rewards_bases_ships']])
nearest_opponent_base_distances = [None]
for opponent_id in range(1, num_players):
num_bases = stacked_bases[opponent_id].sum()
opponent_base_locations = np.where(stacked_bases[opponent_id])
all_opponent_base_distances = [DISTANCES[
opponent_base_locations[0][i], opponent_base_locations[1][i]] for i in (
range(num_bases))] + [99*np.ones((grid_size, grid_size))]
nearest_opponent_base_distances.append(np.stack(
all_opponent_base_distances).min(0))
considered_targets_pos = np.where(potential_targets)
for j in range(potential_targets.sum()):
target_row = considered_targets_pos[0][j]
target_col = considered_targets_pos[1][j]
opponent_id = np.where(stacked_ships[:, target_row, target_col])[0][0]
opp_nearest_base_distances = nearest_opponent_base_distances[opponent_id]
target_distance_to_nearest_base = opp_nearest_base_distances[
target_row, target_col]
my_min_distance_to_opp_nearest_base = opp_nearest_base_distances[
hunting_ships_pos].min()
# if target_row == 20 and target_col == 12 and observation['step'] == 160:
# import pdb; pdb.set_trace()
if target_distance_to_nearest_base < my_min_distance_to_opp_nearest_base:
potential_targets[target_row, target_col] = 0
potential_targets_pos = np.where(potential_targets)
num_potential_targets = potential_targets.sum()
# print(observation['step'], num_hunting_ships, num_potential_targets)
hoarded_one_step_opponent_keys = []
if num_potential_targets > 0 and num_hunting_ships > 0:
# print(observation['step'])
ordered_ship_keys = []
all_target_distances = np.zeros((num_hunting_ships, num_potential_targets))
for i in range(num_hunting_ships):
row = hunting_ships_pos[0][i]
col = hunting_ships_pos[1][i]
ship_k = my_ship_pos_to_k[row*grid_size+col]
ordered_ship_keys.append(ship_k)
potential_target_distances = DISTANCES[row, col][potential_targets]
# Update the target distances to only include potential targets that
# correspond with valid actions
potential_targets_rows = potential_targets_pos[0]
potential_targets_cols = potential_targets_pos[1]
south_dist = np.where(
potential_targets_rows >= row, potential_targets_rows-row,
potential_targets_rows-row+grid_size)
east_dist = np.where(
potential_targets_cols >= col, potential_targets_cols-col,
potential_targets_cols-col+grid_size)
valid_directions = all_ship_scores[ship_k][6]
valid_move_counts = 2*np.ones(num_potential_targets)
for d in NOT_NONE_DIRECTIONS:
if not d in valid_directions:
if d == NORTH:
decrement_ids = south_dist >= grid_size/2
elif d == SOUTH:
decrement_ids = (south_dist <= grid_size/2) & (south_dist > 0)
elif d == EAST:
decrement_ids = (east_dist <= grid_size/2) & (east_dist > 0)
elif d == WEST:
decrement_ids = east_dist >= grid_size/2
valid_move_counts[decrement_ids] -= 1
# Handle the case of being in the same row or column
valid_move_counts[south_dist == 0] -= 1
valid_move_counts[east_dist == 0] -= 1
# if observation['step'] == 91 and row == 6 and col == 3:
# import pdb; pdb.set_trace()
assert np.all(valid_move_counts >= 0)
potential_target_distances[valid_move_counts == 0] += 100
all_target_distances[i] = potential_target_distances
opponent_num_escape_directions = np.zeros(num_potential_targets)
for j in range(num_potential_targets):
target_row = potential_targets_pos[0][j]
target_col = potential_targets_pos[1][j]
opponent_num_escape_directions[j] = len(opponent_ships_sensible_actions[
target_row, target_col])
# First coordinate my hunters to ships that have no valid escape directions
hunting_ships_available = np.ones(num_hunting_ships, dtype=np.bool)
for j in range(num_potential_targets):
num_escape_dirs = opponent_num_escape_directions[j]
if num_escape_dirs == 0:
target_row = potential_targets_pos[0][j]
target_col = potential_targets_pos[1][j]
# Loop over my hunting ships at a distance of max two and take as many
# of the potential escape squares as possible
my_near_ships = np.where((all_target_distances[:, j] <= 2) & (
hunting_ships_available))[0]
num_my_near_ships = my_near_ships.size
if num_my_near_ships > 0:
# You can always attack at most 2 escape squares. Keep track of what
# escape squares each of my ships can attack without collecting
# halite on the next turn (ignoring ship collision halite gain)
my_target_relative_attack_dirs = np.zeros((num_my_near_ships, 5))
for loop_id, my_ship_id in enumerate(my_near_ships):
row = hunting_ships_pos[0][my_ship_id]
col = hunting_ships_pos[1][my_ship_id]
ship_k = my_ship_pos_to_k[row*grid_size+col]
valid_attack_dirs = all_ship_scores[ship_k][6]
considered_attack_dirs = get_dir_from_target(
row, col, target_row, target_col, grid_size)
if all_target_distances[my_ship_id, j] == 1 and (
obs_halite[row, col] == 0):
considered_attack_dirs.append(None)
attack_dirs = list(set(considered_attack_dirs) & set(
valid_attack_dirs))
# Get the relative directions from the target that I can attack
for d in attack_dirs:
move_row, move_col = move_ship_row_col(
row, col, d, grid_size)
relative_covered_dir = MOVE_DIRECTIONS_TO_ID[get_dir_from_target(
target_row, target_col, move_row, move_col, grid_size)[0]]
my_target_relative_attack_dirs[loop_id, relative_covered_dir] = 1
direction_covered = np.zeros(len(MOVE_DIRECTIONS), dtype=np.bool)
for dir_id, d in enumerate(MOVE_DIRECTIONS):
rel_target_row, rel_target_col = move_ship_row_col(
target_row, target_col, d, grid_size)
if override_move_squares_taken[rel_target_row, rel_target_col]:
direction_covered[dir_id] = 1
# First, handle the ships that can only attack a single square that
# is not covered yet
my_target_relative_attack_dirs[:, direction_covered] = 0
# if observation['step'] == 149:
# import pdb; pdb.set_trace()
# Greedily loop over directions by ordering the count of the number
# of ships that cover. Prefer low but strictly positive directions.
while my_target_relative_attack_dirs.sum() > 0:
ship_num_possible_attacks = my_target_relative_attack_dirs.sum(1)
dir_num_possible_attacks = my_target_relative_attack_dirs.sum(0)
# The None action is slightly preferred since that guarantees a max
# distance of 1 on the next turn
dir_num_possible_attacks[0] -= 0.1
non_zero_min_count = dir_num_possible_attacks[
dir_num_possible_attacks > 0].min()
best_dir_ids = np.where(dir_num_possible_attacks == (
non_zero_min_count))[0]
dir_id = np_rng.choice(best_dir_ids)
considered_ships = np.where(
my_target_relative_attack_dirs[:, dir_id])[0]
# Break ties with the number of directions each ship covers
cover_ship_scores = ship_num_possible_attacks[considered_ships]
considered_ships_attacker_id = considered_ships[
np.argmin(cover_ship_scores)]
attacker_id = my_near_ships[considered_ships_attacker_id]
# Move my ship to the relative position of the target
rel_target_row, rel_target_col = move_ship_row_col(
target_row, target_col, MOVE_DIRECTIONS[dir_id], grid_size)
attacker_row = hunting_ships_pos[0][attacker_id]
attacker_col = hunting_ships_pos[1][attacker_id]
ship_k = my_ship_pos_to_k[attacker_row*grid_size+attacker_col]
all_ship_scores[ship_k][0][rel_target_row, rel_target_col] = 2e5
override_move_squares_taken[rel_target_row, rel_target_col] = 1
hunting_ships_available[attacker_id] = 0
# Update the attack dir counts
my_target_relative_attack_dirs[considered_ships_attacker_id] = 0
my_target_relative_attack_dirs[:, dir_id] = 0
# if observation['step'] == 188:
# import pdb; pdb.set_trace()
# Next, coordinate my hunters to ships that have a single moving escape
# direction.
# These ship are preferred targets since it is likely that I can soon box
# them in, especially if it is me who cuts off three of the move directions
# Order the ships so that the ships that had a single escape direction in
# the previous step are handled first, so we can coordinate the
# interception
one_step_opponent_ids = np.arange(num_potential_targets).tolist()
priority_ids = []
for opponent_ship_k in history['prev_step_hoarded_one_step_opponent_keys']:
if opponent_ship_k in ship_key_to_pos:
opponent_pos = ship_key_to_pos[opponent_ship_k]
target_row, target_col = row_col_from_square_grid_pos(
opponent_pos, grid_size)
if potential_targets[target_row, target_col]:
# We need to check because the target may no longer be available for
# pack hunting due to boxing in or getting close to a friendly base
opponent_priority_id = np.where(
(potential_targets_pos[0] == target_row) & (
potential_targets_pos[1] == target_col))[0][0]
priority_ids.append(opponent_priority_id)
remaining_ids = list(set(one_step_opponent_ids) - set(priority_ids))
remaining_ids.sort() # Set intersect can be flaky
one_step_opponent_ids = priority_ids + remaining_ids
one_step_opponent_positions_directions = []
for j in one_step_opponent_ids:
target_row = potential_targets_pos[0][j]
target_col = potential_targets_pos[1][j]
target_escape_directions = opponent_ships_sensible_actions[
target_row, target_col]
move_escape_directions = copy.copy(target_escape_directions)
if (0, 0) in move_escape_directions:
move_escape_directions.remove((0, 0))
num_move_escape_dirs = len(move_escape_directions)
# nearest_target_distances = np.tile(
# all_target_distances.min(1)[:, None], [1, num_potential_targets])
if num_move_escape_dirs == 1:
# The <= ensures we consider piling up on inidividual ships
potential_nearby_attackers = np.where(hunting_ships_available & (
all_target_distances[:, j] <= 2))[0]
if potential_nearby_attackers.size >= 2:
# Figure out if I have at least one available ship at a max distance
# of 2 that can push the opponent in one direction
escape_dir = RELATIVE_DIR_TO_DIRECTION_MAPPING[
move_escape_directions[0]]
potential_nearby_distances = all_target_distances[
potential_nearby_attackers, j]
if potential_nearby_distances.min() == 1:
# The None direction is covered - verify the other directions
uncovered_dirs = copy.copy(NOT_NONE_DIRECTIONS)
uncovered_dirs.remove(escape_dir)
ignore_attacker_ids = []
d1_hunters = []
for attacker_id in potential_nearby_attackers:
attacker_row = hunting_ships_pos[0][attacker_id]
attacker_col = hunting_ships_pos[1][attacker_id]
ship_k = my_ship_pos_to_k[attacker_row*grid_size+attacker_col]
valid_directions = all_ship_scores[ship_k][6]
if escape_dir in valid_directions:
threat_dirs = get_dir_from_target(
target_row, target_col, attacker_row, attacker_col,
grid_size)
uncovered_dirs = list(set(uncovered_dirs) - set(threat_dirs))
if DISTANCES[target_row, target_col][
attacker_row, attacker_col] == 1:
d1_hunters.append(attacker_id)
else:
ignore_attacker_ids.append(attacker_id)
if len(uncovered_dirs) == 0 or (
len(uncovered_dirs) == 1 and len(d1_hunters) > 1):
one_step_opponent_positions_directions.append((
target_row, target_col, escape_dir))
opponent_ship_k = ship_pos_to_key[
target_row*grid_size+target_col]
hoarded_one_step_opponent_keys.append(opponent_ship_k)
if len(uncovered_dirs) > 0:
potential_nearby_attackers = d1_hunters
# Move the attackers in the single escape direction
# import pdb; pdb.set_trace()
for attacker_id in potential_nearby_attackers:
if not attacker_id in ignore_attacker_ids:
attacker_row = hunting_ships_pos[0][attacker_id]
attacker_col = hunting_ships_pos[1][attacker_id]
move_row, move_col = move_ship_row_col(
attacker_row, attacker_col, escape_dir, grid_size)
ship_k = my_ship_pos_to_k[
attacker_row*grid_size+attacker_col]
all_ship_scores[ship_k][0][move_row, move_col] = 2e5
override_move_squares_taken[move_row, move_col] = 1
hunting_ships_available[attacker_id] = 0
# Try to get into a position where the opponent can only move in one
# direction (from two to one escape direction)
for j in range(num_potential_targets):
num_escape_dirs = opponent_num_escape_directions[j]
if num_escape_dirs == 2:
target_row = potential_targets_pos[0][j]
target_col = potential_targets_pos[1][j]
potential_nearby_attackers = np.where(hunting_ships_available & (
all_target_distances[:, j] == 1))[0]
attack_selected = False
if potential_nearby_attackers.size == 2:
escape_directions = opponent_ships_sensible_actions[
target_row, target_col]
if (escape_directions[0][0] == 0 and (
escape_directions[1][0] == 0)) or (
escape_directions[0][1] == 0 and (
escape_directions[1][1] == 0)):
# Scenario: ME | OPPONENT | ME - guess the action and then chase
# Guess the opponent's next action
opponent_id = np.where(
stacked_ships[:, target_row, target_col])[0][0]
escape_dir_scores = np.zeros(2)
for escape_id, escape_dir in enumerate(escape_directions):
move_row, move_col = move_ship_row_col(
target_row, target_col, RELATIVE_DIR_TO_DIRECTION_MAPPING[
escape_dir], grid_size)
opponent_influence = player_influence_maps[opponent_id][
move_row, move_col]
my_influence = player_influence_maps[0][move_row, move_col]
escape_dir_scores[escape_id] = opponent_influence-my_influence
likely_opponent_move = RELATIVE_DIR_TO_DIRECTION_MAPPING[
escape_directions[np.argmax(escape_dir_scores)]]
# Only continue if both my ships can move in the selected
# directions
both_can_move = True
can_stay = np.zeros(2, dtype=np.bool)
for attacker_0_or_1, attacker_id in enumerate(
potential_nearby_attackers):
attacker_row = hunting_ships_pos[0][attacker_id]
attacker_col = hunting_ships_pos[1][attacker_id]
ship_k = my_ship_pos_to_k[attacker_row*grid_size+attacker_col]
both_can_move = both_can_move and likely_opponent_move in (
all_ship_scores[ship_k][6])
can_stay[attacker_0_or_1] = obs_halite[
attacker_row, attacker_col] == 0
if both_can_move:
# If both are on non zero halite squares: move both in the likely
# escape direction. Otherwise, select a random ship to move in
# the escape direction where the ship that remains in place has
# no halite at the considered square
if not np.any(can_stay):
stay_in_place_ids = []
else:
stay_in_place_ids = [np_rng.choice(potential_nearby_attackers[
can_stay])]
for attacker_id in potential_nearby_attackers:
# import pdb; pdb.set_trace()
attacker_row = hunting_ships_pos[0][attacker_id]
attacker_col = hunting_ships_pos[1][attacker_id]
move_dir = None if attacker_id in stay_in_place_ids else (
likely_opponent_move)
move_row, move_col = move_ship_row_col(
attacker_row, attacker_col, move_dir, grid_size)
ship_k = my_ship_pos_to_k[
attacker_row*grid_size+attacker_col]
all_ship_scores[ship_k][0][move_row, move_col] = 2e5
override_move_squares_taken[move_row, move_col] = 1
hunting_ships_available[attacker_id] = 0
attack_selected = True
escape_directions = opponent_ships_sensible_actions[
target_row, target_col]
if not attack_selected and not (0, 0) in escape_directions and len(
escape_directions) == 2:
# Scenario: ME | OPPONENT | | ME - guess the action and then chase
available_nearby = np.where(hunting_ships_available & (
all_target_distances[:, j] <= 2))[0]
if available_nearby.size >= 2:
attacker_rows = hunting_ships_pos[0][available_nearby]
attacker_cols = hunting_ships_pos[1][available_nearby]
north_dist = np.where(
target_row >= attacker_rows, target_row-attacker_rows,
target_row-attacker_rows+grid_size)
vert_rel_pos = np.where(
north_dist < 3, north_dist, north_dist-grid_size)
west_dist = np.where(
target_col >= attacker_cols, target_col-attacker_cols,
target_col-attacker_cols+grid_size)
horiz_rel_pos = np.where(
west_dist < 3, west_dist, west_dist-grid_size)
same_row_ids = (vert_rel_pos == 0)
same_col_ids = (horiz_rel_pos == 0)
consider_attack = False
if np.any(horiz_rel_pos[same_row_ids] < 0) and np.any(
horiz_rel_pos[same_row_ids] > 0):
if np.any(horiz_rel_pos[same_row_ids] == 1) and np.any(
horiz_rel_pos[same_row_ids] == -2):
move_to_target_id = available_nearby[same_row_ids][np.where(
horiz_rel_pos[same_row_ids] == -2)[0][0]]
move_escape_id = available_nearby[same_row_ids][np.where(
horiz_rel_pos[same_row_ids] == 1)[0][0]]
consider_attack = True
elif np.any(horiz_rel_pos[same_row_ids] == -1) and np.any(
horiz_rel_pos[same_row_ids] == 2):
move_to_target_id = available_nearby[same_row_ids][np.where(
horiz_rel_pos[same_row_ids] == 2)[0][0]]
move_escape_id = available_nearby[same_row_ids][np.where(
horiz_rel_pos[same_row_ids] == -1)[0][0]]
consider_attack = True
elif np.any(vert_rel_pos[same_col_ids] < 0) and np.any(
vert_rel_pos[same_col_ids] > 0):
if np.any(vert_rel_pos[same_col_ids] == 1) and np.any(
vert_rel_pos[same_col_ids] == -2):
move_to_target_id = available_nearby[same_col_ids][np.where(
vert_rel_pos[same_col_ids] == -2)[0][0]]
move_escape_id = available_nearby[same_col_ids][np.where(
vert_rel_pos[same_col_ids] == 1)[0][0]]
consider_attack = True
elif np.any(vert_rel_pos[same_col_ids] == -1) and np.any(
vert_rel_pos[same_col_ids] == 2):
move_to_target_id = available_nearby[same_col_ids][np.where(
vert_rel_pos[same_col_ids] == 2)[0][0]]
move_escape_id = available_nearby[same_col_ids][np.where(
vert_rel_pos[same_col_ids] == -1)[0][0]]
consider_attack = True
if consider_attack:
opponent_id = np.where(
stacked_ships[:, target_row, target_col])[0][0]
escape_dir_scores = np.zeros(2)
for escape_id, escape_dir in enumerate(escape_directions):
move_row, move_col = move_ship_row_col(
target_row, target_col, RELATIVE_DIR_TO_DIRECTION_MAPPING[
escape_dir], grid_size)
opponent_influence = player_influence_maps[opponent_id][
move_row, move_col]
my_influence = player_influence_maps[0][move_row, move_col]
escape_dir_scores[escape_id] = opponent_influence-my_influence
likely_opponent_move = RELATIVE_DIR_TO_DIRECTION_MAPPING[
escape_directions[
|
np.argmax(escape_dir_scores)
|
numpy.argmax
|
import numpy as np
import torch
import mathutils
import piq
import lpips
from scipy.spatial.transform import Rotation as R
def rotate2D(deg):
rad = np.deg2rad(deg)
r = R.from_rotvec(rad * np.array([0, 0, 1]))
return r.as_matrix()
def pt2xyz(p, t, r = 1):
"""[Polar to cartesian transform]
Args:
p ([Tensor bx1x...]): [phi \in [0,2pi]]
t ([Tensor bx1x...]): [theta \in [0,pi]]
r (int or Tensor bx1x..., optional): [radius > 0]. Defaults to 1.
Returns:
[x,y,z]: [tuple of bx1x... Tensors]
"""
if(type(p) == torch.Tensor):
cos = torch.cos
sin = torch.sin
else:
cos = np.cos
sin = np.sin
x = r * sin(t) * cos(p)
y = r * sin(t) * sin(p)
z = r * cos(t)
return x,y,z
def xyz2pt(x, y, z):
"""[cartesian to polar transform]
Args:
x ([ndarray or tensor]): [description]
y ([ndarray or tensor]): [description]
z ([ndarray or tensor]): [description]
Returns:
[tuple]: [phi \in [0,2\pi] and theta \in [0, \pi]]
"""
assert(type(x) == type(y),'type mismatch')
assert(type(y) == type(z),'type mismatch')
if(type(x) == torch.Tensor):
acos = torch.acos
atan2 = torch.atan2
atan = torch.atan
else:
acos = np.arccos
atan2 = np.arctan2
atan = np.arctan
r = (x**2+y**2+z**2) ** 0.5
p = atan2(y,x)
p[p<0] = p[p<0] + 2*np.pi
t = acos(z/(r+1e-20))
return p, t
def pt2uv(p,t):
"""[polar to uniform]
Args:
p ([ndarray or tensor]): [description]
t ([ndarray or tensor]): [description]
Returns:
[tuple]: [u \in [0,1] and v \in [0,1]]
"""
return p/(np.pi * 2),t/np.pi
def uv2pt(u,v):
"""[Converts polar to cartesian]
Args:
u ([Tensor or ndarray]): [Azimuth \in [0,1]]
v ([Tensor or ndarray]): [Elevation \in [0,1]]
Returns:
[tuple of Tensor or ndarray]: [\phi \in [0-2 \pi], theta \in [0,\pi] ]
"""
t = v * np.pi
p = u * 2 * np.pi
return p,t
def uv2ptUniform(u,v):
"""[Converts polar to cartesian uniformly on a sphere]
Args:
u ([Tensor or ndarray]): [Azimuth \in [0,1]]
v ([Tensor or ndarray]): [Elevation \in [0,1]]
Returns:
[tuple of Tensor or ndarray]: [\phi \in [0-2 \pi], theta \in [0,\pi] ]
"""
if(type(v) == np.ndarray):
acos = np.arccos
elif(type(v) == torch.Tensor):
acos = torch.acos
t = acos(1- 2 * v)
p = u * 2 * np.pi
return p,t
def intersect_ray_plane(o,w,p,n):
"""[Compute the intersection point between a ray and a plane]
Args:
o ([ndarray]): [ray origin]
w ([ndarray]): [ray direction]
p ([ndarray]): [plane origin]
n ([ndarray]): [plane normal vector]
Returns:
[ndarray]: [intersection point, distance to ray origin]
"""
#derived from <n,p - (o+wt)>=0
t = ((n * p).sum(-1,keepdim=True) - (n * o).sum(-1,keepdim=True)) / ((n * w).sum(-1,keepdim=True) +1e-5)
return o + w * t, t
def boxMuller(u1,u2):
"""[Generate 2d normal distribution given uniform]
Args:
u1 ([type]): [description]
u2 ([type]): [description]
"""
if(type(u1) == np.ndarray):
sin = np.sin
cos = np.cos
ln = np.log
elif(type(u1) == torch.Tensor):
sin = torch.sin
cos = torch.cos
ln = torch.log
z0 = (-2 * ln(u1)) ** 0.5 * cos(2 * np.pi * u2)
z1 = (-2 * ln(u1)) ** 0.5 * sin(2 * np.pi * u2)
return z0, z1
def normalPDF(mu,variance,x):
if(type(x) == np.ndarray):
exp = np.exp
elif(type(x) == torch.Tensor):
exp = torch.exp
coeff = 1 / ((variance * 2 * np.pi) ** 0.5)
e = exp(-0.5 * (x-mu) ** 2 / variance)
return coeff * e
def naiveSampleOnSphere(u,v):
p,t = uv2pt(u,v)
return pt2xyz(p,t)
def uniformSampleOnSphere(u,v):
if(type(u) == np.array):
acos = np.acos
else:
acos = torch.arccos
p,t = (acos(2*v-1), 2 * np.pi * u)
return pt2xyz(p,t)
def vectorNormalize(v):
"""[Normalize a vector as v/||v||]
Args:
v ([Tensor b,1,...]): [Input vector]
Returns:
[Tensor b,1,...]: [Normalized vector]
"""
return v / ((v**2).sum(dim=1) ** 0.5 + 1e-20)
def relerr(a,b):
return (((a-b) ** 2 / b **2) ** 0.5).sum()
def normal2frame(n,dim):
"""[Creates a nxn local frame given a normal vector]
:param n: [nd Normal vector]
:type n: [Array]
:return: [Local frame]
:rtype: [nxn ndarray]
"""
if(type(n) == np.array):
rand = lambda x:np.random.rand(*x.shape)
norm = lambda x:np.linalg.norm(x,axis=-1)
cross = np.cross
stack = lambda x,axis:np.stack(x,axis=axis)
normalize = lambda x:np.linalg.normalize(x,axis=-1)
elif(type(n) == torch.Tensor):
rand = lambda x:torch.rand(*x.shape,dtype=x.dtype,device=n.device)
norm = lambda x:torch.norm(x,axis=-1)
cross = lambda a1,a2,a3,b1,b2,b3:torch.stack(((a2*b3-a3*b2), (a3*b1-a1*b3), (a1*b2 - a2*b1)),dim=-1)
stack = lambda x,axis:torch.stack(x,dim=axis)
normalize = lambda x,axis:torch.nn.functional.normalize(x,dim=axis)
else:
print('Unknown data type')
exit(0)
r = normalize(rand(n),axis=dim)
y = cross(n[...,0],n[...,1],n[...,2],r[...,0],r[...,1],r[...,2])
y = normalize(y,dim)
x = cross(y[...,0],y[...,1],y[...,2],n[...,0],n[...,1],n[...,2])
x = normalize(x,dim)
return stack((x,y,n),axis=dim)
def normalize(x,dim):
return x / ((x ** 2 + 1e-8) ** 0.5).sum(dim=dim,keepdim=True)
def lookAt(Origin, LookAt, Up):
"""[Creates camera matrix in right hand coordinate. Implementation of https://www.scratchapixel.com/lessons/mathematics-physics-for-computer-graphics/lookat-function]
Args:
Origin ([Tensor b,3,...]): [Camera Origin in world space]
LookAt ([Tensor b,3,...]): [Camera lookat position in world space]
Up ([Tensor b,3,...]): [Camera Up direction in world space]
Returns:
[Tensor b,4,4,...]: [Camera extrinsic matrix]
"""
Forward = LookAt - Origin
Forward = vectorNormalize(Forward)
Up = vectorNormalize(Up)
Right = torch.cross(Up, Forward)
Right = vectorNormalize(Right)
newUp = torch.cross(Forward, Right)
newUp = vectorNormalize(newUp)
m = torch.stack((Right,newUp,Forward),dim=1)
newOrigin = torch.einsum('bmn...,bn...->bm...', m, Origin)
m = torch.cat((m,newOrigin.unsqueeze(2)),dim=2)
m = torch.cat((m,torch.zeros_like(m)[:,0:1,:,...]),dim=1)
m[:,3,3,...] = 1
return m
def perspective(fov,near,far):
"""[Generate 4x4 perspective transform matrix. Re-implementation of Mitsuba]
Args:
near ([float]): [near plane]
far ([float]): [far plane]
fov ([float]): [Field of view in degrees]
Returns:
[ndarray]: [4x4 projection matrix]
"""
#mitsuba
recip = 1.0 / (far - near)
cot = 1.0 / np.tan(np.deg2rad(fov * 0.5))
perspective = torch.diagflat(torch.Tensor([cot,cot,far*recip,0.0]))
perspective[2,3] = -near * far * recip
perspective[3,2] = 1.0
return perspective
def perspective_projection(fov,near,far,filmSize=np.array([1,1]),cropSize=np.array([1,1]),cropOffset=np.array([0,0])):
"""[Reimplementation of Mitsuba perspective_projection function]
Args:
fov ([float]): [Field of view in degrees]
near ([float]): [Near plane]
far ([float]): [Far plane]
filmSize ([1x2 ndarray], optional): [Film size]. Defaults to np.array([1,1]).
cropSize ([1x2 ndarray], optional): [crop size]. Defaults to np.array([1,1]).
cropOffset ([1x2 ndarray], optional): [Crop offset]. Defaults to np.array([0,0]).
Returns:
[4x4 tensor]: [Perspective camera projection matrix]
"""
aspect = filmSize[0] / filmSize[1]
rel_offset = cropOffset / filmSize
rel_size = cropSize / filmSize
p = perspective(fov,near,far)
translate = torch.eye(4)
translate[:3,-1] = torch.Tensor([-1.0, -1.0 / aspect, 0.0])
scale = torch.diagflat(torch.Tensor([-0.5,-0.5*aspect,1.0,1.0]))
translateCrop = torch.eye(4)
translateCrop[:3,-1] = torch.Tensor([-rel_offset[0],-rel_offset[1],0.0])
scaleCrop = torch.diagflat(torch.Tensor([1/rel_size[0],1/rel_size[1],1.0,1.0]))
m1 = torch.mm(scaleCrop,torch.mm(translateCrop,torch.mm(scale,torch.mm(translate,p))))
return m1
def sampleRay(h,w,far,near,fov,samples,ext):
"""[Reimplementation of Mitsuba sample_ray]
Args:
far ([float]): [float]
near ([float]): [float]
fov ([float]): [float]
Returns:
[4x4 array]: [float]
"""
aspect = w/h
camera_to_sample = perspective_projection(fov,near,far,filmSize=np.array([w,h]),cropSize=np.array([w,h]))
sample_to_camera = torch.inverse(camera_to_sample[None,...])
samples = np.concatenate((samples,np.zeros_like(samples[:,0:1,...]),np.ones_like(samples[:,0:1,...])),axis=1)
d = torch.einsum('abc,acd->abd',sample_to_camera,torch.Tensor(samples))
d = d[:,:3,...] / d[:,3,...]
d = vectorNormalize(d)
d = torch.einsum('abc,ac...->ab...',ext[:,:3,:3,...].transpose(2,1),d[:,:3,...])
return d
def u1tou2(u1,u2):
"""[Compute shortest rotation between two vectors]
Args:
u1 ([ndarray]): [1st vector]
u2 ([ndarray]): [2nd vector]
Returns:
[Quaternion]: [Shortest rotation]
"""
u1 = u1 / np.sum(u1 ** 2) ** 0.5
u2 = u2 /
|
np.sum(u2 ** 2)
|
numpy.sum
|
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""quantity module : allows manipulation of physical quantities.
TODO:
- [X] : find a better way to include SI units in
- [ ] : sum() : problem with init of iterator, using radd, needs to start with sum(y_q,Quantity(1,Dimension("L")))
- [ ] : avec Q_vectorize qui utilise interp, lève une erreur pas claire si on renvoi une valeur dans un array déjà initialisé avec une autre dimension
- [ ] : make DISPLAY_DIGITS and EXP_THRESHOLD variable-attribute, not constant
- [X] : PENDING : make __true_div__ = __div__
- [ ] : try to factor quantify and make_quantity
- [X] : add a method for fast-friendly display in another unit
- [X] : add methods to check dimensions (is_length, is_surface, etc)
- [ ] : factorize quad and dblquad, and make nquad
- [X] : make a decorator for trigo functions
- [ ] : deal with precision of quads
- [X] : make a round method
- [ ] : quick plot method for array value (matplotlib)
- [ ] : interp and vectorize adds "no-dimension" if needed - homogenize
- [ ] : init favunit to SI unit if none is passed ?
- [X] : make cos, sin, etc method for numpy compatibility
- [ ] : test quantity with complex and fractions.fractions
- [ ] : float must be commented for solvers to work....
- [ ] : make default symbol variable name ?
- [ ] : make favunit defaults to SI ?
- [ ] : for trigo method, prevent when unit is sr ?
- [X] : create a Wrong dimension Error, for trigo functions for eg
- [X] : deal with numpy slicing a[a>1]
- [ ] : improve Inration of eq, ne (ex : assertNotEqual when dealing with arrays)
- [ ] : when uncertainties is implemented, add an automatic plotting
- [X] : add a format method --> need a refactor of repr..
- [X] : add a method to reset favunit ?
- [ ] : better tests for complex number support
- [ ] : see if possible to not rely on sympy, numpy and scipy
- [ ] : improve code for __array_ufunc__
- [ ] : better tests for Fraction support
PROPOSITIONS/QUESTIONS :
- make sum, mean, integrate, is_dimensionless properties IO methods ?
- add a 0 quantity to radd to allow magic function sum ?
- should __pow__ be allowed with array, returning an array of quantities
(and quantity of array if power is scalar)
- should mul and rmul be different :
- [1,2,3]*m = ([1,2,3])m
- m*[1,2,3] = [1m, 2m, 3m]
- make Quantity self)converted to numpy : ex : np.cos(q) if q is dimensionless
'Quantity' object has no attribute 'cos' ???
- when multiplying or dividing not quanity with quantity, propagate favunit ?
- should setting dimension be forbiden ? or with a warning ?
- make a floordiv ?
- no np.all in comparison for indexing a[a>1], but then np.all is needed in functions verifications
- should repr precise the favunit and symbol ?
- switch base system by replacing the dimension dict (or making it setable)
- exponent repr : use re to change “**” to “^” or to “”
- base nominal representation and str should allow plain copy/paste to be reused in code
- list unicode possible changes : micron character, superscripts for exponents
- quantify in each method is ugly
- should redefine every numpy ufunc as method ?
"""
import math
import numbers as nb
import numpy as np
import sympy as sp
import warnings
from .dimension import Dimension, DimensionError, SI_UNIT_SYMBOL
# # Constantes
UNIT_PREFIX= " "
DISPLAY_DIGITS = 2
EXP_THRESHOLD = 2
UNIT_SUFFIX = ""
LATEX_VALUE_UNIT_SEPARATOR = "\,"#" \cdot "
#SCIENTIFIC = '%.' + str(DISPLAY_DIGITS) + 'E' # (syntaxe : "%.2f" % mon_nombre
#CLASSIC = '%.' + str(DISPLAY_DIGITS) + 'f'
HANDLED_FUNCTIONS = {}
class Quantity(object):
"""Quantity class : """
__quantity_priority__ = 1000
DIGITS = DISPLAY_DIGITS
EXP_THRESH = EXP_THRESHOLD
LATEX_SEP = LATEX_VALUE_UNIT_SEPARATOR
def __init__(self, value, dimension, symbol="UndefinedSymbol", favunit=None, description=""):
self.__array_priority__ = 100
self.value = value
self.dimension = dimension
self.symbol = symbol
self.favunit = favunit
self.description = description
def __setattr__(self, name, value):
if name == "value":
if isinstance(value, np.ndarray):
super().__setattr__(name, value)
super().__setattr__("size", self.value.size)
elif (isinstance(value,nb.Number) or type(value) == np.int64 or
type(value) == np.int32):
#isinstance(value, (int, float)):#isinstance(value,float) or
#isinstance(value,int) or type(value) == numpy.int64 or
#type(value) == numpy.int32:
#or numpy.isrealobj(valeur):
super().__setattr__(name, value)
super().__setattr__("size", 1)
elif isinstance(value, list) or isinstance(value, tuple):
super().__setattr__(name, np.array(value))
elif value is None:
super().__setattr__(name, value)
else:
super().__setattr__(name, value)
super().__setattr__("size", 1)
#else:
# raise TypeError(("Value of Quantity must be a number "
# "or numpy array, not {}").format(type(value)))
#elif name == "dimension":
# if isinstance(value,Dimension) :
# super().__setattr__(name,value)
# else:
# raise TypeError(("Dimension of Quantity must be a Dimension,"
# "not {}").format(type(value)))
elif name == "symbol":
if isinstance(value,sp.Expr):
super().__setattr__(name, value)
elif isinstance(value,str):
super().__setattr__(name,sp.Symbol(value))
else:
raise TypeError(("Symbol of Quantity must be a string "
"or a sympy-symbol, "
"not {}").format(type(value)))
elif name == "favunit":
if isinstance(value,Quantity) or value == None:
super().__setattr__(name, value)
elif np.isscalar(value):
super().__setattr__(name, None)
else:
raise TypeError(("Favorite unit of Quantity must be a Quantity "
"or None, not {}").format(type(value)))
#elif name == "description":
# if not isinstance(value, str):
# raise TypeError("desc attribute must be a string.")
# super().__setattr__(name, value)
else:
super().__setattr__(name, value)
def __add__(self, y):
y = quantify(y)
if not self.dimension == y.dimension:
raise DimensionError(self.dimension, y.dimension)
#return Quantity(self.value + y.value,
# self.dimension)
return type(self)(self.value + y.value,
self.dimension)
def __radd__(self, x): return self + x
def __sub__(self, y):
y = quantify(y)
if not self.dimension == y.dimension:
raise DimensionError(self.dimension, y.dimension)
return type(self)(self.value - y.value,
self.dimension)
def __rsub__(self, x): return quantify(x) - self
def __mul__(self,y):
y = quantify(y)
return type(self)(self.value * y.value,
self.dimension * y.dimension,
symbol = self.symbol * y.symbol).rm_dim_if_dimless()
__rmul__ = __mul__
def __matmul__(self, y):
y = quantify(y)
return type(self)(self.value @ y.value,
self.dimension * y.dimension,
symbol = self.symbol * y.symbol).rm_dim_if_dimless()
def __truediv__(self, y):
y = quantify(y)
return type(self)(self.value / y.value,
self.dimension / y.dimension,
symbol = self.symbol / y.symbol).rm_dim_if_dimless()
def __rtruediv__(self, x): return quantify(x) / self
def __floordiv__(self, y):
"""
Any returned quantity should be dimensionless, but leaving the
Quantity().remove() because more intuitive
"""
y = quantify(y)
if not self.dimension == y.dimension:
raise DimensionError(self.dimension, y.dimension)
return type(self)(self.value // y.value,
self.dimension).rm_dim_if_dimless()
def __rfloordiv__(self, x):
x = quantify(x)
if not self.dimension == x.dimension:
raise DimensionError(self.dimension, x.dimension)
return type(self)(x.value // self.value,
self.dimension).rm_dim_if_dimless()
def __mod__(self,y):
"""
There is no rm_dim_if_dimless() because a
modulo operation would not change the dimension.
"""
y = quantify(y)
if not self.dimension == y.dimension:
raise DimensionError(self.dimension, y.dimension)
return type(self)(self.value % y.value,
self.dimension)#.rm_dim_if_dimless()
def __pow__(self,power):
"""
A power must always be a dimensionless scalar.
If a = 1*m, we can't do a ** [1,2], because the result would be
an array of quantity, and can't be a quantity with array-value,
since the quantities won't be the same dimension.
"""
#if not np.isscalar(power):#(isinstance(power,int) or isinstance(power,float)):
# raise TypeError(("Power must be a number, "
# "not {}").format(type(power)))
return type(self)(self.value ** power,
self.dimension ** power,
symbol = self.symbol ** power,
).rm_dim_if_dimless()
def __neg__(self): return self * (-1)
def __pos__(self): return self
def __len__(self): return len(self.value)
def __bool__(self): return bool(self.value)
# min and max uses the iterator
#def __min__(self):
# return Quantity(min(self.value),
# self.dimension,
# favunit=self.favunit)
#def __max__(self):
# return Quantity(max(self.value),
# self.dimension,
# favunit=self.favunit)
def __eq__(self,y):
try:
y = quantify(y)
if self.dimension == y.dimension:
return self.value == y.value # comparing arrays returns array of bool
else:
return False
except Exception as e:
return False
def __ne__(self,y):
return np.invert(self == y) #np.invert for element-wise not, for array compatibility
def __gt__(self,y):
y = quantify(y)
if self.dimension == y.dimension:
return self.value > y.value
else:
raise DimensionError(self.dimension,y.dimension)
def __lt__(self,y):
y = quantify(y)
if self.dimension == y.dimension:
return self.value < y.value
else:
raise DimensionError(self.dimension,y.dimension)
def __ge__(self,y): return (self > y) | (self == y) # or bitwise
def __le__(self,y): return (self < y) | (self == y) # or bitwise
def __abs__(self):
return type(self)(abs(self.value),
self.dimension,
favunit = self.favunit)
def __complex__(self):
if not self.is_dimensionless_ext():
raise DimensionError(self.dimension, Dimension(None), binary=False)
return complex(self.value)
def __int__(self):
if not self.is_dimensionless_ext():
raise DimensionError(self.dimension, Dimension(None), binary=False)
return int(self.value)
def __float__(self):
if not self.is_dimensionless_ext():
raise DimensionError(self.dimension, Dimension(None), binary=False)
return float(self.value)
def __round__(self, i=None):
return type(self)(round(self.value, i),
self.dimension,
favunit = self.favunit)
def __copy__(self):
return type(self)(self.value, self.dimension, favunit=self.favunit, symbol=self.symbol)
def copy(self):
return self.__copy__()
def __repr__(self):
if str(self.symbol) != "UndefinedSymbol":
sym = ", symbol="+str(self.symbol)
else:
sym = ""
return '<Quantity : ' + str(self.value) + " " + str(self.dimension.str_SI_unit()) + sym + ">"
def __str__(self):
complement_value_for_repr = self._compute_complement_value()
if not complement_value_for_repr == "":
return str(self._compute_value()) + UNIT_PREFIX + complement_value_for_repr + UNIT_SUFFIX
else:
return str(self._compute_value()) + UNIT_SUFFIX
def __hash__(self):
return hash(str(self.value)+str(self.dimension))
def __ceil__(self):
"""
To handle math.ceil
"""
return type(self)(math.ceil(self.value), self.dimension)
def __floor__(self):
"""
To handle math.floor
"""
return type(self)(math.floor(self.value), self.dimension)
def __trunc__(self):
return type(self)(math.trunc(self.value), self.dimension)
#@property
#def latex(self):
# return self._repr_latex_()
#@property
#def html(self):
# return self._repr_html_()
#def _repr_pretty_(self, p, cycle):
# """Markdown hook for ipython repr.
# See https://ipython.readthedocs.io/en/stable/config/integrating.html"""
# print("repr_pretty")
# return p.text(self._repr_latex_())
def plot(self, kind="y", other=None, ax=None):
from physipy.quantity.plot import plotting_context
if ax is None:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
with plotting_context():
if kind =="y" and other is None:
ax.plot(self)
elif kind =="x" and other is not None:
ax.plot(self, other)
else:
raise ValueError("kind must be y of x with other")
def _repr_latex_(self):
"""Markdown hook for ipython repr in latex.
See https://ipython.readthedocs.io/en/stable/config/integrating.html"""
# create a copy
q = self.__copy__()
# to set a favunit for display purpose
# only change the favunit if not already defined
if q.favunit == None:
q.favunit = self._pick_smart_favunit()
formatted_value = q._format_value()
complemented = q._compute_complement_value()
if complemented != "":
complement_value_str = sp.printing.latex(sp.parsing.sympy_parser.parse_expr(complemented))
else:
complement_value_str = ""
# if self.value is an array, only wrap the complement in latex
if isinstance(self.value, np.ndarray):
return formatted_value + "$" + self.LATEX_SEP + complement_value_str + "$"
# if self.value is a scalar, use sympy to parse expression
value_str = sp.printing.latex(sp.parsing.sympy_parser.parse_expr(formatted_value))
return "$" + value_str + self.LATEX_SEP + complement_value_str + "$"
def _pick_smart_favunit(self, array_to_scal=np.mean):
"""Method to pick the best favunit among the units dict.
A smart favunit always have the same dimension as self.
The 'best' favunit is the one minimizing the difference with self.
In case self.value is an array, array_to_scal is
used to convert the array to a single value.
"""
from .units import units
from .utils import asqarray
same_dim_unit_list = [value for value in units.values() if self.dimension == value.dimension]
# if no unit with same dim already exists
if len(same_dim_unit_list) == 0:
return None
same_dim_unit_arr = asqarray(same_dim_unit_list)
self_val = self if not isinstance(self.value, np.ndarray) else array_to_scal(self)
best_ixd = np.abs(same_dim_unit_arr - np.abs(self_val)).argmin()
best_favunit = same_dim_unit_list[best_ixd]
return best_favunit
def _format_value(self):
"""Used to format the value on repr as a str.
If the value is > to 10**self.EXP_THRESH, it is displayed with scientific notation.
Else floating point notation is used.
"""
value = self._compute_value()
if not np.isscalar(value):
return str(value)
else:
if abs(value) >= 10**self.EXP_THRESH or abs(value) < 10**(-self.EXP_THRESH):
return ("{:." + str(self.DIGITS) + "e}").format(value)
else:
return ("{:." + str(self.DIGITS) + "f}").format(value)
#def _repr_markdown_(self):
# """Markdown hook for ipython repr in markdown.
# this seems to take precedence over _repr_latex_"""
# return self.__repr__()
#def _repr_html(self):
# return self._repr_latex_()
#def __format_raw__(self, format_spec):
# return format(self.value, format_spec) + " " + str(self.dimension.str_SI_unit())
def __format__(self, format_spec):
"""This method is used when using format or f-string.
The format is applied to the numerical value part only."""
complement_value_for_repr = self._compute_complement_value()
prefix = UNIT_PREFIX
if "~" in format_spec:
format_spec = format_spec.replace("~", "")
prefix = ""
if not complement_value_for_repr == "":
return format(self._compute_value(), format_spec) + prefix + complement_value_for_repr + UNIT_SUFFIX
else:
return format(self._compute_value(), format_spec) + prefix
def _compute_value(self):
"""Return the numerical value corresponding to favunit."""
if isinstance(self.favunit, Quantity):
ratio_favunit = make_quantity(self/self.favunit)
return ratio_favunit.value
else:
return self.value
def _compute_complement_value(self, custom_favunit=None):
"""Return the complement to the value as a str."""
if custom_favunit is None:
favunit = self.favunit
else:
favunit = custom_favunit
if isinstance(favunit, Quantity):
ratio_favunit = make_quantity(self/favunit)
dim_SI = ratio_favunit.dimension
if dim_SI == Dimension(None):
return str(favunit.symbol)
else:
return str(favunit.symbol) + "*" + dim_SI.str_SI_unit()
else:
return self.dimension.str_SI_unit()
#used for plotting
@property
def _SI_unitary_quantity(self):
"""Return a one-value quantity with same dimension.
Such that self = self.value * self._SI_unitary_quantity
"""
return type(self)(1, self.dimension, symbol=self.dimension.str_SI_unit())
def __getitem__(self, idx):
return type(self)(self.value[idx],
self.dimension,
favunit=self.favunit)
def __setitem__(self, idx, q):
q = quantify(q)
if not q.dimension == self.dimension:
raise DimensionError(q.dimension,self.dimension)
if isinstance(idx,np.bool_) and idx == True:
self.valeur = q.value
elif isinstance(idx,np.bool_) and idx == False:
pass
else:
self.value[idx] = q.value
#def __iter__(self):
# if isinstance(self.value,np.ndarray):
# return QuantityIterator(self)
# else:
# return iter(self.value)
@property
def flat(self):
# pint implementation
#for v in self.value.flat:
# yield Quantity(v, self.dimension)
# astropy
return FlatQuantityIterator(self)
def flatten(self):
return type(self)(self.value.flatten(), self.dimension, favunit=self.favunit)
def tolist(self):
return [Quantity(i, self.dimension) for i in self.value]
@property
def real(self):
return type(self)(self.value.real, self.dimension)
@property
def imag(self):
return type(self)(self.value.imag, self.dimension)
@property
def T(self):
return type(self)(self.value.T, self.dimension)
def std(self, *args, **kwargs):
return np.std(self, *args, **kwargs)
def inverse(self):
"""is this method usefull ?"""
return type(self)(1/self.value, 1/self.dimension)
def sum(self, **kwargs): return np.sum(self, **kwargs)
def mean(self, **kwargs): return np.mean(self, **kwargs)
def integrate(self, *args, **kwargs): return np.trapz(self, *args, **kwargs)
def is_dimensionless(self):
return self.dimension == Dimension(None)
def rm_dim_if_dimless(self):
if self.is_dimensionless():
return self.value
else:
return self
def has_integer_dimension_power(self):
return all(value == int(value) for value in self.dimension.dim_dict.values())
def to(self, y):
"""return quantity with another favunit."""
if not isinstance(y, Quantity):
raise TypeError("Cannot express Quantity in not Quantity")
q = self.__copy__()
q.favunit = y
return q
def set_favunit(self, fav):
"""
To be used as one-line declaration : (np.linspace(3, 10)*mum).set_favunit(mum)
"""
self.favunit = fav
return self
def ito(self, y):
"""in-place change of favunit."""
self.favunit = y
return self
def into(self, y):
"""like to, but with same dimension"""
if not self.dimension == y.dimension:
raise ValueError("must have same unit. Try to().")
return self.to(y)
def iinto(self, y):
"""like ito, but with same dimension"""
if not self.dimension == y.dimension:
raise ValueError("must have same unit. Try to().")
return self.ito(y)
# Shortcut for checking dimension
def is_length(self): return self.dimension == Dimension("L")
def is_surface(self): return self.dimension == Dimension("L")**2
def is_volume(self): return self.dimension == Dimension("L")**3
def is_time(self): return self.dimension == Dimension("T")
def is_mass(self): return self.dimension == Dimension("M")
def is_angle(self): return self.dimension == Dimension("RAD")
def is_solid_angle(self): return self.dimension == Dimension("SR")
def is_temperature(self):
return self.dimension == Dimension("theta")
def is_nan(self):
"For use with pandas extension"
return np.isnan(self.value)
def is_dimensionless_ext(self):
return self.is_dimensionless() or self.is_angle()
def check_dim(self, dim):
return self.dimension == dimensionify(dim)
# for munits support
def _plot_get_value_for_plot(self, q_unit):
q_unit = quantify(q_unit)
if not self.dimension == q_unit.dimension:
raise DimensionError(self.dimension, q_unit.dimension)
return self/q_unit
# for munits support
def _plot_extract_q_for_axe(self):
favunit = self.favunit
if isinstance(favunit, Quantity):
ratio_favunit = make_quantity(self/favunit)
dim_SI = ratio_favunit.dimension
if dim_SI == Dimension(None):
return favunit
else:
return make_quantity(favunit * ratio_favunit._SI_unitary_quantity,
symbol=str(favunit.symbol) + "*" + ratio_favunit._SI_unitary_quantity.dimension.str_SI_unit())
else:
return self._SI_unitary_quantity
def __getattr__(self, item):
"""
Called when an attribute lookup has not found the attribute
in the usual places (i.e. it is not an instance attribute
nor is it found in the class tree for self). name is the
attribute name. This method should return the (computed)
attribute value or raise an AttributeError exception.
Note that if the attribute is found through the normal mechanism,
__getattr__() is not called.
"""
if item == '__iter__':
if isinstance(self.value,np.ndarray):
return QuantityIterator(self)
else:
return iter(self.value)
if item.startswith('__array_'):
warnings.warn("The unit of the quantity is stripped.")
if isinstance(self.value, np.ndarray):
return getattr(self.value, item)
else:
# If an `__array_` attributes is requested but the magnitude is not an ndarray,
# we convert the magnitude to a numpy ndarray.
self.value = np.array(self.value)
return getattr(self.value, item)
try:
res = getattr(self.value, item)
return res
except AttributeError as ex:
raise AttributeError("Neither Quantity object nor its value ({}) "
"has attribute '{}'".format(self.value, item))
#def to_numpy(self):
# return np.asarray(self.value)
def reshape(self, *args, **kwargs):
return Quantity(self.value.reshape(*args, **kwargs), self.dimension)
def __array_function__(self, func, types, args, kwargs):
if func not in HANDLED_FUNCTIONS:
return NotImplemented
# Note: this allows subclasses that don't override
# __array_function__ to handle DiagonalArray objects.
#if not all(issubclass(t, self.__class__) for t in types):
# return NotImplemented
return HANDLED_FUNCTIONS[func](*args, **kwargs)
# TODO : make this a static function ?
def __array_ufunc__(self, ufunc, method, *args, **kwargs):
"""
https://numpy.org/doc/1.18/user/basics.dispatch.html?highlight=array%20interface
The __array_ufunc__ receives:
- ufunc, a function like numpy.multiply
- method, a string, differentiating between numpy.multiply(...) and variants like numpy.multiply.outer, numpy.multiply.accumulate, and so on. For the common case, numpy.multiply(...), method == '__call__'.
- inputs, which could be a mixture of different types
- kwargs, keyword arguments passed to the function
This doesn't need __getattr__ nor __array__
"""
if method == "__call__":
return self._ufunc_call(ufunc, method, *args, **kwargs)
elif method == "reduce":
return self._ufunc_reduce(ufunc, method, *args, **kwargs)
elif method == "accumulate":
return self._ufunc_accumulate(ufunc, method, *args, **kwargs)
else:
raise NotImplementedError(f"array ufunc {ufunc} with method {method} not implemented")
def _ufunc_accumulate(self, ufunc, method, *args, **kwargs):
ufunc_name = ufunc.__name__
left = args[0]
# hypot doesn't have a reduce
if ufunc_name in ["add"]:
res = ufunc.accumulate(left.value, **kwargs)
return type(self)(res, left.dimension)
else:
raise NotImplementedError(f"array ufunc {ufunc} with method {method} not implemented")
def _ufunc_reduce(self, ufunc, method, *args, **kwargs):
"""
The method == "reduce" part of __array_ufunc__ interface.
"""
if not method == "reduce":
raise NotImplementedError(f"array ufunc {ufunc} with method {method} not implemented")
ufunc_name = ufunc.__name__
left = args[0] # removed quantify...
# hypot doesn't have a reduce
if ufunc_name in same_dim_out_2 and ufunc_name != "hypot":
res = ufunc.reduce(left.value)
return type(self)(res, left.dimension)
# only multiply seems to be possible
elif ufunc_name in skip_2:
res = ufunc.reduce(left.value)
if ufunc_name == "multiply" or ufunc_name == "matmul":
return type(self)(res, left.dimension ** len(left.value))
else:
raise NotImplementedError(f"array ufunc {ufunc} with method {method} not implemented")
# return booleans :
elif ufunc_name in same_dim_in_2_nodim_out:
res = ufunc.reduce(left.value)
return res
# ValueError: reduce only supported for binary functions
elif ufunc_name in unary_ufuncs:
raise ValueError("reduce only supported for binary functions.")
else:
raise NotImplementedError(f"array ufunc {ufunc} with method {method} not implemented")
def _ufunc_call(self, ufunc, method, *args, **kwargs):
"""
The method == "__call__" part of __array_ufunc__ interface.
"""
if not method == "__call__":
raise NotImplementedError(f"array ufunc {ufunc} with method {method} not implemented")
ufunc_name = ufunc.__name__
left = quantify(args[0])
if ufunc_name in same_dim_out_2:
other = quantify(args[1])
if not left.dimension == other.dimension:
raise DimensionError(left.dimension, other.dimension)
res = ufunc.__call__(left.value,other.value)
return type(self)(res, left.dimension)
elif ufunc_name in skip_2:
other = quantify(args[1])
res = ufunc.__call__(left.value, other.value)
if ufunc_name == "multiply" or ufunc_name == "matmul":
return type(self)(res, left.dimension * other.dimension)
elif ufunc_name == 'divide' or ufunc_name == "true_divide":
return type(self)(res, left.dimension / other.dimension).rm_dim_if_dimless()
elif ufunc_name == "copysign" or ufunc_name == "nextafter":
return type(self)(res, left.dimension)
elif ufunc_name in no_dim_1:
if not left.dimension == Dimension(None):
raise DimensionError(left.dimension, Dimension(None))
res = ufunc.__call__(left.value)
return type(self)(res, Dimension(None))
elif ufunc_name in angle_1:
if not left.is_dimensionless_ext():
raise DimensionError(left.dimension, Dimension(None), binary=True)
res = ufunc.__call__(left.value)
return type(self)(res, Dimension(None)).rm_dim_if_dimless()
elif ufunc_name in same_out:
res = ufunc.__call__(left.value)
return type(self)(res, left.dimension).rm_dim_if_dimless()
elif ufunc_name in special_dict:
if ufunc_name == "sqrt":
res = ufunc.__call__(left.value)
return type(self)(res, left.dimension**(1/2))
elif ufunc_name == "power":
power_num = args[1]
if not (isinstance(power_num,int) or isinstance(power_num,float)):
raise TypeError(("Power must be a number, "
"not {}").format(type(power_num)))
res = ufunc.__call__(left.value, power_num)
return type(self)(res,
left.dimension ** power_num,
symbol = left.symbol ** power_num).rm_dim_if_dimless()
elif ufunc_name == "reciprocal":
res = ufunc.__call__(left.value)
return type(self)(res, 1/left.dimension)
elif ufunc_name == "square":
res = ufunc.__call__(left.value)
return type(self)(res, left.dimension**2)
elif ufunc_name == "cbrt":
res = ufunc.__call__(left.value)
return type(self)(res, left.dimension**(1/3))
elif ufunc_name == "modf":
res = ufunc.__call__(left.value)
frac, integ = res
return (type(self)(frac, left.dimension),
type(self)(integ, left.dimension))
elif ufunc_name == "arctan2":
# both x and y should have same dim such that the ratio is dimless
other = quantify(args[1])
if not left.dimension == other.dimension:
raise DimensionError(left.dimension, other.dimension)
# use the value so that the 0-comparison works
res = ufunc.__call__(left.value, other.value, **kwargs)
return res
else:
raise ValueError
elif ufunc_name in same_dim_in_2_nodim_out:
other = quantify(args[1])
if not left.dimension == other.dimension:
raise DimensionError(left.dimension, other.dimension)
res = ufunc.__call__(left.value, other.value)
return res
elif ufunc_name in inv_angle_1:
if not left.dimension == Dimension(None):
raise DimensionError(left.dimension, Dimension(None))
res = ufunc.__call__(left.value)
return res
#elif ufunc_name in inv_angle_2:
# other = quantify(args[1])
# if not (left.dimension == Dimension(None) and other.dimension == Dimension(None)):
# raise DimensionError(left.dimension, Dimension(None))
# res = ufunc.__call__(left.value, other.value)
# return res
elif ufunc_name in same_dim_in_1_nodim_out:
res = ufunc.__call__(left.value)
return res
elif ufunc_name in no_dim_2:
other = quantify(args[1])
if not (left.dimension == Dimension(None) and other.dimension == Dimension(None)):
raise DimensionError(left.dimension, Dimension(None))
res = ufunc.__call__(left.value, other.value)
return res
else:
raise ValueError("ufunc not implemented ?: ", str(ufunc))
def squeeze(self, *args, **kwargs):
"""
Helper function to wrap numpy's squeeze.
"""
return Quantity(self.value.squeeze(*args, **kwargs), self.dimension)
# Numpy functions
# Override functions - used with __array_function__
def implements(np_function):
def decorator(func):
HANDLED_FUNCTIONS[np_function] = func
return func
return decorator
@implements(np.asanyarray)
def np_asanyarray(a):
return Quantity(np.asanyarray(a.value), a.dimension)
@implements(np.amax)
def np_amax(q): return Quantity(np.amax(q.value), q.dimension, favunit=q.favunit)
@implements(np.amin)
def np_amin(q): return Quantity(np.amin(q.value), q.dimension, favunit=q.favunit)
@implements(np.append)
def np_append(arr, values, **kwargs):
values = quantify(values)
if not arr.dimension == values.dimension:
raise DimensionError(arr.dimension, values.dimension)
return Quantity(np.append(arr.value, values.value, **kwargs), arr.dimension)
@implements(np.argmax)
def np_argmax(a, **kwargs):
return Quantity(np.argmax(a.value, **kwargs), a.dimension)
@implements(np.argsort)
def np_argsort(a, **kwargs):
return np.argsort(a.value, **kwargs)
@implements(np.sort)
def np_sort(a, **kwargs):
return Quantity(np.sort(a.value, **kwargs), a.dimension)
@implements(np.argmin)
def np_argmin(a, **kwargs):
return Quantity(np.argmin(a.value, **kwargs), a.dimension)
@implements(np.around)
def np_around(a, **kwargs):
return Quantity(np.around(a.value, **kwargs), a.dimension)
@implements(np.atleast_1d)
def np_atleast_1d(*arys):
res = [Quantity(np.atleast_1d(arr.value), arr.dimension) for arr in arys]
return res if len(res)>1 else res[0]
@implements(np.atleast_2d)
def np_atleast_2d(*arys):
res = [Quantity(np.atleast_2d(arr.value), arr.dimension) for arr in arys]
return res if len(res)>1 else res[0]
@implements(np.atleast_3d)
def np_atleast_3d(*arys):
res = [Quantity(np.atleast_3d(arr.value), arr.dimension) for arr in arys]
return res if len(res)>1 else res[0]
@implements(np.average)
def np_average(q): return Quantity(np.average(q.value), q.dimension, favunit=q.favunit)
# np.block : todo
@implements(np.broadcast_to)
def np_broadcast_to(array, *args, **kwargs):
return Quantity(np.broadcast_to(array.value, *args, **kwargs), array.dimension)
@implements(np.broadcast_arrays)
def np_broadcast_arrays(*args, **kwargs):
qargs = [quantify(a) for a in args]
# get arrays values
arrs = [qarg.value for qarg in qargs]
# get broadcasted arrays
res = np.broadcast_arrays(*arrs, **kwargs)
return [Quantity(r, q.dimension) for r, q in zip(res, qargs)]
@implements(np.linalg.lstsq)
def np_linalg_lstsq(a, b, **kwargs):
a = quantify(a)
b = quantify(b)
sol = np.linalg.lstsq(a.value, b.value, **kwargs)
return Quantity(sol, b.dimension/a.dimension)
@implements(np.linalg.inv)
def np_inv(a):
return Quantity(np.linalg.inv(a.value), 1/a.dimension)
@implements(np.random.normal)
def np_random_normal(loc=0.0, scale=1.0, **kwargs):
loc = quantify(loc)
scale = quantify(scale)
if not loc.dimension == scale.dimension:
raise DimensionError(loc.dimension, scale.dimension)
return Quantity(np.random.normal(loc=loc.value, scale=scale.value,
**kwargs))
@implements(np.may_share_memory)
def np_may_share_memory(a, b, **kwargs):
return np.may_share_memory(a.value, b.value, **kwargs)
@implements(np.clip)
def np_clip(a, a_min, a_max, *args, **kwargs):
a_min = quantify(a_min)
a_max = quantify(a_max)
if a.dimension != a_min.dimension:
raise DimensionError(a.dimension, a_min.dimension)
if a.dimension != a_max.dimension:
raise DimensionError(a.dimension, a_max.dimension)
return Quantity(np.clip(a.value, a_min.value,
a_max.value, *args, **kwargs), a.dimension)
@implements(np.copyto)
def np_copyto(dst, src, **kwargs):
dst = quantify(dst)
src = quantify(src)
if dst.dimension != src.dimension:
raise DimensionError(dst.dimension, src.dimension)
return np.copyto(dst.value, src.value, **kwargs)
@implements(np.column_stack)
def np_column_stack(tup):
dim = tup[0].dimension
for arr in tup:
if arr.dimension != dim:
raise DimensionError(arr.dimension, dim)
return Quantity(np.column_stack(tuple(arr.value for arr in tup)), dim)
@implements(np.compress)
def np_compress(condition, a, **kwargs):
return Quantity(np.compress(condition, a.value, **kwargs), a.dimension)
@implements(np.concatenate)
def np_concatenate(tup, axis=0, out=None):
dim = tup[0].dimension
for arr in tup:
if arr.dimension != dim:
raise DimensionError(arr.dimension, dim)
return Quantity(np.concatenate(tuple(arr.value for arr in tup)), dim)
@implements(np.copy)
def np_copy(a, **kwargs):
return Quantity(np.copy(a.value, **kwargs), a.dimension)
# np.copyto todo
# np.count_nonzero
@implements(np.cross)
def np_cross(a, b, **kwargs):
return Quantity(np.cross(a.value, b.value),
a.dimension*b.dimension)
# np.cumprod : cant have an array with different dimensions
@implements(np.cumsum)
def np_cumsum(a, **kwargs):
return Quantity(np.cumsum(a.value, **kwargs), a.dimension)
@implements(np.histogram)
def np_histogram(a, bins=10, range=None, normed=None, weights=None, **kwargs):
if range is not None:
range = (quantify(range[0]), quantify(range[1]))
if not range[0].dimension == range[1].dimension:
raise DimensionError(range[0].dimension, range[1].dimension)
hist, bin_edges = np.histogram(a.value, bins=bins, range=range, normed=normed, weights=weights)
return hist, Quantity(bin_edges, a.dimension)
@implements(np.diagonal)
def np_diagonal(a, **kwargs):
return Quantity(np.diagonal(a.value, **kwargs), a.dimension)
#@implements(np.diff)
#def np_diff(a, n=1, axis=-1, prepend=np._NoValue, append=np._NoValue):
# if prepend != np._NoValue:
# if prepend.dimension != a.dimension:
# raise DimensionError(a.dimension, prepend.dimension)
# if append != np._NoValue:
# if append.dimension != a.dimension:
# raise DimensionError(a.dimension, append.dimension)
# return Quantity(np.diff(a.value, n=n, axis=axis, prepend=prepend, append=append), a.dimension)
@implements(np.ndim)
def np_ndim(a):
return np.ndim(a.value)
@implements(np.dot)
def np_dot(a, b, **kwargs):
a = quantify(a)
b = quantify(b)
return Quantity(np.dot(a.value, b.value), a.dimension * b.dimension)
@implements(np.cov)
def np_cov(m, y=None, *args, **kwargs):
m = quantify(m)
if y is not None:
y = quantify(y)
raw =
|
np.cov(m.value, y.value, *args, **kwargs)
|
numpy.cov
|
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
import tensorflow as tf
from pysc2.lib.actions import FunctionCall, FUNCTIONS
from rl.agents.runner import BaseRunner
from rl.common.pre_processing import Preprocessor
from rl.common.pre_processing import is_spatial_action, stack_ndarray_dicts
from rl.common.util import mask_unused_argument_samples, flatten_first_dims, flatten_first_dims_dict
class FeudalRunner(BaseRunner):
def __init__(self, agent, envs, summary_writer, args):
"""
Args:
agent: A2CAgent instance.
envs: SubprocVecEnv instance.
summary_writer: summary writer to log episode scores.
args: {
}
"""
self.agent = agent
self.envs = envs
self.summary_writer = summary_writer
self.train = args.train
self.c = args.c
self.d = args.d
self.T = args.steps_per_batch #T is the length of the actualy trajectory
self.n_steps = 2 * self.c + self.T
self.discount = args.discount
self.preproc = Preprocessor()
self.last_obs = self.preproc.preprocess_obs(self.envs.reset())
print('\n### Feudal Runner #######')
print(f'# agent = {self.agent}')
print(f'# train = {self.train}')
print(f'# n_steps = {self.n_steps}')
print(f'# discount = {self.discount}')
print('######################\n')
self.states = agent.initial_state # Holds the managers and workers hidden states
self.last_c_goals = np.zeros((self.envs.n_envs,self.c,self.d))
self.lc_manager_outputs = np.zeros((self.envs.n_envs,self.c,self.d))
self.episode_counter = 1
self.max_score = 0.0
self.cumulative_score = 0.0
def run_batch(self, train_summary):
last_obs = self.last_obs
shapes = (self.n_steps, self.envs.n_envs)
values = np.zeros(np.concatenate([[2], shapes]), dtype=np.float32) #first dim: manager values, second dim: worker values
rewards = np.zeros(shapes, dtype=np.float32)
dones = np.zeros(shapes, dtype=np.float32)
all_obs, all_actions = [], []
mb_states = self.states #first dim: manager values, second dim: worker values
s = np.zeros((self.n_steps, self.envs.n_envs, self.d), dtype=np.float32)
mb_last_c_goals = np.zeros((self.n_steps, self.envs.n_envs, self.c, self.d), dtype=np.float32)
mb_last_mo =
|
np.zeros((self.n_steps, self.envs.n_envs, self.c, self.d), dtype=np.float32)
|
numpy.zeros
|
"""
Environment Probing Interaction (EPI)
https://arxiv.org/abs/1907.11740
Modules:
0. pretrained task-specific policy for collecting transition dataset
1. EPI policy
2. Embedding model
3. EPI prediction model
4. prediction model
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Normal
import math
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir) # add parent path
from sim2real_policies.utils.rl_utils import load, load_model
from utils.choose_env import choose_env
import torch.optim as optim
import torch.multiprocessing as mp
from torch.multiprocessing import Process
from multiprocessing.managers import BaseManager
torch.multiprocessing.set_start_method('forkserver', force=True) # critical for make multiprocessing work
from torch.utils.tensorboard import SummaryWriter
from gym import spaces
from sim2real_policies.utils.policy_networks import DPG_PolicyNetwork, RandomPolicy, PPO_PolicyNetwork
from sim2real_policies.utils.buffers import ReplayBuffer
from sim2real_policies.sys_id.common.utils import query_params, query_key_params, offline_history_collection
from sim2real_policies.sys_id.common.operations import plot, size_splits
from sim2real_policies.sys_id.common.nets import PredictionNetwork, EmbedNetwork
from sim2real_policies.utils.envs import make_env
from sim2real_policies.utils.evaluate import evaluate, evaluate_epi
from sim2real_policies.ppo.ppo_multiprocess import PPO
from sim2real_policies.td3.td3_multiprocess import TD3_Trainer
from sim2real_policies.utils.load_params import load_params
import pickle
import copy
import time
import argparse
from mujoco_py import MujocoException
# EPI algorthm hyper parameters
DEFAULT_REWARD_SCALE = 1.
PREDICTION_REWARD_SCALE = 0.5
PREDICTION_REWARD_SCALE0 = 1e5
PREDICTOR_LR = 1e-4
EPI_PREDICTOR_LR = 1e-4
EPI_TOTAL_ITR = 1000
EPI_POLICY_ITR = 5 # udpate iterations of EPI polciy; without considering 10 times inside update of ppo policy
PREDICTOR_ITER = 5 # udpate itertations of predictors and embedding net
EVAL_INTERVAL = 100 # evaluation interval (episodes) of task-specific policy
HIDDEN_DIM=512
PREFIX=''
NUM_WORKERS = 3
ENV_NAME = ['SawyerReach', 'SawyerPush', 'SawyerSlide'][0]
RANDOMSEED = 2 # random seed
EPI_TRAJ_LENGTH = 10
EPI_EPISODE_LENGTH = 30 # shorter than normal task-specific episode length, only probing through initial exploration steps
EMBEDDING_DIM = 10
DISCRETE = True # if true, discretized randomization range
VINE = True # if true, data collected in vine manner
SEPARATION_LOSS = True
NO_RESET = True # the env is not reset after EPI rollout in each episode
EPI_POLICY_ALG = ['ppo', 'random'][0]
TASK_POLICY_ALG = ['td3', 'ppo'][0]
# task specific policy
EP_MAX=12000
EP_LEN=100
writer = SummaryWriter()
class EPI(object):
"""
The class of environment probing interaction policies
"""
def __init__(self, env, traj_length=EPI_TRAJ_LENGTH, \
GAMMA=0.9, data_path='./data/', model_path='./model/epi'):
self.embed_dim = EMBEDDING_DIM
self.data_path = data_path
self.model_path = model_path
self.traj_length = traj_length
self.GAMMA = GAMMA
action_space = env.action_space
state_space = env.observation_space
self.state_dim = state_space.shape[0]
self.action_dim = action_space.shape[0]
traj_dim = traj_length*(self.state_dim+self.action_dim)
state_embedding_space = spaces.Box(-np.inf, np.inf, shape=(state_space.shape[0]+self.embed_dim, )) # add the embedding param dim
# initialize epi policy
if EPI_POLICY_ALG == 'ppo':
self.epi_policy = PPO(self.state_dim, self.action_dim)
self.epi_policy.to_cuda()
elif EPI_POLICY_ALG == 'random':
self.epi_policy = RandomPolicy(self.action_dim)
else:
raise NotImplementedError
# initialize task specific policy
if TASK_POLICY_ALG == 'ppo':
self.task_specific_policy = PPO(self.state_dim+self.embed_dim, self.action_dim)
elif TASK_POLICY_ALG == 'td3':
self.task_specific_policy = TD3_Trainer(replay_buffer, state_embedding_space, action_space, \
hidden_dim, q_lr, policy_lr, action_range, policy_target_update_interval)
else:
raise NotImplementedError
self.embed_net = EmbedNetwork(traj_dim, self.embed_dim, HIDDEN_DIM).cuda()
self.sa_dim=self.state_dim+self.action_dim
self.predict_net = PredictionNetwork(self.sa_dim, self.state_dim, HIDDEN_DIM).cuda()
self.sae_dim = self.sa_dim+self.embed_dim
self.epi_predict_net = PredictionNetwork(self.sae_dim, self.state_dim, HIDDEN_DIM).cuda()
self.predict_net_optimizer = optim.Adam(self.predict_net.parameters(), PREDICTOR_LR)
embed_epi_predict_net_params = list(self.epi_predict_net.parameters()) + list(self.embed_net.parameters())
self.embed_epi_predict_net_optimizer = optim.Adam(embed_epi_predict_net_params, EPI_PREDICTOR_LR)
self.criterion = nn.MSELoss()
def save_model(self, model_name=None):
if model_name is 'predictor_and_embedding':
torch.save(self.predict_net.state_dict(), self.model_path +'_predictor')
torch.save(self.epi_predict_net.state_dict(), self.model_path+'_EPIpredictor')
torch.save(self.embed_net.state_dict(), self.model_path+'_embedding')
# print('Predictor, EPI Predictor, and Embedding model saved.')
elif model_name is 'epi_policy':
self.epi_policy.save_model(path = self.model_path +'_'+EPI_POLICY_ALG+ '_epi_policy')
# print('EPI policy saved.')
elif model_name is 'task_specific_policy':
self.task_specific_policy.save_model(path = self.model_path+'_'+TASK_POLICY_ALG + '_policy')
# print('Task specific policy saved.')
def load_model(self, model_name=None):
if model_name is 'predictor_and_embedding':
self.predict_net.load_state_dict(torch.load(self.model_path+'_predictor'))
self.epi_predict_net.load_state_dict(torch.load(self.model_path+'_EPIpredictor'))
self.embed_net.load_state_dict(torch.load(self.model_path+'_embedding'))
self.predict_net.eval()
self.epi_predict_net.eval()
self.embed_net.eval()
# print('Predictor, EPI_Predictor, and Embedding model loaded.')
elif model_name is 'epi_policy':
self.epi_policy.load_model(path = self.model_path +'_'+EPI_POLICY_ALG+ '_epi_policy')
# print('EPI policy loaded.')
elif model_name is 'task_specific_policy':
self.task_specific_policy.load_model(path =self.model_path+'_'+TASK_POLICY_ALG + '_policy')
# print('Task specific policy loaded.')
def load_transition_data(self, path = None):
"""
transition data format:
{
'x_train': (# episodes 1, # steps, state_dim + action_dim)
'x_test': (# episodes 2, # steps, state_dim + action_dim)
'y_train': (# episodes 1, # steps, state_dim)
'y_test': (# episodes 2, # steps, state_dim)
'param_train': (# episodes 1, # steps, param_dic)
'param_test': (# episodes 2, # steps, param_dic)
}
"""
if path is None:
path = self.data_path
if DISCRETE:
path+='_discrete'
if VINE:
path+='_vine'
path+='_data.pckl'
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), path)
data = pickle.load(open(os.path.abspath(path),'rb' ))
return data
def where_equal(self, array_of_array, array):
"""Return index of array_of_array where its item equals to array"""
idx=[]
for i in range(array_of_array.shape[0]):
if (array_of_array[i]==array).all():
idx.append(i)
return idx
# """
# original implementation of separation loss in EPI paper is follow:
# def separation_loss(y_true, y_pred):
#
# y_true = tf.squeeze(y_true)
# env_id, _ = tf.unique(y_true)
#
# mu = []
# sigma = []
# for i in range(EPI.NUM_OF_ENVS):
# idx = tf.where(tf.equal(y_true, env_id[i]))
# traj = tf.gather(y_pred, idx)
# mu.append(tf.squeeze(K.mean(traj, axis=0)))
# this_sigma = tf.maximum(K.mean(K.std(traj, axis=0))-0.1, 0)
# sigma.append(this_sigma)
#
# mu = tf.stack(mu)
# r = tf.reduce_sum(mu * mu, 1)
# r = tf.reshape(r, [-1, 1])
# D = (r - 2 * tf.matmul(mu, tf.transpose(mu)) + tf.transpose(r))/tf.constant(EPI.EMBEDDING_DIMENSION, dtype=tf.float32)
# D = tf.sqrt(D + tf.eye(EPI.NUM_OF_ENVS, dtype=tf.float32))
# distance = K.mean(tf.reduce_sum(0.1 - tf.minimum(D, 0.1)))
#
# sigma = tf.stack(sigma)
#
# return (distance + K.mean(sigma))*0.01
# """
def separation_loss(self, params_list, trajs):
# get list of parameters from ordered dictionary
list_params = []
for params in params_list:
set_params = []
for key, value in list(params.items()):
# print(type(value))
if isinstance(value, np.ndarray):
value = value.reshape(-1).astype(float)
set_params = np.concatenate((set_params, value)).tolist()
else:
set_params.append(value.astype(float).tolist())
list_params.append(set_params)
# unique_params_list = np.unique(np.array(list_params).astype('float32'), axis=0)
unique_params_list = [list(x) for x in set(tuple(x) for x in list_params)]
number_envs = len(unique_params_list)
mu=[]
sigma=[]
for unique_params in unique_params_list:
specific_env_idx = self.where_equal(np.array(list_params), np.array(unique_params))
specific_env_trajs = trajs[specific_env_idx]
specific_env_trajs = torch.FloatTensor(specific_env_trajs).cuda()
embedding = self.embed_net(specific_env_trajs) # (len(specific_env_trajs), len(embedding))
if len(embedding.shape)>2:
embedding = embedding.view(-1, embedding.shape[-1])
mu.append(torch.squeeze(torch.mean(embedding, dim=0)))
this_sigma = torch.max(torch.mean(torch.std(embedding, dim=0))-0.1, 0)[0] # values of max
sigma.append(this_sigma)
mu = torch.stack(mu)
r = torch.sum(mu*mu, 1)
r = r.view(-1,1)
D = (r-2*torch.mm(mu, torch.t(mu)) + torch.t(r))/self.embed_dim
D = torch.sqrt(D+torch.eye(number_envs).cuda())
distance = torch.mean(torch.sum(0.1-torch.min(D, torch.as_tensor(0.1).cuda())))
sigma = torch.stack(sigma)
return (distance + torch.mean(sigma)) * 0.01
def predictor_update(self, input, label, trajs, params_list):
"""
Update the two predictors: 1. predictor with (s,a) as input 2. predictor with (embedding, s,a) as input
"""
# prediction network update
state_action_in_trajs = np.array(trajs[:, :, :, :-1]) # remove the rewards
state_action_in_trajs = state_action_in_trajs.reshape(state_action_in_trajs.shape[0], state_action_in_trajs.shape[1], -1 )# merge last two dims
input = torch.FloatTensor(input).cuda()
label = torch.FloatTensor(label).cuda()
predict = self.predict_net(input)
predict_loss = self.criterion(predict, label)
self.predict_net_optimizer.zero_grad()
predict_loss.backward()
self.predict_net_optimizer.step()
batch_loss = []
# embedding prediction network update
for epi in range(state_action_in_trajs.shape[0]):
for traj in range(state_action_in_trajs.shape[1]):
embedding = self.embed_net(state_action_in_trajs[epi][traj])
embed_input = torch.cat((embedding.repeat(input[epi].shape[0], 1), input[epi]), dim=1) # repeat embedding to the batch size
epi_predict = self.epi_predict_net(embed_input)
epi_predict_loss = self.criterion(epi_predict, label[epi])
if torch.isnan(epi_predict_loss).any(): # capture nan cases
print('Nan EPI prediction loss')
print(state_action_in_trajs[epi][traj], embedding, embed_input, epi_predict, label[epi])
else:
batch_loss.append(epi_predict_loss)
sum_epi_predict_loss = sum(batch_loss)
if SEPARATION_LOSS:
separation_loss=self.separation_loss(params_list, state_action_in_trajs)
if torch.isnan(separation_loss).any(): # capture nan cases
print('Nan separation loss')
else:
sum_epi_predict_loss+=separation_loss
else:
separation_loss = 0.
self.embed_epi_predict_net_optimizer.zero_grad()
sum_epi_predict_loss.backward()
self.embed_epi_predict_net_optimizer.step()
return predict_loss, torch.mean(torch.stack(batch_loss)).detach().cpu().numpy(), separation_loss.detach().cpu().numpy()
def prediction_reward(self, input, label, trajs):
""" Generate prediction reward for each trajectory """
r_trajs = []
sa_trajs = []
rewards = []
predict_rewards = []
state_action_in_trajs = trajs[:, :, :, :-1] # remove the rewards
reward_in_trajs = trajs[:, :, :, -1:] # only the rewards
state_action_in_trajs_ = state_action_in_trajs.reshape(state_action_in_trajs.shape[0], state_action_in_trajs.shape[1], -1 ) # merge last two dims
reward_in_trajs_ = reward_in_trajs.reshape(reward_in_trajs.shape[0], reward_in_trajs.shape[1], -1) # merge last two dims
input = torch.FloatTensor(input).cuda()
label = torch.FloatTensor(label).cuda()
for epi in range(state_action_in_trajs_.shape[0]):
predict = self.predict_net(input[epi])
predict_loss = self.criterion(predict, label[epi])
episode_epi_predict_loss = []
for traj in range(state_action_in_trajs_.shape[1]):
embedding = self.embed_net(state_action_in_trajs_[epi][traj])
# print(embedding)
embed_input = torch.cat((embedding.repeat(input[epi].shape[0], 1), input[epi]), dim=1)
epi_predict = self.epi_predict_net(embed_input)
epi_predict_loss = self.criterion(epi_predict, label[epi])
predict_r = (epi_predict_loss - predict_loss).detach().cpu().numpy()
predict_r = np.clip(predict_r*PREDICTION_REWARD_SCALE0, 0, 1000) # accoring to original implementation, multiplied factor and non-negative
# print(predict_r)
augmented_r = DEFAULT_REWARD_SCALE * reward_in_trajs_[epi][traj] + PREDICTION_REWARD_SCALE * predict_r
rewards.append(augmented_r)
predict_rewards.append(predict_r)
r_trajs.append(augmented_r)
sa_trajs.append(state_action_in_trajs[epi][traj])
return [np.array(sa_trajs), r_trajs], np.mean(rewards), np.mean(predict_rewards)
def EPIpolicy_rollout(self, env, max_steps=30, params=None):
"""
Roll one trajectory with max_steps
return:
traj: shape of (max_steps, state_dim+action_dim+reward_dim)
s_: next observation
env.get_state(): next underlying state
"""
if params is not None:
env.set_dynamics_parameters(params)
# env.renderer_on()
for _ in range(10): # max iteration for getting a single rollout
s = env.reset()
traj=[]
for _ in range(max_steps):
a = self.epi_policy.choose_action(s)
# env.render()
try:
s_, r, done, _ = env.step(a)
except MujocoException:
print('EPI Rollout: MujocoException')
break
s_a_r = np.concatenate((s,a, [r])) # state, action, reward
traj.append(s_a_r)
s=s_
if len(traj) == max_steps:
break
if len(traj)<max_steps:
print('EPI rollout length smaller than expected!')
return traj, [s_, env.get_state()]
def EPIpolicy_update(self, buffer):
"""
update the EPI policy
buffer = [trajectories, rewards]
trajectories: (# trajs, traj_length, state_dim+action_dim)
rewards: (# trajs, traj_length)
"""
# how to learn the policy with the reward for policy, and batch of trajectories to generate one reward
[trajs, rewards]=buffer
states = trajs[:, :, :self.state_dim]
actions = trajs[:, :, self.state_dim:]
# update ppo
s_ = states[:, -1]
# not considering done here, for reaching no problem for pushing may have problem (done is terminal state)
v_s_ = self.epi_policy.critic(torch.Tensor([s_]).cuda()).cpu().detach().numpy()[0, 0]
discounted_r = []
for r in np.array(rewards).swapaxes(0,1)[-2::-1]: # on episode steps dim, [1,2,3,4][-2::-1] gives 3,2,1
v_s_ = np.expand_dims(r, axis=1) + self.GAMMA * v_s_ # make r has same shape as v_s_: (N, 1)
discounted_r.append(v_s_)
discounted_r.reverse()
# print('r: ', np.array(discounted_r).shape) # (traj_length, # trajs, 1)
bs, ba, br = np.vstack(states[:, :-1]), \
np.vstack(actions[:, :-1]), \
np.vstack(np.array(discounted_r).swapaxes(0,1))
# print(bs.shape, ba.shape, br.shape)
self.epi_policy.update(bs, ba, br)
def sample_randomized_params(self, dataset_params, batch_size):
"""
Sample environment parameters from the loaded transition dataset.
Note: this implementation is different from original implementation for the paper,
but it saves the steps for matching the env idexes between the trajectory generation
of EPI policy in randomized envs and the envs in transition dataset.
"""
random_idx = np.random.randint(len(dataset_params), size=batch_size) # with replacement
return random_idx,
|
np.array(dataset_params)
|
numpy.array
|
# from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import time
import datetime
import numpy as np
import tensorflow as tf
#from tf.nn import rnn, rnn_cell
import codecs
import collections
import random
from collections import Counter
import xml.etree.ElementTree as ET
import glob
import nltk
from nltk.stem.porter import PorterStemmer
import sys
import pickle
import os
import shutil
import os.path
from sklearn.metrics import confusion_matrix
def print_and_log(log_str):
print (log_str)
logging.info(log_str)
SESSION_NAME = "session_name"
SESSION_DATA = "session_data"
SESSION_EVENTS = "session_events"
# Data to train auto-encoder
rig_data = []
glyph_data = []
def read_project_data():
for file_name in glob.glob('data/*.txt'):
project_name = file_name[file_name.rfind('/') + 1:]
project_name = project_name[:len(project_name)-4]
print ("File name = %s, project name = %s " % (file_name, project_name))
tree = ET.parse(file_name)
doc = tree.getroot()
for session_element in doc.findall('session'):
session_data = {}
session_name = session_element.attrib['name']
print(session_name)
session_data[SESSION_NAME] = session_name
session_data[SESSION_DATA] = []
session_data[SESSION_EVENTS] = []
frame_elements = session_element.findall('data/frame')
for frame_element in frame_elements:
object_point_elements = frame_element.findall('o')
point_data = []
for object_point_element in object_point_elements:
for s in object_point_element.text.split(','):
point_data.append(float(s))
rig_data.append(point_data[:39])
glyph_data.append(point_data[39:51])
glyph_data.append(point_data[51:63])
def turn_to_intermediate_data(data, data_point_size, batch_size):
rearranged_data = np.array(data)
epoch_size = len(data) // batch_size
return rearranged_data[:epoch_size * batch_size].\
reshape((epoch_size, batch_size, data_point_size))
class Auto_Encoder_Config(object):
session_training_percentage = (0, 0.8)
session_testing_percentage = (0.8, 1.0)
class Autoencoder(object):
def __init__(self, is_training, config):
with tf.device('/gpu:2'):
# multiple batch sizes
self.batch_sizes = batch_sizes = config.batch_sizes
# multiple input sizes
self.n_inputs = n_inputs = config.n_inputs
hidden_size_1 = config.hidden_size_layer_1
hidden_size_2 = config.hidden_size_layer_2
self._input_datas = input_datas = [tf.placeholder(tf.float32, [batch_size, n_input])
for (batch_size, n_input) in zip(batch_sizes, n_inputs)]
weights = {}
biases = {}
with tf.variable_scope("encoder"):
for i, n_input in enumerate(n_inputs):
weights['encoder_h1_' + str(i)] = tf.get_variable('weight_encoder_h1_' + str(i), [n_input, hidden_size_1])
biases['encoder_h1_' + str(i)] = tf.get_variable('bias_encoder_h1_' + str(i), [hidden_size_1])
# # Shared between different input types
# weights['encoder_h2_' + str(i)] = tf.get_variable('weight_encoder_h2_' + str(i), [hidden_size_1, hidden_size_2])
# biases['encoder_h2_' + str(i)] = tf.get_variable('bias_encoder_h2_' + str(i), [hidden_size_2])
weights['encoder_h2'] = tf.get_variable('weight_encoder_h2', [hidden_size_1, hidden_size_2])
biases['encoder_h2'] = tf.get_variable('bias_encoder_h2', [hidden_size_2])
with tf.variable_scope("decoder"):
# Shared between different input types
weights['decoder_b1' ] = tf.get_variable('weight_decoder_b1', [hidden_size_2, hidden_size_1])
biases['decoder_b1' ] = tf.get_variable('bias_decoder_b1', [hidden_size_1])
for i, n_input in enumerate(n_inputs):
# weights['decoder_b1_' + str(i)] = tf.get_variable('weight_decoder_b1' + str(i), [hidden_size_2, hidden_size_1])
# biases['decoder_b1_' + str(i)] = tf.get_variable('bias_decoder_b1_' + str(i), [hidden_size_1])
weights['decoder_b2_' + str(i)] = tf.get_variable("weight_decoder_b2_" + str(i), [hidden_size_1, n_input])
biases['decoder_b2_' + str(i)] = tf.get_variable("bias_decoder_b2_" + str(i), [n_input])
error_squared = []
decodeds = []
for i in xrange(len(n_inputs)):
encoder_layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(input_datas[i], weights['encoder_h1_'+ str(i)]),
biases['encoder_h1_'+ str(i)]))
if is_training and config.keep_prob < 1:
encoder_layer_1 = tf.nn.dropout(encoder_layer_1, config.keep_prob)
# encoder_layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(encoder_layer_1, weights['encoder_h2_' + str(i)]),
# biases['encoder_h2_' + str(i)]))
encoder_layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(encoder_layer_1, weights['encoder_h2']),
biases['encoder_h2']))
if is_training and config.keep_prob < 1:
encoder_layer_2 = tf.nn.dropout(encoder_layer_2, config.keep_prob)
# decoder_layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(encoder_layer_2, weights['decoder_b1_' + str(i)]),
# biases['decoder_b1_' + str(i)]))
decoder_layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(encoder_layer_2, weights['decoder_b1' ]),
biases['decoder_b1']))
# The output layer should be linear to predict real values
decoder_layer_2 = tf.add(tf.matmul(decoder_layer_1, weights['decoder_b2_' + str(i)]),
biases['decoder_b2_' + str(i)])
# size = batch_sizes[i]
error_squared.append(tf.reduce_mean(tf.pow(input_datas[i] - decoder_layer_2, 2)))
decodeds.append(decoder_layer_2)
# error_squared = tf.concat(0, error_squared)
self._cost = cost = tf.reduce_mean(error_squared)
if is_training:
self._lr = tf.Variable(0.0, trainable=False)
self._train_op = tf.train.RMSPropOptimizer(self._lr).minimize(cost)
# tvars = tf.trainable_variables()
# grads, _ = tf.clip_by_global_norm(tf.gradients(cost, tvars), config.max_grad_norm)
# self._train_op = tf.train.GradientDescentOptimizer(self.lr).apply_gradients(zip(grads, tvars))
else:
self._test_op = decodeds
self._saver = saver = tf.train.Saver()
@property
def debug(self):
return self._debug
def assign_lr(self, session, lr_value):
session.run(tf.assign(self.lr, lr_value))
@property
def saver(self):
return self._saver
@property
def input_datas(self):
return self._input_datas
@property
def cost(self):
return self._cost
@property
def lr(self):
return self._lr
@property
def train_op(self):
return self._train_op
@property
def test_op(self):
return self._test_op
'''Generate a training set and a testing set of data'''
def generate_data(datas, config) :
training_data = []
testing_data = []
expectations = []
for data in datas:
expectation = np.mean(data, 0)
expectations.append(expectation)
data -= expectation
# Flatten the data (collapse the project and session hierarchy into a list of session_data)
shuffled_data = random.sample(data, len(data))
training_data.append(shuffled_data[int(config.session_training_percentage[0] * len(shuffled_data)):
int(config.session_training_percentage[1] * len(shuffled_data))])
testing_data.append(shuffled_data[int(config.session_testing_percentage[0] * len(shuffled_data)):
int(config.session_testing_percentage[1] * len(shuffled_data))])
return (training_data, testing_data, expectations)
'''
Parameters:
rearranged_data: (epoch_size, batch_size, data_point_size)
Yields:
Take batch_size of data samples, each is a chain of num_steps data points
x: [batch_size, data_point_size]
'''
def gothrough(rearranged_data):
for i in range(np.shape(rearranged_data)[0]):
x = rearranged_data[i, :, :]
yield x
def run_epoch(session, m, datas, eval_op, verbose=False, is_training=True):
"""Runs the model on the given data."""
start_time = time.time()
# costs = np.zeros(len(m.label_classes))
costs = 0
for step, x in enumerate( zip(*[gothrough(data) for data in datas]) ):
feed_dict = {}
for i in xrange(len(m.input_datas)):
feed_dict[m.input_datas[i]] = x[i]
cost, eval_val = session.run([m.cost, eval_op], feed_dict)
costs += cost
if verbose and not is_training:
print('True values')
print(x)
print('Predicted values')
print(eval_val)
if step % 5 == 0 and step > 0:
print_and_log("cost %.5f, costs %.5f, Step %d, average cost: %.5f" %
(cost, costs, step, costs / (step + 1)))
if not is_training:
print_and_log("End of epoch: costs %.5f, Step %d, average cost: %.5f" %
(costs, step, costs / (step + 1) ))
# default mode is to train and test at the same time
TRAIN = 'TRAIN'
TEST = 'TEST'
mode = TRAIN
if __name__ == '__main__':
# ========================================================================
# ========================================================================
# ===========================SETUP TRAIN TEST=============================
if len(sys.argv) > 1:
train_test_config = sys.argv[1]
if train_test_config == 'train':
mode = TRAIN
if train_test_config == 'test' :
mode = TEST
if mode == TRAIN:
if len(sys.argv) > 2:
log_dir = sys.argv[2]
else:
current_time = datetime.datetime.now()
time_str = '%s_%s_%s_%s_%s_%s' % (current_time.year, current_time.month, current_time.day,
current_time.hour, current_time.minute, current_time.second)
log_dir = 'logs/run_' + time_str
print('Train and output into directory ' + log_dir)
os.makedirs(log_dir)
logging.basicConfig(filename = log_dir + '/logs.log',level=logging.DEBUG)
# Copy the current executed py file to log (To make sure we can replicate the experiment with the same code)
shutil.copy(os.path.realpath(__file__), log_dir)
if mode == TEST:
if len(sys.argv) > 2:
model_path = sys.argv[2]
print('Test using model ' + model_path)
else:
sys.exit("autoencoder.py test model_path")
# ========================================================================
# ========================================================================
# =============================READING INPUT =============================
SIMPLE_SPLIT = 'autoencoder_train_test.pkl'
if os.path.isfile(SIMPLE_SPLIT) :
# Load the file
logging.info("Load file into training and testing data sets " + SIMPLE_SPLIT)
with open(SIMPLE_SPLIT, 'rb') as f:
t = pickle.load(f)
train = t['train']
test = t['test']
expectation = t['expectation']
else:
logging.info("Read training and testing data sets from data directory ")
read_project_data()
train, test, expectation = generate_data([rig_data, glyph_data], Auto_Encoder_Config)
with open(SIMPLE_SPLIT, 'wb') as f:
pickle.dump({'train': train,
'test': test,
'expectation': expectation},
f, pickle.HIGHEST_PROTOCOL)
print_and_log('----Done saving training and testing data---')
print_and_log('Train size ' + str(len(train)))
for i in xrange(len(train)):
print_and_log('Type ' + str(i) + " = " + str(len(train[i])))
print(train[0][5])
print_and_log('Test size ' + str(len(test)))
for i in xrange(len(test)):
print_and_log('Type ' + str(i) + " = " + str(len(test[i])))
print(test[0][5])
print_and_log('expectation')
print_and_log(expectation)
class SmallConfig(object):
"""Small config."""
init_scale = 0.5
learning_rate = 0.02 # Set this value higher without norm clipping
# might make the cost explodes
hidden_size_layer_1 = 50 # the number of LSTM units
hidden_size_layer_2 = 200 # the number of LSTM units
max_epoch = 10 # The number of epochs trained with the initial learning rate
max_max_epoch = 500 # Number of running epochs
keep_prob = 0.8 # Drop out keep probability, = 1.0 no dropout
lr_decay = 0.990 # Learning rate decay
batch_sizes = [200, 400] # We could actually still use batch_size for convenient
n_inputs = [39, 12] # Number of float values for each frame
test_epoch = 50 # Test after these many epochs
save_epoch = 25
max_grad_norm = 5
config = SmallConfig()
intermediate_config = SmallConfig()
intermediate_config.keep_prob = 1
eval_config = SmallConfig()
eval_config.keep_prob = 1
eval_config.batch_sizes = [200, 400]
eval_config_2 = SmallConfig()
eval_config_2.keep_prob = 1
eval_config_2.batch_sizes = [1, 1]
print('Turn train data to intermediate form')
im_train_data = [turn_to_intermediate_data(train_data, config.n_inputs[i], config.batch_sizes[i])
for i, train_data in enumerate(train)]
print('Turn test data to intermediate form')
im_inter_test_data = [turn_to_intermediate_data(test_data, intermediate_config.n_inputs[i],
intermediate_config.batch_sizes[i])
for i, test_data in enumerate(test)]
im_final_test_data = [turn_to_intermediate_data(test_data, eval_config.n_inputs[i],
eval_config.batch_sizes[i])
for i, test_data in enumerate(test)]
logging.info("Train Configuration")
for attr in dir(config):
# Not default properties
if attr[:2] != '__':
log_str = "%s = %s" % (attr, getattr(config, attr))
logging.info(log_str)
logging.info("Evaluation Configuration")
for attr in dir(eval_config):
# Not default properties
if attr[:2] != '__':
log_str = "%s = %s" % (attr, getattr(eval_config, attr))
logging.info(log_str)
with tf.Graph().as_default(), tf.Session(config=tf.ConfigProto(
allow_soft_placement=True)) as session:
initializer = tf.random_uniform_initializer(-config.init_scale,
config.init_scale)
print('-------- Setup m model ---------')
with tf.variable_scope("model", reuse=None, initializer=initializer):
m = Autoencoder(is_training=True, config=config)
print('-------- Setup m_intermediate_test model ---------')
with tf.variable_scope("model", reuse=True, initializer=initializer):
m_intermediate_test = Autoencoder(is_training=False, config=intermediate_config)
print('-------- Setup mtest model ----------')
with tf.variable_scope("model", reuse=True, initializer=initializer):
mtest = Autoencoder(is_training=False, config=eval_config)
with tf.variable_scope("model", reuse=True, initializer=initializer):
mtest_test = Autoencoder(is_training=False, config=eval_config_2)
if mode == TRAIN:
tf.initialize_all_variables().run()
print_and_log('---------------BASELINE-------------')
run_epoch(session, m_intermediate_test, im_inter_test_data,
m_intermediate_test.test_op,
is_training=False,
verbose=False)
print_and_log('----------------TRAIN---------------')
for i in range(config.max_max_epoch):
try:
print_and_log('-------------------------------')
start_time = time.time()
lr_decay = config.lr_decay ** max(i - config.max_epoch, 0.0)
m.assign_lr(session, config.learning_rate * lr_decay)
print_and_log("Epoch: %d Learning rate: %.3f" % (i + 1, session.run(m.lr)))
run_epoch(session, m, im_train_data, m.train_op,
verbose=False)
print_and_log("Time %.3f" % (time.time() - start_time) )
print_and_log('-------------------------------')
if i % config.test_epoch == 0:
print_and_log('----------Intermediate test -----------')
# Run test on train
print_and_log('Run model on train data')
run_epoch(session, m_intermediate_test, im_train_data, m_intermediate_test.test_op,
is_training=False, verbose = False)
print_and_log('Run model on test data')
run_epoch(session, m_intermediate_test, im_inter_test_data, m_intermediate_test.test_op,
is_training=False, verbose = False)
if i % config.save_epoch == 0:
start_time = time.time()
model_path = m.saver.save(session, log_dir + "/model.ckpt")
print_and_log("Model saved in file: %s" % model_path)
print_and_log("Time %.3f" % (time.time() - start_time) )
except ValueError:
print_and_log("Value error, reload the most recent saved model")
m.saver.restore(session, model_path)
break
model_path = m.saver.save(session, log_dir + "/model.ckpt")
print_and_log("Model saved in file: %s" % model_path)
if mode == TEST:
m.saver.restore(session, model_path)
print_and_log("Restore model saved in file: %s" % model_path)
print_and_log('--------------TEST--------------')
print_and_log('Run model on test data')
run_epoch(session, mtest, im_final_test_data, mtest.test_op,
is_training=False, verbose=False)
print_and_log('Run model on sample data')
a = np.array([0.7345144,0.2071555,1.218503,0.6770352,0.2617454,1.340257,0.6781173,0.07657745,1.497948,0.637142,-0.06540541,1.2899,0.6534985,
-0.1020509,1.250801,0.6258702,-0.138501,1.138003,0.6847188,-0.1192688,1.216028,0.7559613,0.1016199,1.152093,0.8359883,-0.0585327,1.101261,
0.6747639,-0.1555298,1.110413,0.6371136,-0.1579534,1.140965,0.5651836,-0.1791936,1.140071,0.6521184,-0.1845737,1.168485])
a -= expectation[0]
b = np.array([-0.4483964,-0.2694907,1.222,-0.4602559,-0.1941137,1.227,-0.4279048,-0.2011898,1.445,-0.3881741,-0.2630816,1.323])
b -= expectation[1]
a = a.reshape((1,1,39))
b = b.reshape((1,1,12))
run_epoch(session, mtest_test, [a,b], mtest_test.test_op,
is_training=False, verbose=True)
run_epoch(session, mtest_test, [np.array(test[0][0]).reshape((1,1,39)),
|
np.array(test[1][0])
|
numpy.array
|
import numpy as np
import cv2
import os
import h5py
from scipy.io import loadmat
import random
class_name = "03001627_chair"
hdf5_path = class_name+"/"+class_name[:8]+"_vox256.hdf5"
voxel_input = h5py.File(hdf5_path, 'r')
voxel_input_voxels = voxel_input["voxels"][:]
voxel_input_points_16 = voxel_input["points_16"][:]
voxel_input_values_16 = voxel_input["values_16"][:]
voxel_input_points_32 = voxel_input["points_32"][:]
voxel_input_values_32 = voxel_input["values_32"][:]
voxel_input_points_64 = voxel_input["points_64"][:]
voxel_input_values_64 = voxel_input["values_64"][:]
if not os.path.exists("tmp"):
os.makedirs("tmp")
for idx in range(64):
vox = voxel_input_voxels[idx,:,:,:,0]*255
img1 = np.clip(np.amax(vox, axis=0)*256, 0,255).astype(np.uint8)
img2 = np.clip(np.amax(vox, axis=1)*256, 0,255).astype(np.uint8)
img3 = np.clip(np.amax(vox, axis=2)*256, 0,255).astype(np.uint8)
cv2.imwrite("tmp/"+str(idx)+"_vox_1.png",img1)
cv2.imwrite("tmp/"+str(idx)+"_vox_2.png",img2)
cv2.imwrite("tmp/"+str(idx)+"_vox_3.png",img3)
vox = np.zeros([256,256,256],np.uint8)
batch_points_int = voxel_input_points_16[idx]
batch_values = voxel_input_values_16[idx]
vox[batch_points_int[:,0],batch_points_int[:,1],batch_points_int[:,2]] = np.reshape(batch_values, [-1])
img1 = np.clip(np.amax(vox, axis=0)*256, 0,255).astype(np.uint8)
img2 = np.clip(np.amax(vox, axis=1)*256, 0,255).astype(np.uint8)
img3 = np.clip(np.amax(vox, axis=2)*256, 0,255).astype(np.uint8)
cv2.imwrite("tmp/"+str(idx)+"_p16_1.png",img1)
cv2.imwrite("tmp/"+str(idx)+"_p16_2.png",img2)
cv2.imwrite("tmp/"+str(idx)+"_p16_3.png",img3)
vox =
|
np.zeros([256,256,256],np.uint8)
|
numpy.zeros
|
import numpy as np
import pandas as pd
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import MinMaxScaler, MaxAbsScaler, StandardScaler, Normalizer
from sklearn.feature_selection import VarianceThreshold, SelectKBest, RFE
from sklearn.model_selection import cross_val_score
from xgboost import XGBRegressor
data = pd.read_excel("/Users/ashzerm/item/GasOline/data/oline.xlsx")
target = np.array(data['RON_LOSS'].copy())
data = data[data.columns[16:]]
data =
|
np.array(data)
|
numpy.array
|
import numpy as np
from PIL import Image
import tensorflow as tf
from groupmembers import print_group_members
from utilities import Utilities
def main():
print_group_members()
feature_for_classification = 'Eyeglasses'
data_file_path = './data/img_align_celeba/'
# read label file
label_file_name = './data/list_attr_celeba.txt'
features = np.genfromtxt(label_file_name, skip_header=1, max_rows=1, dtype='str')
# print(len(features))
# bad method but couldn't find any alternative
feature_col_index = np.where(features == feature_for_classification)[0][0]
print('Eyeglass column index: ', feature_col_index)
label = np.genfromtxt(label_file_name, dtype='str', skip_header=2, usecols=(0, feature_col_index))
dataset_count = len(label)
training_count = int(0.8 * dataset_count)
test_count = int(0.2 * dataset_count)
small_training_count = training_count ##int(0.01 * training_count)
# python's random module isn’t made to deal with numpy arrays
# since it’s not exactly the same as nested python lists
np.random.seed(20)
np.random.shuffle(label)
image_file_names = label[:, 0]
expected_output = label[:, 1]
b = expected_output.astype(np.int).clip(min=0)
one_hot_outputs =
|
np.eye(2)
|
numpy.eye
|
import cv2
import numpy as np
from scipy.ndimage.morphology import distance_transform_cdt
import torch
from scipy.ndimage.morphology import distance_transform_edt, binary_erosion,generate_binary_structure
from skimage.io import imsave
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# ----------- IoU and Accuracy -----------
def compute_iou_and_accuracy(arrs, edge_mask1):
intersection = cv2.bitwise_and(arrs, edge_mask1)
union = cv2.bitwise_or(arrs, edge_mask1)
intersection_sum = np.sum(intersection)
union_sum = np.sum(union)
iou = (intersection_sum) / (union_sum)
total = np.sum(arrs)
correct_predictions = intersection_sum
accuracy = correct_predictions / total
# print(iou, accuracy)
return iou, accuracy
def __surface_distances(result, reference, voxelspacing=None, connectivity=1):
"""
The distances between the surface voxel of binary objects in result and their
nearest partner surface voxel of a binary object in reference.
"""
result = np.atleast_1d(result.astype(np.bool))
reference = np.atleast_1d(reference.astype(np.bool))
if voxelspacing is not None:
voxelspacing = _ni_support._normalize_sequence(voxelspacing, result.ndim)
voxelspacing = np.asarray(voxelspacing, dtype=np.float64)
if not voxelspacing.flags.contiguous:
voxelspacing = voxelspacing.copy()
# binary structure
footprint = generate_binary_structure(result.ndim, connectivity)
# test for emptiness
if 0 == np.count_nonzero(result):
raise RuntimeError('The first supplied array does not contain any binary object.')
if 0 == np.count_nonzero(reference):
raise RuntimeError('The second supplied array does not contain any binary object.')
# extract only 1-pixel border line of objects
result_border = result ^ binary_erosion(result, structure=footprint, iterations=1)
reference_border = reference ^ binary_erosion(reference, structure=footprint, iterations=1)
dt = distance_transform_edt(~reference_border, sampling=voxelspacing)
# print(dt)
reference_border = (reference_border + 0).astype(np.float32)
sds = dt[result_border]
return sds
# ----------- Hausdorff Distance metrics -----------
def hd(result, reference, voxelspacing=None, connectivity=1):
hd1 = __surface_distances(result, reference, voxelspacing, connectivity).max()
hd2 = __surface_distances(reference, result, voxelspacing, connectivity).max()
hd = max(hd1, hd2)
return hd
def hd95(result, reference, voxelspacing=None, connectivity=1):
hd1 = __surface_distances(result, reference, voxelspacing, connectivity)
hd2 = __surface_distances(reference, result, voxelspacing, connectivity)
hd95 = np.percentile(
|
np.hstack((hd1, hd2))
|
numpy.hstack
|
""" Utility routines
"""
from __future__ import (print_function, absolute_import, division, unicode_literals)
import numpy as np
import os
import glob
import pdb
from matplotlib import pyplot as plt
from astropy.table import Table
from astropy.io import fits
from xastropy.xutils import xdebug as xdb
from cosredux import utils as cr_utils
def set_background_region(obj_tr, segm, coadd_corrtag_woPHA_file, apert=25., ywidth=50., low_yoff=-10.,
check=False):
""" Defines background region (2 regions for FUVA, 1 region for FUVB)
Parameters
----------
obj_tr : float, int
object trace
segm : str
segment
coadd_corrtag_woPHA_file : str
For wavelength info
apert: float, optional
aperture
ywidth : float, optional
width of the region
low_yoff: float, int, optional
offset from the aperture for the lower region
check : bool, optional
plot region
Returns
-------
bg_region : dict
dict with background region(s)
"""
# Load
data = Table.read(coadd_corrtag_woPHA_file)
wave = data['WAVELENGTH'].data
# Set
bg_region = {}
if segm == 'FUVA':
x1=1200.
x2=max(wave)
elif segm == 'FUVB':
x1=900.
x2=max(wave)
bg_region['lower'] = (x1,x2, obj_tr-apert+low_yoff, obj_tr-apert-ywidth+low_yoff)
if segm == 'FUVA':
bg_region['upper'] = (x1,x2, obj_tr+apert, obj_tr+apert+ywidth)
# Write and Return
outfile = coadd_corrtag_woPHA_file.replace('.fits', '_bgregion.json')
if check:
yfull = data['YFULL']
plt.scatter(wave,yfull,s=1)
# Upper
for key in ['lower', 'upper']:
try:
x1,x2,y1,y2 = bg_region[key]
except KeyError:
continue
plt.plot([x1,x2,x2,x1,x1],[y1,y1,y2,y2,y1],'r',linewidth=3.3)
plt.xlim(x1-10,x2+10)
if segm == 'FUVB':
plt.xlim(50.,x2+10)
plt.ylim(min(yfull[wave > x1]),max(yfull[wave > x1]))
plt.show()
# Return
return bg_region
def get_pha_values_science(region, corrtagfile, segm, background=True):
""" Grab the PHA values in the input region
Parameters
----------
region : dict
background or extraction region(s)
corrtagfile: str
segm: str
background : bool, optional
is it background region
Returns
-------
all_phas : ndarray
PHA values in the region
xdopp_min : float
xdopp_max : float
min and max values for XDOPP in the region(s)
"""
if background:
reg_keys = ['lower', 'upper']
if segm == 'FUVB':
reg_keys = ['lower']
else:
reg_keys = ['extraction']
# Read
data = Table.read(corrtagfile)
wave = data['WAVELENGTH']
xdopp = data['XDOPP'].data
yfull = data['YFULL']
dq = data['DQ']
pha = data['PHA'].data
# Loop
all_phas = []
all_xdopp = []
for key in reg_keys:
try:
x1,x2,y1,y2 = region[key]
except KeyError:
print("No region={:s} provided. Skipping it".format(key))
continue
if (y1 > y2):
yn=y1
y1=y2
y2=yn
if (x1 > x2):
xn=x1
x1=x2
x2=xn
iphas = (wave >= x1) & (wave <= x2) & (dq == 0) & (yfull > y1) & (yfull < y2)
all_phas.append(pha[iphas])
all_xdopp.append(xdopp[iphas])
# Concatenate
all_phas = np.concatenate(all_phas)
all_xdopp = np.concatenate(all_xdopp)
xdopp_min, xdopp_max = np.min(all_xdopp), np.max(all_xdopp)
# Return
return all_phas, xdopp_min, xdopp_max
def get_pha_values_dark(bg_region, dark_corrtag, xdopp_mnx):
""" Grab the PHA values in the input region
Parameters
----------
bg_region : dict
background region(s)
dark_corrtag : str
dark file
xdopp_mnx : tuple
min and max values for XDOPP in the region(s)
Returns
-------
all_phas : ndarray
PHA values in the region
# xdopp_min : float
# xdopp_max : float
"""
# Read
data = Table.read(dark_corrtag)
xdopp = data['XDOPP'].data
yfull = data['YFULL']
dq = data['DQ']
pha = data['PHA'].data
all_phas = []
for key in ['lower', 'upper']:
try:
x1,x2,y1,y2 = bg_region[key]
except KeyError:
print("No region={:s} provided. Skipping it".format(key))
continue
# Over-ride with xdopp
x1, x2 = xdopp_mnx
if (y1 > y2):
yn=y1
y1=y2
y2=yn
if (x1 > x2):
xn=x1
x1=x2
x2=xn
iphas = (xdopp >= x1) & (xdopp <= x2) & (dq == 0) & (yfull > y1) & (yfull < y2)
all_phas.append(pha[iphas])
# Concatenate
all_phas =
|
np.concatenate(all_phas)
|
numpy.concatenate
|
import os
import os.path as osp
import numpy as np
import random
import collections
import torch
import torchvision
import cv2
from torch.utils import data
import matplotlib.pyplot as plt
import nibabel as nib
from skimage.transform import resize
import SimpleITK as sitk
import math
from batchgenerators.transforms.abstract_transforms import Compose
from batchgenerators.transforms.spatial_transforms import SpatialTransform, MirrorTransform
from batchgenerators.transforms.color_transforms import BrightnessMultiplicativeTransform, GammaTransform, \
BrightnessTransform, ContrastAugmentationTransform
from batchgenerators.transforms.noise_transforms import GaussianNoiseTransform, GaussianBlurTransform
from batchgenerators.transforms.resample_transforms import SimulateLowResolutionTransform
class MOTSDataSet(data.Dataset):
def __init__(self, root, list_path, max_iters=None, crop_size=(64, 192, 192), mean=(128, 128, 128), scale=True,
mirror=True, ignore_label=255):
self.root = root
self.list_path = list_path
self.crop_d, self.crop_h, self.crop_w = crop_size
self.scale = scale
self.ignore_label = ignore_label
self.mean = mean
self.is_mirror = mirror
self.img_ids = [i_id.strip().split() for i_id in open(self.root + self.list_path)]
if not max_iters == None:
self.img_ids = self.img_ids * int(np.ceil(float(max_iters) / len(self.img_ids)))
self.files = []
spacing = {
0: [0.8, 0.8, 1.5],
1: [0.8, 0.8, 1.5],
2: [0.8, 0.8, 1.5],
3: [0.8, 0.8, 1.5],
4: [0.8, 0.8, 1.5],
5: [0.8, 0.8, 1.5],
6: [0.8, 0.8, 1.5],
}
print("Start preprocessing....")
for item in self.img_ids:
print(item)
image_path, label_path = item
task_id = int(image_path[16 + 5])
if task_id != 1:
name = osp.splitext(osp.basename(label_path))[0]
else:
name = label_path[31 + 5:41 + 5]
img_file = osp.join(self.root, image_path)
label_file = osp.join(self.root, label_path)
label = nib.load(label_file).get_data()
if task_id == 1:
label = label.transpose((1, 2, 0))
boud_h, boud_w, boud_d = np.where(label >= 1)
self.files.append({
"image": img_file,
"label": label_file,
"name": name,
"task_id": task_id,
"spacing": spacing[task_id],
"bbx": [boud_h, boud_w, boud_d]
})
print('{} images are loaded!'.format(len(self.img_ids)))
def __len__(self):
return len(self.files)
def truncate(self, CT, task_id):
min_HU = -325
max_HU = 325
subtract = 0
divide = 325.
# truncate
CT[np.where(CT <= min_HU)] = min_HU
CT[np.where(CT >= max_HU)] = max_HU
CT = CT - subtract
CT = CT / divide
return CT
def id2trainId(self, label, task_id):
if task_id == 0 or task_id == 1 or task_id == 3:
organ = (label >= 1)
tumor = (label == 2)
elif task_id == 2:
organ = (label == 1)
tumor = (label == 2)
elif task_id == 4 or task_id == 5:
organ = None
tumor = (label == 1)
elif task_id == 6:
organ = (label == 1)
tumor = None
else:
print("Error, No such task!")
return None
shape = label.shape
results_map = np.zeros((2, shape[0], shape[1], shape[2])).astype(np.float32)
if organ is None:
results_map[0, :, :, :] = results_map[0, :, :, :] - 1
else:
results_map[0, :, :, :] = np.where(organ, 1, 0)
if tumor is None:
results_map[1, :, :, :] = results_map[1, :, :, :] - 1
else:
results_map[1, :, :, :] = np.where(tumor, 1, 0)
return results_map
def locate_bbx(self, label, scaler, bbx):
scale_d = int(self.crop_d * scaler)
scale_h = int(self.crop_h * scaler)
scale_w = int(self.crop_w * scaler)
img_h, img_w, img_d = label.shape
# boud_h, boud_w, boud_d = np.where(label >= 1)
boud_h, boud_w, boud_d = bbx
margin = 32 # pixels
bbx_h_min = boud_h.min()
bbx_h_max = boud_h.max()
bbx_w_min = boud_w.min()
bbx_w_max = boud_w.max()
bbx_d_min = boud_d.min()
bbx_d_max = boud_d.max()
if (bbx_h_max - bbx_h_min) <= scale_h:
bbx_h_maxt = bbx_h_max + math.ceil((scale_h - (bbx_h_max - bbx_h_min)) / 2)
bbx_h_mint = bbx_h_min - math.ceil((scale_h - (bbx_h_max - bbx_h_min)) / 2)
if bbx_h_mint < 0:
bbx_h_maxt -= bbx_h_mint
bbx_h_mint = 0
bbx_h_max = bbx_h_maxt
bbx_h_min = bbx_h_mint
if (bbx_w_max - bbx_w_min) <= scale_w:
bbx_w_maxt = bbx_w_max + math.ceil((scale_w - (bbx_w_max - bbx_w_min)) / 2)
bbx_w_mint = bbx_w_min - math.ceil((scale_w - (bbx_w_max - bbx_w_min)) / 2)
if bbx_w_mint < 0:
bbx_w_maxt -= bbx_w_mint
bbx_w_mint = 0
bbx_w_max = bbx_w_maxt
bbx_w_min = bbx_w_mint
if (bbx_d_max - bbx_d_min) <= scale_d:
bbx_d_maxt = bbx_d_max + math.ceil((scale_d - (bbx_d_max - bbx_d_min)) / 2)
bbx_d_mint = bbx_d_min - math.ceil((scale_d - (bbx_d_max - bbx_d_min)) / 2)
if bbx_d_mint < 0:
bbx_d_maxt -= bbx_d_mint
bbx_d_mint = 0
bbx_d_max = bbx_d_maxt
bbx_d_min = bbx_d_mint
bbx_h_min = np.max([bbx_h_min - margin, 0])
bbx_h_max = np.min([bbx_h_max + margin, img_h])
bbx_w_min = np.max([bbx_w_min - margin, 0])
bbx_w_max = np.min([bbx_w_max + margin, img_w])
bbx_d_min = np.max([bbx_d_min - margin, 0])
bbx_d_max = np.min([bbx_d_max + margin, img_d])
if random.random() < 0.8:
d0 = random.randint(bbx_d_min, np.max([bbx_d_max - scale_d, bbx_d_min]))
h0 = random.randint(bbx_h_min, np.max([bbx_h_max - scale_h, bbx_h_min]))
w0 = random.randint(bbx_w_min, np.max([bbx_w_max - scale_w, bbx_w_min]))
else:
d0 = random.randint(0, img_d - scale_d)
h0 = random.randint(0, img_h - scale_h)
w0 = random.randint(0, img_w - scale_w)
d1 = d0 + scale_d
h1 = h0 + scale_h
w1 = w0 + scale_w
return [h0, h1, w0, w1, d0, d1]
def pad_image(self, img, target_size):
"""Pad an image up to the target size."""
rows_missing = math.ceil(target_size[0] - img.shape[0])
cols_missing = math.ceil(target_size[1] - img.shape[1])
dept_missing = math.ceil(target_size[2] - img.shape[2])
if rows_missing < 0:
rows_missing = 0
if cols_missing < 0:
cols_missing = 0
if dept_missing < 0:
dept_missing = 0
padded_img = np.pad(img, ((0, rows_missing), (0, cols_missing), (0, dept_missing)), 'constant')
return padded_img
def __getitem__(self, index):
datafiles = self.files[index]
# read nii file
imageNII = nib.load(datafiles["image"])
labelNII = nib.load(datafiles["label"])
image = imageNII.get_data()
label = labelNII.get_data()
name = datafiles["name"]
task_id = datafiles["task_id"]
if task_id == 1:
image = image.transpose((1, 2, 0))
label = label.transpose((1, 2, 0))
if self.scale and np.random.uniform() < 0.2:
scaler = np.random.uniform(0.7, 1.4)
else:
scaler = 1
image = self.pad_image(image, [self.crop_h * scaler, self.crop_w * scaler, self.crop_d * scaler])
label = self.pad_image(label, [self.crop_h * scaler, self.crop_w * scaler, self.crop_d * scaler])
# print(datafiles["label"])
[h0, h1, w0, w1, d0, d1] = self.locate_bbx(label, scaler, datafiles["bbx"])
image = image[h0: h1, w0: w1, d0: d1]
label = label[h0: h1, w0: w1, d0: d1]
image = self.truncate(image, task_id)
label = self.id2trainId(label, task_id)
image = image[np.newaxis, :]
image = image.transpose((0, 3, 1, 2)) # Channel x Depth x H x W
label = label.transpose((0, 3, 1, 2)) # Depth x H x W
if self.is_mirror:
if np.random.rand(1) <= 0.5: # flip W
image = image[:, :, :, ::-1]
label = label[:, :, :, ::-1]
if
|
np.random.rand(1)
|
numpy.random.rand
|
import tensorflow as tf
from time import time
import numpy as np
from random import shuffle
import os
from keras.applications.mobilenet_v2 import MobileNetV2
from keras.applications.inception_v3 import InceptionV3
from keras.applications.resnet50 import ResNet50
from keras.applications.vgg16 import VGG16
from keras_efficientnets import EfficientNetB0
from DatasetProvider import DatasetProvider
from keras.optimizers import *
from sklearn.cluster import KMeans
from shutil import copy
from matplotlib import pyplot as plt
from matplotlib import ticker, cm
#from keras_adamw import AdamW, get_weight_decays, fill_dict_in_order
from sklearn.metrics.pairwise import cosine_similarity, euclidean_distances
import sys
sys.path.append('../keras-auto-augment/')
from PIL import Image
from dataset import Cifar10ImageDataGenerator, SVHNImageDataGenerator, ImageNetImageDataGenerator
from keras import backend as K
import keras
import argparse
import glob
import pickle
import random
random.seed(10)
from keras.models import Sequential
from keras.layers import Dense, Conv2D, MaxPooling2D, Input, Conv2DTranspose, Flatten, Add, Activation, UpSampling2D, \
Dropout, BatchNormalization, GlobalAveragePooling2D, Layer, Lambda
from keras.models import Model
from utils import *
import sys
# Model and dataset directory:
batch_size = 256
cluster_idx = 6
figure_size = (15, 15)
checkpoint_idx = -1
#distance_range = 2
dataset = 'Oxford_IIIT_Pet'
dataset_dir = '../../datasets'
results_dir = './visualization'
number_of_similar_samples = 15
number_of_effective_clusters = 5
number_of_samples_per_cluster = 30
model_folder = 'backbone_EfficientNet_rbf_dims_64_centers_50_learning_rate_7.487e-05_weights_imagenet_augmentation_autogment_'
model_dir = os.path.join('models', dataset, model_folder)
# Import the model setup function and read the hyperparameters:
sys.path.append(model_dir)
from run_experiment import ModelSetup
def compute_embeddings_activations(tf_sess, img_input, tensors, x_train):
length = tensors[0].shape.as_list()[-1]
length1 = tensors[1].shape.as_list()[-1]
length2 = tensors[2].shape.as_list()[-1]
start, samples = 0, x_train.shape[0]
np_embeddings = -np.ones([samples, length])#, dtype=np.uint8)
np_activations = -np.ones([samples, length1])
np_predictions = -np.ones([samples, length2])
while start < samples:
embeds, acts, preds = tf_sess.run(tensors, feed_dict={img_input: x_train[start:start+batch_size, :, :, :]})
np_embeddings[start:start+batch_size, :] = embeds
np_activations[start:start+batch_size, :] = acts
np_predictions[start:start+batch_size, :] = preds
start += batch_size
print('Extract embeddings and predictions: {:05d}/{:05d}'.format(start, samples))
print('Sum of the unfilled elements in embeddings: {:d}'.format(np.sum(np_embeddings==-1)))
print('Sum of the unfilled elements in activations: {:d}'.format(np.sum(np_activations==-1)))
print('Sum of the unfilled elements in predictions: {:d}'.format(np.sum(np_predictions==-1)))
return np_embeddings, np_activations, np_predictions
def load_obj(name):
with open(name + '.pkl', 'rb') as f:
return pickle.load(f)
def augmentation_prepration():
parser = argparse.ArgumentParser()
args = parser.parse_args()
args.depth = int(28)
args.width = int(10)
args.epochs = int(1)
args.cutout = False
args.auto_augment = True
return args
def plot_ground(w, distance_range=2):
fig = plt.figure(figsize=figure_size)
#ax = fig.add_subplot(111, aspect='equal')
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
ax = fig.add_axes([left, bottom, width, height])
xlist = np.linspace(-distance_range, distance_range, 100)
ylist = np.linspace(-distance_range, distance_range, 100)
X, Y = np.meshgrid(xlist, ylist)
Z = np.sqrt(X ** 2 + Y ** 2)
cp = plt.contour(X, Y, Z, colors=6*['red'], linewidths=1.0)
ax.clabel(cp, inline=True, fontsize=16)
cp = plt.contourf(X, Y, 1-Z/w, cmap=cm.PuBu_r)
plt.axis('equal')
plt.axis('tight')
#plt.colorbar()
tick_values = 0.8*distance_range
xy_labels = np.around(np.abs(np.linspace(-tick_values, tick_values, 5)), decimals=1)
xy_ticks = np.linspace(-tick_values, tick_values, 5)
plt.xticks(xy_ticks, xy_labels)
plt.yticks(xy_ticks, xy_labels)
for tick in ax.xaxis.get_major_ticks():
tick.label.set_fontsize(24)
for tick in ax.yaxis.get_major_ticks():
tick.label.set_fontsize(24)
#ax.set_title('Cluster')
ax.set_xlabel('Distance to the cluster center', fontsize=24)
ax.set_ylabel('Distance to the cluster center', fontsize=24)
#plt.show()
#plt.show()
return ax, plt
def compute_metric_distance(a, b, r=None):
# Compute the distances between a sample a and samples in matrix b based on the trained metric r
a, b = np.squeeze(a), np.squeeze(b)
if r is None:
print('Define the distance based on dot product!')
def compute_dist(_a, _b, _r):
# Compute distance between two samples
distance = np.dot(_a, _b)
return distance
else:
print('Define the distance based on the trained metric!')
r = np.squeeze(r)
def compute_dist(_a, _b, _r):
# Compute distance between two samples
diff = np.expand_dims(_a - _b, 0)
distance = np.matmul(np.matmul(diff, np.diag(_r)), np.transpose(diff))
return distance
if len(a.shape) == 1 and len(b.shape) == 1:
distances = compute_dist(a, b, r)
elif len(a.shape) == 1 and len(b.shape) != 1:
distances = np.zeros(b.shape[0])
for i in range(b.shape[0]):
distances[i] = compute_dist(a, b[i, :], r)
elif len(a.shape) != 1 and len(b.shape) == 1:
distances = np.zeros(a.shape[0])
for i in range(a.shape[0]):
distances[i] = compute_dist(a[i, :], b, r)
else:
distances = np.zeros([a.shape[0], b.shape[0]])
for i in range(a.shape[0]):
for j in range(b.shape[0]):
distances[i, j] = compute_dist(a[i, :], b[j, :], r)
return np.squeeze(distances)
def find_samples(np_embeddings, width, distance_range=2):
number_of_bins = 15
samples = [1, 0, 0, 3, 0, 5, 0, 9, 0, 12, 0, 0, 16, 0, 0, 0]
distances = np.sqrt(width*(1-np_embeddings))
#if distance_range < np.min(distances):
# distance_range = (np.min(distances)+np.max(distances))/2
bin_edges = np.linspace(0, distance_range, number_of_bins)
#samples_per_bin, = int(number_of_samples/number_of_bins), []
indecies, theta = [], []
for i in range(len(bin_edges)-1):
samples_per_bin = samples[i]
if samples_per_bin > 0:
found_indecies = list(np.where(np.bitwise_and(distances>bin_edges[i], distances<bin_edges[i+1]))[0])
shuffle(found_indecies)
found_indecies = found_indecies[:samples_per_bin]
indecies += list(found_indecies)
N = len(found_indecies)
theta += list(np.linspace(0, 2*np.pi*(1-1/np.max([1, N])), N)+(np.pi/18)*(np.random.rand(N)-0.5))
samples_per_bin = samples[i]
return np.array(indecies), np.array(theta)
def plot_images(ax, images, embeddings, w, theta, image_size=[64, 64]):
distances = np.sqrt(w*(1-embeddings))
for i in range(images.shape[0]):
x, y = distances[i]*np.cos(theta[i]), distances[i]*np.sin(theta[i])
im = np.array(Image.fromarray(images[i, :, :, :]).resize(image_size))
imagebox = offsetbox.AnnotationBbox(offsetbox.OffsetImage(im), np.array([x, y]))
ax.add_artist(imagebox)
def plot_single_images(ax, images, embeddings, w, theta, distance_range=2, image_size=[96, 96]):
distances = np.sqrt(w*(1-embeddings))
x, y = distances*np.cos(theta), distances*np.sin(theta)
if x < -distance_range:
x, y = distance_range, distance_range
im = np.array(Image.fromarray(images[:, :, :]).resize(image_size))
im = prepare_test_image(im)
imagebox = offsetbox.AnnotationBbox(offsetbox.OffsetImage(im), np.array([x, y]))
ax.add_artist(imagebox)
def discriminant_clusters(activatios, weights, clusters):
values = np.multiply(activatios, weights)
indecies = np.flip(np.argsort(values)[-clusters-1:])
return indecies
def prepare_test_image(image):
image[0:5, :, :], image[-5:, :, :] = [255, 0, 0], [255, 0, 0]
image[:, 0:5, :], image[:, -5:, :] = [255, 0, 0], [255, 0, 0]
return image
def main():
paramters_dict = load_obj(os.path.join(model_dir, 'parameters'))
# Set the keras session
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
tf_sess = tf.Session(config=config)
K.set_session(tf_sess)
# Prepare the data
data_provider = DatasetProvider(dataset_dir, dataset)
x_train_org, y_train, x_test_org, y_test = data_provider.load_data()
number_of_classes, image_size_dataset = data_provider.number_of_classes, data_provider.image_size
datagen = Cifar10ImageDataGenerator(augmentation_prepration())
x_train, x_test = datagen.standardize(x_train_org), datagen.standardize(x_test_org)
#x_train, x_test = x_train[:1000, :, :, :], x_test[:500, :, :, :]
#y_train, y_test = y_train[:1000, :], y_test[:500, :]
# Build the model:
backbone, rbf_dims, number_of_centers = paramters_dict['backbone'], paramters_dict['rbf_dims'], paramters_dict['centers']
dropout, weights = paramters_dict['dropout'], paramters_dict['weights']
model_definer = ModelSetup(x_train.shape[1:], backbone, rbf_dims, number_of_centers, dropout, number_of_classes, weights)
model, img_input, embeddings, activations, predictions = model_definer.define_model()
model.summary()
# Load the model:
filenames = sorted(glob.glob(os.path.join(model_dir, '*.h5')))
print(filenames)
model.load_weights(filenames[checkpoint_idx])
print(filenames[checkpoint_idx])
cluster_coordinate = model.layers[-2].get_weights()[0]
distance_metric = model.layers[-2].get_weights()[1]
output_weights = model.layers[-2].get_weights()[-1][1:, :]
width = model.layers[-2].get_weights()[2]
np.set_printoptions(precision=4, suppress=True)
# Compute the embeddings, activations and Test the accuracy:
embeddings_train, activations_train, train_predictions = compute_embeddings_activations(tf_sess, img_input, [embeddings, activations, model.output], x_train)
embeddings_test, activations_test, test_predictions = compute_embeddings_activations(tf_sess, img_input, [embeddings, activations, model.output], x_test)
train_accuracy = np.mean(np.argmax(train_predictions, 1)==np.argmax(y_train, 1))
test_accuracy = np.mean(np.argmax(test_predictions, 1)==np.argmax(y_test, 1))
print('Testing the loaded model. Training accuracy: {:0.4f}, test accuracy: {:0.4f}.'.format(train_accuracy, test_accuracy))
# Plot the contour of the distances to the center of the classifier (background color is proportional to the activation value)
_activations = activations_train[:, cluster_idx]
dists = np.sqrt(width[0, cluster_idx]*(1-_activations))
min_dist, max_dist = np.min(dists), np.max(dists)
distance_range = np.max([2, (min_dist+max_dist)/2])
ax, fig = plot_ground(width[0, cluster_idx], distance_range)
# For a given cluster get the sample with lower metric distance than 4/5 (histogram)
samples_indices, theta = find_samples(_activations, width[0, cluster_idx], distance_range)
# Make the scatter plot to show the images based on their distance and a random angle to the center
plot_images(ax, x_train_org[samples_indices, :, :, :], activations_train[samples_indices, cluster_idx], width[0, cluster_idx], theta)
# Save the complete image
fig.savefig('sample_cluster.png', bbox_inches = 'tight')
random.seed(10)
rand_idx = [np.random.randint(0, x_test.shape[0]) for x in range(20)]
rand_idx = [779, 56, 1665, 3526, 2523, 435, 2701, 2428, 3429, 952]
for sp in range(len(rand_idx)):
# Test sample ID:
test_idx = rand_idx[sp]
# Find the similar samples to a given test image in training samples based on embedding (trained metric distance)
sample_label = np.argmax(y_test[test_idx, :])
sample_prediction = np.argmax(test_predictions[test_idx, :])
#distances = cosine_similarity(embeddings_test, embeddings_train)[test_idx, :]
#distances = euclidean_distances(embeddings_test, embeddings_train)[test_idx, :]
distances = compute_metric_distance(embeddings_test[test_idx, :], embeddings_train, distance_metric)
idx =
|
np.argsort(distances)
|
numpy.argsort
|
from mock import patch
import pyCGM_Single.pyCGM as pyCGM
import pytest
import numpy as np
rounding_precision = 6
class TestUpperBodyAxis():
"""
This class tests the upper body axis functions in pyCGM.py:
headJC
thoraxJC
findshoulderJC
shoulderAxisCalc
elbowJointCenter
wristJointCenter
handJointCenter
"""
nan_3d = [np.nan, np.nan, np.nan]
rand_coor = [np.random.randint(0, 10), np.random.randint(0, 10), np.random.randint(0, 10)]
@pytest.mark.parametrize(["frame", "vsk", "expected"], [
# Test from running sample data
({'LFHD': np.array([184.55158997, 409.68713379, 1721.34289551]), 'RFHD': np.array([325.82983398, 402.55450439, 1722.49816895]), 'LBHD': np.array([197.8621521 , 251.28889465, 1696.90197754]), 'RBHD': np.array([304.39898682, 242.91339111, 1694.97497559])},
{'HeadOffset': 0.2571990469310653},
[[[255.21685582510975, 407.11593887758056, 1721.8253843887082], [254.19105385179665, 406.146809183757, 1721.9176771191715], [255.19034370229795, 406.2160090443217, 1722.9159912851449]], [255.19071197509766, 406.1208190917969, 1721.9205322265625]]),
# Basic test with a variance of 1 in the x and y dimensions of the markers
({'LFHD': np.array([1, 1, 0]), 'RFHD': np.array([0, 1, 0]), 'LBHD': np.array([1, 0, 0]), 'RBHD': np.array([0, 0, 0])},
{'HeadOffset': 0.0},
[[[0.5, 2, 0], [1.5, 1, 0], [0.5, 1, -1]], [0.5, 1, 0]]),
# Setting the markers so there's no variance in the x-dimension
({'LFHD': np.array([0, 1, 0]), 'RFHD': np.array([0, 1, 0]), 'LBHD': np.array([0, 0, 0]), 'RBHD': np.array([0, 0, 0])},
{'HeadOffset': 0.0},
[[nan_3d, nan_3d, nan_3d], [0, 1, 0]]),
# Setting the markers so there's no variance in the y-dimension
({'LFHD': np.array([1, 0, 0]), 'RFHD': np.array([0, 0, 0]), 'LBHD': np.array([1, 0, 0]), 'RBHD': np.array([0, 0, 0])},
{'HeadOffset': 0.0},
[[nan_3d, nan_3d, nan_3d], [0.5, 0, 0]]),
# Setting each marker in a different xy quadrant
({'LFHD': np.array([-1, 1, 0]), 'RFHD': np.array([1, 1, 0]), 'LBHD': np.array([-1, -1, 0]), 'RBHD': np.array([1, -1, 0])},
{'HeadOffset': 0.0},
[[[0, 2, 0], [-1, 1, 0], [0, 1, 1]], [0, 1, 0]]),
# Setting values of the markers so that midpoints will be on diagonals
({'LFHD': np.array([-2, 1, 0]), 'RFHD': np.array([1, 2, 0]), 'LBHD': np.array([-1, -2, 0]), 'RBHD': np.array([2, -1, 0])},
{'HeadOffset': 0.0},
[[[-0.81622777, 2.4486833 , 0], [-1.4486833, 1.18377223, 0], [-0.5, 1.5, 1]], [-0.5, 1.5, 0]]),
# Adding the value of 1 in the z dimension for all 4 markers
({'LFHD': np.array([1, 1, 1]), 'RFHD': np.array([0, 1, 1]), 'LBHD': np.array([1, 0, 1]), 'RBHD': np.array([0, 0, 1])},
{'HeadOffset': 0.0},
[[[0.5, 2, 1], [1.5, 1, 1], [0.5, 1, 0]], [0.5, 1, 1]]),
# Setting the z dimension value higher for LFHD and LBHD
({'LFHD': np.array([1, 1, 2]), 'RFHD': np.array([0, 1, 1]), 'LBHD': np.array([1, 0, 2]), 'RBHD': np.array([0, 0, 1])},
{'HeadOffset': 0.0},
[[[0.5, 2, 1.5], [1.20710678, 1, 2.20710678], [1.20710678, 1, 0.79289322]], [0.5, 1, 1.5]]),
# Setting the z dimension value higher for LFHD and RFHD
({'LFHD': np.array([1, 1, 2]), 'RFHD': np.array([0, 1, 2]), 'LBHD': np.array([1, 0, 1]), 'RBHD': np.array([0, 0, 1])},
{'HeadOffset': 0.0},
[[[0.5, 1.70710678, 2.70710678], [1.5, 1, 2], [0.5, 1.70710678, 1.29289322]], [0.5, 1, 2]]),
# Adding a value for HeadOffset
({'LFHD': np.array([1, 1, 0]), 'RFHD': np.array([0, 1, 0]), 'LBHD': np.array([1, 0, 0]), 'RBHD': np.array([0, 0, 0])},
{'HeadOffset': 0.5},
[[[0.5, 1.87758256, 0.47942554], [1.5, 1, 0], [0.5, 1.47942554, -0.87758256]], [0.5, 1, 0]]),
# Testing that when frame is a list of ints and headOffset is an int
({'LFHD': [1, 1, 0], 'RFHD': [0, 1, 0], 'LBHD': [1, 0, 0], 'RBHD': [0, 0, 0]},
{'HeadOffset': 1.0},
[[[0.5, 1.5403023058681398, 0.8414709848078965], [1.5, 1, 0], [0.5, 1.8414709848078965, -0.5403023058681398]], [0.5, 1, 0]]),
# Testing that when frame is a numpy array of ints and headOffset is an int
({'LFHD': np.array([1, 1, 0], dtype='int'), 'RFHD': np.array([0, 1, 0], dtype='int'),
'LBHD': np.array([1, 0, 0], dtype='int'), 'RBHD': np.array([0, 0, 0], dtype='int')},
{'HeadOffset': 1},
[[[0.5, 1.5403023058681398, 0.8414709848078965], [1.5, 1, 0], [0.5, 1.8414709848078965, -0.5403023058681398]], [0.5, 1, 0]]),
# Testing that when frame is a list of floats and headOffset is a float
({'LFHD': [1.0, 1.0, 0.0], 'RFHD': [0.0, 1.0, 0.0], 'LBHD': [1.0, 0.0, 0.0], 'RBHD': [0.0, 0.0, 0.0]},
{'HeadOffset': 1.0},
[[[0.5, 1.5403023058681398, 0.8414709848078965], [1.5, 1, 0], [0.5, 1.8414709848078965, -0.5403023058681398]], [0.5, 1, 0]]),
# Testing that when frame is a numpy array of floats and headOffset is a float
({'LFHD': np.array([1.0, 1.0, 0.0], dtype='float'), 'RFHD': np.array([0.0, 1.0, 0.0], dtype='float'),
'LBHD': np.array([1.0, 0.0, 0.0], dtype='float'), 'RBHD': np.array([0.0, 0.0, 0.0], dtype='float')},
{'HeadOffset': 1.0},
[[[0.5, 1.5403023058681398, 0.8414709848078965], [1.5, 1, 0], [0.5, 1.8414709848078965, -0.5403023058681398]], [0.5, 1, 0]])])
def test_headJC(self, frame, vsk, expected):
"""
This test provides coverage of the headJC function in pyCGM.py, defined as headJC(frame, vsk)
This test takes 3 parameters:
frame: dictionary of marker lists
vsk: dictionary containing subject measurements from a VSK file
expected: the expected result from calling headJC on frame and vsk
The function uses the LFHD, RFHD, LBHD, and RBHD markers from the frame to calculate the midpoints of the front, back, left, and right center positions of the head.
The head axis vector components are then calculated using the aforementioned midpoints.
Afterwords, the axes are made orthogonal by calculating the cross product of each individual axis.
Finally, the head axis is then rotated around the y axis based off the head offset angle in the VSK.
This test is checking to make sure the head joint center and head joint axis are calculated correctly given
the 4 coordinates given in frame. This includes testing when there is no variance in the coordinates,
when the coordinates are in different quadrants, when the midpoints will be on diagonals, and when the z
dimension is variable. It also checks to see the difference when a value is set for HeadOffSet in vsk.
Lastly, it checks that the resulting output is correct when frame is a list of ints, a numpy array of
ints, a list of floats, and a numpy array of floats and when headOffset is an int and a float.
"""
result = pyCGM.headJC(frame, vsk)
np.testing.assert_almost_equal(result[0], expected[0], rounding_precision)
np.testing.assert_almost_equal(result[1], expected[1], rounding_precision)
@pytest.mark.parametrize(["frame", "expected"], [
# Test from running sample data
({'C7': np.array([251.22619629, 229.75683594, 1533.77624512]), 'T10': np.array([228.64323425, 192.32041931, 1279.6418457]), 'CLAV': np.array([256.78051758, 371.28042603, 1459.70300293]), 'STRN': np.array([251.67492676, 414.10391235, 1292.08508301])},
[[[256.23991128535846, 365.30496976939753, 1459.662169500559], [257.1435863244796, 364.21960599061947, 1459.588978712983], [256.0843053658035, 364.32180498523223, 1458.6575930699294]], [256.149810236564, 364.3090603933987, 1459.6553639290375]]),
# Basic test with a variance of 1 in the x and y dimensions of the markers
({'C7': np.array([1, 1, 0]), 'T10': np.array([0, 1, 0]), 'CLAV': np.array([1, 0, 0]), 'STRN': np.array([0, 0, 0])},
[[[1, 6, 0], [1, 7, 1], [0, 7, 0]], [1, 7, 0]]),
# Setting the markers so there's no variance in the x-dimension
({'C7': np.array([0, 1, 0]), 'T10': np.array([0, 1, 0]), 'CLAV': np.array([0, 0, 0]), 'STRN': np.array([0, 0, 0])},
[[nan_3d, nan_3d, nan_3d], nan_3d]),
# Setting the markers so there's no variance in the y-dimension
({'C7': np.array([1, 0, 0]), 'T10': np.array([0, 0, 0]), 'CLAV': np.array([1, 0, 0]), 'STRN': np.array([0, 0, 0])},
[[nan_3d, nan_3d, nan_3d], nan_3d]),
# Setting each marker in a different xy quadrant
({'C7': np.array([-1, 1, 0]), 'T10': np.array([1, 1, 0]), 'CLAV': np.array([-1, -1, 0]), 'STRN': np.array([1, -1, 0])},
[[[-1, 5, 0], [-1, 6, -1], [0, 6, 0]], [-1, 6, 0]]),
# Setting values of the markers so that midpoints will be on diagonals
({'C7': np.array([-2, 1, 0]), 'T10': np.array([1, 2, 0]), 'CLAV': np.array([-1, -2, 0]), 'STRN': np.array([2, -1, 0])},
[[[-2.8973666, 3.69209979, 0], [-3.21359436, 4.64078309, -1], [-2.26491106, 4.95701085, 0]], [-3.21359436, 4.64078309, 0]]),
# Adding the value of 1 in the z dimension for all 4 markers
({'C7': np.array([1, 1, 1]), 'T10': np.array([0, 1, 1]), 'CLAV': np.array([1, 0, 1]), 'STRN': np.array([0, 0, 1])},
[[[1, 6, 1], [1, 7, 2], [0, 7, 1]], [1, 7, 1]]),
# Setting the z dimension value higher for C7 and CLAV
({'C7': np.array([1, 1, 2]), 'T10': np.array([0, 1, 1]), 'CLAV': np.array([1, 0, 2]), 'STRN': np.array([0, 0, 1])},
[[[1, 6, 2], [0.29289322, 7, 2.70710678], [0.29289322, 7, 1.29289322]], [1, 7, 2]]),
# Setting the z dimension value higher for C7 and T10
({'C7': np.array([1, 1, 2]), 'T10': np.array([0, 1, 2]), 'CLAV': np.array([1, 0, 1]), 'STRN': np.array([0, 0, 1])},
[[[1, 4.24264069, 5.24264069], [1, 4.24264069, 6.65685425], [0, 4.94974747, 5.94974747]], [1, 4.94974747, 5.94974747]]),
# Testing that when frame is a list of ints
({'C7': [1, 1, 2], 'T10': [0, 1, 2], 'CLAV': [1, 0, 1], 'STRN': [0, 0, 1]},
[[[1, 4.24264069, 5.24264069], [1, 4.24264069, 6.65685425], [0, 4.94974747, 5.94974747]],
[1, 4.94974747, 5.94974747]]),
# Testing that when frame is a numpy array of ints
({'C7': np.array([1, 1, 2], dtype='int'), 'T10': np.array([0, 1, 2], dtype='int'),
'CLAV': np.array([1, 0, 1], dtype='int'), 'STRN': np.array([0, 0, 1], dtype='int')},
[[[1, 4.24264069, 5.24264069], [1, 4.24264069, 6.65685425], [0, 4.94974747, 5.94974747]],
[1, 4.94974747, 5.94974747]]),
# Testing that when frame is a list of floats
({'C7': [1.0, 1.0, 2.0], 'T10': [0.0, 1.0, 2.0], 'CLAV': [1.0, 0.0, 1.0], 'STRN': [0.0, 0.0, 1.0]},
[[[1, 4.24264069, 5.24264069], [1, 4.24264069, 6.65685425], [0, 4.94974747, 5.94974747]],
[1, 4.94974747, 5.94974747]]),
# Testing that when frame is a numpy array of floats
({'C7': np.array([1.0, 1.0, 2.0], dtype='float'), 'T10': np.array([0.0, 1.0, 2.0], dtype='float'),
'CLAV': np.array([1.0, 0.0, 1.0], dtype='float'), 'STRN': np.array([0.0, 0.0, 1.0], dtype='float')},
[[[1, 4.24264069, 5.24264069], [1, 4.24264069, 6.65685425], [0, 4.94974747, 5.94974747]],
[1, 4.94974747, 5.94974747]])])
def test_thoraxJC(self, frame, expected):
"""
This test provides coverage of the thoraxJC function in pyCGM.py, defined as thoraxJC(frame)
This test takes 2 parameters:
frame: dictionary of marker lists
expected: the expected result from calling thoraxJC on frame
The function uses the CLAV, C7, STRN, and T10 markers from the frame to calculate the midpoints of the front, back, left, and right center positions of the thorax.
The thorax axis vector components are then calculated using subtracting the pairs (left to right, back to front) of the aforementioned midpoints.
Afterwords, the axes are made orthogonal by calculating the cross product of each individual axis.
Finally, the head axis is then rotated around the x axis based off the thorax offset angle in the VSK.
This test is checking to make sure the thorax joint center and thorax joint axis are calculated correctly given
the 4 coordinates given in frame. This includes testing when there is no variance in the coordinates,
when the coordinates are in different quadrants, when the midpoints will be on diagonals, and when the z
dimension is variable. Lastly, it checks that the resulting output is correct when frame is a list of ints, a
numpy array of ints, a list of floats, and a numpy array of floats.
"""
result = pyCGM.thoraxJC(frame)
np.testing.assert_almost_equal(result[0], expected[0], rounding_precision)
np.testing.assert_almost_equal(result[1], expected[1], rounding_precision)
@pytest.mark.parametrize(["frame", "thorax", "wand", "vsk", "expected_args"], [
# Test from running sample data
({'RSHO': np.array([428.88476562, 270.552948, 1500.73010254]), 'LSHO': np.array([68.24668121, 269.01049805, 1510.1072998])},
[[[256.23991128535846, 365.30496976939753, 1459.662169500559], [257.1435863244796, 364.21960599061947, 1459.588978712983], [256.0843053658035, 364.32180498523223, 1458.6575930699294]], [256.149810236564, 364.3090603933987, 1459.6553639290375]],
[[255.92550222678443, 364.3226950497605, 1460.6297868417887], [256.42380097331767, 364.27770361353487, 1460.6165849382387]],
{'RightShoulderOffset': 40.0, 'LeftShoulderOffset': 40.0},
[[[255.92550222678443, 364.3226950497605, 1460.6297868417887], [256.149810236564, 364.3090603933987, 1459.6553639290375], np.array([ 428.88476562, 270.552948 , 1500.73010254]), 47.0],
[[256.42380097331767, 364.27770361353487, 1460.6165849382387], [256.149810236564, 364.3090603933987, 1459.6553639290375], np.array([68.24668121, 269.01049805, 1510.1072998]), 47.0]]),
# Basic test with zeros for all params
({'RSHO': np.array([0, 0, 0]), 'LSHO': np.array([0, 0, 0])},
[[rand_coor, rand_coor, rand_coor], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0]],
{'RightShoulderOffset': 0.0, 'LeftShoulderOffset': 0.0},
[[[0, 0, 0], [0, 0, 0], np.array([0, 0, 0]), 7.0],
[[0, 0, 0], [0, 0, 0], np.array([0, 0, 0]), 7.0]]),
# Testing when values are added to RSHO and LSHO
({'RSHO': np.array([2, -1, 3]), 'LSHO': np.array([-3, 1, 2])},
[[rand_coor, rand_coor, rand_coor], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0]],
{'RightShoulderOffset': 0.0, 'LeftShoulderOffset': 0.0},
[[[0, 0, 0], [0, 0, 0], np.array([2, -1, 3]), 7.0],
[[0, 0, 0], [0, 0, 0], np.array([-3, 1, 2]), 7.0]]),
# Testing when a value is added to thorax_origin
({'RSHO': np.array([0, 0, 0]), 'LSHO': np.array([0, 0, 0])},
[[rand_coor, rand_coor, rand_coor], [5, -2, 7]],
[[0, 0, 0], [0, 0, 0]],
{'RightShoulderOffset': 0.0, 'LeftShoulderOffset': 0.0},
[[[0, 0, 0], [5, -2, 7], np.array([0, 0, 0]), 7.0],
[[0, 0, 0], [5, -2, 7], np.array([0, 0, 0]), 7.0]]),
# Testing when a value is added to wand
({'RSHO': np.array([0, 0, 0]), 'LSHO': np.array([0, 0, 0])},
[[rand_coor, rand_coor, rand_coor], [0, 0, 0]],
[[2, 6, -4], [-3, 5, 2]],
{'RightShoulderOffset': 0.0, 'LeftShoulderOffset': 0.0},
[[[2, 6, -4], [0, 0, 0], np.array([0, 0, 0]), 7.0],
[[-3, 5, 2], [0, 0, 0], np.array([0, 0, 0]), 7.0]]),
# Testing when values are added to RightShoulderOffset and LeftShoulderOffset
({'RSHO': np.array([0, 0, 0]), 'LSHO': np.array([0, 0, 0])},
[[rand_coor, rand_coor, rand_coor], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0]],
{'RightShoulderOffset': 20.0, 'LeftShoulderOffset': -20.0},
[[[0, 0, 0], [0, 0, 0], np.array([0, 0, 0]), 27.0],
[[0, 0, 0], [0, 0, 0], np.array([0, 0, 0]), -13.0]]),
# Adding when values are added to all params
({'RSHO': np.array([3, -5, 2]), 'LSHO': np.array([-7, 3 , 9])},
[[rand_coor, rand_coor, rand_coor], [-1, -9, -5]],
[[-7, -1, 5], [5, -9, 2]],
{'RightShoulderOffset': -6.0, 'LeftShoulderOffset': 42.0},
[[[-7, -1, 5], [-1, -9, -5], np.array([3, -5, 2]), 1.0],
[[5, -9, 2], [-1, -9, -5], np.array([-7, 3 , 9]), 49.0]]),
# Testing that when frame, thorax, wand and vsk are lists of ints
({'RSHO': [3, -5, 2], 'LSHO': [-7, 3, 9]},
[[rand_coor, rand_coor, rand_coor], [-1, -9, -5]],
[[-7, -1, 5], [5, -9, 2]],
{'RightShoulderOffset': -6, 'LeftShoulderOffset': 42},
[[[-7, -1, 5], [-1, -9, -5], np.array([3, -5, 2]), 1.0],
[[5, -9, 2], [-1, -9, -5], np.array([-7, 3, 9]), 49.0]]),
# Testing that when frame, wand and vsk are numpy arrays of ints
({'RSHO': np.array([3, -5, 2], dtype='int'), 'LSHO': np.array([-7, 3, 9], dtype='int')},
[[rand_coor, rand_coor, rand_coor], np.array([-1, -9, -5], dtype='int')],
np.array([[-7, -1, 5], [5, -9, 2]], dtype='int'),
{'RightShoulderOffset': -6, 'LeftShoulderOffset': 42},
[[[-7, -1, 5], [-1, -9, -5], np.array([3, -5, 2]), 1.0],
[[5, -9, 2], [-1, -9, -5], np.array([-7, 3, 9]), 49.0]]),
# Testing that when frame, thorax, wand and vsk are lists of floats
({'RSHO': [3.0, -5.0, 2.0], 'LSHO': [-7.0, 3.0, 9.0]},
[[rand_coor, rand_coor, rand_coor], [-1.0, -9.0, -5.0]],
[[-7.0, -1.0, 5.0], [5.0, -9.0, 2.0]],
{'RightShoulderOffset': -6.0, 'LeftShoulderOffset': 42.0},
[[[-7, -1, 5], [-1, -9, -5], np.array([3, -5, 2]), 1.0],
[[5, -9, 2], [-1, -9, -5], np.array([-7, 3, 9]), 49.0]]),
# Testing that when frame, wand and vsk are numpy arrays of floats
({'RSHO': np.array([3.0, -5.0, 2.0], dtype='float'), 'LSHO': np.array([-7.0, 3.0, 9.0], dtype='float')},
[[rand_coor, rand_coor, rand_coor], np.array([-1.0, -9.0, -5.0], dtype='float')],
np.array([[-7.0, -1.0, 5.0], [5.0, -9.0, 2.0]], dtype='float'),
{'RightShoulderOffset': -6.0, 'LeftShoulderOffset': 42.0},
[[[-7, -1, 5], [-1, -9, -5], np.array([3, -5, 2]), 1.0],
[[5, -9, 2], [-1, -9, -5], np.array([-7, 3, 9]), 49.0]])])
def test_findshoulderJC(self, frame, thorax, wand, vsk, expected_args):
"""
This test provides coverage of the findshoulderJC function in pyCGM.py, defined as findshoulderJC(frame, thorax, wand, vsk)
This test takes 5 parameters:
frame: dictionary of marker lists
thorax: array containing several x,y,z markers for the thorax
wand: array containing two x,y,z markers for wand
vsk: dictionary containing subject measurements from a VSK file
expected_args: the expected arguments used to call the mocked function, findJointC
The function uses the RSHO and LSHO markers from the frame given, as well as the thorax origin position and the wand.
The right shoulder joint center by using the the RSHO marker, right wand position, and thorax origin position, as positions in a
plane for the Rodriques' rotation formula to find the right shoulder joint center. It is the same for the left shoulder joint center,
although the left wand and LSHO markers are used instead.
This test is checking to make sure the shoulder joint center is calculated correctly given the input parameters.
This tests mocks findJointC to make sure the correct parameters are being passed into it given the parameters
passed into findshoulderJC.
Lastly, it checks that the resulting output is correct when frame and wand are a list of ints, a
numpy array of ints, a list of floats, and a numpy array of floats, vsk values are either an int or a float,
and thorax values are either an int or a float. Thorax cannot be a numpy array due it not being shaped like
a multi-dimensional array.
"""
rand_coor = [np.random.randint(0, 10), np.random.randint(0, 10), np.random.randint(0, 10)]
with patch.object(pyCGM, 'findJointC', return_value=rand_coor) as mock_findJointC:
result = pyCGM.findshoulderJC(frame, thorax, wand, vsk)
# Asserting that there were only 2 calls to findJointC
np.testing.assert_equal(mock_findJointC.call_count, 2)
# Asserting that the correct params were sent in the 1st (right) call to findJointC
np.testing.assert_almost_equal(expected_args[0][0], mock_findJointC.call_args_list[0][0][0], rounding_precision)
np.testing.assert_almost_equal(expected_args[0][1], mock_findJointC.call_args_list[0][0][1], rounding_precision)
np.testing.assert_almost_equal(expected_args[0][2], mock_findJointC.call_args_list[0][0][2], rounding_precision)
np.testing.assert_almost_equal(expected_args[0][3], mock_findJointC.call_args_list[0][0][3], rounding_precision)
# Asserting that the correct params were sent in the 2nd (left) call to findJointC
np.testing.assert_almost_equal(expected_args[1][0], mock_findJointC.call_args_list[1][0][0], rounding_precision)
np.testing.assert_almost_equal(expected_args[1][1], mock_findJointC.call_args_list[1][0][1], rounding_precision)
np.testing.assert_almost_equal(expected_args[1][2], mock_findJointC.call_args_list[1][0][2], rounding_precision)
np.testing.assert_almost_equal(expected_args[1][3], mock_findJointC.call_args_list[1][0][3], rounding_precision)
# Asserting that findShoulderJC returned the correct result given the return value given by mocked findJointC
np.testing.assert_almost_equal(result[0], rand_coor, rounding_precision)
np.testing.assert_almost_equal(result[1], rand_coor, rounding_precision)
@pytest.mark.parametrize(["thorax", "shoulderJC", "wand", "expected"], [
# Test from running sample data
([[[256.23991128535846, 365.30496976939753, 1459.662169500559], [257.1435863244796, 364.21960599061947, 1459.588978712983], [256.0843053658035, 364.32180498523223, 1458.6575930699294]], [256.149810236564, 364.3090603933987, 1459.6553639290375]],
[np.array([429.66951995, 275.06718615, 1453.95397813]), np.array([64.51952734, 274.93442161, 1463.6313334 ])],
[[255.92550222678443, 364.3226950497605, 1460.6297868417887], [256.42380097331767, 364.27770361353487, 1460.6165849382387]],
[[np.array([429.66951995, 275.06718615, 1453.95397813]), np.array([64.51952734, 274.93442161, 1463.6313334 ])],
[[[430.12731330596756, 275.9513661907463, 1454.0469882869343], [429.6862168456729, 275.1632337671314, 1452.9587414419757], [428.78061812142147, 275.5243518770602, 1453.9831850281803]],
[[64.10400324869988, 275.83192826468195, 1463.7790545425955], [64.59882848203122, 274.80838068265837, 1464.620183745389], [65.42564601518438, 275.3570272042577, 1463.6125331307376]]]]),
# Test with zeros for all params
([[rand_coor, rand_coor, rand_coor], [0, 0, 0]],
[np.array([0, 0, 0]), np.array([0, 0, 0])],
[[0, 0, 0], [0, 0, 0]],
[[np.array([0, 0, 0]), np.array([0, 0, 0])],
[[nan_3d, nan_3d, nan_3d],
[nan_3d, nan_3d, nan_3d]]]),
# Testing when adding values in thorax but zeros for all other params
([[rand_coor, rand_coor, rand_coor], [8, 2, -6]],
[np.array([0, 0, 0]), np.array([0, 0, 0])],
[[0, 0, 0], [0, 0, 0]],
[[np.array([0, 0, 0]), np.array([0, 0, 0])],
[[nan_3d, nan_3d, [0.78446454, 0.19611614, -0.58834841]],
[nan_3d, nan_3d, [0.78446454, 0.19611614, -0.58834841]]]]),
# Testing when adding values in shoulderJC but zeros for all other params
([[rand_coor, rand_coor, rand_coor], [0, 0, 0]],
[np.array([1, 5, -3]), np.array([0, -9, 2])],
[[0, 0, 0], [0, 0, 0]],
[[np.array([1, 5, -3]), np.array([0, -9, 2])],
[[nan_3d, nan_3d, [0.830969149054, 4.154845745271, -2.4929074471]],
[nan_3d, nan_3d, [0.0, -8.02381293981, 1.783069542181]]]]),
# Testing when adding values in wand but zeros for all other params
([[rand_coor, rand_coor, rand_coor], [0, 0, 0]],
[np.array([0, 0, 0]), np.array([0, 0, 0])],
[[1, 0, -7], [-3, 5, 3]],
[[np.array([0, 0, 0]), np.array([0, 0, 0])],
[[nan_3d, nan_3d, nan_3d],
[nan_3d, nan_3d, nan_3d]]]),
# Testing when adding values to thorax and shoulderJC
([[rand_coor, rand_coor, rand_coor], [8, 2, -6]],
[np.array([1, 5, -3]), np.array([0, -9, 2])],
[[0, 0, 0], [0, 0, 0]],
[[np.array([1, 5, -3]), np.array([0, -9, 2])],
[[[0.50428457, 4.62821343, -3.78488277], [1.15140320, 5.85290468, -3.49963055], [1.85518611, 4.63349167, -3.36650833]],
[[-0.5611251741, -9.179560055, 1.191979749], [-0.65430149, -8.305871473, 2.3001252440], [0.5069794004, -8.302903324, 1.493020599]]]]),
# Testing when adding values to thorax and wand
([[rand_coor, rand_coor, rand_coor], [8, 2, -6]],
[np.array([0, 0, 0]), np.array([0, 0, 0])],
[[1, 0, -7], [-3, 5, 3]],
[[np.array([0, 0, 0]), np.array([0, 0, 0])],
[[[-0.269430125, 0.96225044, -0.03849001], [0.55859, 0.18871284, 0.80769095], [0.78446454, 0.19611614, -0.58834841]],
[[-0.6130824329, 0.10218040549, -0.7833831087], [-0.09351638899, 0.9752423423, 0.20039226212], [0.7844645405, 0.19611613513, -0.5883484054]]]]),
# Testing when adding values to shoulderJC and wand
([[rand_coor, rand_coor, rand_coor], [0, 0, 0]],
[np.array([1, 5, -3]), np.array([0, -9, 2])],
[[1, 0, -7], [-3, 5, 3]],
[[np.array([1, 5, -3]), np.array([0, -9, 2])],
[[[1.98367400, 4.88758011, -2.85947514], [0.93824211, 5.52256679, -2.14964131], [0.83096915, 4.15484575, -2.49290745]],
[[-0.80094836, -9.12988352, 1.41552417], [-0.59873343, -8.82624991, 2.78187543], [0.0, -8.02381294, 1.78306954]]]]),
# Testing when adding values to thorax, shoulderJC and wand
([[rand_coor, rand_coor, rand_coor], [8, 2, -6]],
[np.array([1, 5, -3]), np.array([0, -9, 2])],
[[1, 0, -7], [-3, 5, 3]],
[[np.array([1, 5, -3]), np.array([0, -9, 2])],
[[[0.93321781, 5.62330046, -3.77912558], [1.51400083, 5.69077360, -2.49143833], [1.85518611, 4.63349167, -3.36650833]],
[[-0.64460664, -9.08385127, 1.24009787], [-0.57223612, -8.287942994, 2.40684228], [0.50697940, -8.30290332, 1.4930206]]]]),
# Testing that when thorax, shoulderJC, and wand are lists of ints
([[rand_coor, rand_coor, rand_coor], [8, 2, -6]],
[[1, 5, -3], [0, -9, 2]],
[[1, 0, -7], [-3, 5, 3]],
[[np.array([1, 5, -3]), np.array([0, -9, 2])],
[[[0.93321781, 5.62330046, -3.77912558], [1.51400083, 5.69077360, -2.49143833],
[1.85518611, 4.63349167, -3.36650833]],
[[-0.64460664, -9.08385127, 1.24009787], [-0.57223612, -8.287942994, 2.40684228],
[0.50697940, -8.30290332, 1.4930206]]]]),
# Testing that when thorax, shoulderJC and wand are numpy arrays of ints
([[rand_coor, rand_coor, rand_coor], np.array([8, 2, -6], dtype='int')],
np.array([np.array([1, 5, -3], dtype='int'), np.array([0, -9, 2], dtype='int')], dtype='int'),
np.array([np.array([1, 0, -7], dtype='int'), np.array([-3, 5, 3], dtype='int')], dtype='int'),
[[np.array([1, 5, -3]), np.array([0, -9, 2])],
[[[0.93321781, 5.62330046, -3.77912558], [1.51400083, 5.69077360, -2.49143833],
[1.85518611, 4.63349167, -3.36650833]],
[[-0.64460664, -9.08385127, 1.24009787], [-0.57223612, -8.287942994, 2.40684228],
[0.50697940, -8.30290332, 1.4930206]]]]),
# Testing that when thorax, shoulderJC and wand are lists of floats
([[rand_coor, rand_coor, rand_coor], [8.0, 2.0, -6.0]],
[[1.0, 5.0, -3.0], [0.0, -9.0, 2.0]],
[[1.0, 0.0, -7.0], [-3.0, 5.0, 3.0]],
[[np.array([1, 5, -3]), np.array([0, -9, 2])],
[[[0.93321781, 5.62330046, -3.77912558], [1.51400083, 5.69077360, -2.49143833],
[1.85518611, 4.63349167, -3.36650833]],
[[-0.64460664, -9.08385127, 1.24009787], [-0.57223612, -8.287942994, 2.40684228],
[0.50697940, -8.30290332, 1.4930206]]]]),
# Testing that when thorax, shoulderJC and wand are numpy arrays of floats
([[rand_coor, rand_coor, rand_coor], np.array([8.0, 2.0, -6.0], dtype='float')],
np.array([np.array([1.0, 5.0, -3.0], dtype='float'), np.array([0.0, -9.0, 2.0], dtype='float')], dtype='float'),
np.array([np.array([1.0, 0.0, -7.0], dtype='float'), np.array([-3.0, 5.0, 3.0], dtype='float')], dtype='float'),
[[np.array([1.0, 5.0, -3.0]), np.array([0.0, -9.0, 2.0])],
[[[0.93321781, 5.62330046, -3.77912558], [1.51400083, 5.69077360, -2.49143833],
[1.85518611, 4.63349167, -3.36650833]],
[[-0.64460664, -9.08385127, 1.24009787], [-0.57223612, -8.287942994, 2.40684228],
[0.50697940, -8.30290332, 1.4930206]]]])])
def test_shoulderAxisCalc(self, thorax, shoulderJC, wand, expected):
"""
This test provides coverage of the shoulderAxisCalc function in pyCGM.py, defined as shoulderAxisCalc(frame, thorax, shoulderJC, wand)
This test takes 4 parameters:
thorax: array containing several x,y,z markers for the thorax
shoulderJC: array containing x,y,z position of the shoulder joint center
wand: array containing two x,y,z markers for wand
expected: the expected result from calling shoulderAxisCalc on thorax, shoulderJC, and wand
For the left and right shoulder axis, the respective axis is calculated by taking the difference from the respective direction (left or right) and the throax origin.
The difference is then used to get the direction of each respective shoulder joint center for each shoulder axis in the order of Z, X, Y.
The direction is then applied backwords to each shoulder joint center to account for variations in marker sizes.
Lastly, it checks that the resulting output is correct when shoulderJC and wand are a list of ints, a
numpy array of ints, a list of floats, and a numpy array of floats, and thorax values are either an int or a
float. Thorax cannot be a numpy array due it not being shaped like a multi-dimensional array.
"""
result = pyCGM.shoulderAxisCalc(None, thorax, shoulderJC, wand)
np.testing.assert_almost_equal(result[0], expected[0], rounding_precision)
np.testing.assert_almost_equal(result[1], expected[1], rounding_precision)
@pytest.mark.parametrize(["frame", "thorax", "shoulderJC", "vsk", "mockReturnVal", "expectedMockArgs", "expected"], [
# Test from running sample data
({'RSHO': np.array([428.88476562, 270.552948, 1500.73010254]), 'LSHO': np.array([68.24668121, 269.01049805, 1510.1072998]),
'RELB': np.array([658.90338135, 326.07580566, 1285.28515625]), 'LELB': np.array([-156.32162476, 335.2583313, 1287.39916992]),
'RWRA': np.array([ 776.51898193, 495.68103027, 1108.38464355]), 'RWRB': np.array([ 830.9072876 , 436.75341797, 1119.11901855]),
'LWRA': np.array([-249.28146362, 525.32977295, 1117.09057617]), 'LWRB': np.array([-311.77532959, 477.22512817, 1125.1619873 ])},
[[rand_coor, [257.1435863244796, 364.21960599061947, 1459.588978712983], rand_coor],
[256.149810236564, 364.3090603933987, 1459.6553639290375]],
[np.array([429.66951995, 275.06718615, 1453.95397813]), np.array([64.51952734, 274.93442161, 1463.6313334])],
{'RightElbowWidth': 74.0, 'LeftElbowWidth': 74.0, 'RightWristWidth': 55.0, 'LeftWristWidth': 55.0},
[[633.66707588, 304.95542115, 1256.07799541], [-129.16952219, 316.8671644, 1258.06440717]],
[[[429.7839232523795, 96.8248244295684, 904.5644429627703], [429.66951995, 275.06718615, 1453.95397813], [658.90338135, 326.07580566, 1285.28515625], -44.0],
[[-409.6146956013004, 530.6280208729519, 1671.682014527917], [64.51952734, 274.93442161, 1463.6313334], [-156.32162476, 335.2583313, 1287.39916992], 44.0]],
[[np.array([633.66707587, 304.95542115, 1256.07799541]),
np.array([-129.16952218, 316.8671644, 1258.06440717])],
[[[633.8107013869995, 303.96579004975194, 1256.07658506845], [634.3524799178464, 305.0538658933253, 1256.799473014224], [632.9532180390149, 304.85083190737765, 1256.770431750491]],
[[-129.32391792749496, 315.8807291324946, 1258.008662931836], [-128.45117135279028, 316.79382333592827, 1257.3726028780698], [-128.49119037560908, 316.72030884193634, 1258.7843373067021]]],
[[793.3281430325068, 451.2913478825204, 1084.4325513020426], [-272.4594189740742, 485.801522109477, 1091.3666238350822]]]),
# Test with zeros for all params
({'RSHO': np.array([0, 0, 0]), 'LSHO': np.array([0, 0, 0]), 'RELB': np.array([0, 0, 0]), 'LELB': np.array([0, 0, 0]),
'RWRA': np.array([0, 0, 0]), 'RWRB': np.array([0, 0, 0]), 'LWRA': np.array([0, 0, 0]), 'LWRB': np.array([0, 0, 0])},
[[rand_coor, [0, 0, 0], rand_coor], [0, 0, 0]],
[np.array([0, 0, 0]), np.array([0, 0, 0])],
{'RightElbowWidth': 0.0, 'LeftElbowWidth': 0.0, 'RightWristWidth': 0.0, 'LeftWristWidth': 0.0},
[[0, 0, 0], [0, 0, 0]],
[[nan_3d, [0, 0, 0], [0, 0, 0], -7.0], [nan_3d, [0, 0, 0], [0, 0, 0], 7.0]],
[[np.array([0, 0, 0]), np.array([0, 0, 0])], [[nan_3d, nan_3d, nan_3d], [nan_3d, nan_3d, nan_3d]], [nan_3d, nan_3d]]),
# Testing when values are added to frame
({'RSHO': np.array([9, -7, -6]), 'LSHO': np.array([3, -8, 5]), 'RELB': np.array([-9, 1, -4]), 'LELB': np.array([-4, 1, -6]),
'RWRA': np.array([2, -3, 9]), 'RWRB': np.array([-4, -2, -7]), 'LWRA': np.array([-9, 1, -1]), 'LWRB': np.array([-3, -4, -9])},
[[rand_coor, [0, 0, 0], rand_coor], [0, 0, 0]],
[np.array([0, 0, 0]), np.array([0, 0, 0])],
{'RightElbowWidth': 0.0, 'LeftElbowWidth': 0.0, 'RightWristWidth': 0.0, 'LeftWristWidth': 0.0},
[[0, 0, 0], [0, 0, 0]],
[[[149.87576359540907, -228.48721408225754, -418.8422716102348], [0, 0, 0], [-9, 1, -4], -7.0], [[282.73117218166414, -326.69276820761615, -251.76957615571214], [0, 0, 0], [-4, 1, -6], 7.0]],
[[np.array([0, 0, 0]), np.array([0, 0, 0])],
[[nan_3d, nan_3d, nan_3d],
[nan_3d, nan_3d, nan_3d]],
[[4.7413281, -5.7386979, -1.35541665], [-4.96790631, 4.69256216, -8.09628108]]]),
# Testing when values are added to thorax
({'RSHO': np.array([0, 0, 0]), 'LSHO': np.array([0, 0, 0]), 'RELB': np.array([0, 0, 0]), 'LELB': np.array([0, 0, 0]),
'RWRA': np.array([0, 0, 0]), 'RWRB': np.array([0, 0, 0]), 'LWRA': np.array([0, 0, 0]), 'LWRB': np.array([0, 0, 0])},
[[rand_coor, [-9, 5, -5], rand_coor], [-5, -2, -3]],
[np.array([0, 0, 0]), np.array([0, 0, 0])],
{'RightElbowWidth': 0.0, 'LeftElbowWidth': 0.0, 'RightWristWidth': 0.0, 'LeftWristWidth': 0.0},
[[0, 0, 0], [0, 0, 0]],
[[nan_3d, [0, 0, 0], [0, 0, 0], -7.0],
[nan_3d, [0, 0, 0], [0, 0, 0], 7.0]],
[[np.array([0, 0, 0]), np.array([0, 0, 0])], [[nan_3d, nan_3d, nan_3d], [nan_3d, nan_3d, nan_3d]], [nan_3d, nan_3d]]),
# Testing when values are added to shoulderJC
({'RSHO': np.array([0, 0, 0]), 'LSHO': np.array([0, 0, 0]), 'RELB': np.array([0, 0, 0]), 'LELB': np.array([0, 0, 0]),
'RWRA': np.array([0, 0, 0]), 'RWRB': np.array([0, 0, 0]), 'LWRA': np.array([0, 0, 0]), 'LWRB': np.array([0, 0, 0])},
[[rand_coor, [0, 0, 0], rand_coor], [0, 0, 0]],
[np.array([-2, -8, -3]), np.array([5, -3, 2])],
{'RightElbowWidth': 0.0, 'LeftElbowWidth': 0.0, 'RightWristWidth': 0.0, 'LeftWristWidth': 0.0},
[[0, 0, 0], [0, 0, 0]],
[[nan_3d, [-2, -8, -3], [0, 0, 0], -7.0],
[nan_3d, [5, -3, 2], [0, 0, 0], 7.0]],
[[np.array([0, 0, 0]), np.array([0, 0, 0])],
[[nan_3d, nan_3d, [-0.2279211529192759, -0.9116846116771036, -0.3418817293789138]],
[nan_3d, nan_3d, [0.8111071056538127, -0.48666426339228763, 0.3244428422615251]]],
[nan_3d, nan_3d]]),
# Testing when values are added to vsk
({'RSHO': np.array([0, 0, 0]), 'LSHO': np.array([0, 0, 0]), 'RELB': np.array([0, 0, 0]), 'LELB': np.array([0, 0, 0]),
'RWRA': np.array([0, 0, 0]), 'RWRB': np.array([0, 0, 0]), 'LWRA': np.array([0, 0, 0]), 'LWRB': np.array([0, 0, 0])},
[[rand_coor, [0, 0, 0], rand_coor], [0, 0, 0]],
[np.array([0, 0, 0]), np.array([0, 0, 0])],
{'RightElbowWidth': -38.0, 'LeftElbowWidth': 6.0, 'RightWristWidth': 47.0, 'LeftWristWidth': -7.0},
[[0, 0, 0], [0, 0, 0]],
[[nan_3d, [0, 0, 0], [0, 0, 0], 12.0],
[nan_3d, [0, 0, 0], [0, 0, 0], 10.0]],
[[np.array([0, 0, 0]), np.array([0, 0, 0])], [[nan_3d, nan_3d, nan_3d], [nan_3d, nan_3d, nan_3d]], [nan_3d, nan_3d]]),
# Testing when values are added to mockReturnVal
({'RSHO': np.array([0, 0, 0]), 'LSHO': np.array([0, 0, 0]), 'RELB': np.array([0, 0, 0]), 'LELB': np.array([0, 0, 0]),
'RWRA': np.array([0, 0, 0]), 'RWRB': np.array([0, 0, 0]), 'LWRA': np.array([0, 0, 0]), 'LWRB': np.array([0, 0, 0])},
[[rand_coor, [0, 0, 0], rand_coor], [0, 0, 0]],
[np.array([0, 0, 0]), np.array([0, 0, 0])],
{'RightElbowWidth': 0.0, 'LeftElbowWidth': 0.0, 'RightWristWidth': 0.0, 'LeftWristWidth': 0.0},
[[5, 4, -4], [6, 3, 5]],
[[nan_3d, [0, 0, 0], [0, 0, 0], -7.0],
[nan_3d, [0, 0, 0], [0, 0, 0], 7.0]],
[[np.array([5, 4, -4]), np.array([6, 3, 5])],
[[nan_3d, nan_3d, [4.337733821467478, 3.4701870571739826, -3.4701870571739826]],
[nan_3d, nan_3d, [5.2828628343993635, 2.6414314171996818, 4.4023856953328036]]],
[nan_3d, nan_3d]]),
# Testing when values are added to frame and thorax
({'RSHO': np.array([9, -7, -6]), 'LSHO': np.array([3, -8, 5]), 'RELB': np.array([-9, 1, -4]), 'LELB': np.array([-4, 1, -6]),
'RWRA': np.array([2, -3, 9]), 'RWRB': np.array([-4, -2, -7]), 'LWRA': np.array([-9, 1, -1]), 'LWRB': np.array([-3, -4, -9])},
[[rand_coor, [-9, 5, -5], rand_coor], [-5, -2, -3]],
[np.array([0, 0, 0]), np.array([0, 0, 0])],
{'RightElbowWidth': 0.0, 'LeftElbowWidth': 0.0, 'RightWristWidth': 0.0, 'LeftWristWidth': 0.0},
[[0, 0, 0], [0, 0, 0]],
[[[149.87576359540907, -228.48721408225754, -418.8422716102348], [0, 0, 0], [-9, 1, -4], -7.0],
[[282.73117218166414, -326.69276820761615, -251.76957615571214], [0, 0, 0], [-4, 1, -6], 7.0]],
[[np.array([0, 0, 0]), np.array([0, 0, 0])], [[nan_3d, nan_3d, nan_3d], [nan_3d, nan_3d, nan_3d]],
[[4.7413281, -5.7386979, -1.35541665], [-4.96790631, 4.69256216, -8.09628108]]]),
# Testing when values are added to frame, thorax, and shoulderJC
({'RSHO': np.array([9, -7, -6]), 'LSHO': np.array([3, -8, 5]), 'RELB': np.array([-9, 1, -4]), 'LELB': np.array([-4, 1, -6]),
'RWRA': np.array([2, -3, 9]), 'RWRB': np.array([-4, -2, -7]), 'LWRA': np.array([-9, 1, -1]), 'LWRB': np.array([-3, -4, -9])},
[[rand_coor, [-9, 5, -5], rand_coor], [-5, -2, -3]],
[np.array([-2, -8, -3]), np.array([5, -3, 2])],
{'RightElbowWidth': 0.0, 'LeftElbowWidth': 0.0, 'RightWristWidth': 0.0, 'LeftWristWidth': 0.0},
[[0, 0, 0], [0, 0, 0]],
[[[-311.42865408643604, -195.76081109238007, 342.15327877363165], [-2, -8, -3], [-9, 1, -4], -7.0],
[[183.9753004933977, -292.7114070209339, -364.32791656553934], [5, -3, 2], [-4, 1, -6], 7.0]],
[[np.array([0, 0, 0]), np.array([0, 0, 0])],
[[[-0.9661174276011973, 0.2554279765068226, -0.03706298561739535], [0.12111591199009825, 0.3218504585188577, -0.9390118307103527], [-0.2279211529192759, -0.9116846116771036, -0.3418817293789138]],
[[-0.40160401780320154, -0.06011448807273248, 0.9138383123989052], [-0.4252287337918506, -0.8715182976051595, -0.24420561192811296], [0.8111071056538127, -0.48666426339228763, 0.3244428422615251]]],
[[4.7413281, -5.7386979, -1.35541665], [-4.96790631, 4.69256216, -8.09628108]]]),
# Testing when values are added to frame, thorax, shoulderJC, and vsk
({'RSHO': np.array([9, -7, -6]), 'LSHO': np.array([3, -8, 5]), 'RELB': np.array([-9, 1, -4]), 'LELB': np.array([-4, 1, -6]),
'RWRA': np.array([2, -3, 9]), 'RWRB': np.array([-4, -2, -7]), 'LWRA': np.array([-9, 1, -1]), 'LWRB': np.array([-3, -4, -9])},
[[rand_coor, [-9, 5, -5], rand_coor], [-5, -2, -3]],
[np.array([-2, -8, -3]), np.array([5, -3, 2])],
{'RightElbowWidth': -38.0, 'LeftElbowWidth': 6.0, 'RightWristWidth': 47.0, 'LeftWristWidth': -7.0},
[[0, 0, 0], [0, 0, 0]],
[[[-311.42865408643604, -195.76081109238007, 342.15327877363165], [-2, -8, -3], [-9, 1, -4], 12.0],
[[183.9753004933977, -292.7114070209339, -364.32791656553934], [5, -3, 2], [-4, 1, -6], 10.0]],
[[np.array([0, 0, 0]), np.array([0, 0, 0])],
[[[-0.9685895544902782, 0.17643783885299713, 0.17522546605219314], [-0.09942948749879241, 0.3710806621909213, -0.9232621075099284], [-0.2279211529192759, -0.9116846116771036, -0.3418817293789138]],
[[-0.10295276972565287, 0.4272479327059481, 0.8982538233730544], [-0.5757655689286321, -0.7619823480470763, 0.29644040025096585], [0.8111071056538127, -0.48666426339228763, 0.3244428422615251]]],
[[24.015786700696715, -16.61146942090584, -9.262886851567883], [-5.48395315345786, 1.5962810792528397, -6.54814053962642]]]),
# Testing when values are added to frame, thorax, shoulderJC, vsk and mockReturnVal
({'RSHO': np.array([9, -7, -6]), 'LSHO': np.array([3, -8, 5]), 'RELB': np.array([-9, 1, -4]), 'LELB': np.array([-4, 1, -6]),
'RWRA': np.array([2, -3, 9]), 'RWRB': np.array([-4, -2, -7]), 'LWRA': np.array([-9, 1, -1]), 'LWRB': np.array([-3, -4, -9])},
[[rand_coor, [-9, 5, -5], rand_coor], [-5, -2, -3]],
[np.array([-2, -8, -3]), np.array([5, -3, 2])],
{'RightElbowWidth': -38.0, 'LeftElbowWidth': 6.0, 'RightWristWidth': 47.0, 'LeftWristWidth': -7.0},
[[5, 4, -4], [6, 3, 5]],
[[[-311.42865408643604, -195.76081109238007, 342.15327877363165], [-2, -8, -3], [-9, 1, -4], 12.0],
[[183.9753004933977, -292.7114070209339, -364.32791656553934], [5, -3, 2], [-4, 1, -6], 10.0]],
[[np.array([5, 4, -4]), np.array([6, 3, 5])],
[[[4.156741342815987, 4.506819397152288, -3.8209778344606247], [4.809375978699987, 4.029428853750657, -4.981221904092206], [4.4974292889675835, 3.138450209658714, -3.928204184138226]],
[[6.726856988207308, 2.5997910101837682, 5.558132316896694], [5.329224487433077, 2.760784472038086, 5.702022893446135], [5.852558043845103, 2.1153482630706173, 4.557674131535308]]],
[[17.14176226312361, -25.58951560761187, -7.246255574147096], [-5.726512929518925, 1.5474273567891164, -6.699526795132392]]]),
# Testing that when frame, thorax, and shoulderJC are list of ints and vsk values are ints
({'RSHO': [9, -7, -6], 'LSHO': [3, -8, 5], 'RELB': [-9, 1, -4], 'LELB': [-4, 1, -6],
'RWRA': [2, -3, 9], 'RWRB': [-4, -2, -7], 'LWRA': [-9, 1, -1], 'LWRB': [-3, -4, -9]},
[[rand_coor, [-9, 5, -5], rand_coor], [-5, -2, -3]],
[[-2, -8, -3], [5, -3, 2]],
{'RightElbowWidth': -38, 'LeftElbowWidth': 6, 'RightWristWidth': 47, 'LeftWristWidth': -7},
[[5, 4, -4], [6, 3, 5]],
[[[-311.42865408643604, -195.76081109238007, 342.15327877363165], [-2, -8, -3], [-9, 1, -4], 12.0],
[[183.9753004933977, -292.7114070209339, -364.32791656553934], [5, -3, 2], [-4, 1, -6], 10.0]],
[[np.array([5, 4, -4]), np.array([6, 3, 5])],
[[[4.156741342815987, 4.506819397152288, -3.8209778344606247], [4.809375978699987, 4.029428853750657, -4.981221904092206], [4.4974292889675835, 3.138450209658714, -3.928204184138226]],
[[6.726856988207308, 2.5997910101837682, 5.558132316896694], [5.329224487433077, 2.760784472038086, 5.702022893446135], [5.852558043845103, 2.1153482630706173, 4.557674131535308]]],
[[17.14176226312361, -25.58951560761187, -7.246255574147096], [-5.726512929518925, 1.5474273567891164, -6.699526795132392]]]),
# Testing that when frame, thorax, and shoulderJC are a numpy array of ints and vsk values are ints
({'RSHO': np.array([9, -7, -6], dtype='int'), 'LSHO': np.array([3, -8, 5], dtype='int'),
'RELB': np.array([-9, 1, -4], dtype='int'), 'LELB': np.array([-4, 1, -6], dtype='int'),
'RWRA': np.array([2, -3, 9], dtype='int'), 'RWRB': np.array([-4, -2, -7], dtype='int'),
'LWRA': np.array([-9, 1, -1], dtype='int'), 'LWRB': np.array([-3, -4, -9], dtype='int')},
[[rand_coor, np.array([-9, 5, -5], dtype='int'), rand_coor], np.array([-5, -2, -3], dtype='int')],
[np.array([-2, -8, -3], dtype='int'), np.array([5, -3, 2], dtype='int')],
{'RightElbowWidth': -38, 'LeftElbowWidth': 6, 'RightWristWidth': 47, 'LeftWristWidth': -7},
[[5, 4, -4], [6, 3, 5]],
[[[-311.42865408643604, -195.76081109238007, 342.15327877363165], [-2, -8, -3], [-9, 1, -4], 12.0],
[[183.9753004933977, -292.7114070209339, -364.32791656553934], [5, -3, 2], [-4, 1, -6], 10.0]],
[[np.array([5, 4, -4]), np.array([6, 3, 5])],
[[[4.156741342815987, 4.506819397152288, -3.8209778344606247], [4.809375978699987, 4.029428853750657, -4.981221904092206], [4.4974292889675835, 3.138450209658714, -3.928204184138226]],
[[6.726856988207308, 2.5997910101837682, 5.558132316896694], [5.329224487433077, 2.760784472038086, 5.702022893446135], [5.852558043845103, 2.1153482630706173, 4.557674131535308]]],
[[17.14176226312361, -25.58951560761187, -7.246255574147096], [-5.726512929518925, 1.5474273567891164, -6.699526795132392]]]),
# Testing that when frame, thorax, and shoulderJC are a list of floats and vsk values are floats
({'RSHO': [9.0, -7.0, -6.0], 'LSHO': [3.0, -8.0, 5.0], 'RELB': [-9.0, 1.0, -4.0], 'LELB': [-4.0, 1.0, -6.0],
'RWRA': [2.0, -3.0, 9.0], 'RWRB': [-4.0, -2.0, -7.0], 'LWRA': [-9.0, 1.0, -1.0], 'LWRB': [-3.0, -4.0, -9.0]},
[[rand_coor, [-9.0, 5.0, -5.0], rand_coor], [-5.0, -2.0, -3.0]],
[[-2.0, -8.0, -3.0], [5.0, -3.0, 2.0]],
{'RightElbowWidth': -38.0, 'LeftElbowWidth': 6.0, 'RightWristWidth': 47.0, 'LeftWristWidth': -7.0},
[[5, 4, -4], [6, 3, 5]],
[[[-311.42865408643604, -195.76081109238007, 342.15327877363165], [-2, -8, -3], [-9, 1, -4], 12.0],
[[183.9753004933977, -292.7114070209339, -364.32791656553934], [5, -3, 2], [-4, 1, -6], 10.0]],
[[
|
np.array([5, 4, -4])
|
numpy.array
|
#!/usr/bin/python3
import Jetson.GPIO as GPIO
from datetime import datetime
import numpy as np
import cv2
def check_spray(frame=0,
save_check_photo=True,
trigger_photo=False,
path_check_photo=None,
position=0,
reshape_photo=300,
convertion_base=0,
qqt_sprayer=0,
phis_dist=0,
cut_width=0,
count_photos=0):
# trigger_photo = 'check_photo' variable from mov_detect
# check_check_photo_name = 'photo_name' variable from infer_camera_processing
'''This function in going to take a photo from the sprayed weed and check if it
was sprayed correctly.
count_photos: if it's the first photo, it will adjust the phisical distance for a first time.
disk_hole_num: the quantity of holes in the rotary reader to be used to resize the lines
convertion_base: This is the base to be used to count photos.
Below are the step in this process:
* Take a photo
* Blur it
* define which color we are going to filter, other colors are going to be dismissed
'''
print('[WEEDS] Taking photo of the sprayed map')
if trigger_photo == False:
resized_bbox_map = 0
else:
now = datetime.now()
#Setting basis for filename
period = [now.year, now.month, now.day, now.hour, now.minute, now.second]
for idx, time in enumerate(period):
if len(f'{time}') == 1:
period[idx] = f'0{time}'
photo_name = ''.join([str(x) for x in period])
# Cutting the width photo, so when resize it won't be weird (IF YOU WANT TO CENTRALIZE CUT IN BOTH SIDE,
# IF YOU DON'T CUT IN ONE SIDE AND MULTP. BY 2)
# It also will put the infer camera and check camera on the same basis
frame = frame[:,cut_width:frame.shape[1]]
print('WIDTH AND HEIGHT AFTER CUT', frame.shape[0], frame.shape[1])
print('[WEEDS] CHECK PHOTO TRIGGERED')
count_photos += 1
# This is going to be the base file to put the contours of the sprayed photos.
sprayed_map = np.zeros((reshape_photo, reshape_photo), np.uint8)
# HSV RANGE (RED AND BLUE)
low =
|
np.array([0, 0, 0])
|
numpy.array
|
import numpy as np
import os
import urllib
import subprocess
import tempfile
from collections import OrderedDict
from lucid.modelzoo.vision_base import Model
from lucid.misc.io import save
from lucid.misc.io.writing import write_handle
from lucid.scratch.rl_util.nmf import LayerNMF, rescale_opacity
from lucid.scratch.rl_util.attribution import (
get_acts,
default_score_fn,
get_grad,
get_attr,
get_multi_path_attr,
)
from lucid.scratch.rl_util.util import (
get_shape,
concatenate_horizontally,
channels_to_rgb,
conv2d,
norm_filter,
brightness_to_opacity,
)
from .compiling import get_compiled_js
from ..svelte3 import compile_html
def get_model(model_bytes):
model_fd, model_path = tempfile.mkstemp(suffix=".model.pb")
with open(model_fd, "wb") as model_file:
model_file.write(model_bytes)
return Model.load(model_path)
def exists_path(model, *, from_names, to_names, without_names=[]):
for from_name in from_names:
if from_name not in without_names:
if from_name in to_names:
return True
next_names = [
name.rsplit(":", 1)[0]
for node in model.graph_def.node
if node.name == from_name
for name in node.input
]
if exists_path(
model,
from_names=next_names,
to_names=to_names,
without_names=without_names,
):
return True
return False
def longest_common_prefix(l):
l = set([s[: min(map(len, l))] for s in l])
while len(l) > 1:
l = set([s[:-1] for s in l])
return list(l)[0]
def longest_common_suffix(l):
l = set([s[-min(map(len, l)) :] for s in l])
while len(l) > 1:
l = set([s[1:] for s in l])
return list(l)[0]
def get_abbreviator(names):
if len(names) <= 1:
return slice(None, None)
prefix = longest_common_prefix(names)
prefix = prefix.rsplit("/", 1)[0] + "/" if "/" in prefix else ""
suffix = longest_common_suffix(names)
suffix = "/" + suffix.split("/", 1)[-1] if "/" in suffix else ""
return slice(len(prefix), None if len(suffix) == 0 else -len(suffix))
def get_layer_names(
model,
output_names,
*,
name_contains_one_of,
op_is_one_of,
bottleneck_only,
discard_first_n,
):
if isinstance(name_contains_one_of, str):
name_contains_one_of = [name_contains_one_of]
if isinstance(op_is_one_of, str):
name_contains_one_of = [op_is_one_of]
nodes = model.graph_def.node
shape_condition = lambda node: len(get_shape(model, node.name)) >= 4
op_condition = lambda node: any(node.op.lower() == s.lower() for s in op_is_one_of)
if bottleneck_only:
bottleneck_names = [
node.name
for node in nodes
if not exists_path(
model,
from_names=output_names,
to_names=[model.input_name],
without_names=[node.name],
)
]
conv_names = [node.name for node in nodes if node.op.lower()[:4] == "conv"]
bottleneck_condition = lambda node: not exists_path(
model,
from_names=[node.name],
to_names=conv_names,
without_names=bottleneck_names,
)
else:
bottleneck_condition = lambda node: True
layer_names = [
node.name
for node in nodes
if shape_condition(node) and op_condition(node) and bottleneck_condition(node)
]
abbreviator = get_abbreviator(layer_names)
if name_contains_one_of is None:
name_condition = lambda name: True
else:
name_condition = lambda name: any(s in name for s in name_contains_one_of)
return OrderedDict(
[(name[abbreviator], name) for name in layer_names if name_condition(name)][
discard_first_n:
]
)
def batched_get(data, batch_size, process_minibatch):
n_points = data.shape[0]
n_minibatches = -((-n_points) // batch_size)
return np.concatenate(
[
process_minibatch(data[i * batch_size : (i + 1) * batch_size])
for i in range(n_minibatches)
],
axis=0,
)
def compute_gae(trajectories, *, gae_gamma, gae_lambda):
values = trajectories["values"]
next_values = values[:, 1:]
rewards = trajectories["rewards"][:, :-1]
try:
dones = trajectories["dones"][:, :-1]
except KeyError:
dones = trajectories["firsts"][:, 1:]
assert next_values.shape == rewards.shape == dones.shape
deltas = rewards + (1 - dones) * gae_gamma * next_values - values[:, :-1]
result = np.zeros(values.shape, values.dtype)
for step in reversed(range(values.shape[1] - 1)):
result[:, step] = (
deltas[:, step]
+ (1 - dones[:, step]) * gae_gamma * gae_lambda * result[:, step + 1]
)
return result
def get_bookmarks(trajectories, *, sign, num):
advantages = trajectories["advantages"]
dones = trajectories["dones"].copy()
dones[:, -1] = np.ones_like(dones[:, -1])
high_scores_and_coords = []
for trajectory in range(advantages.shape[0]):
high_score = 0
high_score_coords = None
for step in range(advantages.shape[1]):
score = advantages[trajectory][step] * sign
if score > high_score:
high_score = score
high_score_coords = (trajectory, step)
if dones[trajectory][step] and high_score_coords is not None:
high_scores_and_coords.append((high_score, high_score_coords))
high_score = 0
high_score_coords = None
high_scores_and_coords.sort(key=lambda x: -x[0])
return list(map(lambda x: x[1], high_scores_and_coords[:num]))
def number_to_string(x):
s = str(x)
if s.endswith(".0"):
s = s[:-2]
return "".join([c for c in s if c.isdigit() or c == "e"])
def get_html_colors(n, grayscale=False, mix_with=None, mix_weight=0.5, **kwargs):
if grayscale:
colors = np.linspace(0, 1, n)[..., None].repeat(3, axis=1)
else:
colors = channels_to_rgb(np.eye(n), **kwargs)
colors = colors / colors.max(axis=-1, keepdims=True)
if mix_with is not None:
colors = colors * (1 - mix_weight) + mix_with[None] * mix_weight
colors = np.round(colors * 255)
colors = np.vectorize(lambda x: hex(x)[2:].zfill(2))(colors.astype(int))
return ["#" + "".join(color) for color in colors]
def removeprefix(s, prefix):
if s.startswith(prefix):
return s[len(prefix) :]
return s
def generate(
*,
output_dir,
model_bytes,
observations,
observations_full=None,
trajectories,
policy_logits_name,
value_function_name,
env_name=None,
numpy_precision=6,
inline_js=True,
inline_large_json=None,
batch_size=512,
action_combos=None,
action_group_fns=[
lambda combo: "RIGHT" in combo,
lambda combo: "LEFT" in combo,
lambda combo: "UP" in combo,
lambda combo: "DOWN" in combo,
lambda combo: "RIGHT" not in combo
and "LEFT" not in combo
and "UP" not in combo
and "DOWN" not in combo,
],
layer_kwargs={},
input_layer_include=False,
input_layer_name="input",
gae_gamma=None,
gae_lambda=None,
trajectory_bookmarks=16,
nmf_features=8,
nmf_attr_opts=None,
vis_subdiv_mults=[0.25, 0.5, 1, 2],
vis_subdiv_mult_default=1,
vis_expand_mults=[1, 2, 4, 8],
vis_expand_mult_default=4,
vis_thumbnail_num_mult=4,
vis_thumbnail_expand_mult=4,
scrub_range=(42 / 64, 44 / 64),
attr_integrate_steps=10,
attr_max_paths=None,
attr_policy=False,
attr_single_channels=True,
observations_subdir="observations/",
trajectories_subdir="trajectories/",
trajectories_scrub_subdir="trajectories_scrub/",
features_subdir="features/",
thumbnails_subdir="thumbnails/",
attribution_subdir="attribution/",
attribution_scrub_subdir="attribution_scrub/",
features_grids_subdir="features_grids/",
attribution_totals_subdir="attribution_totals/",
video_height="16em",
video_width="16em",
video_speed=12,
policy_display_height="2em",
policy_display_width="40em",
navigator_width="24em",
scrubber_height="4em",
scrubber_width="48em",
scrubber_visible_duration=256,
legend_item_height="6em",
legend_item_width="6em",
feature_viewer_height="40em",
feature_viewer_width="40em",
attribution_weight=0.9,
graph_colors={
"v": "green",
"action": "red",
"action_group": "orange",
"advantage": "blue",
},
trajectory_color="blue",
):
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
model = get_model(model_bytes)
if rank == 0:
js_source_path = get_compiled_js()
if env_name is None:
env_name = "unknown"
if inline_large_json is None:
inline_large_json = "://" not in output_dir
layer_kwargs.setdefault("name_contains_one_of", None)
layer_kwargs.setdefault("op_is_one_of", ["relu"])
layer_kwargs.setdefault("bottleneck_only", True)
layer_kwargs.setdefault("discard_first_n", 0)
if observations_full is None:
observations_full = observations
if "observations_full" not in trajectories:
trajectories["observations_full"] = trajectories["observations"]
if np.issubdtype(observations.dtype, np.integer):
observations = observations / np.float32(255)
if np.issubdtype(observations_full.dtype, np.integer):
observations_full = observations_full / np.float32(255)
if np.issubdtype(trajectories["observations"].dtype, np.integer):
trajectories["observations"] = trajectories["observations"] / np.float32(255)
if np.issubdtype(trajectories["observations_full"].dtype, np.integer):
trajectories["observations_full"] = trajectories[
"observations_full"
] / np.float32(255)
if action_combos is None:
num_actions = get_shape(model, policy_logits_name)[-1]
action_combos = list(map(lambda x: (str(x),), range(num_actions)))
if env_name == "coinrun_old":
action_combos = [
(),
("RIGHT",),
("LEFT",),
("UP",),
("RIGHT", "UP"),
("LEFT", "UP"),
("DOWN",),
("A",),
("B",),
][:num_actions]
if gae_gamma is None:
gae_gamma = 0.999
if gae_lambda is None:
gae_lambda = 0.95
layer_names = get_layer_names(
model, [policy_logits_name, value_function_name], **layer_kwargs
)
if not layer_names:
raise RuntimeError(
"No appropriate layers found. "
"Please adapt layer_kwargs to your architecture"
)
squash = lambda s: s.replace("/", "").replace("_", "")
if len(set([squash(layer_key) for layer_key in layer_names.keys()])) < len(
layer_names
):
raise RuntimeError(
"Error squashing abbreviated layer names. "
"Different substitutions must be used"
)
mpi_enumerate = lambda l: (
lambda indices: list(enumerate(l))[indices[rank] : indices[rank + 1]]
)(np.linspace(0, len(l), comm.Get_size() + 1).astype(int))
save_image = lambda image, path: save(
image, os.path.join(output_dir, path), domain=(0, 1)
)
save_images = lambda images, path: save_image(
concatenate_horizontally(images), path
)
json_preloaded = {}
save_json = lambda data, path: (
json_preloaded.update({path: data})
if inline_large_json
else save(data, os.path.join(output_dir, path), indent=None)
)
get_scrub_slice = lambda width: slice(
int(np.round(scrub_range[0] * width)),
int(
np.maximum(
np.round(scrub_range[1] * width), np.round(scrub_range[0] * width) + 1
)
),
)
action_groups = [
[action for action, combo in enumerate(action_combos) if group_fn(combo)]
for group_fn in action_group_fns
]
action_groups = list(
filter(lambda action_group: len(action_group) > 1, action_groups)
)
for index, observation in mpi_enumerate(observations_full):
observation_path = os.path.join(observations_subdir, f"{index}.png")
save_image(observation, observation_path)
for index, trajectory_observations in mpi_enumerate(
trajectories["observations_full"]
):
trajectory_path = os.path.join(trajectories_subdir, f"{index}.png")
save_images(trajectory_observations, trajectory_path)
scrub_slice = get_scrub_slice(trajectory_observations.shape[2])
scrub = trajectory_observations[:, :, scrub_slice, :]
scrub_path = os.path.join(trajectories_scrub_subdir, f"{index}.png")
save_images(scrub, scrub_path)
trajectories["policy_logits"] = []
trajectories["values"] = []
for trajectory_observations in trajectories["observations"]:
trajectories["policy_logits"].append(
batched_get(
trajectory_observations,
batch_size,
lambda minibatch: get_acts(model, policy_logits_name, minibatch),
)
)
trajectories["values"].append(
batched_get(
trajectory_observations,
batch_size,
lambda minibatch: get_acts(model, value_function_name, minibatch),
)
)
trajectories["policy_logits"] = np.array(trajectories["policy_logits"])
trajectories["values"] = np.array(trajectories["values"])
trajectories["advantages"] = compute_gae(
trajectories, gae_gamma=gae_gamma, gae_lambda=gae_lambda
)
if "dones" not in trajectories:
trajectories["dones"] = np.concatenate(
[
trajectories["firsts"][:, 1:],
np.zeros_like(trajectories["firsts"][:, :1]),
],
axis=-1,
)
bookmarks = {
"high": get_bookmarks(trajectories, sign=1, num=trajectory_bookmarks),
"low": get_bookmarks(trajectories, sign=-1, num=trajectory_bookmarks),
}
nmf_kwargs = {"attr_layer_name": value_function_name}
if nmf_attr_opts is not None:
nmf_kwargs["attr_opts"] = nmf_attr_opts
nmfs = {
layer_key: LayerNMF(
model,
layer_name,
observations,
obses_full=observations_full,
features=nmf_features,
**nmf_kwargs,
)
for layer_key, layer_name in layer_names.items()
}
features = []
attributions = []
attribution_totals = []
for layer_key, layer_name in layer_names.items():
nmf = nmfs[layer_key]
if rank == 0:
thumbnails = []
for number in range(nmf.features):
thumbnail = nmf.vis_dataset_thumbnail(
number,
num_mult=vis_thumbnail_num_mult,
expand_mult=vis_thumbnail_expand_mult,
)[0]
thumbnail = rescale_opacity(thumbnail, max_scale=1, keep_zeros=True)
thumbnails.append(thumbnail)
thumbnails_path = os.path.join(
thumbnails_subdir, f"{squash(layer_key)}.png"
)
save_images(thumbnails, thumbnails_path)
for _, number in mpi_enumerate(range(nmf.features)):
feature = {
"layer": layer_key,
"number": number,
"images": [],
"overlay_grids": [],
"metadata": {"subdiv_mult": [], "expand_mult": []},
}
for subdiv_mult in vis_subdiv_mults:
for expand_mult in vis_expand_mults:
image, overlay_grid = nmf.vis_dataset(
number, subdiv_mult=subdiv_mult, expand_mult=expand_mult
)
image = rescale_opacity(image)
filename_root = (
f"{squash(layer_key)}_"
f"feature{number}_"
f"{number_to_string(subdiv_mult)}_"
f"{number_to_string(expand_mult)}"
)
image_filename = filename_root + ".png"
overlay_grid_filename = filename_root + ".json"
image_path = os.path.join(features_subdir, image_filename)
overlay_grid_path = os.path.join(
features_grids_subdir, overlay_grid_filename
)
save_image(image, image_path)
save_json(overlay_grid, overlay_grid_path)
feature["images"].append(image_filename)
feature["overlay_grids"].append(overlay_grid_filename)
feature["metadata"]["subdiv_mult"].append(subdiv_mult)
feature["metadata"]["expand_mult"].append(expand_mult)
features.append(feature)
for layer_key, layer_name in (
[(input_layer_name, None)] if input_layer_include else []
) + list(layer_names.items()):
if layer_name is None:
nmf = None
else:
nmf = nmfs[layer_key]
for index, trajectory_observations in mpi_enumerate(
trajectories["observations"]
):
attribution = {
"layer": layer_key,
"trajectory": index,
"images": [],
"metadata": {"type": [], "data": [], "direction": [], "channel": []},
}
if layer_name is not None:
totals = {
"layer": layer_key,
"trajectory": index,
"channels": [],
"residuals": [],
"metadata": {"type": [], "data": []},
}
def get_attr_minibatch(
minibatch, output_name, *, score_fn=default_score_fn
):
if layer_name is None:
return get_grad(model, output_name, minibatch, score_fn=score_fn)
elif attr_max_paths is None:
return get_attr(
model,
output_name,
layer_name,
minibatch,
score_fn=score_fn,
integrate_steps=attr_integrate_steps,
)
else:
return get_multi_path_attr(
model,
output_name,
layer_name,
minibatch,
nmf,
score_fn=score_fn,
integrate_steps=attr_integrate_steps,
max_paths=attr_max_paths,
)
def get_attr_batched(output_name, *, score_fn=default_score_fn):
return batched_get(
trajectory_observations,
batch_size,
lambda minibatch: get_attr_minibatch(
minibatch, output_name, score_fn=score_fn
),
)
def transform_attr(attr):
if layer_name is None:
return attr, None
else:
attr_trans = nmf.transform(np.maximum(attr, 0)) - nmf.transform(
np.maximum(-attr, 0)
)
attr_res = (
attr
- (
nmf.inverse_transform(np.maximum(attr_trans, 0))
- nmf.inverse_transform(np.maximum(-attr_trans, 0))
)
).sum(-1, keepdims=True)
nmf_norms = nmf.channel_dirs.sum(-1)
return attr_trans * nmf_norms[None, None, None], attr_res
def save_attr(attr, attr_res, *, type_, data):
if attr_res is None:
attr_res = np.zeros_like(attr).sum(-1, keepdims=True)
filename_root = f"{squash(layer_key)}_{index}_{type_}"
if data is not None:
filename_root = f"{filename_root}_{data}"
if layer_name is not None:
channels_filename = f"{filename_root}_channels.json"
residuals_filename = f"{filename_root}_residuals.json"
channels_path = os.path.join(
attribution_totals_subdir, channels_filename
)
residuals_path = os.path.join(
attribution_totals_subdir, residuals_filename
)
save_json(attr.sum(-2).sum(-2), channels_path)
save_json(attr_res[..., 0].sum(-1).sum(-1), residuals_path)
totals["channels"].append(channels_filename)
totals["residuals"].append(residuals_filename)
totals["metadata"]["type"].append(type_)
totals["metadata"]["data"].append(data)
attr_scale = np.median(attr.max(axis=(-3, -2, -1)))
if attr_scale == 0:
attr_scale = attr.max()
if attr_scale == 0:
attr_scale = 1
attr_scaled = attr / attr_scale
attr_res_scaled = attr_res / attr_scale
channels = ["prin", "all"]
if attr_single_channels and layer_name is not None:
channels += list(range(nmf.features)) + ["res"]
for direction in ["abs", "pos", "neg"]:
if direction == "abs":
attr = np.abs(attr_scaled)
attr_res = np.abs(attr_res_scaled)
elif direction == "pos":
attr = np.maximum(attr_scaled, 0)
attr_res = np.maximum(attr_res_scaled, 0)
elif direction == "neg":
attr = np.maximum(-attr_scaled, 0)
attr_res =
|
np.maximum(-attr_res_scaled, 0)
|
numpy.maximum
|
import torch
import numpy as np
from tqdm import tqdm
from data.imagenet.move import move_file
from torchvision import datasets, transforms
from data.voc.voc_dataset import VOC_CLASSES
from sklearn.metrics import average_precision_score
from data.voc.voc_dataloader import get_voc_dataloader
from torchvision.datasets import VOCSegmentation as VOC
def fetch_dataloader(dataset, path, batch_size):
if dataset == "voc":
VOC(path, "2012", "train", True)
train = get_voc_dataloader('train', batch_size)
val = get_voc_dataloader('val', batch_size)
test = get_voc_dataloader('test', batch_size)
elif dataset == "ImageNet":
move_file()
normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
train = torch.utils.data.DataLoader(
datasets.ImageNet(
root=path,
split="train",
transform=transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])),
batch_size=batch_size,
num_workers=4,
shuffle=True, pin_memory=True, drop_last=True)
val = torch.utils.data.DataLoader(
datasets.ImageNet(
root=path,
split="val",
transform=transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])),
batch_size=batch_size,
num_workers=4,
shuffle=True, pin_memory=True, drop_last=False)
test = torch.utils.data.DataLoader(
datasets.ImageFolder(
root=path,
split="val",
transform=transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])),
batch_size=batch_size,
num_workers=4,
shuffle=False, pin_memory=True, drop_last=False)
else:
raise NameError("This dataset is not supported.")
return train, val, test
def test_imagenet(test_iter, model, criterion, device):
model.eval()
test_loss = 0
with torch.no_grad():
y_true = np.zeros((0, 1000))
y_score = np.zeros((0, 1000))
for src, tgt in tqdm(test_iter):
src = src.to(device)
tgt = tgt.to(device)
logits = model(src)
y_true = np.concatenate((y_true, tgt.cpu().numpy()), axis=0)
y_score = np.concatenate((y_score, logits.cpu().numpy()), axis=0)
loss = criterion(logits, tgt)
test_loss += loss.item()
aps = []
for i in range(1, y_true.shape[1]):
ap = average_precision_score(y_true[:, i], y_score[:, i])
aps.append(ap)
mAP = np.mean(aps)
test_loss /= len(test_iter)
print(
f"Test Loss: {round(test_loss, 3)}, Test Accuracy: {round(mAP,3)}")
def test_voc(test_iter, model, device):
model.eval()
print("Testing...")
with torch.no_grad():
y_true = np.zeros((0, 21))
y_score =
|
np.zeros((0, 21))
|
numpy.zeros
|
import os
import sys
import gc
import numpy as np
import pandas as pd
import math
import scipy.stats as scst
import scipy as sp
import scipy.linalg as la
from bgen_reader import read_bgen
import qtl_loader_utils
import pdb
from glimix_core.lmm import LMM
def run_QTL_analysis_load_intersect_phenotype_covariates_kinship_sample_mapping(pheno_filename, anno_filename, geno_prefix,
plinkGenotype, minimum_test_samples= 10, relatedness_score=None, cis_mode=True, skipAutosomeFiltering = False, snps_filename=None,
feature_filename=None, snp_feature_filename=None, selection='all', covariates_filename=None, randomeff_filename=None,
sample_mapping_filename=None, extended_anno_filename=None, feature_variant_covariate_filename=None):
# pheno_filename = "/Users/chaaya/dhonveli_dkfz/hipsci_pipeline/geuvadis_CEU_test_data/Expression/Geuvadis_CEU_YRI_Expr.txt.gz"
# anno_filename = "/Users/chaaya/dhonveli_dkfz/hipsci_pipeline/geuvadis_CEU_test_data/Expression/Geuvadis_CEU_Annot.txt"
# geno_prefix = "/Users/chaaya/dhonveli_dkfz/limix_qtl/limix_qtl-master/Limix_QTL/test_data/Genotypes/Geuvadis"
# plinkGenotype = "/Users/chaaya/dhonveli_dkfz/limix_qtl/limix_qtl-master/Limix_QTL/test_data/Genotypes/Geuvadis"
# minimum_test_samples = 10
# relatedness_score = 0.95
# cis_mode = True
# skipAutosomeFiltering = False
# snps_filename = None
# feature_filename = None
# snp_feature_filename = None
# selection = 'all'
# covariates_filename = "/Users/chaaya/dhonveli_dkfz/limix_qtl/limix_qtl-master/Limix_QTL/test_data/Expression/Geuvadis_CEU_YRI_covariates.txt"
# randomeff_filename = "/Users/chaaya/dhonveli_dkfz/limix_qtl/limix_qtl-master/Limix_QTL/test_data/Genotypes/Geuvadis_chr1_kinship.normalized.txt,/Users/chaaya/dhonveli_dkfz/limix_qtl/limix_qtl-master/Limix_QTL/test_data/Genotypes/Geuvadis_readdepth.txt"
# sample_mapping_filename = "/Users/chaaya/dhonveli_dkfz/limix_qtl/limix_qtl-master/Limix_QTL/test_data/Geuvadis_CEU_gte.txt"
# extended_anno_filename = None
# feature_variant_covariate_filename = None
# output_dir = "/Users/chaaya/dhonveli_dkfz/limix_qtl/limix_qtl-master/Limix_QTL/test_data/Output2/"
# window_size = 250000
# min_maf = 0.05
# min_hwe_P = 0.001
# min_call_rate = 0.95
# blocksize = 1000
# gaussianize_method = None
# genetic_range = "all"
# seed = np.random.randint(40000)
# n_perm = 0
# write_permutations = False
# regressCovariatesUpfront = False
# write_feature_top_permutations = False
# selection based on coordinates
selectionStart = None
selectionEnd = None
if(":" in selection):
parts = selection.split(":")
if("-" not in parts[1]):
print("No correct sub selection.")
print("Given in: "+selection)
print("Expected format: (chr number):(start location)-(stop location)")
sys.exit()
chromosome = parts[0]
if("-" in parts[1]):
parts2 = parts[1].split("-")
selectionStart = int(parts2[0])
selectionEnd = int(parts2[1])
else :
chromosome=selection
''' function to take input and intersect sample and genotype.'''
#Load input data files & filter for relevant data
#Load input data filesf
# loading phenotype and annotation files
phenotype_df = qtl_loader_utils.get_phenotype_df(pheno_filename)
annotation_df = qtl_loader_utils.get_annotation_df(anno_filename)
phenotype_df.columns = phenotype_df.columns.astype("str")
phenotype_df.index = phenotype_df.index.astype("str")
annotation_df.columns = annotation_df.columns.astype("str")
annotation_df.index = annotation_df.index.astype("str")
# loading genotype
if(plinkGenotype):
bim,fam,bed = qtl_loader_utils.get_genotype_data(geno_prefix)
bgen=None
else :
bgen = read_bgen(geno_prefix+'.bgen', verbose=False)
bed=None
fam =bgen['samples']
fam = fam.to_frame("iid")
fam.index=fam["iid"]
bim = bgen['variants'].compute()
bim = bim.assign(i = range(bim.shape[0]))
bim['id'] = bim['rsid']
bim = bim.rename(index=str, columns={"id": "snp"})
bim['a1'] = bim['allele_ids'].str.split(",", expand=True)[0]
bim.index = bim["snp"].astype(str).values
bim.index.name = "candidate"
##Fix chromosome ids
bim['chrom'].replace('^chr','',regex=True,inplace=True)
bim['chrom'].replace(['X', 'Y', 'XY', 'MT'], ['23', '24', '25', '26'],inplace=True)
##Remove non-biallelic & non-ploidy 2 (to be sure).
print("Warning, the current software only supports biallelic SNPs and ploidy 2")
bim.loc[np.logical_and(bim['nalleles']<3,bim['nalleles']>0),:]
# converting chromsome names
annotation_df.replace(['X', 'Y', 'XY', 'MT'], ['23', '24', '25', '26'],inplace=True)
if chromosome=='X' :
chromosome = '23'
elif chromosome=='Y':
chromosome = '24'
elif chromosome=='XY':
chromosome='25'
elif chromosome=='MT':
chromosome='26'
print("Intersecting data.")
if(annotation_df.shape[0] != annotation_df.groupby(annotation_df.index).first().shape[0]):
print("Only one location per feature supported. If multiple locations are needed please look at: --extended_anno_file")
sys.exit()
##Make sure that there is only one entry per feature id!.
sample2individual_df = qtl_loader_utils.get_samplemapping_df(sample_mapping_filename,list(phenotype_df.columns),'sample')
sample2individual_df.index = sample2individual_df.index.astype('str')
sample2individual_df = sample2individual_df.astype('str')
sample2individual_df['sample']=sample2individual_df.index
sample2individual_df = sample2individual_df.drop_duplicates();
##Filter first the linking files!
#Subset linking to relevant genotypes.
orgSize = sample2individual_df.shape[0]
sample2individual_df = sample2individual_df.loc[sample2individual_df['iid'].map(lambda x: x in list(map(str, fam.index))),:]
diff = orgSize- sample2individual_df.shape[0]
orgSize = sample2individual_df.shape[0]
print("Dropped: "+str(diff)+" samples because they are not present in the genotype file.")
#Subset linking to relevant phenotypes.
sample2individual_df = sample2individual_df.loc[np.intersect1d(sample2individual_df.index,phenotype_df.columns),:]
diff = orgSize- sample2individual_df.shape[0]
orgSize = sample2individual_df.shape[0]
print("Dropped: "+str(diff)+" samples because they are not present in the phenotype file.")
#Subset linking vs kinship.
kinship_df = None
readdepth_df = None
if randomeff_filename is not None:
kinship_df,readdepth_df = qtl_loader_utils.get_randeff_df(randomeff_filename)
if kinship_df is not None:
#Filter from individual2sample_df & sample2individual_df since we don't want to filter from the genotypes.
sample2individual_df = sample2individual_df[sample2individual_df['iid'].map(lambda x: x in list(map(str, kinship_df.index)))]
diff = orgSize- sample2individual_df.shape[0]
orgSize = sample2individual_df.shape[0]
print("Dropped: "+str(diff)+" samples because they are not present in the kinship file.")
if readdepth_df is not None:
#This needs to come from the covariate site not the genotype side!
#Filter from individual2sample_df & sample2individual_df since we don't want to filter from the genotypes.
sample2individual_df = sample2individual_df[sample2individual_df['sample'].map(lambda x: x in list(map(str, readdepth_df.index)))]
diff = orgSize- sample2individual_df.shape[0]
orgSize = sample2individual_df.shape[0]
print("Dropped: "+str(diff)+" samples because they are not present in the second random effect file.")
#Subset linking vs covariates.
covariate_df = qtl_loader_utils.get_covariate_df(covariates_filename)
if covariate_df is not None:
if np.nansum(covariate_df==1,0).max()<covariate_df.shape[0]: covariate_df.insert(0, 'ones', np.ones(covariate_df.shape[0]))
sample2individual_df = sample2individual_df.loc[list(set(sample2individual_df.index) & set(covariate_df.index)),:]
diff = orgSize- sample2individual_df.shape[0]
orgSize = sample2individual_df.shape[0]
print("Dropped: "+str(diff)+" samples because they are not present in the covariate file.")
###
print("Number of samples with genotype & phenotype data: " + str(sample2individual_df.shape[0]))
if(sample2individual_df.shape[0]<minimum_test_samples):
print("Not enough samples with both genotype & phenotype data.")
sys.exit()
##Filter now the actual data!
#Filter phenotype data based on the linking files.
phenotype_df = phenotype_df.loc[list(set(phenotype_df.index)&set(annotation_df.index)),sample2individual_df.index.values]
#Filter kinship data based on the linking files.
genetically_unique_individuals = None
if kinship_df is not None:
kinship_df = kinship_df.loc[np.intersect1d(kinship_df.index,sample2individual_df['iid']),np.intersect1d(kinship_df.index,sample2individual_df['iid'])]
if (kinship_df is not None) and (relatedness_score is not None):
genetically_unique_individuals = get_unique_genetic_samples(kinship_df, relatedness_score);
#Filter covariate data based on the linking files.
snp_feature_filter_df= qtl_loader_utils.get_snp_feature_df(snp_feature_filename)
try:
feature_filter_df = qtl_loader_utils.get_snp_df(feature_filename)
except:
if feature_filename is not None:
feature_filter_df=pd.DataFrame(index=feature_filename)
#Do filtering on features.
if feature_filter_df is not None:
phenotype_df = phenotype_df.loc[feature_filter_df.index,:]
##Filtering on features to test.
if snp_feature_filter_df is not None:
lst3 = set(phenotype_df.index).intersection(np.unique(snp_feature_filter_df['feature_id']))
phenotype_df = phenotype_df.loc[lst3,:]
##Filtering on features to test from the combined feature snp filter.
if ((not cis_mode) and len(set(bim['chrom']))<22) :
print("Warning, running a trans-analysis on snp data from less than 22 chromosomes.\nTo merge data later the permutation P-values need to be written out.")
if(cis_mode):
#Remove features from the annotation that are on chromosomes which are not present anyway.
annotation_df = annotation_df[np.in1d(annotation_df['chromosome'],list(set(bim['chrom'])))]
#Prepare to filter on snps.
snp_filter_df = qtl_loader_utils.get_snp_df(snps_filename)
if snp_filter_df is not None:
toSelect = set(snp_filter_df.index).intersection(set(bim['snp']))
bim = bim.loc[bim['snp'].isin(toSelect)]
##Filtering on SNPs to test from the snp filter.
if snp_feature_filter_df is not None:
toSelect = set(np.unique(snp_feature_filter_df['snp_id'])).intersection(set(bim['snp']))
bim = bim.loc[bim['snp'].isin(toSelect)]
##Filtering on features to test from the combined feature snp filter.
#Filtering for sites on non allosomes.
if not skipAutosomeFiltering :
annotation_df = annotation_df[annotation_df['chromosome'].map(lambda x: x in list(map(str, range(1, 23))))]
#Determine features to be tested
if chromosome=='all':
feature_list = list(set(annotation_df.index)&set(phenotype_df.index))
else:
if not selectionStart is None :
lowest = min([selectionStart,selectionEnd])
highest = max([selectionStart,selectionEnd])
annotation_df['mean'] = ((annotation_df["start"] + annotation_df["end"])/2)
feature_list = list(set(annotation_df.iloc[(annotation_df['chromosome'].values==chromosome) & (annotation_df['mean'].values>=lowest) & (annotation_df["mean"].values<highest)].index.values)&set(phenotype_df.index))
del annotation_df['mean']
else :
feature_list = list(set(annotation_df[annotation_df['chromosome']==chromosome].index)&set(phenotype_df.index))
#Drop not used feature information.
phenotype_df = phenotype_df.loc[feature_list,:]
gc.collect()
print("Number of features to be tested: " + str(len(feature_list)))
print("Total number of variants to be considered, before variante QC and feature intersection: " + str(bim.shape[0]))
if(phenotype_df.shape[1]<minimum_test_samples):
print("Not enough samples with both genotype & phenotype data, for current number of covariates.")
sys.exit()
if extended_anno_filename is not None:
complete_annotation_df = pd.read_csv(extended_anno_filename,sep='\t',index_col=0)
annotation_df['index']=annotation_df.index
complete_annotation_df['index']=complete_annotation_df.index
complete_annotation_df = pd.concat([annotation_df,complete_annotation_df]).drop_duplicates()
del complete_annotation_df['index']
else:
complete_annotation_df = annotation_df
feature_variant_covariate_df = qtl_loader_utils.get_snp_feature_df(feature_variant_covariate_filename)
if len(bim["snp"].values) > len(set(bim["snp"].values)):
print("Warning duplicated SNP ids (After filtering if applied).")
print("Removing variants observed twice.")
bim = bim[bim["snp"].value_counts()==1]
return [phenotype_df, kinship_df,readdepth_df, covariate_df, sample2individual_df, complete_annotation_df, annotation_df, snp_filter_df,
snp_feature_filter_df, genetically_unique_individuals, minimum_test_samples, feature_list, bim, fam, bed, bgen, chromosome,
selectionStart, selectionEnd, feature_variant_covariate_df]
def run_structLMM_QTL_analysis_load_intersect_phenotype_environments_covariates_kinship_sample_mapping\
(pheno_filename, anno_filename, env_filename, geno_prefix, plinkGenotype,
cis_mode = True, association_mode = True, skipAutosomeFiltering = False, minimum_test_samples = 10,
relatedness_score = 0.95, snps_filename = None, feature_filename = None,
snp_feature_filename = None, selection = 'all', covariates_filename = None, kinship_filename = None,
sample_mapping_filename = None, extended_anno_filename = None, feature_variant_covariate_filename = None):
selectionStart = None
selectionEnd = None
if(":" in selection):
parts = selection.split(":")
if("-" not in parts[1]):
print("No correct sub selection.")
print("Given in: "+selection)
print("Expected format: (chr number):(start location)-(stop location)")
sys.exit()
chromosome = parts[0]
if("-" in parts[1]):
parts2 = parts[1].split("-")
selectionStart = int(parts2[0])
selectionEnd = int(parts2[1])
else :
chromosome=selection
''' function to take input and intersect sample and genotype.'''
#Load input data files & filter for relevant data
#Load input data filesf
phenotype_df = qtl_loader_utils.get_phenotype_df(pheno_filename)
annotation_df = qtl_loader_utils.get_annotation_df(anno_filename)
if(plinkGenotype):
bim,fam,bed = qtl_loader_utils.get_genotype_data(geno_prefix)
annotation_df.replace(['X', 'Y', 'XY', 'MT'], ['23', '24', '25', '26'],inplace=True)
if chromosome=='X' :
chromosome = '23'
elif chromosome=='Y':
chromosome = '24'
elif chromosome=='XY':
chromosome='25'
elif chromosome=='MT':
chromosome='26'
#X -> 23
#Y -> 24
#XY -> 25
#MT -> 26
else :
geno_prefix+='.bgen'
print(geno_prefix)
print("Intersecting data.")
if(annotation_df.shape[0] != annotation_df.groupby(annotation_df.index).first().shape[0]):
print("Only one location per feature supported. If multiple locations are needed please look at: --extended_anno_file")
sys.exit()
##Make sure that there is only one entry per feature id!.
sample2individual_df = qtl_loader_utils.get_samplemapping_df(sample_mapping_filename,list(phenotype_df.columns),'sample')
sample2individual_df['sample']=sample2individual_df.index
sample2individual_df = sample2individual_df.drop_duplicates();
##Filter first the linking files!
#Subset linking to relevant genotypes.
orgSize = sample2individual_df.shape[0]
sample2individual_df = sample2individual_df.loc[sample2individual_df['iid'].map(lambda x: x in list(map(str, fam.index))),:]
diff = orgSize- sample2individual_df.shape[0]
orgSize = sample2individual_df.shape[0]
print("Dropped: "+str(diff)+" samples because they are not present in the genotype file.")
#Subset linking to relevant phenotypes.
sample2individual_df = sample2individual_df.loc[np.intersect1d(sample2individual_df.index,phenotype_df.columns),:]
diff = orgSize- sample2individual_df.shape[0]
orgSize = sample2individual_df.shape[0]
print("Dropped: "+str(diff)+" samples because they are not present in the phenotype file.")
#Subset linking vs kinship.
kinship_df = qtl_loader_utils.get_kinship_df(kinship_filename)
if kinship_df is not None:
#Filter from individual2sample_df & sample2individual_df since we don't want to filter from the genotypes.
sample2individual_df = sample2individual_df[sample2individual_df['iid'].map(lambda x: x in list(map(str, kinship_df.index)))]
diff = orgSize- sample2individual_df.shape[0]
orgSize = sample2individual_df.shape[0]
print("Dropped: "+str(diff)+" samples because they are not present in the kinship file.")
#Subset linking vs covariates.
covariate_df = qtl_loader_utils.get_covariate_df(covariates_filename)
if covariate_df is not None:
if np.nansum(covariate_df==1,0).max()<covariate_df.shape[0]: covariate_df.insert(0, 'ones',np.ones(covariate_df.shape[0]))
sample2individual_df = sample2individual_df.loc[list(set(sample2individual_df.index) & set(covariate_df.index)),:]
diff = orgSize- sample2individual_df.shape[0]
orgSize = sample2individual_df.shape[0]
print("Dropped: "+str(diff)+" samples because they are not present in the covariate file.")
#Subset linking vs environments.
environment_df = qtl_loader_utils.get_env_df(env_filename)
if np.nansum(environment_df==1,0).max()<environment_df.shape[0]: environment_df.insert(0, 'ones',np.ones(environment_df.shape[0]))
sample2individual_df = sample2individual_df.loc[list(set(sample2individual_df.index) & set(environment_df.index)),:]
diff = orgSize - sample2individual_df.shape[0]
orgSize = sample2individual_df.shape[0]
print("Dropped: "+str(diff)+" samples because they are not present in the environment file.")
###
print("Number of samples with genotype & phenotype data: " + str(sample2individual_df.shape[0]))
if(sample2individual_df.shape[0]<minimum_test_samples):
print("Not enough samples with both genotype & phenotype data.")
sys.exit()
##Filter now the actual data!
#Filter phenotype data based on the linking files.
phenotype_df = phenotype_df.loc[list(set(phenotype_df.index)&set(annotation_df.index)),sample2individual_df.index.values]
#Filter kinship data based on the linking files.
genetically_unique_individuals = None
if kinship_df is not None:
kinship_df = kinship_df.loc[np.intersect1d(kinship_df.index,sample2individual_df['iid']),np.intersect1d(kinship_df.index,sample2individual_df['iid'])]
genetically_unique_individuals = get_unique_genetic_samples(kinship_df, relatedness_score);
#Filter covariate data based on the linking files.
if covariate_df is not None:
covariate_df = covariate_df.loc[np.intersect1d(covariate_df.index,sample2individual_df.index.values),:]
snp_feature_filter_df= qtl_loader_utils.get_snp_feature_df(snp_feature_filename)
try:
feature_filter_df = qtl_loader_utils.get_snp_df(feature_filename)
except:
if feature_filename is not None:
feature_filter_df=pd.DataFrame(index=feature_filename)
#Do filtering on features.
if feature_filter_df is not None:
phenotype_df = phenotype_df.loc[feature_filter_df.index,:]
##Filtering on features to test.
if snp_feature_filter_df is not None:
phenotype_df = phenotype_df.loc[np.unique(snp_feature_filter_df['feature']),:]
##Filtering on features to test from the combined feature snp filter.
if ((not cis_mode) and len(set(bim['chrom']))<22) :
print("Warning, running a trans-analysis on snp data from less than 22 chromosomes.\nTo merge data later the permutation P-values need to be written out.")
if(cis_mode):
#Remove features from the annotation that are on chromosomes which are not present anyway.
annotation_df = annotation_df[np.in1d(annotation_df['chromosome'],list(set(bim['chrom'])))]
#Prepare to filter on snps.
snp_filter_df = qtl_loader_utils.get_snp_df(snps_filename)
if snp_filter_df is not None:
toSelect = set(snp_filter_df.index).intersection(set(bim['snp']))
bim = bim.loc[bim['snp'].isin(toSelect)]
##Filtering on SNPs to test from the snp filter.
if snp_feature_filter_df is not None:
toSelect = set(np.unique(snp_feature_filter_df['snp_id'])).intersection(set(bim['snp']))
bim = bim.loc[bim['snp'].isin(toSelect)]
##Filtering on features to test from the combined feature snp filter.
#Filtering for sites on non allosomes.
if not skipAutosomeFiltering :
annotation_df = annotation_df[annotation_df['chromosome'].map(lambda x: x in list(map(str, range(1, 23))))]
#Determine features to be tested
if chromosome=='all':
feature_list = list(set(annotation_df.index)&set(phenotype_df.index))
else:
if not selectionStart is None :
lowest = min([selectionStart,selectionEnd])
highest = max([selectionStart,selectionEnd])
annotation_df['mean'] = ((annotation_df["start"] + annotation_df["end"])/2)
feature_list = list(set(annotation_df.iloc[(annotation_df['chromosome'].values==chromosome) & (annotation_df['mean'].values>=lowest) & (annotation_df["mean"].values<highest)].index.values)&set(phenotype_df.index))
del annotation_df['mean']
else :
feature_list = list(set(annotation_df[annotation_df['chromosome']==chromosome].index)&set(phenotype_df.index))
print("Number of features to be tested: " + str(len(feature_list)))
print("Total number of variants to be considered, before variante QC and feature intersection: " + str(bim.shape[0]))
if(phenotype_df.shape[1]<minimum_test_samples):
print("Not enough samples with both genotype & phenotype data, for current number of covariates.")
sys.exit()
if extended_anno_filename is not None:
complete_annotation_df = pd.read_csv(extended_anno_filename,sep='\t',index_col=0)
annotation_df['index']=annotation_df.index
complete_annotation_df['index']=complete_annotation_df.index
complete_annotation_df = pd.concat([annotation_df,complete_annotation_df]).drop_duplicates()
del complete_annotation_df['index']
else:
complete_annotation_df = annotation_df
feature_variant_covariate_df = qtl_loader_utils.get_snp_feature_df(feature_variant_covariate_filename)
return [phenotype_df, kinship_df, covariate_df, environment_df, sample2individual_df, complete_annotation_df, annotation_df, snp_filter_df, snp_feature_filter_df, genetically_unique_individuals, minimum_test_samples, feature_list,bim,fam,bed, chromosome, selectionStart, selectionEnd, feature_variant_covariate_df]
def run_PrsQtl_analysis_load_intersect_phenotype_covariates_kinship_sample_mapping\
(pheno_filename, anno_filename, prsFile, minimum_test_samples= 10, relatedness_score=0.95, skipAutosomeFiltering = False, snps_filename=None,
feature_filename=None, snp_feature_filename=None, selection='all', covariates_filename=None, kinship_filename=None, sample_mapping_filename=None, feature_variant_covariate_filename=None):
selectionStart = None
selectionEnd = None
if(":" in selection):
parts = selection.split(":")
if("-" not in parts[1]):
print("No correct sub selection.")
print("Given in: "+selection)
print("Expected format: (chr number):(start location)-(stop location)")
sys.exit()
chromosome = parts[0]
if("-" in parts[1]):
parts2 = parts[1].split("-")
selectionStart = int(parts2[0])
selectionEnd = int(parts2[1])
else :
chromosome=selection
''' function to take input and intersect sample and genotype.'''
#Load input data files & filter for relevant data
#Load input data filesf
#import pdb; pdb.set_trace();
phenotype_df = qtl_loader_utils.get_phenotype_df(pheno_filename)
annotation_df = qtl_loader_utils.get_annotation_df(anno_filename)
phenotype_df.columns = phenotype_df.columns.astype("str")
phenotype_df.index = phenotype_df.index.astype("str")
annotation_df.columns = annotation_df.columns.astype("str")
annotation_df.index = annotation_df.index.astype("str")
if(annotation_df.shape[0] != annotation_df.groupby(annotation_df.index).first().shape[0]):
print("Only one location per feature supported. If multiple locations are needed please look at: --extended_anno_file")
sys.exit()
#Determine features to be tested
if chromosome!='all':
if not selectionStart is None :
lowest = min([selectionStart,selectionEnd])
highest = max([selectionStart,selectionEnd])
annotation_df['mean'] = ((annotation_df["start"] + annotation_df["end"])/2)
feature_list = list(set(annotation_df.iloc[(annotation_df['chromosome'].values==chromosome) & (annotation_df['mean'].values>=lowest) & (annotation_df["mean"].values<highest)].index.values))
annotation_df = annotation_df.loc[feature_list,]
del annotation_df['mean']
else :
feature_list = list(annotation_df[annotation_df['chromosome']==chromosome].index)
annotation_df = annotation_df.loc[feature_list,]
#To be able to read variants from a large file we change the loading here.
#First we subset the genes to the chunk and get the relevant SNPs based on that.
snp_feature_filter_df= qtl_loader_utils.get_snp_feature_df(snp_feature_filename)
feature_filter_df = qtl_loader_utils.get_snp_df(feature_filename)
snp_filter_df = qtl_loader_utils.get_snp_df(snps_filename)
feature_variant_covariate_df = qtl_loader_utils.get_snp_feature_df(feature_variant_covariate_filename)
#import pdb; pdb.set_trace()
#Do filtering on variants and features first stage.
if snp_feature_filter_df is not None:
if feature_filter_df is not None:
toSelect = set(feature_filter_df.index.values).intersection(set(annotation_df.index.values))
annotation_df = annotation_df.loc[toSelect,]
toSelect = list(set(snp_feature_filter_df['feature'].values).intersection(set(annotation_df.index.values)))
snp_feature_filter_df = snp_feature_filter_df.loc[snp_feature_filter_df['feature'].isin(toSelect)]
relSnps = snp_feature_filter_df['snp_id'].values
if snp_filter_df is not None:
relSnps = set(snp_filter_df.index).intersection(set(relSnps))
if feature_variant_covariate_df is not None:
feature_variant_covariate_df = feature_variant_covariate_df.loc[feature_variant_covariate_df['feature'].isin(toSelect)]
relSnps = np.union1d(relSnps, feature_variant_covariate_df["snp_id"].values)
relSnps = np.unique(relSnps)
risk_df = qtl_loader_utils.get_grs_subset_df(prsFile, relSnps)
if risk_df is None:
print("No variants selected during SNP reading.")
sys.exit()
risk_df = risk_df.assign(SnpId=risk_df.index.values)
risk_df = risk_df.drop_duplicates(keep='first')
risk_df = risk_df.drop(['SnpId'], axis='columns')
risk_df = risk_df.loc[risk_df.isnull().sum(axis=1)!=risk_df.shape[1],]
elif snp_filter_df is not None:
relSnps = snp_filter_df.index
if feature_variant_covariate_df is not None:
feature_variant_covariate_df = feature_variant_covariate_df.loc[feature_variant_covariate_df['feature'].isin(toSelect)]
relSnps = np.union1d(relSnps, feature_variant_covariate_df["snp_id"].values)
relSnps = np.unique(relSnps)
risk_df = qtl_loader_utils.get_grs_subset_df(prsFile, relSnps)
if risk_df is None:
print("No variants selected during SNP reading.")
sys.exit()
risk_df = risk_df.assign(SnpId=risk_df.index.values)
risk_df = risk_df.drop_duplicates(keep='first')
risk_df = risk_df.drop(['SnpId'], axis='columns')
risk_df = risk_df.loc[risk_df.isnull().sum(axis=1)!=risk_df.shape[1],]
else :
risk_df = qtl_loader_utils.get_phenotype_df(prsFile)
print("Intersecting data.")
risk_df = risk_df.astype(float)
#pdb.set_trace();
##Make sure that there is only one entry per feature id!.
sample2individual_df = qtl_loader_utils.get_samplemapping_df(
_filename,list(phenotype_df.columns),'sample')
sample2individual_df.index = sample2individual_df.index.astype('str')
sample2individual_df = sample2individual_df.astype('str')
sample2individual_df['sample']=sample2individual_df.index
sample2individual_df = sample2individual_df.drop_duplicates();
##Filter first the linking files!
#Subset linking to relevant genotypes.
orgSize = sample2individual_df.shape[0]
sample2individual_df = sample2individual_df.loc[sample2individual_df['iid'].map(lambda x: x in list(map(str, risk_df.columns))),:]
diff = orgSize- sample2individual_df.shape[0]
orgSize = sample2individual_df.shape[0]
print("Dropped: "+str(diff)+" samples because they are not present in the genotype file.")
#Subset linking to relevant phenotypes.
sample2individual_df = sample2individual_df.loc[np.intersect1d(sample2individual_df.index,phenotype_df.columns),:]
diff = orgSize- sample2individual_df.shape[0]
orgSize = sample2individual_df.shape[0]
print("Dropped: "+str(diff)+" samples because they are not present in the phenotype file.")
#Subset linking vs kinship.
# extract filename from randomeffects filename
kinship_filename,readdepth_filename = randomeff_filename.split(",")
kinship_df = qtl_loader_utils.get_kinship_df(kinship_filename)
c = qtl_loader_utils.get_readdepth_df(readdepth_filename)
randomeff_df = mixRandomEff(kinship_df,kinship_df)
if kinship_df is not None:
#Filter from individual2sample_df & sample2individual_df since we don't want to filter from the genotypes.
sample2individual_df = sample2individual_df[sample2individual_df['iid'].map(lambda x: x in list(map(str, kinship_df.index)))]
diff = orgSize- sample2individual_df.shape[0]
orgSize = sample2individual_df.shape[0]
print("Dropped: "+str(diff)+" samples because they are not present in the kinship file.")
#Subset linking vs covariates.
covariate_df = qtl_loader_utils.get_covariate_df(covariates_filename)
if covariate_df is not None:
if np.nansum(covariate_df==1,0).max()<covariate_df.shape[0]: covariate_df.insert(0, 'ones',np.ones(covariate_df.shape[0]))
sample2individual_df = sample2individual_df.loc[list(set(sample2individual_df.index) & set(covariate_df.index)),:]
diff = orgSize- sample2individual_df.shape[0]
orgSize = sample2individual_df.shape[0]
print("Dropped: "+str(diff)+" samples because they are not present in the covariate file.")
###
print("Number of samples with genotype & phenotype data: " + str(sample2individual_df.shape[0]))
if(sample2individual_df.shape[0]<minimum_test_samples):
print("Not enough samples with both genotype & phenotype data.")
sys.exit()
#import pdb; pdb.set_trace()
##Filter now the actual data!
#Filter phenotype data based on the linking files.
phenotype_df = phenotype_df.loc[list(set(phenotype_df.index)&set(annotation_df.index)),sample2individual_df.index.values]
#Filter kinship data based on the linking files.
genetically_unique_individuals = None
if kinship_df is not None:
kinship_df = kinship_df.loc[np.intersect1d(kinship_df.index,sample2individual_df['iid']),np.intersect1d(kinship_df.index,sample2individual_df['iid'])]
if kinship_df is not None and (relatedness_score is not None):
genetically_unique_individuals = get_unique_genetic_samples(kinship_df, relatedness_score);
#Filter covariate data based on the linking files.
#Do filtering on features.
if feature_filter_df is not None:
toSelect = set(feature_filter_df.index.values).intersection(set(phenotype_df.index.values))
phenotype_df = phenotype_df.loc[toSelect,:]
##Filtering on features to test.
if snp_feature_filter_df is not None:
toSelect = set(snp_feature_filter_df['feature'].values).intersection(set(phenotype_df.index.values))
phenotype_df = phenotype_df.loc[toSelect,:]
if feature_filter_df is not None:
snp_feature_filter_df = snp_feature_filter_df.loc[snp_feature_filter_df['feature'].isin(toSelect)]
##Filtering on features to test from the combined feature snp filter.
#Prepare to filter on SNPs.
if snp_filter_df is not None:
toSelect = set(snp_filter_df.index).intersection(set(risk_df.index.values))
risk_df=risk_df.loc[toSelect,:]
##Filtering on SNPs to test from the snp filter.
if snp_feature_filter_df is not None:
toSelect = set(np.unique(snp_feature_filter_df['snp_id'])).intersection(set(risk_df.index.values))
risk_df=risk_df.loc[toSelect,:]
##Filtering on features to test from the combined feature snp filter.
#Filtering for sites on non allosomes.
if not skipAutosomeFiltering :
annotation_df = annotation_df[annotation_df['chromosome'].map(lambda x: x in list(map(str, range(1, 23))))]
feature_list = list(set(annotation_df.index)&set(phenotype_df.index))
print("Number of features to be tested: " + str(len(feature_list)))
print("Total number of variants to be considered, before variante QC and feature intersection: " + str(risk_df.shape[0]))
if(phenotype_df.shape[1]<minimum_test_samples):
print("Not enough samples with both genotype & phenotype data, for current number of covariates.")
sys.exit()
return [phenotype_df, kinship_df, covariate_df, sample2individual_df, annotation_df, snp_filter_df, snp_feature_filter_df, genetically_unique_individuals, minimum_test_samples, feature_list, risk_df, chromosome, selectionStart, selectionEnd, feature_variant_covariate_df]
def merge_QTL_results(results_dir):
'''Merge QTL results for individual chromosomes into a combined, indexed
hdf5 file.'''
qtl_results_files = sorted(glob.glob(results_dir+'qtl_results_*.txt'))
hdf5_outfile = qtl_output.hdf5_writer(results_dir+'qtl_results.h5')
for filename in qtl_results_files:
df = pd.read_csv(filename,sep='\t')
hdf5_outfile.add_result_df(df)
hdf5_outfile.close()
def chunker(seq, size):
return (seq[pos:pos + np.int(size)] for pos in range(0, len(seq), np.int(size)))
def get_unique_genetic_samples(kinship_df, relatedness_score):
# tril returns the lower triungular.
# if two lines are > identity then kinship_df>=relatedness_score should have an offdiagonal 1.
# if there is one 1 in the tril then it means that in the upper triul there was a line withe identical genotype
return (kinship_df.index[(np.tril(kinship_df>=relatedness_score,k=-1)).sum(1)==0])
def force_normal_distribution(phenotype, method='gaussnorm', reference=None):
_doc='rank transform x into ref/ gaussian;keep the range; keep ties'
if method=='log':
return np.log(1+phenotype)
if method=='log_standardize':
temp=np.log(1+phenotype)
return (temp-np.nanmean(temp))/np.nanstd(temp)
if method=='arcsin':
return np.arcsin(np.sqrt(phenotype))
if method=='arcsin_standardize':
temp=np.arcsin(np.sqrt(phenotype))
return (temp-np.nanmean(temp))/np.nanstd(temp)
if method=='standardize':
return (phenotype-np.nanmean(phenotype))/np.nanstd(phenotype)
indextoupdate = np.isfinite(phenotype)
y1 = phenotype[indextoupdate]
yuni,yindex=np.unique(y1, return_inverse=True)
phenotypenorm=phenotype.copy()
if method =='gaussnorm':
sref = scst.norm.isf(np.linspace(0.001, 0.999,num=yuni.shape[0])[::-1])
phenotypenorm[indextoupdate]=sref[yindex]
return phenotypenorm
elif method=='ranknorm':
try:
xref1=np.unique(reference[np.isfinite(reference)])
sref=np.sort(xref1)[np.linspace(0,xref1.shape[0]-0.001, num=y1.shape[0]).astype(int)]
except:
print ('reference missing. provide reference to force_normal_distribution or choose gaussnorm')
return 1
phenotypenorm[indextoupdate]=sref[np.argsort(np.argsort(y1))]
return phenotypenorm
elif method=='ranknorm_duplicates':
try:
xref1=np.unique(reference[np.isfinite(reference)])### unique values from reference
sref=np.sort(xref1)[np.linspace(0,xref1.shape[0]-0.001, num=yuni.shape[0]).astype(int)]
except:
print ('reference missing. provide reference to force_normal_distribution or choose gaussnorm')
return 1
phenotypenorm[indextoupdate]=sref[yindex]
return phenotypenorm
else:
print ('methods are: log, log_standardize, standardize, gaussnorm, ranknorm, ranknorm_duplicates, arcsin, arcsin_standardize')
#get_shuffeld_genotypes_preserving_kinship(genetically_unique_individuals, relatedness_score, snp_matrix_DF,kinship_df.loc[individual_ids,individual_ids], n_perm)
def get_shuffeld_genotypes_preserving_kinship(genetically_unique_individuals, relatedness_score, snp_matrix_DF,kinship_df1,n_perm):
# take only one line for replicates (those with the same name)
boolean_selection = ~snp_matrix_DF.index.duplicated()
temp = snp_matrix_DF.loc[boolean_selection,:]
boolean_selection = ~kinship_df1.index.duplicated()
kinship_df1 = kinship_df1.loc[boolean_selection, boolean_selection]
# subset snp matrix to genetically_unique_individuals
u_snp_matrix = temp.loc[genetically_unique_individuals,:]
'''has replicates but not same lines form donor (np.setdiff1d(individual_ids,genetically_unique_individuals))'''
#Shuffle and reinflate
locationBuffer = np.zeros(snp_matrix_DF.shape[0], dtype=np.int)
#Prepare location search for permuted snp_matrix_df.
index_samples = np.arange(u_snp_matrix.shape[0])
for index,current_name in enumerate(genetically_unique_individuals):
# find all samples that are related to current_name, or are current_name itself.
kinship_row = kinship_df1.loc[current_name]
selection = np.logical_or(kinship_row>=relatedness_score, kinship_row.index==current_name)
locationBuffer[np.where(selection)] = index
snp_matrix_copy = np.zeros((snp_matrix_DF.shape[0],snp_matrix_DF.shape[1]*n_perm))
counter = 0
end = (snp_matrix_DF.shape[1])
for perm_id in range(0,n_perm) :
np.random.shuffle(index_samples)
temp_u = u_snp_matrix.values[index_samples,:]
snp_matrix_copy[:,counter:end] = temp_u[locationBuffer,:]
counter+= snp_matrix_DF.shape[1]
end+= snp_matrix_DF.shape[1]
return(snp_matrix_copy)
def get_shuffeld_genotypes(snp_matrix_DF,n_perm):
snp_matrix_copy = np.zeros((snp_matrix_DF.shape[0],snp_matrix_DF.shape[1]*n_perm))
counter = 0
end = (snp_matrix_DF.shape[1])
index_samples = np.arange(snp_matrix_DF.shape[0])
for perm_id in range(0,n_perm) :
|
np.random.shuffle(index_samples)
|
numpy.random.shuffle
|
"""
auspectra696.py
696 project
Handles the primary functions
"""
# !/usr/bin/env python3
from __future__ import print_function
import sys
from argparse import ArgumentParser
import numpy as np
import matplotlib.pyplot as plt
import os
import numpy as np
import matplotlib.pyplot as plt
import xlrd
import pandas as pd
import collections as cl
import six
SUCCESS = 0
INVALID_DATA = 1
IO_ERROR = 2
__author__ = 'salwan'
# DEFAULT_DATA_FILE_NAME = 'LongerTest.xlsx'
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
DEFAULT_DATA_FILE_NAME = os.path.join(DATA_DIR, "LongerTest.xlsx")
def warning(*objs):
"""Writes a message to stderr."""
print("WARNING: ", *objs, file=sys.stderr)
def parse_cmdline(argv):
"""
Returns the parsed argument list and return code.
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
"""
if argv is None:
argv = sys.argv[1:]
# initialize the parser object:
parser = ArgumentParser(
description='Reads data from xlsx file, analyzes it, plots it, and reports key parameters. '
'All program output is user-controlled'
'')
parser.add_argument("-w", "--workbook", help="The location (directory and file name) of the Excel file with "
" The default file is {} ".format(DEFAULT_DATA_FILE_NAME),
default=DEFAULT_DATA_FILE_NAME)
parser.add_argument("-p", "--plot", help="Plot data from Excel file (default is true). Goes to 'data' directory",
action='store_true')
parser.add_argument("-n", "--normalize", help="Normalize data to max absorbance (default is true).",
action='store_true')
parser.add_argument("-t", "--table",
help="Tabular summary of SampleID, Amax, lMax, size (default is true). Goes to 'data' directory",
action='store_true')
args = None
try:
args = parser.parse_args(argv)
# args.wb_data = xlrd.open_workbook(input("Enter a file name (LongerTest.xlsx for testing purposes): "))
except IOError as e:
warning("Problems reading file:", e)
parser.print_help()
return args, IO_ERROR
return vars(args), SUCCESS # make sample input have a list of expected args and compare
def norm(rawAbs, Amax, x):
absoNorm = [x / Amax for x in rawAbs] # normalizes to Amax
maxAbsAfterNorm = max(absoNorm)
return absoNorm
def data_analysisNorm(data_file):
#read data from xlsx
wb_data = xlrd.open_workbook(data_file)
sheet1 = wb_data.sheet_by_index(0)
r = sheet1.nrows
c = sheet1.ncols
xLimLflt = sheet1.cell(1, 0).value # must be less than 400
xLimL = int(xLimLflt)
# Upper limit
xLimUflt = sheet1.cell(r - 1, 0).value
xLimU = int(xLimUflt)
# dict for extracted or calculated values from data
data = cl.OrderedDict({'Sample ID': [],
'lambdaMax (nm)': [],
'Amax': [],
'Size (nm)': []
})
for x in range(3, c):
# 299 is the number of data points minus 2
lambdas = sheet1.col_values(colx=0, start_rowx=(xLimU - 299) - xLimL, end_rowx=r) # x-vals (wavelength)
abso = sheet1.col_values(colx=x, start_rowx=(xLimU - 299) - xLimL, end_rowx=r) # y-vals (absorbance)
# 400 is the lambda we start plotting at
sID = sheet1.cell(0, x).value # name of each column
lMax = abso.index(max(abso)) + 400 # find max lambda for a column
Amax = max(abso) # get max Abs to norm against it
absoNorm = norm(abso, Amax, x)
# absoNorm = [x / Amax for x in abso] # normalizes to Amax
size = -0.02111514 * (lMax ** 2.0) + 24.6 * (lMax) - 7065.
# J. Phys. Chem. C 2007, 111, 14664-14669
# if lambdaMax outisde of this range then 1) particles aggregated and 2)outside of correlation
if 518 < lMax < 570:
data['Size (nm)'].append(int(size))
else:
data['Size (nm)'].append('>100')
# added extracted/calculated items into dict 'data'
data['Sample ID'].append(sID)
data['lambdaMax (nm)'].append(lMax)
data['Amax'].append(Amax)
# plot each column (cycle in loop)
plt.plot(lambdas, absoNorm, linewidth=2, label=sheet1.cell(0, x).value)
axes = plt.gca()
box = axes.get_position()
axes.set_position([box.x0, box.y0, box.width * 0.983, box.height])
plt.xlabel('Wavelength (nm)')
plt.ylabel('Absorbance (Normalized to Amax)')
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), fancybox=True, shadow=True)
axes.set_xlim([400, 700])
axes.set_ylim([0, 1.5])
# plt.show()
plt.savefig('data/dataOutput/AuPlotNorm.png', format='png', dpi=500)
return data
def data_analysis(data_file, plot=True):
#read data from xlsx
wb_data = xlrd.open_workbook(data_file)
sheet1 = wb_data.sheet_by_index(0)
r = sheet1.nrows
c = sheet1.ncols
xLimLflt = sheet1.cell(1, 0).value # must be less than 400
xLimL = int(xLimLflt)
# Upper limit
xLimUflt = sheet1.cell(r - 1, 0).value
xLimU = int(xLimUflt)
# dict for extracted or calculated values from data
data = cl.OrderedDict({'Sample ID': [],
'lambdaMax (nm)': [],
'Amax': [],
'Size (nm)': []
})
for x in range(3, c):
# 299 is the number of data points minus 2
lambdas = sheet1.col_values(colx=0, start_rowx=(xLimU - 299) - xLimL, end_rowx=r) # x-vals (wavelength)
abso = sheet1.col_values(colx=x, start_rowx=(xLimU - 299) - xLimL, end_rowx=r) # y-vals (absorbance)
# 400 is the lambda we start plotting at
sID = sheet1.cell(0, x).value # name of each column
lMax = abso.index(max(abso)) + 400 # find max lambda for a column
Amax = max(abso) # get max Abs to norm against it
size = -0.02111514 * (lMax ** 2.0) + 24.6 * (lMax) - 7065.
# J. Phys. Chem. C 2007, 111, 14664-14669
# if lambdaMax outisde of this range then 1) particles aggregated and 2)outside of correlation
if 518 < lMax < 570:
data['Size (nm)'].append(int(size))
else:
data['Size (nm)'].append('>100')
# added extracted/calculated items into dict 'data'
data['Sample ID'].append(sID)
data['lambdaMax (nm)'].append(lMax)
data['Amax'].append(Amax)
# plot each column (cycle in loop)
if plot is True:
plt.plot(lambdas, abso, linewidth=2, label=sheet1.cell(0, x).value)
axes = plt.gca()
box = axes.get_position()
axes.set_position([box.x0, box.y0, box.width * 0.983, box.height])
plt.xlabel('Wavelength (nm)')
plt.ylabel('Absorbance')
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), fancybox=True, shadow=True)
axes.set_xlim([400, 700])
axes.set_ylim([0, Amax + 0.05])
plt.savefig('data/dataOutput/AuPlot.png', format='png', dpi=5000)
return data
# output data frame as nice table
def render_mpl_table(data, col_width=4.0, row_height=0.625, font_size=14,
header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w',
bbox=[0, 0, 1, 1], header_columns=0,
ax=None, **kwargs):
if ax is None:
size = (np.array(data.shape[::-1]) + np.array([0, 1])) *
|
np.array([col_width, row_height])
|
numpy.array
|
import math
import numpy as np
import pytest
import vg
def test_basic():
perpendicular = np.array([[1.0, 1.0, 0.0], [-1.0, 1.0, 0.0]])
assert vg.angle(*perpendicular) == 90
assert vg.angle(*perpendicular[::-1]) == 90
assert isinstance(vg.angle(*perpendicular), float)
acute = np.array([[1.0, 2.0, 0.0], [-1.0, 2.0, 0.0]])
acute_angle = math.acos(3.0 / 5.0)
assert vg.angle(*acute, units="rad") == acute_angle
assert vg.angle(*acute, units="rad") == acute_angle
def test_units():
v1 = np.array([1, 1, 0])
v2 = np.array([-1, 1, 0])
assert vg.angle(v1, v2, units="deg") == 90
assert vg.angle(v2, v1, units="rad") == math.pi / 2.0
with pytest.raises(ValueError):
vg.angle(v2, v1, units="cm")
def test_assume_normalized():
acute = np.array([[1.0, 2.0, 0.0], [-1.0, 2.0, 0.0]])
acute_angle = math.acos(3.0 / 5.0)
np.testing.assert_almost_equal(
vg.angle(*acute, units="rad", assume_normalized=False), acute_angle
)
np.testing.assert_raises(
AssertionError,
np.testing.assert_almost_equal,
vg.angle(*acute, units="rad", assume_normalized=True),
acute_angle,
)
acute_norm = vg.normalize(acute)
np.testing.assert_almost_equal(
vg.angle(*acute_norm, units="rad", assume_normalized=False), acute_angle
)
np.testing.assert_almost_equal(
vg.angle(*acute_norm, units="rad", assume_normalized=True), acute_angle
)
def test_look():
v1 =
|
np.array([1, 1, 1])
|
numpy.array
|
import numpy as np
from scipy.stats import pearsonr
from skimage import morphology
import matplotlib.pyplot as plt
from src.correlation_map import apply_motion_correction
from utils.io_functs import create_directory, export_np_array
from visualisation.depth_projection import depth_volume_plot
"""
ROI extraction
------
We will now generate a function that extracts ROIs (regions of interest). The function should take 4 inputs: a
correlation map, the final stack of aligned frames, a correlation threshold value and a max size of an ROI in pixels.
The function should:
* Identify the pixel with the highest correlation value in the correlation map (the ROI seed). Initialize the list of
pixels in this ROI with this **seed.**
* Compute the individual correlations of the fluorescence time-series in this pixel with its 8 neighbours. A convenient
way of idetifying the neighbours of a region is by dilating the reion by one piexl. You can do this by importing
morphology from skimage and using `morphology.binary_dilation`.
* Add the neighbours whose correlation exceeds the threshold to the ROI.
* Repeat by looking at the neighbouring pixels of the new ROI and computing the correlation of their fluorescence with
the total fluorescence of the ROI. Add the pixels to the ROI if they exceed the threshold.
* Stop the function if no neighbouring pixels exceed the threshold or if the size of the ROI exceeds the maximum size
(the last input to the function).
* The function should return the pixels within the ROI, the fluoresence trace of the ROI, the size of the ROI and the
correlation map with the values of the pixels in the extracted ROI set to zero.
Mike's notes for finding the regions:
1. use the threshold and find the maximum correlation value in the map as a seed
2. take indices of nearest neighbours
3. assign seed as the template trace and extract traces of neighbours
4. find correlation with template trace and that of each neighbouring trace
5. join neighbours beyond a given threshold and reasign the total average as the new trace
"""
def next_roi(correlation_volume, frames, correlation_threshold, max_volume):
# find maximum existing correlation point
this_max = np.nanmax(correlation_volume)
# print(this_max)
# get the index coordinates max correlation value (seed)
result = np.where(correlation_volume == this_max)
coords = list(zip(result[0], result[1], result[2]))
# store each index for each dimension
I, J, K = coords[0][:]
# extract timeseries for the seed
this_roi_trace = np.squeeze(frames[:, I, J, K])
# create a correlation map for the ROI
this_roi = np.zeros_like(correlation_volume)
# assign correlation value to seed as 1
this_roi[I, J, K] = 1
this_correlation_map = np.copy(correlation_volume)
this_correlation_map[I, J, K] = 0;
added = 1
while np.sum(this_roi != 0) < max_volume and added == 1:
added = 0
# dilated = morphology.binary_dilation(this_roi, np.ones((3, 3, 3))).astype(np.uint8)
dilated = morphology.binary_dilation(this_roi, morphology.cube(width=3)).astype(np.uint8)# converta boolean type
new_pixels = dilated - this_roi
# locate index of neighbouring pixels and stack as coordinated
coords = np.stack(np.where(new_pixels == 1), axis=1).astype(dtype=np.int32)
# iterate through each neighbour and calc correlation with ROI
for a in range(coords.shape[0]):
# extract index for coordinate
I, J, K = coords[a]
# check it hasn't already been used otherwise it would've been set to zero
"""
map_corr_func = lambda a, b, c: pearsonr(a[:,b], c)[0]
list(map(map_corr_func, frames, coords, Y))
"""
if this_correlation_map[I, J, K] != 0:
# extract time series
Y = np.squeeze(frames[:, I, J, K])
# calculate timeseries correlation with the roi timeseries
C, _ = pearsonr(this_roi_trace, Y)
# if they are highly correlated join, and update the masks
if C > correlation_threshold:
# mark as part of the ROI
this_roi[I, J, K] = 1
# set correlation value to 0 on the map
this_correlation_map[I, J, K] = 0
# add to ROI timeseries
this_roi_trace = this_roi_trace + Y # check if you need to average rather than add
# keep in while loop
added = 1
return this_roi, this_roi_trace, np.sum(this_roi), this_correlation_map
if __name__ == '__main__':
parent_path = f'F:\\OptovinScape\\20210628\\tiff_stacks\\20210628_6dpf_elavl3_H2B_fish3_run1'
# read in aligned frames
aligned_frames = apply_motion_correction(parent_path=parent_path)
# read in correlation map
original_correlation_map = np.load(f"{parent_path}\\correlation_vol_reduced.npy")
# original_correlation_map = np.load(f"{parent_path}\\correlation_vol.npy")
correlation_map = np.copy(original_correlation_map)
n_rois = 200
# create a timeseries array of all ROIs
all_traces = np.zeros((n_rois, aligned_frames.shape[0]))
# create an ROI volume
all_rois =
|
np.zeros_like(original_correlation_map)
|
numpy.zeros_like
|
import cv2
import numpy as np
import random
import os
def smudge_boundaries(img, block_size):
# WIP: COMPLTETE IT LATER, NOT ON PRIORITY
# we have to smudge the internal boundaries area which is the center area vertically and horizontally
h, w = img.shape[:2]
cv2.namedWindow('final img', cv2.WINDOW_FREERATIO)
signs = [-1, 1]
hori_smudge_y = int((h/2.0) - (block_size/2))
for x in range(0, w, block_size):
add_sub = random.choice(signs)
patch_y = int((h / 2.0) + add_sub*2 * block_size)
img_patch = img[patch_y: patch_y + block_size, x: x + block_size]
# cv2.imshow('patch img', img_patch)
# cv2.waitKey(0)
# print(img_patch.shape)
img[hori_smudge_y:hori_smudge_y+block_size, x:x + block_size] = img_patch
img[hori_smudge_y-int(block_size/2):hori_smudge_y+int(block_size/2), x:x+block_size] = \
cv2.GaussianBlur(img[hori_smudge_y-int(block_size/2):hori_smudge_y+int(block_size/2), x:x+block_size],\
(5, 5), 0)
# print("x: ", x)
# smudge the center area
# pass
cv2.imshow('patch img', img_patch)
cv2.imshow('final img', img)
cv2.waitKey(0)
for y in range(0, h, block_size):
add_sub = random.choice(signs)
vert_smudge_x = int((w / 2.0) + add_sub*2 * block_size)
print("y: ", y)
def stack_img(img1, img2, side="RIGHT"):
# stack THE imgs according to the side
if side == "RIGHT":
stacked_img =
|
np.concatenate((img1, img2), axis=1)
|
numpy.concatenate
|
# -*- coding: UTF-8 -*-
"""
此脚本用于展示随机变量引起的模型幻觉
"""
import numpy as np
import matplotlib.pyplot as plt
def generateData(seed, num):
x = 0
np.random.seed(seed)
data = []
for i in range(num):
x +=
|
np.random.normal()
|
numpy.random.normal
|
# -*- coding: utf-8 -*-
# Copyright 2018 the HERA Project
# Licensed under the MIT License
'''Tests for io.py'''
import unittest
import numpy as np
import pyuvdata
from pyuvdata import UVCal, UVData
from hera_cal.data import DATA_PATH
from collections import OrderedDict as odict
from hera_cal.datacontainer import DataContainer
import hera_cal.io as io
from hera_cal.io import HERACal, HERAData
from hera_cal.utils import polnum2str, polstr2num, jnum2str, jstr2num
import os
import warnings
import shutil
import copy
class Test_HERACal(unittest.TestCase):
def setUp(self):
self.fname_xx = os.path.join(DATA_PATH, "test_input/zen.2457698.40355.xx.HH.uvc.omni.calfits")
self.fname_yy = os.path.join(DATA_PATH, "test_input/zen.2457698.40355.yy.HH.uvc.omni.calfits")
self.fname_both = os.path.join(DATA_PATH, "test_input/zen.2457698.40355.HH.uvcA.omni.calfits")
def test_init(self):
hc = HERACal(self.fname_xx)
self.assertEqual(hc.filepaths, [self.fname_xx])
hc = HERACal([self.fname_xx, self.fname_yy])
self.assertEqual(hc.filepaths, [self.fname_xx, self.fname_yy])
hc = HERACal((self.fname_xx, self.fname_yy))
self.assertEqual(hc.filepaths, [self.fname_xx, self.fname_yy])
with self.assertRaises(TypeError):
hc = HERACal([0, 1])
with self.assertRaises(ValueError):
hc = HERACal(None)
def test_read(self):
# test one file with both polarizations and a non-None total quality array
hc = HERACal(self.fname_both)
gains, flags, quals, total_qual = hc.read()
uvc = UVCal()
uvc.read_calfits(self.fname_both)
np.testing.assert_array_equal(uvc.gain_array[0, 0, :, :, 0].T, gains[9, 'jxx'])
np.testing.assert_array_equal(uvc.flag_array[0, 0, :, :, 0].T, flags[9, 'jxx'])
np.testing.assert_array_equal(uvc.quality_array[0, 0, :, :, 0].T, quals[9, 'jxx'])
np.testing.assert_array_equal(uvc.total_quality_array[0, :, :, 0].T, total_qual['jxx'])
np.testing.assert_array_equal(np.unique(uvc.freq_array), hc.freqs)
np.testing.assert_array_equal(np.unique(uvc.time_array), hc.times)
self.assertEqual(hc.pols, ['jxx', 'jyy'])
self.assertEqual(set([ant[0] for ant in hc.ants]), set(uvc.ant_array))
# test list loading
hc = HERACal([self.fname_xx, self.fname_yy])
gains, flags, quals, total_qual = hc.read()
self.assertEqual(len(gains.keys()), 36)
self.assertEqual(len(flags.keys()), 36)
self.assertEqual(len(quals.keys()), 36)
self.assertEqual(hc.freqs.shape, (1024,))
self.assertEqual(hc.times.shape, (3,))
self.assertEqual(sorted(hc.pols), ['jxx', 'jyy'])
def test_write(self):
hc = HERACal(self.fname_both)
gains, flags, quals, total_qual = hc.read()
for key in gains.keys():
gains[key] *= 2.0 + 1.0j
flags[key] = np.logical_not(flags[key])
quals[key] *= 2.0
for key in total_qual.keys():
total_qual[key] *= 2
hc.update(gains=gains, flags=flags, quals=quals, total_qual=total_qual)
hc.write_calfits('test.calfits', clobber=True)
gains_in, flags_in, quals_in, total_qual_in = hc.read()
hc2 = HERACal('test.calfits')
gains_out, flags_out, quals_out, total_qual_out = hc2.read()
for key in gains_in.keys():
np.testing.assert_array_equal(gains_in[key] * (2.0 + 1.0j), gains_out[key])
np.testing.assert_array_equal(np.logical_not(flags_in[key]), flags_out[key])
np.testing.assert_array_equal(quals_in[key] * (2.0), quals_out[key])
for key in total_qual.keys():
np.testing.assert_array_equal(total_qual_in[key] * (2.0), total_qual_out[key])
os.remove('test.calfits')
from hera_cal.data import DATA_PATH
import os
class Test_HERAData(unittest.TestCase):
def setUp(self):
self.uvh5_1 = os.path.join(DATA_PATH, "zen.2458116.61019.xx.HH.h5XRS_downselected")
self.uvh5_2 = os.path.join(DATA_PATH, "zen.2458116.61765.xx.HH.h5XRS_downselected")
self.miriad_1 = os.path.join(DATA_PATH, "zen.2458043.12552.xx.HH.uvORA")
self.miriad_2 = os.path.join(DATA_PATH, "zen.2458043.13298.xx.HH.uvORA")
self.uvfits = os.path.join(DATA_PATH, 'zen.2458043.12552.xx.HH.uvA.vis.uvfits')
self.four_pol = [os.path.join(DATA_PATH, 'zen.2457698.40355.{}.HH.uvcA'.format(pol))
for pol in ['xx', 'yy', 'xy', 'yx']]
def test_init(self):
# single uvh5 file
hd = HERAData(self.uvh5_1)
self.assertEqual(hd.filepaths, [self.uvh5_1])
for meta in hd.HERAData_metas:
self.assertIsNotNone(getattr(hd, meta))
self.assertEqual(len(hd.freqs), 1024)
self.assertEqual(len(hd.bls), 3)
self.assertEqual(len(hd.times), 60)
self.assertEqual(len(hd.lsts), 60)
self.assertEqual(hd._writers, {})
# multiple uvh5 files
files = [self.uvh5_1, self.uvh5_2]
hd = HERAData(files)
self.assertEqual(hd.filepaths, files)
for meta in hd.HERAData_metas:
self.assertIsNotNone(getattr(hd, meta))
for f in files:
self.assertEqual(len(hd.freqs[f]), 1024)
self.assertEqual(len(hd.bls[f]), 3)
self.assertEqual(len(hd.times[f]), 60)
self.assertEqual(len(hd.lsts[f]), 60)
self.assertFalse(hasattr(hd, '_writers'))
# miriad
hd = HERAData(self.miriad_1, filetype='miriad')
self.assertEqual(hd.filepaths, [self.miriad_1])
for meta in hd.HERAData_metas:
self.assertIsNone(getattr(hd, meta))
# uvfits
hd = HERAData(self.uvfits, filetype='uvfits')
self.assertEqual(hd.filepaths, [self.uvfits])
for meta in hd.HERAData_metas:
self.assertIsNone(getattr(hd, meta))
# test errors
with self.assertRaises(TypeError):
hd = HERAData([1, 2])
with self.assertRaises(ValueError):
hd = HERAData(None)
with self.assertRaises(NotImplementedError):
hd = HERAData(self.uvh5_1, 'not a real type')
with self.assertRaises(IOError):
hd = HERAData('fake path')
def test_reset(self):
hd = HERAData(self.uvh5_1)
hd.read()
hd.reset()
self.assertIsNone(hd.data_array)
self.assertIsNone(hd.flag_array)
self.assertIsNone(hd.nsample_array)
self.assertEqual(hd.filepaths, [self.uvh5_1])
for meta in hd.HERAData_metas:
self.assertIsNotNone(getattr(hd, meta))
self.assertEqual(len(hd.freqs), 1024)
self.assertEqual(len(hd.bls), 3)
self.assertEqual(len(hd.times), 60)
self.assertEqual(len(hd.lsts), 60)
self.assertEqual(hd._writers, {})
def test_get_metadata_dict(self):
hd = HERAData(self.uvh5_1)
metas = hd.get_metadata_dict()
for meta in hd.HERAData_metas:
self.assertTrue(meta in metas)
self.assertEqual(len(metas['freqs']), 1024)
self.assertEqual(len(metas['bls']), 3)
self.assertEqual(len(metas['times']), 60)
self.assertEqual(len(metas['lsts']), 60)
np.testing.assert_array_equal(metas['times'], np.unique(list(metas['times_by_bl'].values())))
np.testing.assert_array_equal(metas['lsts'], np.unique(list(metas['lsts_by_bl'].values())))
def test_determine_blt_slicing(self):
hd = HERAData(self.uvh5_1)
for s in hd._blt_slices.values():
self.assertIsInstance(s, slice)
for bl, s in hd._blt_slices.items():
np.testing.assert_array_equal(np.arange(180)[np.logical_and(hd.ant_1_array == bl[0],
hd.ant_2_array == bl[1])], np.arange(180)[s])
# test check for non-regular spacing
hd.ant_1_array = hd.ant_2_array
with self.assertRaises(NotImplementedError):
hd._determine_blt_slicing()
def test_determine_pol_indexing(self):
hd = HERAData(self.uvh5_1)
self.assertEqual(hd._polnum_indices, {-5: 0})
hd = HERAData(self.four_pol, filetype='miriad')
hd.read(bls=[(53, 53)])
self.assertEqual(hd._polnum_indices, {-8: 3, -7: 2, -6: 1, -5: 0})
def test_get_slice(self):
hd = HERAData(self.uvh5_1)
hd.read()
for bl in hd.bls:
np.testing.assert_array_equal(hd._get_slice(hd.data_array, bl), hd.get_data(bl))
np.testing.assert_array_equal(hd._get_slice(hd.data_array, (54, 53, 'XX')),
hd.get_data((54, 53, 'XX')))
np.testing.assert_array_equal(hd._get_slice(hd.data_array, (53, 54))['XX'],
hd.get_data((53, 54, 'XX')))
np.testing.assert_array_equal(hd._get_slice(hd.data_array, 'XX')[(53, 54)],
hd.get_data((53, 54, 'XX')))
with self.assertRaises(KeyError):
hd._get_slice(hd.data_array, (1, 2, 3, 4))
hd = HERAData(self.four_pol, filetype='miriad')
d, f, n = hd.read(bls=[(80, 81)])
for p in d.pols():
np.testing.assert_array_almost_equal(hd._get_slice(hd.data_array, (80, 81, p)),
hd.get_data((80, 81, p)))
np.testing.assert_array_almost_equal(hd._get_slice(hd.data_array, (81, 80, p)),
hd.get_data((81, 80, p)))
def test_set_slice(self):
hd = HERAData(self.uvh5_1)
hd.read()
np.random.seed(21)
for bl in hd.bls:
new_vis = np.random.randn(60, 1024) + np.random.randn(60, 1024) * 1.0j
hd._set_slice(hd.data_array, bl, new_vis)
np.testing.assert_array_almost_equal(new_vis, hd.get_data(bl))
new_vis = np.random.randn(60, 1024) + np.random.randn(60, 1024) * 1.0j
hd._set_slice(hd.data_array, (54, 53, 'xx'), new_vis)
np.testing.assert_array_almost_equal(np.conj(new_vis), hd.get_data((53, 54, 'xx')))
new_vis = np.random.randn(60, 1024) + np.random.randn(60, 1024) * 1.0j
hd._set_slice(hd.data_array, (53, 54), {'xx': new_vis})
np.testing.assert_array_almost_equal(new_vis, hd.get_data((53, 54, 'xx')))
new_vis = np.random.randn(60, 1024) + np.random.randn(60, 1024) * 1.0j
to_set = {(53, 54): new_vis, (54, 54): 2 * new_vis, (53, 53): 3 * new_vis}
hd._set_slice(hd.data_array, 'XX', to_set)
np.testing.assert_array_almost_equal(new_vis, hd.get_data((53, 54, 'xx')))
with self.assertRaises(KeyError):
hd._set_slice(hd.data_array, (1, 2, 3, 4), None)
def test_build_datacontainers(self):
hd = HERAData(self.uvh5_1)
d, f, n = hd.read()
for bl in hd.bls:
np.testing.assert_array_almost_equal(d[bl], hd.get_data(bl))
np.testing.assert_array_almost_equal(f[bl], hd.get_flags(bl))
np.testing.assert_array_almost_equal(n[bl], hd.get_nsamples(bl))
for dc in [d, f, n]:
self.assertIsInstance(dc, DataContainer)
for k in dc.antpos.keys():
self.assertTrue(
|
np.all(dc.antpos[k] == hd.antpos[k])
|
numpy.all
|
import unittest
from nose.plugins.skip import SkipTest
import numpy
import theano
from theano.tensor import dmatrix, iscalar, lscalar, dmatrices
from theano import tensor
from theano.compile import In
from theano.compile import pfunc
from theano.compile import shared
from theano.compile import config
def data_of(s):
"""Return the raw value of a shared variable"""
return s.container.storage[0]
class Test_pfunc(unittest.TestCase):
def test_doc(self):
"""Ensure the code given in pfunc.txt works as expected"""
# Example #1.
a = lscalar()
b = shared(1)
f1 = pfunc([a], (a + b))
f2 = pfunc([In(a, value=44)], a + b, updates={b: b + 1})
self.assertTrue(b.get_value() == 1)
self.assertTrue(f1(3) == 4)
self.assertTrue(f2(3) == 4)
self.assertTrue(b.get_value() == 2)
self.assertTrue(f1(3) == 5)
b.set_value(0)
self.assertTrue(f1(3) == 3)
# Example #2.
a = tensor.lscalar()
b = shared(7)
f1 = pfunc([a], a + b)
f2 = pfunc([a], a * b)
self.assertTrue(f1(5) == 12)
b.set_value(8)
self.assertTrue(f1(5) == 13)
self.assertTrue(f2(4) == 32)
def test_shared(self):
# CHECK: two functions (f1 and f2) can share w
w = shared(numpy.random.rand(2, 2), 'w')
wval = w.get_value(borrow=False)
x = dmatrix()
out1 = w + x
out2 = w * x
f1 = pfunc([x], [out1])
f2 = pfunc([x], [out2])
xval = numpy.random.rand(2, 2)
assert numpy.all(f1(xval) == xval + wval)
assert numpy.all(f2(xval) == xval * wval)
# CHECK: updating a shared value
f3 = pfunc([x], out1, updates=[(w, (w - 1))])
# f3 changes the value of w
assert numpy.all(f3(xval) == xval + wval)
# this same value is read by f1
assert numpy.all(f1(xval) == xval + (wval - 1))
w.set_value(w.get_value(borrow=True) * 10, borrow=True)
# this same value is read by f1
assert numpy.all(f1(xval) == xval + w.get_value(borrow=True))
def test_no_shared_as_input(self):
"""Test that shared variables cannot be used as function inputs."""
w_init = numpy.random.rand(2, 2)
w = shared(w_init.copy(), 'w')
try:
pfunc([w], theano.tensor.sum(w * w))
assert False
except TypeError as e:
msg = 'Cannot use a shared variable (w) as explicit input'
if str(e).find(msg) < 0:
raise
def test_default_container(self):
# Ensure it is possible to (implicitly) use a shared variable in a
# function, as a 'state' that can be updated at will.
rng = numpy.random.RandomState(1827)
w_init = rng.rand(5)
w = shared(w_init.copy(), 'w')
reg = theano.tensor.sum(w * w)
f = pfunc([], reg)
assert f() == numpy.sum(w_init * w_init)
# Change the value of w and ensure the output changes accordingly.
w.set_value(w.get_value(borrow=True) + 1.0, borrow=True)
assert f() == numpy.sum((w_init + 1) ** 2)
def test_default_scalar_container(self):
# Similar in spirit to test_default_container, but updating a scalar
# variable. This is a sanity check for non mutable types.
x = shared(0.0, 'x')
f = pfunc([], x)
assert f() == 0
x.set_value(x.get_value(borrow=True) + 1, borrow=True)
assert f() == 1
def test_param_strict(self):
a = tensor.dvector()
b = shared(7)
out = a + b
f = pfunc([In(a, strict=False)], [out])
# works, rand generates float64 by default
f(
|
numpy.random.rand(8)
|
numpy.random.rand
|
# -*- coding: utf-8 -*-
# Copyright (c) 2019 the HERA Project
# Licensed under the MIT License
"""Tests for metrics_io module."""
import pytest
import yaml
import numpy as np
import os
import h5py
import pyuvdata.tests as uvtest
from hera_qm.data import DATA_PATH
from hera_qm import metrics_io
import hera_qm.tests as qmtest
from hera_qm.version import hera_qm_version_str
class dummy_class(object):
"""A dummy class to break h5py object types."""
def __init__(self):
"""Create blank object."""
pass
def test_reds_list_to_dict_type():
"""Test type returned is dict."""
test_list = [(1, 2), (3, 4)]
test_dict = metrics_io._reds_list_to_dict(test_list)
assert isinstance(test_dict, dict)
def test_reds_dict_to_list_type():
"""Test type returned is list."""
test_dict = {'0': [[0, 1], [1, 2]], '1': [[0, 2], [1, 3]]}
test_list = metrics_io._reds_dict_to_list(test_dict)
assert isinstance(test_list, list)
def test_reds_list_to_dict_to_list_unchanged():
"""Test list to dict to list conversion does not change input."""
test_list = [[(1, 2), (3, 4)]]
test_dict = metrics_io._reds_list_to_dict(test_list)
test_list2 = metrics_io._reds_dict_to_list(test_dict)
assert np.allclose(test_list, test_list2)
def test_recursive_error_for_object_arrays():
"""Test a TypeError is raised if dictionary items are np.arrays of objects."""
test_file = os.path.join(DATA_PATH, 'test_output', 'test.h5')
path = '/'
bad_dict = {'1': np.array(['123', 1, np.pi], dtype='object')}
with h5py.File(test_file, 'w') as h5_test:
pytest.raises(TypeError, metrics_io._recursively_save_dict_to_group,
h5_test, path, bad_dict)
os.remove(test_file)
def test_recursive_error_for_dict_of_object():
"""Test a TypeError is raised if dictionary items are objects."""
test_file = os.path.join(DATA_PATH, 'test_output', 'test.h5')
path = '/'
bad_dict = {'0': dummy_class()}
with h5py.File(test_file, 'w') as h5_test:
pytest.raises(TypeError, metrics_io._recursively_save_dict_to_group,
h5_test, path, bad_dict)
os.remove(test_file)
def test_recursive_error_for_object_in_nested_dict():
"""Test TypeError is raised if object is nested in dict."""
test_file = os.path.join(DATA_PATH, 'test_output', 'test.h5')
path = '/'
bad_dict = {'0': {'0.0': dummy_class()}}
with h5py.File(test_file, 'w') as h5_test:
pytest.raises(TypeError, metrics_io._recursively_save_dict_to_group,
h5_test, path, bad_dict)
os.remove(test_file)
def test_recursive_adds_numpy_array_to_h5file():
"""Test that proper numpy arrays are added to h5file."""
test_file = os.path.join(DATA_PATH, 'test_output', 'test.h5')
test_array = np.arange(10)
path = '/'
good_dict = {'0': test_array}
with h5py.File(test_file, 'w') as h5_test:
metrics_io._recursively_save_dict_to_group(h5_test, path, good_dict)
assert np.allclose(test_array, h5_test["0"][()])
os.remove(test_file)
def test_recursive_adds_nested_numpy_array_to_h5file():
"""Test that a numpy array nested in a dict is added to h5file."""
test_file = os.path.join(DATA_PATH, 'test_output', 'test.h5')
test_array = np.arange(10)
path = '/'
good_dict = {'0': {1: test_array}}
with h5py.File(test_file, 'w') as h5_test:
metrics_io._recursively_save_dict_to_group(h5_test, path, good_dict)
assert np.allclose(test_array, h5_test["0/1"][()])
os.remove(test_file)
def test_recursive_adds_scalar_to_h5file():
"""Test that a scalar type is added to h5file."""
test_file = os.path.join(DATA_PATH, 'test_output', 'test.h5')
test_scalar = 'hello world'
path = '/'
good_dict = {'filestem': test_scalar}
with h5py.File(test_file, 'w') as h5_test:
metrics_io._recursively_save_dict_to_group(h5_test, path, good_dict)
# we convert to np.string_ types so use that to compare
assert np.string_(test_scalar), h5_test["filestem"][()]
os.remove(test_file)
def test_recursive_adds_nested_scalar_to_h5file():
"""Test that a scalar nested in a dict is added to h5file."""
test_file = os.path.join(DATA_PATH, 'test_output', 'test.h5')
test_scalar = 'hello world'
good_dict = {'0': {'filestem': test_scalar}}
path = '/'
with h5py.File(test_file, 'w') as h5_test:
metrics_io._recursively_save_dict_to_group(h5_test, path, good_dict)
assert np.string_(test_scalar), h5_test["0/filestem"][()]
os.remove(test_file)
def test_write_metric_error_for_existing_file():
"""Test an error is raised if an existing file is given and overwrite=False."""
test_file = os.path.join(DATA_PATH, 'test_output', 'test.h5')
with open(test_file, 'w') as f:
pass
pytest.raises(IOError, metrics_io.write_metric_file, test_file, {})
os.remove(test_file)
def test_write_metric_error_for_existing_file_no_appellation():
"""Test an error is raised if an existing file is given with no appelation and overwrite=False."""
test_file = os.path.join(DATA_PATH, 'test_output', 'test')
with open(test_file + '.hdf5', 'w') as f:
pass
pytest.raises(IOError, metrics_io.write_metric_file, test_file, {})
os.remove(test_file + '.hdf5')
def test_write_metric_succeeds_for_existing_file_no_appellation_overwrite():
"""Test an write is successful if an existing file is given and overwrite=True."""
test_file = os.path.join(DATA_PATH, 'test_output', 'test')
with open(test_file + '.hdf5', 'w') as f:
pass
metrics_io.write_metric_file(test_file, {}, True)
assert os.path.exists(test_file + '.hdf5')
os.remove(test_file + '.hdf5')
def test_write_metric_file_hdf5():
"""Test that correct hdf5 structure created from write_metric_file."""
test_file = os.path.join(DATA_PATH, 'test_output', 'test.h5')
test_scalar = 'hello world'
test_array = np.arange(10)
test_dict = {'filestem': test_scalar, 1: {'filestem': test_scalar, '1': test_array}}
path = '/'
metrics_io.write_metric_file(test_file, test_dict)
with h5py.File(test_file, 'r') as test_h5:
assert np.string_(test_scalar) == test_h5["/Metrics/filestem"][()]
assert np.string_(test_scalar) == test_h5["/Metrics/1/filestem"][()]
assert np.allclose(test_array, test_h5["Metrics/1/1"][()])
os.remove(test_file)
def test_write_metric_file_hdf5_no_appellation_exists():
"""Test hdf5 file created from write_metric_file if no appellation given."""
test_file = os.path.join(DATA_PATH, 'test_output', 'test')
test_scalar = 'hello world'
test_array = np.arange(10)
test_dict = {'filestem': test_scalar, 1: {'filestem': test_scalar, '1': test_array}}
path = '/'
metrics_io.write_metric_file(test_file, test_dict)
test_file += '.hdf5'
assert os.path.exists(test_file)
os.remove(test_file)
def test_write_metric_warning_json():
"""Test the known warning is issued when writing to json."""
json_file = os.path.join(DATA_PATH, 'test_output', 'test_save.json')
test_scalar = 'hello world'
test_array = np.arange(10)
test_dict = {'filestem': test_scalar, 1: {'filestem': test_scalar, '1': test_array}}
warn_message = ["JSON-type files can still be written but are no longer "
"written by default.\n"
"Write to HDF5 format for future compatibility."]
with uvtest.check_warnings(
PendingDeprecationWarning, match=warn_message, nwarnings=1
):
json_dict = metrics_io.write_metric_file(json_file, test_dict, overwrite=True)
assert os.path.exists(json_file)
os.remove(json_file)
def test_write_metric_warning_pickle():
"""Test the known warning is issued when writing to pickles."""
pickle_file = os.path.join(DATA_PATH, 'test_output', 'test_save.pkl')
test_scalar = 'hello world'
test_array =
|
np.arange(10)
|
numpy.arange
|
import sys
import numpy as np
from scipy.sparse import csr_matrix
if sys.version_info[0] >= 3:
from topn import topn as ct
from topn import topn_threaded as ct_thread
else:
import topn as ct
import topn_threaded as ct_thread
def awesome_topn(r, c, d, ntop, n_rows=-1, n_jobs=1):
"""
r, c, and d are 1D numpy arrays all of the same length N.
This function will return arrays rn, cn, and dn of length n <= N such
that the set of triples {(rn[i], cn[i], dn[i]) : 0 < i < n} is a subset of
{(r[j], c[j], d[j]) : 0 < j < N} and that for every distinct value
x = rn[i], dn[i] is among the first ntop existing largest d[j]'s whose
r[j] = x.
Input:
r and c: two 1D integer arrays of the same length
d: 1D array of single or double precision floating point type of the
same length as r or c
ntop maximum number of maximum d's returned
n_rows: an int. If > -1 it will replace output rn with Rn the
index pointer array for the compressed sparse row (CSR) matrix
whose elements are {C[rn[i], cn[i]] = dn: 0 < i < n}. This matrix
will have its number of rows = n_rows. Thus the length of Rn is
n_rows + 1
n_jobs: number of threads, must be >= 1
Output:
(rn, cn, dn) where rn, cn, dn are all arrays as described above, or
(Rn, cn, dn) where Rn is described above
"""
dtype = r.dtype
assert c.dtype == dtype
idx_dtype = np.int32
rr = r.astype(idx_dtype)
len_r = len(r)
if (n_rows + 1) > len_r:
rr.resize(n_rows + 1, refcheck=False)
cc = c.astype(idx_dtype)
dd = d.copy()
new_len = ct_thread.topn_threaded(
rr, cc, dd,
ntop,
n_rows,
n_jobs
)
rr.resize((new_len if n_rows < 0 else (n_rows + 1)), refcheck=False)
cc.resize(new_len, refcheck=False)
dd.resize(new_len, refcheck=False)
return rr, cc, dd
def awesome_hstack_topn(blocks, ntop, sort=True, use_threads=False, n_jobs=1):
"""
Returns, in CSR format, the matrix formed by horizontally stacking the
sequence of CSR matrices in parameter 'blocks', with only the largest ntop
elements of each row returned. Also, each row will be sorted in
descending order only when
ntop < total number of columns in blocks or sort=True,
otherwise the rows will be unsorted.
:param blocks: list of CSR matrices to be stacked horizontally.
:param ntop: int. The maximum number of elements to be returned for
each row.
:param sort: bool. Each row of the returned matrix will be sorted in
descending order only when ntop < total number of columns in blocks
or sort=True, otherwise the rows will be unsorted.
:param use_threads: bool. Will use the multi-threaded versions of this
routine if True otherwise the single threaded version will be used.
In multi-core systems setting this to True can lead to acceleration.
:param n_jobs: int. When use_threads=True, denotes the number of threads
that are to be spawned by the multi-threaded routines. Recommended
value is number of cores minus one.
Output:
(scipy.sparse.csr_matrix) matrix in CSR format
"""
n_blocks = len(blocks)
r = np.concatenate([b.indptr for b in blocks])
c = np.concatenate([b.indices for b in blocks])
d = np.concatenate([b.data for b in blocks])
n_cols = np.array([b.shape[1] for b in blocks]).astype(c.dtype)
M = blocks[0].shape[0]
N =
|
np.sum(n_cols)
|
numpy.sum
|
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 30 17:33:29 2016
@author: betienne
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.utils.extmath import randomized_svd
class MCA(object):
def __init__(self, X, ind=None, supp=None, n_components=None):
"""
Starts a MCA
Params:
X : array of size (n,m), typically a pandas dataframe
ncols : number of categorical variables
n_components : number of axis to keep (non-zero eigenvalues)
If None, it is equal to min(n-1,m-ncol)
supp : supplementary variables, will not be taken into the computation but can
be represented.
"""
self.ncols = X.shape[1]
if supp:
self.X_supp = pd.get_dummies(X[supp])
self.columns_supp = list(self.X_supp.columns)
self.X_supp = self.X_supp.values
self.m_supp = self.X_supp.shape[1]
self.supp = True if supp else False
if ind:
X = pd.get_dummies(X[ind])
else:
X = pd.get_dummies(X)
self.index = list(X.index)
self.columns = list(X.columns)
self.K =
|
np.matrix(X.values, dtype=np.int8)
|
numpy.matrix
|
# Modifications copyright 2021 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) 2019 <NAME>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Drawing functions for yolo
"""
from typing import List, Dict, Tuple, Any
import numpy as np
import cv2
def draw_outputs(img: np.array, outputs: Tuple[List[np.array], List[float], List[str]],
class_names: Dict[str, Any]) -> np.array:
"""Draw object bounding box, confident score, and class name on
the object in the image.
Input:
- img: the image
- outputs: the outputs of prediction, which contain the
object' bounding box, confident score, and class
index
- class_names: dictionary of classes string names
Output:
- img: the image with the draw of outputs
"""
boxes, objectness, classes = outputs
width_height = np.flip(img.shape[0:2])
for i, oneclass in enumerate(classes):
x1y1 = tuple((
|
np.array(boxes[i][0:2])
|
numpy.array
|
# MIT License
#
# Copyright (C) IBM Corporation 2019
#
# 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.
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import unittest
import numpy as np
from art.utils import load_dataset, master_seed
from tests.utils_test import get_classifier_kr_tf, get_classifier_kr_tf_binary
from art.wrappers.output_reverse_sigmoid import OutputReverseSigmoid
logger = logging.getLogger(__name__)
class TestReverseSigmoid(unittest.TestCase):
"""
A unittest class for testing the Reverse Sigmoid wrapper.
"""
@classmethod
def setUpClass(cls):
(x_train, y_train), (x_test, y_test), _, _ = load_dataset('mnist')
cls.mnist = (x_train, y_train), (x_test, y_test)
def setUp(self):
master_seed(1234)
def test_reverse_sigmoid(self):
"""
Test reverse sigmoid
"""
(_, _), (x_test, _) = self.mnist
classifier = get_classifier_kr_tf()
wrapped_classifier = OutputReverseSigmoid(classifier=classifier, beta=1.0, gamma=0.1)
classifier_prediction_expected = np.asarray([[0.12109935, 0.0498215, 0.0993958, 0.06410096, 0.11366928,
0.04645343, 0.06419807, 0.30685693, 0.07616714, 0.05823757]],
dtype=np.float32)
wrapped_classifier_prediction_expected = np.asarray([[0.10733664, 0.07743666, 0.09712707, 0.08230411,
0.10377649, 0.0764482, 0.08234023, 0.20600921, 0.08703023,
0.08019119]], dtype=np.float32)
np.testing.assert_array_almost_equal(classifier.predict(x_test[0:1]), classifier_prediction_expected, decimal=4)
np.testing.assert_array_almost_equal(wrapped_classifier.predict(x_test[0:1]),
wrapped_classifier_prediction_expected, decimal=4)
def test_reverse_sigmoid_beta(self):
"""
Test reverse sigmoid parameter beta
"""
(_, _), (x_test, _) = self.mnist
classifier = get_classifier_kr_tf()
wrapped_classifier = OutputReverseSigmoid(classifier=classifier, beta=0.75, gamma=0.1)
classifier_prediction_expected = np.asarray([[0.12109935, 0.0498215, 0.0993958, 0.06410096, 0.11366928,
0.04645343, 0.06419807, 0.30685693, 0.07616714, 0.05823757]],
dtype=np.float32)
wrapped_classifier_prediction_expected = np.asarray([[0.1097239, 0.07264659, 0.09752058, 0.07914664, 0.10549247,
0.07124537, 0.07919333, 0.22350204, 0.08514594,
0.07638316]], dtype=np.float32)
np.testing.assert_array_almost_equal(classifier.predict(x_test[0:1]), classifier_prediction_expected, decimal=4)
np.testing.assert_array_almost_equal(wrapped_classifier.predict(x_test[0:1]),
wrapped_classifier_prediction_expected, decimal=4)
def test_reverse_sigmoid_gamma(self):
"""
Test reverse sigmoid parameter gamma
"""
(_, _), (x_test, _) = self.mnist
classifier = get_classifier_kr_tf()
wrapped_classifier = OutputReverseSigmoid(classifier=classifier, beta=1.0, gamma=0.5)
classifier_prediction_expected = np.asarray([[0.12109935, 0.0498215, 0.0993958, 0.06410096, 0.11366928,
0.04645343, 0.06419807, 0.30685693, 0.07616714, 0.05823757]],
dtype=np.float32)
wrapped_classifier_prediction_expected = np.asarray([[0.09699764, 0.10062696, 0.09689676, 0.09873781, 0.0968849,
0.10121989, 0.0987279, 0.11275949, 0.09774373,
0.09940492]], dtype=np.float32)
np.testing.assert_array_almost_equal(classifier.predict(x_test[0:1]), classifier_prediction_expected, decimal=4)
np.testing.assert_array_almost_equal(wrapped_classifier.predict(x_test[0:1]),
wrapped_classifier_prediction_expected, decimal=4)
def test_reverse_sigmoid_binary(self):
"""
Test reverse sigmoid for binary classifier
"""
(_, _), (x_test, _) = self.mnist
classifier = get_classifier_kr_tf_binary()
wrapped_classifier = OutputReverseSigmoid(classifier=classifier, beta=1.0, gamma=0.1)
classifier_prediction_expected = np.asarray([[0.5301345]], dtype=np.float32)
wrapped_classifier_prediction_expected = np.asarray([[0.52711743]], dtype=np.float32)
np.testing.assert_array_almost_equal(classifier.predict(x_test[0:1]), classifier_prediction_expected, decimal=4)
np.testing.assert_array_almost_equal(wrapped_classifier.predict(x_test[0:1]),
wrapped_classifier_prediction_expected, decimal=4)
def test_reverse_sigmoid_beta_binary(self):
"""
Test reverse sigmoid parameter beta for binary classifier
"""
(_, _), (x_test, _) = self.mnist
classifier = get_classifier_kr_tf_binary()
wrapped_classifier = OutputReverseSigmoid(classifier=classifier, beta=0.75, gamma=0.1)
classifier_prediction_expected = np.asarray([[0.5301345]], dtype=np.float32)
wrapped_classifier_prediction_expected =
|
np.asarray([[0.5278717]], dtype=np.float32)
|
numpy.asarray
|
"""Implements base two-point counter, to be extended when implementing a new engine."""
import os
import time
import numpy as np
from .utils import BaseClass, get_mpi, _make_array, _nan_to_zero
from . import utils
class TwoPointCounterError(Exception):
"""Exception raised when issue with two-point counting."""
def get_twopoint_counter(engine='corrfunc'):
"""
Return :class:`BaseTwoPointCounter`-subclass corresponding to input engine name.
Parameters
----------
engine : string, default='corrfunc'
Name of two-point counter engine, one of ["corrfunc", "analytic", "jackknife"].
Returns
-------
counter : type
Two-point counter class.
"""
if isinstance(engine, str):
if engine.lower() == 'corrfunc':
from . import corrfunc
try:
engine = BaseTwoPointCounter._registry[engine.lower()]
except KeyError:
raise TwoPointCounterError('Unknown two-point counter {}.'.format(engine))
return engine
class RegisteredTwoPointCounter(type(BaseClass)):
"""Metaclass registering :class:`BaseTwoPointCounter`-derived classes."""
_registry = {}
def __new__(meta, name, bases, class_dict):
cls = super().__new__(meta, name, bases, class_dict)
meta._registry[cls.name] = cls
return cls
class MetaTwoPointCounter(type(BaseClass)):
"""Metaclass to return correct two-point counter engine."""
def __call__(cls, *args, engine='corrfunc', **kwargs):
return get_twopoint_counter(engine)(*args, **kwargs)
class TwoPointCounter(BaseClass, metaclass=MetaTwoPointCounter):
"""
Entry point to two-point counter engines.
Parameters
----------
engine : string, default='corrfunc'
Name of two-point counter engine, one of ["corrfunc", "analytical"].
args : list
Arguments for two-point counter engine, see :class:`BaseTwoPointCounter`.
kwargs : dict
Arguments for two-point counter engine, see :class:`BaseTwoPointCounter`.
Returns
-------
engine : BaseTwoPointCounter
"""
@classmethod
def from_state(cls, state):
"""Return new two-point counter based on state dictionary."""
state = state.copy()
cls = get_twopoint_counter(state.pop('name'))
new = cls.__new__(cls)
new.__setstate__(state)
return new
def _vlogical_and(*arrays):
# & between any number of arrays
toret = arrays[0].copy()
for array in arrays[1:]: toret &= array
return toret
def get_default_nrealizations(weights):
"""Return default number of realizations given input bitwise weights = the number of bits in input weights plus one."""
return 1 + 8 * sum(weight.dtype.itemsize for weight in weights)
def get_inverse_probability_weight(*weights, noffset=1, nrealizations=None, default_value=0., dtype='f8'):
r"""
Return inverse probability weight given input bitwise weights.
Inverse probability weight is computed as::math:`\mathrm{nrealizations}/(\mathrm{noffset} + \mathrm{popcount}(w_{1} \& w_{2} \& ...))`.
If denominator is 0, weight is set to default_value.
Parameters
----------
weights : int arrays
Bitwise weights.
noffset : int, default=1
The offset to be added to the bitwise counts in the denominator (defaults to 1).
nrealizations : int, default=None
Number of realizations (defaults to the number of bits in input weights plus one).
default_value : float, default=0.
Default weight value, if the denominator is zero (defaults to 0).
dtype : string, np.dtype
Type for output weight.
Returns
-------
weight : array
IIP weight.
"""
if nrealizations is None:
nrealizations = get_default_nrealizations(weights[0])
# denom = noffset + sum(utils.popcount(w1 & w2) for w1, w2 in zip(*weights))
denom = noffset + sum(utils.popcount(_vlogical_and(*weight)) for weight in zip(*weights))
mask = denom == 0
denom[mask] = 1
toret = np.empty_like(denom, dtype=dtype)
toret[...] = nrealizations / denom
toret[mask] = default_value
return toret
def _format_positions(positions, mode='auto', position_type='xyz', dtype=None, copy=True, mpicomm=None, mpiroot=None):
# Format input array of positions
# position_type in ["xyz", "rdd", "pos"]
mode = mode.lower()
position_type = position_type.lower()
if position_type == 'auto':
if mode in ['theta', 'angular']: position_type = 'rd'
else: position_type = 'xyz'
def __format_positions(positions):
pt = position_type
if position_type == 'pos': # array of shape (N, 3)
positions = np.array(positions, dtype=dtype, copy=copy)
if positions.shape[-1] != 3:
return None, 'For position type = {}, please provide a (N, 3) array for positions'.format(position_type)
positions = positions.T
pt = 'xyz'
# Array of shape (3, N)
for ip, p in enumerate(positions):
# Cast to the input dtype if exists (may be set by previous weights)
positions[ip] = np.array(p, dtype=dtype, copy=copy)
size = len(positions[0])
dt = positions[0].dtype
if not np.issubdtype(dt, np.floating):
return None, 'Input position arrays should be of floating type, not {}'.format(dt)
for p in positions[1:]:
if len(p) != size:
return None, 'All position arrays should be of the same size'
if p.dtype != dt:
return None, 'All position arrays should be of the same type, you can e.g. provide dtype'
if pt != 'auto' and len(positions) != len(pt):
return None, 'For position type = {}, please provide a list of {:d} arrays for positions (found {:d})'.format(pt, len(pt), len(positions))
if mode in ['theta', 'angular']:
if pt == 'xyz':
positions = utils.cartesian_to_sky(positions, degree=True)[:2]
elif pt in ['rdd', 'rdz']:
positions = list(positions)[:2]
elif pt != 'rd':
return None, 'For mode = {}, position type should be one of ["xyz", "rdz", "rd"]'.format(mode)
else:
if pt == 'rdd':
positions = utils.sky_to_cartesian(positions, degree=True)
elif pt != 'xyz':
return None, 'For mode = {}, position type should be one of ["pos", "xyz", "rdd"]'.format(mode)
return positions, None
error = None
if mpiroot is None or (mpicomm.rank == mpiroot):
if positions is not None and (position_type == 'pos' or not all(position is None for position in positions)):
positions, error = __format_positions(positions) # return error separately to raise on all processes
if mpicomm is not None:
error = mpicomm.allgather(error)
else:
error = [error]
errors = [err for err in error if err is not None]
if errors:
raise TwoPointCounterError(errors[0])
if mpiroot is not None and mpicomm.bcast(positions is not None if mpicomm.rank == mpiroot else None, root=mpiroot):
n = mpicomm.bcast(len(positions) if mpicomm.rank == mpiroot else None, root=mpiroot)
if mpicomm.rank != mpiroot: positions = [None] * n
positions = [get_mpi().scatter_array(position, mpicomm=mpicomm, root=mpiroot) for position in positions]
return positions
def _format_weights(weights, weight_type='auto', size=None, dtype=None, copy=True, mpicomm=None, mpiroot=None):
# Format input weights, as a list of n_bitwise_weights uint8 arrays, and optionally a float array for individual weights.
# Return formated list of weights, and n_bitwise_weights.
def __format_weights(weights):
islist = isinstance(weights, (tuple, list)) or getattr(weights, 'ndim', 1) == 2
if not islist:
weights = [weights]
if all(weight is None for weight in weights):
return [], 0
individual_weights, bitwise_weights = [], []
for w in weights:
if np.issubdtype(w.dtype, np.integer):
if weight_type == 'product_individual': # enforce float individual weight
individual_weights.append(w)
else: # certainly bitwise weight
bitwise_weights.append(w)
else:
individual_weights.append(w)
# any integer array bit size will be a multiple of 8
bitwise_weights = utils.reformat_bitarrays(*bitwise_weights, dtype=np.uint8, copy=copy)
n_bitwise_weights = len(bitwise_weights)
weights = bitwise_weights
if individual_weights:
if len(individual_weights) > 1 or copy:
weight = np.prod(individual_weights, axis=0, dtype=dtype)
else:
weight = individual_weights[0].astype(dtype, copy=False)
weights += [weight]
return weights, n_bitwise_weights
weights, n_bitwise_weights = __format_weights(weights)
if mpiroot is None:
if mpicomm is not None:
size_weights = mpicomm.allgather(len(weights))
if len(set(size_weights)) != 1:
raise ValueError('mpiroot = None but weights are None/empty on some ranks')
else:
n = mpicomm.bcast(len(weights) if mpicomm.rank == mpiroot else None, root=mpiroot)
if mpicomm.rank != mpiroot: weights = [None] * n
weights = [get_mpi().scatter_array(weight, mpicomm=mpicomm, root=mpiroot) for weight in weights]
n_bitwise_weights = mpicomm.bcast(n_bitwise_weights, root=mpiroot)
if size is not None:
if not all(len(weight) == size for weight in weights):
raise ValueError('All weight arrays should be of the same size as position arrays')
return weights, n_bitwise_weights
class BaseTwoPointCounter(BaseClass, metaclass=RegisteredTwoPointCounter):
"""
Base class for two-point counters.
Extend this class to implement a new two-point counter engine.
Attributes
----------
wcounts : array
(Optionally weighted) two-point counts.
wnorm : float
Two-point count normalization.
"""
name = 'base'
def __init__(self, mode, edges, positions1, positions2=None, weights1=None, weights2=None,
bin_type='auto', position_type='auto', weight_type='auto', weight_attrs=None,
twopoint_weights=None, los='midpoint', boxsize=None, compute_sepsavg=True, dtype=None,
nthreads=None, mpicomm=None, mpiroot=None, **kwargs):
r"""
Initialize :class:`BaseTwoPointCounter`, and run actual two-point counts
(calling :meth:`run`), setting :attr:`wcounts` and :attr:`sep`.
Parameters
----------
mode : string
Type of two-point counts, one of:
- "theta": as a function of angle (in degree) between two particles
- "s": as a function of distance between two particles
- "smu": as a function of distance between two particles and cosine angle :math:`\mu` w.r.t. the line-of-sight
- "rppi": as a function of distance transverse (:math:`r_{p}`) and parallel (:math:`\pi`) to the line-of-sight
- "rp": same as "rppi", without binning in :math:`\pi`
edges : tuple, array
Tuple of bin edges (arrays), for the first (e.g. :math:`r_{p}`)
and optionally second (e.g. :math:`\pi > 0`, :math:`\mu \in [-1, 1]`) dimensions.
In case of single-dimension binning (e.g. ``mode`` is "theta", "s" or "rp"),
the single array of bin edges can be provided directly.
Edges are inclusive on the low end, exclusive on the high end,
i.e. a pair separated by :math:`s` falls in bin `i` if ``edges[i] <= s < edges[i+1]``.
In case ``mode`` is "smu" however, the first :math:`\mu`-bin is exclusive on the low end
(increase the :math:`\mu`-range by a tiny value to include :math:`\mu = \pm 1`).
Pairs at separation :math:`s = 0` are included in the :math:`\mu = 0` bin.
In case of auto-correlation (no ``positions2`` provided), auto-pairs (pairs of same objects) are not counted.
In case of cross-correlation, all pairs are counted.
In any case, duplicate objects (with separation zero) will be counted.
positions1 : list, array
Positions in the first catalog. Typically of shape (3, N), but can be (2, N) when ``mode`` is "theta".
See ``position_type``.
positions2 : list, array, default=None
Optionally, for cross-two-point counts, positions in the second catalog. See ``positions1``.
weights1 : array, list, default=None
Weights of the first catalog. Not required if ``weight_type`` is either ``None`` or "auto".
See ``weight_type``.
weights2 : array, list, default=None
Optionally, for cross-two-point counts, weights in the second catalog. See ``weights1``.
bin_type : string, default='auto'
Binning type for first dimension, e.g. :math:`r_{p}` when ``mode`` is "rppi".
Set to ``lin`` for speed-up in case of linearly-spaced bins.
In this case, the bin number for a pair separated by a (3D, projected, angular...) separation
``sep`` is given by ``(sep - edges[0])/(edges[-1] - edges[0])*(len(edges) - 1)``,
i.e. only the first and last bins of input edges are considered.
Then setting ``compute_sepsavg`` is virtually costless.
For non-linear binning, set to "custom".
"auto" allows for auto-detection of the binning type:
linear binning will be chosen if input edges are
within ``rtol = 1e-05`` (relative tolerance) *or* ``atol = 1e-08``
(absolute tolerance) of the array
``np.linspace(edges[0], edges[-1], len(edges))``.
position_type : string, default='auto'
Type of input positions, one of:
- "rd": RA/Dec in degree, only if ``mode`` is "theta"
- "rdd": RA/Dec in degree, distance, for any ``mode``
- "xyz": Cartesian positions, shape (3, N)
- "pos": Cartesian positions, shape (N, 3).
weight_type : string, default='auto'
The type of weighting to apply to provided weights. One of:
- ``None``: no weights are applied.
- "product_individual": each pair is weighted by the product of weights :math:`w_{1} w_{2}`.
- "inverse_bitwise": each pair is weighted by :math:`\mathrm{nrealizations}/(\mathrm{noffset} + \mathrm{popcount}(w_{1} \& w_{2}))`.
Multiple bitwise weights can be provided as a list.
Individual weights can additionally be provided as float arrays.
In case of cross-correlations with floating weights, bitwise weights are automatically turned to IIP weights,
i.e. :math:`\mathrm{nrealizations}/(\mathrm{noffset} + \mathrm{popcount}(w_{1}))`.
- "auto": automatically choose weighting based on input ``weights1`` and ``weights2``,
i.e. ``None`` when ``weights1`` and ``weights2`` are ``None``,
"inverse_bitwise" if one of input weights is integer, else "product_individual".
In addition, angular upweights can be provided with ``twopoint_weights``.
weight_attrs : dict, default=None
Dictionary of weighting scheme attributes. In case ``weight_type`` is "inverse_bitwise",
one can provide "nrealizations", the total number of realizations (*including* current one;
defaulting to the number of bits in input weights plus one);
"noffset", the offset to be added to the bitwise counts in the denominator (defaulting to 1)
and "default_value", the default value of pairwise weights if the denominator is zero (defaulting to 0).
One can also provide "nalways", stating the number of bits systematically set to 1 (defaulting to 0),
and "nnever", stating the number of bits systematically set to 0 (defaulting to 0).
These will only impact the normalization factors.
For example, for the "zero-truncated" estimator (arXiv:1912.08803), one would use noffset = 0, nalways = 1, nnever = 0.
twopoint_weights : WeightTwoPointEstimator, default=None
Weights to be applied to each pair of particles.
A :class:`WeightTwoPointEstimator` instance or any object with arrays ``sep``
(separations) and ``weight`` (weight at given separation) as attributes
(i.e. to be accessed through ``twopoint_weights.sep``, ``twopoint_weights.weight``)
or as keys (i.e. ``twopoint_weights['sep']``, ``twopoint_weights['weight']``)
or as element (i.e. ``sep, weight = twopoint_weights``)
los : string, default='midpoint'
Line-of-sight to be used when ``mode`` is "smu", "rppi" or "rp"; one of:
- "midpoint": the mean position of the pair: :math:`\mathbf{\eta} = (\mathbf{r}_{1} + \mathbf{r}_{2})/2`
- "x", "y" or "z": cartesian axis
boxsize : array, float, default=None
For periodic wrapping, the side-length(s) of the periodic cube.
compute_sepsavg : bool, default=True
Set to ``False`` to *not* calculate the average separation for each bin.
This can make the two-point counts faster if ``bin_type`` is "custom".
In this case, :attr:`sep` will be set the midpoint of input edges.
dtype : string, np.dtype, default=None
Array type for positions and weights.
If ``None``, defaults to type of first ``positions1`` array.
Double precision is highly recommended in case ``mode`` is "theta",
``twopoint_weights`` is provided (due to cosine), or ``compute_sepsavg`` is ``True``.
nthreads : int, default=None
Number of OpenMP threads to use.
mpicomm : MPI communicator, default=None
The MPI communicator, to MPI-distribute calculation.
mpiroot : int, default=None
In case ``mpicomm`` is provided, if ``None``, input positions and weights are assumed to be scattered across all ranks.
Else the MPI rank where input positions and weights are gathered.
kwargs : dict
Two-point counter engine-specific options.
"""
self.attrs = kwargs
self.mpicomm = mpicomm
if self.mpicomm is None and mpiroot is not None:
raise TwoPointCounterError('mpiroot is not None, but no mpicomm provided')
self._set_nthreads(nthreads)
self._set_mode(mode)
self._set_boxsize(boxsize)
self._set_edges(edges, bin_type=bin_type)
self._set_los(los)
self._set_compute_sepsavg(compute_sepsavg)
self._set_positions(positions1, positions2, position_type=position_type, dtype=dtype, copy=False, mpiroot=mpiroot)
self._set_weights(weights1, weights2, weight_type=weight_type, twopoint_weights=twopoint_weights, weight_attrs=weight_attrs, copy=False, mpiroot=mpiroot)
self._set_zeros()
self._set_reversible()
self.wnorm = self.normalization()
t0 = time.time()
self.run()
t1 = time.time()
if not self.with_mpi or self.mpicomm.rank == 0:
self.log_debug('Two-point counts computed in elapsed time {:.2f} s.'.format(t1 - t0))
del self.positions1, self.positions2, self.weights1, self.weights2
def run(self):
"""
Method that computes the actual two-point counts and set :attr:`wcounts` and :attr:`sep`,
to be implemented in your new engine.
"""
raise NotImplementedError('Implement method "run" in your {}'.format(self.__class__.__name__))
def _set_nthreads(self, nthreads):
if nthreads is None:
self.nthreads = int(os.getenv('OMP_NUM_THREADS', '1'))
else:
self.nthreads = int(nthreads)
def _set_mode(self, mode):
self.mode = mode.lower()
def _set_reversible(self):
self.is_reversible = self.mode in ['theta', 's', 'rp', 'rppi']
if self.mode == 'smu':
self.is_reversible = self.autocorr or (self.los_type not in ['firstpoint', 'endpoint']) # even smu is reversible for midpoint los, i.e. positions1 <-> positions2
def _set_zeros(self):
self._set_default_seps()
self.wcounts = np.zeros_like(self.sep)
self.ncounts = np.zeros_like(self.sep, dtype='i8')
def _set_compute_sepsavg(self, compute_sepsavg):
if 'compute_sepavg' in self.attrs:
self.log_warning('Use compute_sepsavg instead of compute_sepavg.')
compute_sepsavg = self.attrs.pop('compute_sepavg')
if np.ndim(compute_sepsavg) == 0:
compute_sepsavg = (compute_sepsavg,) * self.ndim
self.compute_sepsavg = [bool(c) for c in compute_sepsavg]
if len(self.compute_sepsavg) != self.ndim:
raise TwoPointCounterError('compute_sepsavg must be either a boolean or its length must match number of dimensions = {:d} for mode = {:d}'.format(self.ndim, self.mode))
def _set_edges(self, edges, bin_type='auto'):
if np.ndim(edges[0]) == 0:
edges = (edges,)
self.edges = [np.array(edge, dtype='f8') for edge in edges]
if self.mode in ['smu', 'rppi']:
if not self.ndim == 2:
raise TwoPointCounterError('A tuple of edges should be provided to two-point counter in mode {}'.format(self.mode))
else:
if not self.ndim == 1:
raise TwoPointCounterError('Only one edge array should be provided to two-point counter in mode {}'.format(self.mode))
self._set_bin_type(bin_type)
def _set_bin_type(self, bin_type):
self.bin_type = bin_type.lower()
allowed_bin_types = ['lin', 'custom', 'auto']
if self.bin_type not in allowed_bin_types:
raise TwoPointCounterError('bin type should be one of {}'.format(allowed_bin_types))
if self.bin_type == 'auto':
edges = self.edges[0]
if np.allclose(edges, np.linspace(edges[0], edges[-1], len(edges))):
self.bin_type = 'lin'
@property
def shape(self):
"""Return shape of obtained counts :attr:`wcounts`."""
return tuple(len(edges) - 1 for edges in self.edges)
@property
def ndim(self):
"""Return binning dimensionality."""
return len(self.edges)
@property
def periodic(self):
"""Whether periodic wrapping is used (i.e. :attr:`boxsize` is not ``None``)."""
return self.boxsize is not None
@property
def with_mpi(self):
"""Whether to use MPI."""
if not hasattr(self, 'mpicomm'): self.mpicomm = None
return self.mpicomm is not None and self.mpicomm.size > 1
def _set_positions(self, positions1, positions2=None, position_type='auto', dtype=None, copy=False, mpiroot=None):
self.positions1 = _format_positions(positions1, mode=self.mode, position_type=position_type, dtype=dtype, copy=copy, mpicomm=self.mpicomm, mpiroot=mpiroot)
self.dtype = self.positions1[0].dtype
self.positions2 = _format_positions(positions2, mode=self.mode, position_type=position_type, dtype=self.dtype, copy=copy, mpicomm=self.mpicomm, mpiroot=mpiroot)
self.autocorr = self.positions2 is None
if self.periodic:
self.positions1 = [p % b.astype(p.dtype) for p, b in zip(self.positions1, self.boxsize)]
if not self.autocorr:
self.positions2 = [p % b.astype(p.dtype) for p, b in zip(self.positions2, self.boxsize)]
self.size1 = self.size2 = len(self.positions1[0])
if not self.autocorr: self.size2 = len(self.positions2[0])
if self.with_mpi:
self.size1, self.size2 = self.mpicomm.allreduce(self.size1), self.mpicomm.allreduce(self.size2)
def _set_weights(self, weights1, weights2=None, weight_type='auto', twopoint_weights=None, weight_attrs=None, copy=False, mpiroot=None):
if weight_type is not None: weight_type = weight_type.lower()
allowed_weight_types = [None, 'auto', 'product_individual', 'inverse_bitwise']
if weight_type not in allowed_weight_types:
raise TwoPointCounterError('weight_type should be one of {}'.format(allowed_weight_types))
self.weight_type = weight_type
weight_attrs = weight_attrs or {}
self.weight_attrs = {}
self.n_bitwise_weights = 0
if weight_type is None:
self.weights1 = self.weights2 = []
else:
self.weight_attrs.update(nalways=weight_attrs.get('nalways', 0), nnever=weight_attrs.get('nnever', 0))
noffset = weight_attrs.get('noffset', 1)
default_value = weight_attrs.get('default_value', 0.)
self.weight_attrs.update(noffset=noffset, default_value=default_value)
self.weights1, n_bitwise_weights1 = _format_weights(weights1, weight_type=self.weight_type, size=len(self.positions1[0]), dtype=self.dtype, copy=copy, mpicomm=self.mpicomm, mpiroot=mpiroot)
def get_nrealizations(n_bitwise_weights):
nrealizations = weight_attrs.get('nrealizations', None)
if nrealizations is None:
nrealizations = n_bitwise_weights * 8 + 1
return nrealizations
if self.autocorr:
nrealizations = get_nrealizations(n_bitwise_weights1)
self.weight_attrs.update(nrealizations=nrealizations)
self.weights2 = self.weights1
self.n_bitwise_weights = n_bitwise_weights1
else:
self.weights2, n_bitwise_weights2 = _format_weights(weights2, weight_type=self.weight_type, size=len(self.positions2[0]), dtype=self.dtype, copy=copy, mpicomm=self.mpicomm, mpiroot=mpiroot)
if n_bitwise_weights2 == n_bitwise_weights1:
nrealizations = get_nrealizations(n_bitwise_weights1)
self.n_bitwise_weights = n_bitwise_weights1
else:
if n_bitwise_weights2 == 0:
indweights = self.weights1[n_bitwise_weights1] if len(self.weights1) > n_bitwise_weights1 else 1.
nrealizations = get_nrealizations(n_bitwise_weights1)
self.weights1 = [get_inverse_probability_weight(self.weights1[:n_bitwise_weights1], nrealizations=nrealizations,
noffset=noffset, default_value=default_value, dtype=self.dtype) * indweights]
self.n_bitwise_weights = 0
if not self.with_mpi or self.mpicomm.rank == 0:
self.log_info('Setting IIP weights for first catalog.')
elif n_bitwise_weights1 == 0:
indweights = self.weights2[n_bitwise_weights2] if len(self.weights2) > n_bitwise_weights2 else 1.
nrealizations = get_nrealizations(n_bitwise_weights2)
self.weights2 = [get_inverse_probability_weight(self.weights2[:n_bitwise_weights2], nrealizations=nrealizations,
noffset=noffset, default_value=default_value, dtype=self.dtype) * indweights]
self.n_bitwise_weights = 0
if not self.with_mpi or self.mpicomm.rank == 0:
self.log_info('Setting IIP weights for second catalog.')
else:
raise TwoPointCounterError('Incompatible length of bitwise weights: {:d} and {:d} bytes'.format(n_bitwise_weights1, n_bitwise_weights2))
self.weight_attrs.update(nrealizations=nrealizations)
if len(self.weights1) == len(self.weights2) + 1:
self.weights2.append(np.ones(len(self.positions2[0]), dtype=self.dtype))
elif len(self.weights1) == len(self.weights2) - 1:
self.weights1.append(np.ones(len(self.positions1[0]), dtype=self.dtype))
elif len(self.weights1) != len(self.weights2):
raise ValueError('Something fishy happened with weights; number of weights1/weights2 is {:d}/{:d}'.format(len(self.weights1), len(self.weights2)))
self.twopoint_weights = twopoint_weights
self.cos_twopoint_weights = None
if twopoint_weights is not None:
if self.periodic:
raise TwoPointCounterError('Cannot use angular weights in case of periodic boundary conditions (boxsize)')
from collections import namedtuple
TwoPointWeight = namedtuple('TwoPointWeight', ['sep', 'weight'])
try:
sep = twopoint_weights.sep
weight = twopoint_weights.weight
except AttributeError:
try:
sep = twopoint_weights['sep']
weight = twopoint_weights['weight']
except IndexError:
sep, weight = twopoint_weights
# just to make sure we use the correct dtype
sep = np.cos(np.radians(np.array(sep, dtype=self.dtype)))
argsort = np.argsort(sep)
self.cos_twopoint_weights = TwoPointWeight(sep=np.array(sep[argsort], dtype=self.dtype), weight=
|
np.array(weight[argsort], dtype=self.dtype)
|
numpy.array
|
from __future__ import print_function
import numpy as np
from scipy.special import factorial
def gamma_hrf(duration, A=1., tau=1.08, n=3, delta=2.05, Fs=1.0):
r"""A gamma function hrf model, with two parameters, based on
[Boynton1996]_
Parameters
----------
duration: float
the length of the HRF (in the inverse units of the sampling rate)
A: float
a scaling factor, sets the max of the function, defaults to 1
tau: float
The time constant of the gamma function, defaults to 1.08
n: int
The phase delay of the gamma function, defaults to 3
delta: float
A pure delay, allowing for an additional delay from the onset of the
time-series to the beginning of the gamma hrf, defaults to 2.05
Fs: float
The sampling rate, defaults to 1.0
Returns
-------
h: the gamma function hrf, as a function of time
Notes
-----
This is based on equation 3 in Boynton (1996):
.. math::
h(t) =
\frac{(\frac{t-\delta}{\tau})^{(n-1)}
e^{-(\frac{t-\delta}{\tau})}}{\tau(n-1)!}
<NAME>, <NAME>, <NAME> and <NAME>
(1996). Linear Systems Analysis of Functional Magnetic Resonance Imaging in
Human V1. J Neurosci 16: 4207-4221
"""
# XXX Maybe change to take out the time (Fs, duration, etc) from this and
# instead implement this in units of sampling interval (pushing the time
# aspect to the higher level)?
if type(n) is not int:
print(('gamma_hrf received unusual input, converting n from %s to %i'
% (str(n), int(n))))
n = int(n)
#Prevent negative delta values:
if delta < 0:
raise ValueError('in gamma_hrf, delta cannot be smaller than 0')
#Prevent cases in which the delta is larger than the entire hrf:
if delta > duration:
e_s = 'in gamma_hrf, delta cannot be larger than the duration'
raise ValueError(e_s)
t_max = duration - delta
t = np.hstack([np.zeros((delta * Fs)), np.linspace(0, t_max, t_max * Fs)])
t_tau = t / tau
h = (t_tau ** (n - 1) * np.exp(-1 * (t_tau)) /
(tau * factorial(n - 1)))
return A * h / max(h)
def polonsky_hrf(A, B, tau1, f1, tau2, f2, t_max, Fs=1.0):
r""" HRF based on Polonsky (2000):
.. math::
H(t) = exp(\frac{-t}{\tau_1}) sin(2\cdot\pi f_1 \cdot t) -a\cdot
exp(-\frac{t}{\tau_2})*sin(2\pi f_2 t)
<NAME>, <NAME>, <NAME> and <NAME>
(2000). Neuronal activity in human primary visual cortex correlates with
perception during binocular rivalry. Nature Neuroscience 3: 1153-1159
"""
sampling_interval = 1 / float(Fs)
t = np.arange(0, t_max, sampling_interval)
h = (np.exp(-t / tau1) * np.sin(2 * np.pi * f1 * t) -
(B *
|
np.exp(-t / tau2)
|
numpy.exp
|
import json
import os
from neuralparticles.tools.param_helpers import *
from neuralparticles.tools.data_helpers import PatchExtractor, get_data, get_data_pair, get_norm_factor, get_nearest_idx
import numpy as np
from neuralparticles.tools.uniio import readNumpyRaw
from neuralparticles.tensorflow.models.PUNet import PUNet
import shutil, math
import keras
from keras.models import Model
from neuralparticles.tools.plot_helpers import write_csv, plot_particles
if __name__ == "__main__":
data_path = getParam("data", "data/")
config_path = getParam("config", "config/version_00.txt")
mode = int(getParam("mode", 0))
cnt = int(getParam("cnt", 100))
patch_seed = int(getParam("seed", 0))
dataset = int(getParam("dataset", -1))
checkUnusedParams()
if not os.path.exists(data_path + "statistics/"):
os.makedirs(data_path + "statistics/")
np.random.seed(34)
src_path = data_path + "source/"
ref_path = data_path + "reference/"
with open(config_path, 'r') as f:
config = json.loads(f.read())
with open(os.path.dirname(config_path) + '/' + config['data'], 'r') as f:
data_config = json.loads(f.read())
with open(os.path.dirname(config_path) + '/' + config['preprocess'], 'r') as f:
pre_config = json.loads(f.read())
with open(os.path.dirname(config_path) + '/' + config['train'], 'r') as f:
train_config = json.loads(f.read())
fac_d = math.pow(pre_config['factor'], 1/data_config['dim'])
par_cnt = pre_config['par_cnt']
par_cnt_ref = pre_config['par_cnt_ref']
patch_size = pre_config['patch_size'] * data_config['res'] / fac_d
patch_size_ref = pre_config['patch_size_ref'] * data_config['res']
norm_factor = get_norm_factor(data_path, config_path)
config_dict = {**data_config, **pre_config, **train_config}
punet = PUNet(**config_dict)
punet.load_model(data_path + "models/%s_%s_trained.h5" % (data_config['prefix'], config['id']))
features = Model(inputs=punet.model.inputs, outputs=[punet.model.get_layer("concatenate_1").output])
if len(punet.model.inputs) > 1:
print("Too many inputs!")
exit()
if mode < 10: # synthetic data
input_points = np.ones((cnt, par_cnt, punet.model.inputs[0].get_shape()[-1])) * (-2)
if mode == 0:
for i in range(cnt):
input_points[i,0,:3] = i * 0.01
elif mode == 1:
for i in range(cnt):
input_points[i,0,:3] = 0.5
input_points[i,0,3:6] = [i*norm_factor[0]/cnt,0,0]
else:
print("Mode %d not supported!" % mode)
output = features.predict(input_points)[:,0]
write_csv(data_path + "statistics/%s_%s-%s-%s_m%02d_features.csv"%(data_config['prefix'], data_config['id'], pre_config['id'], train_config['id'], mode), output)
if mode >= 10: # real data
d_start = 0
d_end = data_config['test_count']
if dataset < 0:
dataset = d_start
t_start = 0
t_end = data_config['frame_count']
output = None
if mode == 10 or mode == 11:
np.random.seed(patch_seed)
patch_pos = np.random.random((cnt, 3)) * data_config['res'] / fac_d
input_points = np.ones(((t_end-t_start), cnt, par_cnt, punet.model.inputs[0].get_shape()[-1])) * (-2)
src_data = None
p_idx = 0
patch_path = data_path + "statistics/%s_%s-%s-%s_m%02d_patches/"%(data_config['prefix'], data_config['id'], pre_config['id'], train_config['id'], mode)
if not os.path.exists(patch_path):
os.makedirs(patch_path)
patch_path += "patch_%04d.png"
print(t_end)
for t in range(t_start, t_end):
print(t)
path_src = "%sreal/%s_%s_d%03d_%03d" % (data_path, data_config['prefix'], data_config['id'], dataset, t)
src_data, sdf_data, par_aux = get_data(path_src, par_aux=train_config['features'])
patch_extractor = PatchExtractor(src_data, sdf_data, patch_size, par_cnt, pre_config['surf'], 0, aux_data=par_aux, features=train_config['features'], pad_val=pre_config['pad_val'], bnd=data_config['bnd']/fac_d, last_pos=patch_pos, temp_coh=True, stride_hys=1.0, shuffle=True)
patch_pos = patch_extractor.positions
patches = patch_extractor.get_patches()[0]
ci = np.argmin(
|
np.linalg.norm(patches[...,:3], axis=-1)
|
numpy.linalg.norm
|
import numpy as np
import matplotlib as mpl
import mpl_toolkits.axes_grid1 as mplax
import matplotlib.colors as mplc
import matplotlib.cm as mplcm
import numba
import warnings
import scipy.misc as scm
import scipy.optimize as spo
import scipy.ndimage as scnd
import scipy.signal as scsig
import skimage.color as skc
import stemtool as st
def move_by_phase(image_to_move, x_pixels, y_pixels):
"""
Move Images with sub-pixel precision
Parameters
----------
image_to_move: ndarray
Original Image to be moved
x_pixels: float
Pixels to shift in X direction
y_pixels: float
Pixels to Shift in Y direction
Returns
-------
moved_image: ndarray
Moved Image
Notes
-----
The underlying idea is that a shift in the real space
is phase shift in Fourier space. So we take the original
image, and take it's Fourier transform. Also, we calculate
how much the image shifts result in the phase change, by
calculating the Fourier pixel dimensions. We then multiply
the FFT of the image with the phase shift value and then
take the inverse FFT.
:Authors:
<NAME> <<EMAIL>>
"""
image_size = (np.asarray(image_to_move.shape)).astype(int)
fourier_cal_y = np.linspace(
(-image_size[0] / 2), ((image_size[0] / 2) - 1), image_size[0]
)
fourier_cal_y = fourier_cal_y / (image_size[0]).astype(np.float64)
fourier_cal_x = np.linspace(
(-image_size[1] / 2), ((image_size[1] / 2) - 1), image_size[1]
)
fourier_cal_x = fourier_cal_x / (image_size[1]).astype(np.float64)
[fourier_mesh_x, fourier_mesh_y] = np.meshgrid(fourier_cal_x, fourier_cal_y)
move_matrix = np.multiply(fourier_mesh_x, x_pixels) + np.multiply(
fourier_mesh_y, y_pixels
)
move_phase = np.exp((-2) * np.pi * 1j * move_matrix)
original_image_fft = np.fft.fftshift(np.fft.fft2(image_to_move))
moved_in_fourier = np.multiply(move_phase, original_image_fft)
moved_image = np.fft.ifft2(moved_in_fourier)
return moved_image
def image_normalizer(image_orig):
"""
Normalizing Image
Parameters
----------
image_orig: ndarray
'image_orig' is the original input image to be normalized
Returns
-------
image_norm: ndarray
Normalized Image
Notes
-----
We normalize a real valued image here
so that it's values lie between o and 1.
This is done by first subtracting the
minimum value of the image from the
image itself, and then subsequently
dividing the image by the maximum value
of the subtracted image.
:Authors:
<NAME> <<EMAIL>>
"""
image_norm = np.zeros_like(image_orig, dtype=np.float64)
image_norm = (image_orig -
|
np.amin(image_orig)
|
numpy.amin
|
"""
Analyze PGWAVE seeds
$Header: /nfs/slac/g/glast/ground/cvs/pointlike/python/uw/like2/analyze/pgwave.py,v 1.1 2016/03/21 18:54:57 burnett Exp $
"""
import os, pickle
import numpy as np
import pylab as plt
import pandas as pd
from skymaps import SkyDir
from .. import associate, seeds
from .analysis_base import FloatFormat
from . import (analysis_base, _html, sourceinfo)
from analysis_base import html_table, FloatFormat
class PGwave( sourceinfo.SourceInfo):
"""Analysis of the PGWave seeds
<br>
<p>
From file %(pgw_filename)s, month %(month)s
"""
def setup(self, **kw):
self.plotfolder = self.seedname='pgwave'
self.spectral_type='power law'
assert self.skymodel.startswith('month'), 'Current folder not a month'
self.month=int(self.skymodel[5:]);
try:
self.pgw_filename='/nfs/farm/g/glast/g/catalog/transients/TBIN_%d_all_pgw.txt'% (self.month-1)
assert os.path.exists(self.pgw_filename), 'PGWAVE file %s not found'% pgw_filensme
t=self.df = seeds.read_seedfile('pgw')
prefix = 'PGW_%02d'%self.month
except:
self.pgw_filename='/nfs/farm/g/glast/g/catalog/transients/P302/PGW/1m_1mp15_PGW_ALL.fits'
t=self.df = seeds.read_seedfile('PGW')
prefix = 'PG{:02d}'.format(self.month)
sdirs = map(SkyDir, t.ra,t.dec)
t['l']=[s.l() for s in sdirs]
t.l[t.l>180]-=360
t['b']=[s.b() for s in sdirs]
# now make tables for sources that were accepted
sdf = pickle.load(open('sources.pickle'))
used = [n.startswith(prefix) for n in sdf.index]
self.udf=udf = sdf[used]
good = (udf.ts>10) & (udf.a<0.50) & (udf.locqual<8)
print ('Used, good:',sum(used),sum(good))
self.good=good
def skyplot(self):
"""seed positions
"""
t=self.df
fig, axx = plt.subplots(2,2, figsize=(12,12))
ax = axx[0,0]
ax.plot(t.l, t.b, '.')
plt.setp(ax, xlabel='l', ylabel='b', xlim=(180,-180), ylim=(-90,90))
ax.axhline(0, color='k', alpha=0.3)
ax.axvline(0, color='k', alpha=0.3)
ax = axx[1,0]
sinb = np.sin(np.radians(t.b))
dom = np.linspace(-1,1,51)
ax.hist(list(sinb),dom);
plt.setp(ax, xlabel='sin(b)')
ax.grid(True, alpha=0.5)
ax = axx[0,1]
ax.plot(t.l, t.b, '.')
plt.setp(ax, xlabel='l', ylabel='b', xlim=(180,-180), ylim=(-25,25))
ax.axhline(0, color='k', alpha=0.3)
ax.axvline(0, color='k', alpha=0.3)
ax= axx[1,1]
ax.hist(list(t.l), np.linspace(-180, 180,31));
plt.setp(ax, xlim=(180,-180), xlabel='l')
ax.grid(True, alpha=0.5)
return fig
def seed_skyplot(self):
"""seed positions
"""
t=self.df
fig, ax = plt.subplots(1,1, figsize=(8,8))
ax.plot(t.l, t.b, '.')
plt.setp(ax, xlabel='l', ylabel='b', xlim=(180,-180), ylim=(-90,90))
ax.axhline(0, color='k', alpha=0.8)
ax.axvline(0, color='k', alpha=0.8)
return fig
def pg_cumulative_ts(self):
""" Cumulative TS for accepted seeds
"""
fig=self.cumulative_ts(self.udf[self.good].ts, check_localized=False);
plt.setp(fig.get_axes()[0], xlim=(9,100), ylim=(1,100))
return fig
def skyplot_good(self):
""" positions of accepted PGWAVE seeds
"""
udf = self.udf
good =self.good
glon =
|
np.array(udf.glon[good],float)
|
numpy.array
|
"""
Optimization code for Gaussian Process
"""
import numpy as np
from numpy.linalg import LinAlgError
from scipy.linalg import cholesky, cho_solve
from scipy.spatial.distance import pdist, squareform
from .math import ichol_gauss
def elbo(params, mask, *args):
"""ELBO with full posterior covariance matrix"""
t, mu, post_cov = args
K, dK = kernel(t, params)
dK *= mask[np.newaxis, np.newaxis, :]
try:
L = cholesky(K, lower=True)
except LinAlgError:
return -np.inf, np.zeros_like(params)
Kinv = cho_solve((L, True), np.eye(K.shape[0])) # K inverse
if mu.ndim == 1:
mu = mu[:, np.newaxis]
alpha = cho_solve((L, True), mu)
ll_dims = -0.5 * np.einsum("ik,ik->k", mu, alpha)
tmp =
|
np.einsum("ik,jk->ijk", alpha, alpha)
|
numpy.einsum
|
import numpy as np
import os.path
import scipy.misc
import imageio
import tensorflow as tf
import time
import scipy.io
import pdb
import myParams
import GTools as GT
from tensorflow.python.client import timeline
FLAGS = tf.app.flags.FLAGS
def np3DCToImg(label,FN):
# label=label+0.37;
LabelA=np.sqrt(np.power(label[:,:,:,0],2)+np.power(label[:,:,:,1],2))
LabelP=np.arctan2(label[:,:,:,1],label[:,:,:,0])/(2*np.pi)+0.5;
image = np.concatenate([label[:,:,:,0], label[:,:,:,1],LabelA,LabelP], axis=2)
image = np.reshape(image,[image.shape[0], image.shape[1], image.shape[2], 1])
image = np.concatenate([image,image,image], axis=3)
image = image[:,:,:,:]
image=np.reshape(image,[image.shape[1], image.shape[2],image.shape[3]])
filename = '%s.png' % (FN)
filename = os.path.join(myParams.myDict['train_dir'], filename)
# scipy.misc.toimage(image, cmin=0., cmax=1.).save(filename)
imageio.imwrite(filename,image)
return
def _summarize_progress(train_data, label, gene_output, batch, suffix, max_samples=8):
td = train_data
size = [label.shape[1], label.shape[2]]
if max_samples>myParams.myDict['batch_size']:
max_samples=myParams.myDict['batch_size']
# AEops = [v for v in td.sess.graph.get_operations() if "ForPNG" in v.name and not ("_1" in v.name)]
# AEouts = [v.outputs[0] for v in AEops]
# label=td.sess.run(AEouts[0])
# filename = 'WV%06d_%s' % (batch, suffix)
# np3DCToImg(label,filename)
if myParams.myDict['ImgMode'] == 'Cmplx_MB':
Matops = [v for v in td.sess.graph.get_operations() if "ForMat" in v.name and not (("_1" in v.name) or ("ApplyAdam" in v.name) or ("Assign" in v.name) or ("read" in v.name) or ("optimizer" in v.name))]
Matouts = [v.outputs[0] for v in Matops]
VLen=Matouts.__len__()
if VLen>1:
for x in Matops: print(x.name +' ' + str(x.outputs[0].shape))
# pdb.set_trace()
# save all:
TrainSummary={}
filenamex = 'ForMat_%06d.mat' % (batch)
filename = os.path.join(myParams.myDict['train_dir'], filenamex)
var_list=[]
for i in range(0, VLen):
var_list.append(Matops[i].name);
tmp=td.sess.run(Matouts[i])
s1=Matops[i].name
print("Saving %s" % (s1))
s1=s1.replace(':','_')
s1=s1.replace('/','_')
TrainSummary[s1]=tmp
scipy.io.savemat(filename,TrainSummary)
Matops = [v for v in td.sess.graph.get_operations() if "ForOut" in v.name and not (("_1" in v.name) or ("ApplyAdam" in v.name) or ("Assign" in v.name) or ("read" in v.name) or ("optimizer" in v.name))]
Matouts = [v.outputs[0] for v in Matops]
VLen=Matouts.__len__()
if VLen>1:
for x in Matops: print(x.name +' ' + str(x.outputs[0].shape))
# pdb.set_trace()
# save all:
TrainSummary={}
filenamex = 'ForOut_%06d.mat' % (batch)
filename = os.path.join(myParams.myDict['train_dir'], filenamex)
var_list=[]
for i in range(0, VLen):
var_list.append(Matops[i].name);
tmp=td.sess.run(Matouts[i])
s1=Matops[i].name
print("Saving %s" % (s1))
s1=s1.replace(':','_')
s1=s1.replace('/','_')
TrainSummary[s1]=tmp
scipy.io.savemat(filename,TrainSummary)
LabelA=np.sqrt(np.power(label[:,:,:,0],2)+np.power(label[:,:,:,1],2))
LabelP=np.arctan2(label[:,:,:,1],label[:,:,:,0])/(2*np.pi)+0.5;
GeneA=np.sqrt(np.power(gene_output[:,:,:,0],2)+np.power(gene_output[:,:,:,1],2))
GeneA=np.maximum(np.minimum(GeneA, 1.0), 0.0)
GeneP=np.arctan2(gene_output[:,:,:,1],gene_output[:,:,:,0])/(2*np.pi)+0.5;
gene_output=(gene_output+1)/2
label=(label+1)/2
# clipped = tf.maximum(tf.minimum(gene_output, 1.0), 0.0)
clipped = np.maximum(np.minimum(gene_output, 1.0), 0.0)
# image = tf.concat([clipped[:,:,:,0], label[:,:,:,0], clipped[:,:,:,1], label[:,:,:,1],LabelA,GeneA,LabelP,GeneP], 2)
image=np.concatenate((clipped[:,:,:,0], label[:,:,:,0], clipped[:,:,:,1], label[:,:,:,1],LabelA,GeneA,LabelP,GeneP), axis=2)
# image = tf.reshape(image,[image.shape[0], image.shape[1], image.shape[2], 1])
image = np.reshape(image,[image.shape[0], image.shape[1], image.shape[2], 1])
# image = tf.concat([image,image,image], 3)
image = np.concatenate((image,image,image), axis=3)
image = image[0:max_samples,:,:,:]
# image = tf.concat([image[i,:,:,:] for i in range(int(max_samples))], 0)
# image = np.concatenate(((image[i,:,:,:] for i in ra/nge(int(max_samples)))), axis=0)
image = np.reshape(image,[image.shape[0]*image.shape[1],image.shape[2],image.shape[3]])
# image = td.sess.run(image)
filename = 'batch%06d_%s.png' % (batch, suffix)
filename = os.path.join(myParams.myDict['train_dir'], filename)
# scipy.misc.toimage(image, cmin=0., cmax=1.).save(filename)
imageio.imwrite(filename,image)
print(" Saved %s" % (filename,))
return
if myParams.myDict['ImgMode'] == 'Cmplx_AP':
Matops = [v for v in td.sess.graph.get_operations() if "ForMat" in v.name and not (("_1" in v.name) or ("ApplyAdam" in v.name) or ("Assign" in v.name) or ("read" in v.name) or ("optimizer" in v.name))]
Matouts = [v.outputs[0] for v in Matops]
VLen=Matouts.__len__()
if VLen>1:
for x in Matops: print(x.name +' ' + str(x.outputs[0].shape))
# pdb.set_trace()
# save all:
TrainSummary={}
filenamex = 'ForMat_%06d.mat' % (batch)
filename = os.path.join(myParams.myDict['train_dir'], filenamex)
var_list=[]
for i in range(0, VLen):
var_list.append(Matops[i].name);
tmp=td.sess.run(Matouts[i])
s1=Matops[i].name
print("Saving %s" % (s1))
s1=s1.replace(':','_')
s1=s1.replace('/','_')
TrainSummary[s1]=tmp
scipy.io.savemat(filename,TrainSummary)
Matops = [v for v in td.sess.graph.get_operations() if "ForOut" in v.name and not (("_1" in v.name) or ("ApplyAdam" in v.name) or ("Assign" in v.name) or ("read" in v.name) or ("optimizer" in v.name))]
Matouts = [v.outputs[0] for v in Matops]
VLen=Matouts.__len__()
if VLen>1:
for x in Matops: print(x.name +' ' + str(x.outputs[0].shape))
# pdb.set_trace()
# save all:
TrainSummary={}
filenamex = 'ForOut_%06d.mat' % (batch)
filename = os.path.join(myParams.myDict['train_dir'], filenamex)
var_list=[]
for i in range(0, VLen):
var_list.append(Matops[i].name);
tmp=td.sess.run(Matouts[i])
s1=Matops[i].name
print("Saving %s" % (s1))
s1=s1.replace(':','_')
s1=s1.replace('/','_')
TrainSummary[s1]=tmp
scipy.io.savemat(filename,TrainSummary)
LabelA=np.sqrt(np.power(label[:,:,:,0],2)+np.power(label[:,:,:,1],2))
LabelP=np.arctan2(label[:,:,:,1],label[:,:,:,0])/(2*np.pi)+0.5;
GeneA=np.sqrt(np.power(gene_output[:,:,:,0],2)+np.power(gene_output[:,:,:,1],2))
GeneA=np.maximum(np.minimum(GeneA, 1.0), 0.0)
GeneP=np.arctan2(gene_output[:,:,:,1],gene_output[:,:,:,0])/(2*np.pi)+0.5;
gene_output=(gene_output+1)/2
label=(label+1)/2
# clipped = tf.maximum(tf.minimum(gene_output, 1.0), 0.0)
clipped = np.maximum(np.minimum(gene_output, 1.0), 0.0)
# image = tf.concat([clipped[:,:,:,0], label[:,:,:,0], clipped[:,:,:,1], label[:,:,:,1],LabelA,GeneA,LabelP,GeneP], 2)
# image=np.concatenate((clipped[:,:,:,0], label[:,:,:,0], clipped[:,:,:,1], label[:,:,:,1],LabelA,GeneA,LabelP,GeneP), axis=2)
image=np.concatenate((LabelA,GeneA,LabelP,GeneP), axis=2)
# image = tf.reshape(image,[image.shape[0], image.shape[1], image.shape[2], 1])
image = np.reshape(image,[image.shape[0], image.shape[1], image.shape[2], 1])
# image = tf.concat([image,image,image], 3)
image = np.concatenate((image,image,image), axis=3)
image = image[0:max_samples,:,:,:]
# image = tf.concat([image[i,:,:,:] for i in range(int(max_samples))], 0)
# image = np.concatenate(((image[i,:,:,:] for i in ra/nge(int(max_samples)))), axis=0)
# image = np.concatenate((image[0,:,:,:],image[1,:,:,:],image[2,:,:,:],image[3,:,:,:],image[4,:,:,:],image[5,:,:,:],image[6,:,:,:],image[7,:,:,:]), axis=0)
# image = np.concatenate((image[0,:,:,:],image[1,:,:,:],image[2,:,:,:],image[3,:,:,:],image[4,:,:,:],image[5,:,:,:]), axis=0)
# image = np.concatenate((image[0,:,:,:],image[1,:,:,:],image[2,:,:,:],image[3,:,:,:]), axis=0)
image = np.reshape(image,[image.shape[0]*image.shape[1],image.shape[2],image.shape[3]])
# image = td.sess.run(image)
filename = 'batch%06d_%s.png' % (batch, suffix)
filename = os.path.join(myParams.myDict['train_dir'], filename)
# scipy.misc.toimage(image, cmin=0., cmax=1.).save(filename)
imageio.imwrite(filename,image)
print(" Saved %s" % (filename,))
return
if myParams.myDict['ImgMode'] == 'Cmplx':
Matops = [v for v in td.sess.graph.get_operations() if "ForMat" in v.name and not (("_1" in v.name) or ("ApplyAdam" in v.name) or ("Assign" in v.name) or ("read" in v.name) or ("optimizer" in v.name))]
Matouts = [v.outputs[0] for v in Matops]
VLen=Matouts.__len__()
if VLen>1:
for x in Matops: print(x.name +' ' + str(x.outputs[0].shape))
# pdb.set_trace()
# save all:
TrainSummary={}
filenamex = 'ForMat_%06d.mat' % (batch)
filename = os.path.join(myParams.myDict['train_dir'], filenamex)
var_list=[]
for i in range(0, VLen):
var_list.append(Matops[i].name);
tmp=td.sess.run(Matouts[i])
s1=Matops[i].name
print("Saving %s" % (s1))
s1=s1.replace(':','_')
s1=s1.replace('/','_')
TrainSummary[s1]=tmp
scipy.io.savemat(filename,TrainSummary)
Matops = [v for v in td.sess.graph.get_operations() if "ForOut" in v.name and not (("_1" in v.name) or ("ApplyAdam" in v.name) or ("Assign" in v.name) or ("read" in v.name) or ("optimizer" in v.name))]
Matouts = [v.outputs[0] for v in Matops]
VLen=Matouts.__len__()
if VLen>1:
for x in Matops: print(x.name +' ' + str(x.outputs[0].shape))
# pdb.set_trace()
# save all:
TrainSummary={}
filenamex = 'ForOut_%06d.mat' % (batch)
filename = os.path.join(myParams.myDict['train_dir'], filenamex)
var_list=[]
for i in range(0, VLen):
var_list.append(Matops[i].name);
tmp=td.sess.run(Matouts[i])
s1=Matops[i].name
print("Saving %s" % (s1))
s1=s1.replace(':','_')
s1=s1.replace('/','_')
TrainSummary[s1]=tmp
scipy.io.savemat(filename,TrainSummary)
LabelA=np.sqrt(np.power(label[:,:,:,0],2)+np.power(label[:,:,:,1],2))
LabelP=np.arctan2(label[:,:,:,1],label[:,:,:,0])/(2*np.pi)+0.5;
GeneA=np.sqrt(np.power(gene_output[:,:,:,0],2)+np.power(gene_output[:,:,:,1],2))
GeneA=np.maximum(np.minimum(GeneA, 1.0), 0.0)
GeneP=np.arctan2(gene_output[:,:,:,1],gene_output[:,:,:,0])/(2*np.pi)+0.5;
gene_output=(gene_output+1)/2
label=(label+1)/2
# clipped = tf.maximum(tf.minimum(gene_output, 1.0), 0.0)
clipped = np.maximum(np.minimum(gene_output, 1.0), 0.0)
# image = tf.concat([clipped[:,:,:,0], label[:,:,:,0], clipped[:,:,:,1], label[:,:,:,1],LabelA,GeneA,LabelP,GeneP], 2)
image=np.concatenate((clipped[:,:,:,0], label[:,:,:,0], clipped[:,:,:,1], label[:,:,:,1],LabelA,GeneA,LabelP,GeneP), axis=2)
# image = tf.reshape(image,[image.shape[0], image.shape[1], image.shape[2], 1])
image = np.reshape(image,[image.shape[0], image.shape[1], image.shape[2], 1])
# image = tf.concat([image,image,image], 3)
image = np.concatenate((image,image,image), axis=3)
image = image[0:max_samples,:,:,:]
# image = tf.concat([image[i,:,:,:] for i in range(int(max_samples))], 0)
# image = np.concatenate(((image[i,:,:,:] for i in ra/nge(int(max_samples)))), axis=0)
# image = np.concatenate((image[0,:,:,:],image[1,:,:,:],image[2,:,:,:],image[3,:,:,:],image[4,:,:,:],image[5,:,:,:],image[6,:,:,:],image[7,:,:,:]), axis=0)
# image = np.concatenate((image[0,:,:,:],image[1,:,:,:],image[2,:,:,:],image[3,:,:,:],image[4,:,:,:],image[5,:,:,:]), axis=0)
# image = np.concatenate((image[0,:,:,:],image[1,:,:,:],image[2,:,:,:],image[3,:,:,:]), axis=0)
image = np.reshape(image,[image.shape[0]*image.shape[1],image.shape[2],image.shape[3]])
# image = td.sess.run(image)
filename = 'batch%06d_%s.png' % (batch, suffix)
filename = os.path.join(myParams.myDict['train_dir'], filename)
# scipy.misc.toimage(image, cmin=0., cmax=1.).save(filename)
imageio.imwrite(filename,image)
print(" Saved %s" % (filename,))
return
if myParams.myDict['ImgMode'] == 'SimpleImg2':
clipped = np.maximum(np.minimum(gene_output, 1.0), 0.0)
image=np.concatenate((clipped[:,:,:,0],label[:,:,:,0],clipped[:,:,:,1],label[:,:,:,1]), axis=2)
image = np.reshape(image,[image.shape[0], image.shape[1], image.shape[2], 1])
image = np.concatenate((image,image,image), axis=3)
image = image[0:max_samples,:,:,:]
image =
|
np.reshape(image,[image.shape[0]*image.shape[1],image.shape[2],image.shape[3]])
|
numpy.reshape
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
An extension to the standard STScI data model for MIRI dark reference
data. Essentially the same as the MIRI measured image data model, with
additional metadata.
:Reference:
The STScI jwst.datamodels documentation. See
https://jwst-pipeline.readthedocs.io/en/latest/jwst/datamodels/index.html
:History:
19 Dec 2012: Created
21 Jan 2013: Included data type in metadata.
23 Jan 2013: Added plotting.
05 Feb 2013: Reformatted test code using "with" context manager.
Modified to use functions from MiriDataModel.
08 Feb 2013: Replaced 'to_fits' with more generic 'save' method.
21 Feb 2013: Base a dark reference model on MiriMeasuredModel rather than
MiriRampModel, to allow for 3-D dark data.
04 Mar 2013: Only check the dimensionality of the main data array if it
has been explicitly provided.
04 Jul 2013: Don't display masked data when it is the same as
unmasked data.
10 Dec 2013: Delimiter in MIRI schema names changed from "." to "_".
10 Apr 2014: Modified for jsonschema draft 4: Functions made more
independent of schema structure. Modified to define data
units using the set_data_units method.
09 Jul 2014: JWST reference flags table added.
29 Aug 2014: JWST reference flags table updated.
Included new reference file keywords (REFTYPE, AUTHOR, PEDIGREE)
25 Sep 2014: Updated the reference flags. insert_value_column function
used to convert between 3 column and 4 column flag tables.
TYPE and REFTYPE are no longer identical.
30 Sep 2014: Superflous flags commented out.
28 Oct 2014: Disabled automatic inclusion of the FITERR extension.
16 Jan 2015: Ensure the main data array is 3-D or 4-D when specified
explicitly or when read from a file.
20 Aug 2015: Duplicated parts of schema now reference STScI model.
11 Sep 2015: Removed duplicated plot method.
01 Jun 2016: DARK data can now be 2-D, 3-D or 4-D.
20 Jun 2016: DARK DQ array can also now be 2-D, 3-D or 4-D.
15 Jul 2016: Removed obsolete flags.
17 Mar 2017: Corrected some documentation typos.
15 Jun 2017: Added average_group and extract_group methods.
Added a comment to the data model created by the
average_group and extract_group methods.
15 Jun 2017: meta.reffile schema level removed to match changes in the
JWST build 7.1 data models release. meta.reffile.type also
changed to meta.reftype. TYPE keyword replaced by DATAMODL.
Added average_groups function.
07 Jul 2017: Added averaged flag.
12 Jul 2017: Replaced "clobber" parameter with "overwrite".
06 Jul 2018: Merged schema with JWST software. DARK data is now only
accepted with 4-D data, err and dq arrays.
15 Nov 2018: Schema switched to use JWST darkMIRI.schema.
3-D DARK reference data are no longer accepted.
30 Jan 2019: self.meta.model_type now set to the name of the STScI data
model this model is designed to match (skipped if there isn't
a corresponding model defined in ancestry.py).
07 Oct 2019: Removed '.yaml' suffix from schema references.
26 Mar 2020: Ensure the model_type remains as originally defined when saving
to a file.
@author: <NAME> (UKATC), <NAME> (UKATC)
"""
import numpy as np
#import numpy.ma as ma
#import numpy.linalg as LA
# Import the MIRI ramp data model utilities.
from miri.datamodels.ancestry import get_my_model_type
from miri.datamodels.dqflags import insert_value_column
from miri.datamodels.miri_measured_model import MiriMeasuredModel
# List all classes and global functions here.
__all__ = ['dark_reference_flags', 'MiriDarkReferenceModel']
# The new JWST dark reference flags. Note that these flags are a subset
# of the JWST master flags table. The names and descriptions are the same
# but the bit values can be different.
dark_reference_setup = \
[(0, 'DO_NOT_USE', 'Bad pixel. Do not use.'),
(1, 'UNRELIABLE_DARK', 'Dark variance large')]
dark_reference_flags = insert_value_column(dark_reference_setup)
#
# Global helper function
#
def linear_regression(x, y):
"""
Linear regression function. Fit an intercept and a slope
to a set of x,y coordinates
"""
#print("Fitting", y, "\nagainst", x)
matrix = np.vstack( [x, np.ones_like(x)] ).T
slope, intercept = np.linalg.lstsq(matrix,y)[0]
#print("gives slope=", slope, "intercept=", intercept)
return (slope, intercept)
class MiriDarkReferenceModel(MiriMeasuredModel):
"""
A data model for MIRI dark reference data.
:Parameters:
init: shape tuple, file path, file object, pyfits.HDUList, numpy array
An optional initializer for the data model, which can have one
of the following forms:
* None: A default data model with no shape. (If a data array is
provided in the data parameter, the shape is derived from the
array.)
* Shape tuple: Initialize with empty data of the given shape.
* File path: Initialize from the given file.
* Readable file object: Initialize from the given file object.
* pyfits.HDUList: Initialize from the given pyfits.HDUList.
data: numpy array (optional)
A 3-D or 4-D array containing the dark data.
If a data parameter is provided, its contents overwrite the
data initialized by the init parameter.
err: numpy array (optional)
An array containing the uncertainty in the dark data.
Must be broadcastable onto the data array.
dq: numpy array (optional)
An array containing the quality of the dark data.
Must be broadcastable onto the data array.
dq_def: list of tuples or numpy record array (optional)
Either: A list of tuples containing (value:int, name:str, title:str),
giving the meaning of values stored in the data quality array. For
example: [(0, 'good','Good data'), (1, 'dead', 'Dead Pixel'),
(2, 'hot', 'Hot Pixel')];
Or: A numpy record array containing the same information as above.
If not specified, it will default to the MIRI reserved flags.
integration: number, optional
The integration number for which this dark is valid.
fitted_after_frame: number, optional
The frame number beyond which the dark is fitted.
averaged: bool, optional
Indicates if the data model contains averaged dark data.
The default is False.
\*\*kwargs:
All other keyword arguments are passed to the DataModel initialiser.
See the jwst.datamodels documentation for the meaning of these keywords.
"""
schema_url = "miri_dark_reference.schema"
_default_dq_def = dark_reference_flags
def __init__(self, init=None, data=None, dq=None, err=None,
dq_def=None, integration=None, fitted_after=None,
averaged=False, **kwargs):
"""
Initialises the MiriDarkReferenceModel class.
Parameters: See class doc string.
"""
super(MiriDarkReferenceModel, self).__init__(init=init, data=data,
dq=dq, err=err,
dq_def=dq_def,
**kwargs)
# Data type is dark.
self.meta.reftype = 'DARK'
# Initialise the model type
self._init_data_type()
self.averaged = averaged
# This is a reference data model.
self._reference_model()
# Define the exposure type (if not already contained in the data model)
if not self.meta.exposure.type:
self.set_exposure_type( datatype='DARK' )
if integration is not None:
self.meta.integration_number = integration
if fitted_after is not None:
self.meta.fitted_after_frame = fitted_after
# The main data array should be 2-D, 3-D or 4-D.
# TODO: Can this check be included in the schema?
if data is not None:
if not hasattr(data, 'ndim'):
data = np.asarray(data)
if data.ndim < 2 or data.ndim > 4:
strg = "The main data array in a dark reference object must be "
strg += "2-D, 3-D or 4-D. %d-D data provided" % data.ndim
raise ValueError(strg)
elif self.data is not None and len(self.data) > 0 and \
hasattr(self.data, 'ndim'):
if self.data.ndim < 2 or self.data.ndim > 4:
strg = "The main data array in a dark reference object must be "
strg += "2-D, 3-D or 4-D. %d-D data provided" % self.data.ndim
raise ValueError(strg)
# if fiterr is not None:
# self.fiterr = fiterr
# self._fiterr_mask = None
# self._fiterr_fill = 'max'
# self._fiterr_fill_value = None
#
# # Set the units of the fiterr array, if defined in the schema.
# fitunits = self.set_data_units('fiterr')
def _init_data_type(self):
# Initialise the data model type
model_type = get_my_model_type( self.__class__.__name__ )
self.meta.model_type = model_type
def on_save(self, path):
super(MiriDarkReferenceModel, self).on_save(path)
# Re-initialise data type on save
self._init_data_type()
def __str__(self):
"""
Return the contents of the dark reference object as a readable
string.
"""
# First obtain a string describing the underlying measured
# model.
strg = super(MiriDarkReferenceModel, self).__str__()
# Add the extras
# if self.fiterr is not None:
# strg += self.get_data_str('fiterr', underline=True, underchar="-")
# if self.maskable():
# fiterr_masked = self.fiterr_masked
# if fiterr_masked is not None:
# title = self.get_data_title('fiterr') + " (masked)"
# len2 = len(title)
# title += "\n" + (len2 * '~')
# strg += title + "\n" + str(fiterr_masked) + "\n"
return strg
def slope_data(self, startgroup=None, endgroup=None):
"""
Return a new data model in which the group planes have
been fitted with a straight line to make slope data.
The units of the output data change from 'DN' to 'DN/s'
NOTE: This function is very inefficient!
:Parameters:
startgroup: int, optional
The first group to be averaged. Defaults to the first group
in the data model.
endgroup: int, optional
The last group to be averaged. Defaults to the last group in
the data model.
:Returned:
slope_model: MiriDarkReferenceModel
A MiriDarkReferenceModel with a slope fitted to all
the group data.
"""
# First determine the group time from the detector readout mode
grptime = 1.0
if hasattr(self, 'meta') and hasattr( self.meta, 'exposure'):
if hasattr(self.meta.exposure, 'group_time') and \
self.meta.exposure.group_time is not None:
grptime = self.meta.exposure.group_time
elif hasattr( self.meta.exposure, 'readpatt') and \
self.meta.exposure.readpatt is not None:
readpatt = self.meta.exposure.readpatt
# TODO: Subarray modes not implemented yet
if 'FAST' in readpatt:
grptime = 2.785
else:
grptime = 27.85
if hasattr(self.meta.exposure, 'group_time'):
self.meta.exposure.group_time = grptime
if self.data.ndim == 4:
nints = self.data.shape[0]
ngroups = self.data.shape[1]
nrows = self.data.shape[2]
ncolumns = self.data.shape[3]
# Initialise the output.
output = np.zeros([nints, nrows, ncolumns], dtype=self.data.dtype)
# Full straight line fit
if startgroup is None and endgroup is None:
timearray = grptime * np.array( list(range(0, ngroups)) )
for intg in range(0, nints):
for row in range(0, nrows):
for column in range(0, ncolumns):
# Ouch! Slope calculated one (row,column) at a time.
# Can the efficiency be improved?
(slope, ic) = linear_regression( timearray,
self.data[intg,:,row,column] )
output[intg,row,column] = slope
else:
if startgroup is None:
startgroup = 0
if endgroup is None:
endgroup = self.data.shape[1]
timearray = grptime * np.array( list(range(startgroup, endgroup)) )
for intg in range(0, nints):
for row in range(0, nrows):
for column in range(0, ncolumns):
# Ouch! Slope calculated one (row,column) at a time.
# Can the efficiency be improved?
(slope, ic) = linear_regression( timearray,
self.data[intg,startgroup:endgroup,row,column] )
output[intg,row,column] = slope
output_dq = np.squeeze(self.dq)
# Create a new 3-D dark data model from this slope data.
newmodel = MiriDarkReferenceModel( data=output, err=None,
dq=output_dq )
# Copy the metadata to the new data model.
# NOTE: The WCS metadata may be copied incorrectly.
newmodel.copy_metadata( self )
if grptime == 1.0:
newmodel.meta.data.units = 'DN/group'
else:
newmodel.meta.data.units = 'DN/s'
newmodel.add_comment( "TGROUP assumed %.3fs" % grptime )
historystrg = "New DARK made by calculating the slope for %d groups" % \
ngroups
newmodel.add_comment( historystrg )
return newmodel
elif self.data.ndim == 3:
ngroups = self.data.shape[0]
nrows = self.data.shape[1]
ncolumns = self.data.shape[2]
# Initialise the output.
output = np.zeros([nrows, ncolumns], dtype=self.data.dtype)
# Full straight line fit
if startgroup is None and endgroup is None:
timearray = grptime * np.array( list(range(0, ngroups)) )
for row in range(0, nrows):
for column in range(0, ncolumns):
# Ouch! Slope calculated one (row,column) at a time.
# Can the efficiency be improved?
(slope, ic) = linear_regression( timearray,
self.data[intg,:,row,column] )
output[intg,row,column] = slope
else:
if startgroup is None:
startgroup = 0
if endgroup is None:
endgroup = self.data.shape[1]
timearray = grptime * np.array( list(range(startgroup, endgroup)) )
for row in range(0, nrows):
for column in range(0, ncolumns):
# Ouch! Slope calculated one (row,column) at a time.
# Can the efficiency be improved?
(slope, ic) = linear_regression( timearray,
self.data[intg,startgroup:endgroup,row,column] )
output[intg,row,column] = slope
output_dq = np.squeeze(self.dq)
# Create a new 3-D dark data model from this slope data.
newmodel = MiriDarkReferenceModel( data=output, err=None,
dq=output_dq, averaged=True )
# Copy the metadata to the new data model.
# NOTE: The WCS metadata may be copied incorrectly.
newmodel.copy_metadata( self )
if grptime == 1.0:
newmodel.meta.data.units = 'DN/group'
else:
newmodel.meta.data.units = 'DN/s'
newmodel.add_comment( "TGROUP assumed %.3fs" % grptime )
historystrg = "New DARK made by calculating the slope for %d groups" % \
ngroups
newmodel.add_comment( historystrg )
return newmodel
else:
raise TypeError("Data model has wrong number of dimensions")
def average_groups(self, startgroup=None, endgroup=None, normalize=False):
"""
Return a new data model in which the groups have been averaged.
A 4-D data model [integrations, groups, rows, columns] will be
reduced to 3-D [integrations, rows, columns] and a 3-D model
[groups, rows, columns] will be reduced to 2-D [rows, columns].
:Parameters:
startgroup: int, optional
The first group to be averaged. Defaults to the first group
in the data model.
endgroup: int, optional
The last group to be averaged. Defaults to the last group in
the data model.
normalize: bool, optional
If True, normalize the data so the average is 1.0.
The default is False.
:Returned:
averaged_model: MiriDarkReferenceModel
A MiriDarkReferenceModel with all the group data averaged together.
"""
if self.data.ndim == 4:
# Determine a new 3-D dark data model by averaging together
# the specified groups.
if startgroup is None and endgroup is None:
ngroups = self.data.shape[1]
cube_data = np.sum(self.data, 1)
cube_data = cube_data / float(ngroups)
#cube_err = LA.norm(self.err, ord=2, axis=1)
errsq = self.err * self.err
cube_err = np.sum(errsq, 1)
cube_err = np.sqrt( cube_err ) / float(ngroups)
else:
if startgroup is None:
startgroup = 0
if endgroup is None:
endgroup = self.data.shape[1]
ngroups = endgroup - startgroup + 1
cube_data = np.sum(self.data[:,startgroup:endgroup,:,:], 1)
cube_data = cube_data / float(ngroups)
#cube_err = LA.norm(self.err, ord=2, axis=1)
errsq = self.err[:,startgroup:endgroup,:,:] * \
self.err[:,startgroup:endgroup,:,:]
cube_err = np.sum(errsq, 1)
cube_err = np.sqrt( cube_err ) / float(ngroups)
if normalize:
posdata = np.where(cube_data > 0.0)
factor = np.mean(cube_data[posdata])
# print("Normalizing by a factor of %f" % factor)
if factor > 0.0:
cube_data = cube_data / factor
cube_err = cube_err / factor
cube_dq = np.squeeze(self.dq)
newmodel = MiriDarkReferenceModel( data=cube_data, err=cube_err,
dq=cube_dq )
# Copy the metadata to the new data model.
# NOTE: The WCS metadata may be copied incorrectly.
newmodel.copy_metadata( self )
historystrg = "New DARK made by averaging groups %d to %d" % \
(startgroup, endgroup)
if normalize:
historystrg += " (normalized to 1.0)"
newmodel.add_comment( historystrg )
return newmodel
elif self.data.ndim == 3:
# Determine a new 2-D dark data model by averaging together
# all the groups.
if startgroup is None and endgroup is None:
ngroups = self.data.shape[0]
image_data = np.sum(self.data, 0)
image_data = image_data / float(ngroups)
errsq = self.err * self.err
image_err = np.sum(errsq, 0)
image_err = np.sqrt( image_err ) / float(ngroups)
else:
if startgroup is None:
startgroup = 0
if endgroup is None:
endgroup = self.data.shape[0]
ngroups = endgroup - startgroup + 1
image_data = np.sum(self.data[startgroup:endgroup,:,:], 0)
image_data = image_data / float(ngroups)
errsq = self.err[startgroup:endgroup,:,:] * \
self.err[startgroup:endgroup,:,:]
image_err = np.sum(errsq, 0)
image_err = np.sqrt( image_err ) / float(ngroups)
if normalize:
posdata = np.where(image_data > 0.0)
factor = np.mean(image_data[posdata])
# print("Normalizing by a factor of %f" % factor)
if factor > 0.0:
image_data = image_data / factor
image_err = image_err / factor
image_dq = np.squeeze(self.dq)
newmodel = MiriDarkReferenceModel( data=image_data, err=image_err,
dq=image_dq, averaged=True )
# Copy the metadata to the new data model.
# NOTE: The WCS metadata may be copied incorrectly.
newmodel.copy_metadata( self )
historystrg = "New DARK made by averaging groups %d to %d" % \
(startgroup, endgroup)
if normalize:
historystrg += " (normalized to 1.0)"
newmodel.add_comment( historystrg )
return newmodel
else:
raise TypeError("Data model has wrong number of dimensions")
def extract_group(self, group=0, normalize=False):
"""
Return a new data model containing a single group extracted
from the current data model.
A 4-D data model [integrations, groups, rows, columns] will be
reduced to 3-D [integrations, rows, columns] and a 3-D model
[groups, rows, columns] will be reduced to 2-D [rows, columns].
:Parameters:
group: int
The group to be extracted.
normalize: bool, optional
If True, normalize the data so the average is 1.0.
The default is False.
:Returned:
extracted_model: MiriDarkReferenceModel
A MiriDarkReferenceModel with a single group extracted.
"""
if self.data.ndim == 4:
# Determine a new 3-D dark data model by extracting the
# specified group.
cube_data = self.data[:,group,:,:]
cube_err = self.err[:,group,:,:]
if normalize:
posdata = np.where(cube_data > 0.0)
factor = np.mean(cube_data[posdata])
# print("Normalizing by a factor of %f" % factor)
if factor > 0.0:
cube_data = cube_data / factor
cube_err = cube_err / factor
cube_dq = np.squeeze(self.dq)
newmodel = MiriDarkReferenceModel( data=cube_data, err=cube_err,
dq=cube_dq )
# Copy the metadata to the new data model.
# NOTE: The WCS metadata may be copied incorrectly.
newmodel.copy_metadata( self )
historystrg = "New DARK made by extracting group %d" % group
if normalize:
historystrg += " (normalized to 1.0)"
newmodel.add_comment( historystrg )
return newmodel
elif self.data.ndim == 3:
# Determine a new 2-D dark data model by extracting the
# specified group.
image_data = self.data[group,:,:]
image_err = self.err[group,:,:]
if normalize:
posdata = np.where(image_data > 0.0)
factor =
|
np.mean(image_data[posdata])
|
numpy.mean
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 23 12:37:35 2015
Fock State Simulation, based on <NAME>, Chapman group
thesis
use fourth order Runge-Kutta to integrate equations.
@author: zag
"""
import numpy as np
import matplotlib.pyplot as plt
from numba import autojit
import sys
import time
from tqdm import trange
##########################
#Define Runge-Kutta method
##########################
def ynplus1(func, yn,t,dt,**kwargs):
"""evolve Runge kutta with function func which takes two input arguments
yn and t and possibly extra arguments
Parameters
------------
yn : iterable
value at the previous iteration
t : float
the time at current iteration
dt : float
time step
Returns
-----------
yn : iterable
evolution of wavefunction after one step
"""
k1 = func(yn,t,**kwargs)
k2 = func(yn+dt/2*k1,t+dt/2,**kwargs)
k3 = func(yn+dt/2*k2,t+dt/2,**kwargs)
k4 = func(yn+dt*k3,t+dt,**kwargs)
a = k1+ 2 * k2 + 2 * k3 + k4
return yn + dt*a/6
#########################
#Calculate magnetic field
#########################
def heaviside(x):
"""heaviside step function"""
return 0.5 * (np.sign(x) + 1)
def bcon(t):
a = (2-0.210) * heaviside(2e-3 -t)
b = (2-0.210)/2e-3 * heaviside(t)*heaviside(2e-3-t)*t
return a-b + 0.210
def bzdot(Bz,t,tauB):
return 1/tauB*(bcon(t)-Bz)
def calculate_magnetic_field(total_time,dt,tauB):
num_iter = int(total_time/dt)
#prop_func = bzdot(yn,t,tauB)
#create list of magnetic fields
Blist = np.zeros(num_iter)
Blist[0] = bcon(0)
#define function to iterate
def func(yn,t):
return bzdot(yn,t,tauB)
#now iterate in time
for i in range(1,num_iter,1):
Blist[i] = ynplus1(func,Blist[i-1],i*dt,dt)
return Blist
#######################################################################
#FOCK STATE
#Vector is k[i] where [n-1,n0,n1] = [k-m1,N-2k+ml,k], k in (0,(N+ml)/2)
#######################################################################
@autojit
def tri_ham(c,bfield,psi,n_atoms):
'''compute the tridiagonal hamiltonian for fock state
Parameters
----------
c : float
quadratic zeeman shift
bfield : float
magnetic field in hz
psi : np.array(complex)
wavefunction
n_atoms : int
total number of atoms
Returns
-------
ans : np.array(complex)
1d Hamiltonian in pairs basis.
'''
ans = np.empty(len(psi), dtype=complex)
#first for diagonal interation
for i in range(len(psi)):
ans[i] = (i*(2*(n_atoms-2*i))-1)* c/n_atoms*psi[i] + 2 * bfield * i*psi[i]
#now for ineraction with kp = i-1
for i in range(1,len(psi)):
ans[i] += i * np.sqrt((n_atoms - 2 * (i-1) - 1)*(n_atoms - 2*(i-1)))*psi[i-1]* c/n_atoms
#now for kp = i +1
for i in range(len(psi)-1):
ans[i] += (i+1)*np.sqrt((n_atoms-2*(i+1)+1)*(n_atoms-2*(i+1)+2))*psi[i+1]* c/n_atoms
return ans
def tri_ham2(c,bfield,psi,n_atoms,m):
ans = np.empty(len(psi), dtype = complex)
#may need higher precision integration
def func_to_integrate(yn,t,bfield,c,n_atoms):
com = tri_ham(c,bfield,yn,n_atoms)
return np.complex(0,-1)*com
def set_up_simulation(total_time,dt,tauB,mag_time,c,n_atoms):
num_steps = int(total_time/dt)
#calculate B field
b_field = calculate_magnetic_field(mag_time,dt,tauB)
params = {
'c':c,
'n_atoms':n_atoms,
'bfield':b_field[0]
}
b_steps = int(mag_time/dt)
return params, num_steps,b_steps,b_field
def create_init_state(n_atoms,pairs = 0):
state = np.zeros(int(n_atoms/2)+1,dtype = complex)
state[pairs]= np.complex(1,0)
return state
def get_bfield(bfield,b_steps,step):
if step < b_steps:
ans = bfield[step]
else:
ans = 0.21
return 2*np.pi * 276.8 * ans**2*2
################################################
#Calculate Expectation Values
################################################
@autojit
def calc_n0_vals(psi,num_atoms):
n0 = 0
n0sqr = 0
for k in range(len(psi)):
n0 += (num_atoms-2*k) * abs(psi[k])**2
n0sqr += (num_atoms-2*k)**2 * abs(psi[k])**2
n0var = n0sqr - n0**2
return n0, n0sqr , n0var
@autojit
def calc_sx_sqr(psi,n):
ans = 0
#where i indexes k
for i in range(len(psi)):
ans += (-4*i*i+2*i*n-i+n)*np.abs(psi[i]*psi[i])
for i in range(len(psi)-1):
ans += i*np.sqrt((n-2*i+1)*(n-2*i+2))*np.abs(psi[i]*psi[i+1])
for i in range(1,len(psi)):
ans += (i+1)*np.sqrt((n-2*i)*(n-2*i-1))*np.abs(psi[i]*psi[i-1])
return ans
@autojit
def calc_qyz_sqr(psi,n):
ans = 0
#here i indexes k
for i in range(len(psi)):
ans += (-4*i*i+2*i*n-i+n)*np.abs(psi[i]*psi[i])
for i in range(len(psi)-1):
ans += -i*np.sqrt((n-2*i+1)*(n-2*i+2))*np.abs(psi[i]*psi[i+1])
for i in range(1,len(psi)):
ans += -(i+1)*np.sqrt((n-2*i)*(n-2*i-1))*np.abs(psi[i]*psi[i-1])
return ans
###############################################
# main routine
###############################################
def fock_sim(total_time,dt,mag_time,tauB,n_atoms,c, bf,npairs):
try:
"""bf,c,total_time,dt are a list"""
#calculate B field
num_steps = [int(total_time[i]/dt[i]) for i in range(len(dt))]
psi = create_init_state(n_atoms,npairs)
psi_init = create_init_state(n_atoms,npairs)
n0_ret = np.array([])
n0sqr_ret = np.zeros([])
n0var_ret = np.zeros([])
sxsqr_ret = np.zeros([])
qyzsqr_ret = np.zeros([])
time_ret = np.zeros([])
init_norm_ret = np.zeros([])
t_sim = 0
for step in trange(len(dt),desc='outer_loop',leave=True):
params = {
'c':c[step],
'n_atoms':n_atoms,
'bfield':bf[step]**2*277
}
n0 = np.zeros(num_steps[step])
n0sqr = np.zeros(num_steps[step])
n0var = np.zeros(num_steps[step])
sxsqr = np.zeros(num_steps[step])
qyzsqr = np.zeros(num_steps[step])
time =
|
np.zeros(num_steps[step])
|
numpy.zeros
|
__author__ = 'sibirrer'
from astrofunc.LensingProfiles.sis import SIS
import numpy as np
import pytest
class TestSIS(object):
"""
tests the Gaussian methods
"""
def setup(self):
self.SIS = SIS()
def test_function(self):
x = np.array([1])
y = np.array([2])
phi_E = 1.
values = self.SIS.function(x, y, phi_E)
assert values[0] == 2.2360679774997898
x = np.array([0])
y = np.array([0])
phi_E = 1.
values = self.SIS.function( x, y, phi_E)
assert values[0] == 0
x = np.array([2,3,4])
y = np.array([1,1,1])
values = self.SIS.function( x, y, phi_E)
assert values[0] == 2.2360679774997898
assert values[1] == 3.1622776601683795
assert values[2] == 4.1231056256176606
def test_derivatives(self):
x = np.array([1])
y = np.array([2])
phi_E = 1.
f_x, f_y = self.SIS.derivatives( x, y, phi_E)
assert f_x[0] == 0.44721359549995793
assert f_y[0] == 0.89442719099991586
x = np.array([0])
y = np.array([0])
f_x, f_y = self.SIS.derivatives( x, y, phi_E)
assert f_x[0] == 0
assert f_y[0] == 0
x = np.array([1,3,4])
y = np.array([2,1,1])
values = self.SIS.derivatives(x, y, phi_E)
assert values[0][0] == 0.44721359549995793
assert values[1][0] == 0.89442719099991586
assert values[0][1] == 0.94868329805051377
assert values[1][1] == 0.31622776601683794
def test_hessian(self):
x = np.array([1])
y = np.array([2])
phi_E = 1.
f_xx, f_yy,f_xy = self.SIS.hessian( x, y, phi_E)
assert f_xx[0] == 0.35777087639996635
assert f_yy[0] == 0.089442719099991588
assert f_xy[0] == -0.17888543819998318
x =
|
np.array([1,3,4])
|
numpy.array
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import random
import statistics
import tensorflow as tf
from sklearn import linear_model
from sklearn.model_selection import ShuffleSplit
from sklearn.metrics import auc, precision_recall_curve, roc_auc_score
from utils.data_helper import load_test
flags = tf.app.flags
FLAGS = flags.FLAGS
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def get_normalized_inner_product_score(vector1, vector2):
"""
adapted from https://github.com/THUDM/GATNE
Calculate normalized inner product for vector1 and vector2.
"""
return np.dot(vector1, vector2) / (np.linalg.norm(vector1) * np.linalg.norm(vector2))
def get_sigmoid_score(vector1, vector2):
"""
Calculate sigmoid score of the dot product for vector1 and vector2.
"""
return sigmoid(np.dot(vector1, vector2))
def get_average_score(vector1, vector2):
"""
Calculate average (element-wise average) for vector1 and vector2.
Note the result is not a scalar, it has dimension same as vector1 or vector2.
"""
return (vector1 + vector2)/2
def get_hadamard_score(vector1, vector2):
"""
Calculate Hadamard product score (element-wise multiplication) for vector1 and vector2.
Note the result is not a scalar, it has dimension same as vector1 or vector2.
"""
return np.multiply(vector1, vector2)
def get_l1_score(vector1, vector2):
"""
Calculate Weighted-L1 for vector1 and vector2.
Note the result is not a scalar, it has dimension same as vector1 or vector2.
"""
return np.abs(vector1 - vector2)
def get_l2_score(vector1, vector2):
"""
Calculate Weighted-L2 for vector1 and vector2.
Note the result is not a scalar, it has dimension same as vector1 or vector2.
"""
return np.square(vector1 - vector2)
def get_link_score(embeds, node1, node2, score_type):
"""
Calculate link_score for node1 and node2 according to score_type.
"""
if score_type not in ["cosine", "sigmoid", "hadamard", "average", "l1", "l2"]:
raise NotImplementedError
vector_dimension = len(embeds[random.choice(list(embeds.keys()))])
try:
vector1 = embeds[node1]
vector2 = embeds[node2]
except Exception as e:
# print(e)
if score_type in ["cosine", "sigmoid"]:
return 0
elif score_type in ["hadamard", "average", "l1", "l2"]:
return np.zeros(vector_dimension)
if score_type == "cosine":
score = get_normalized_inner_product_score(vector1, vector2)
elif score_type == "sigmoid":
score = get_sigmoid_score(vector1, vector2)
elif score_type == "hadamard":
score = get_hadamard_score(vector1, vector2)
elif score_type == "average":
score = get_average_score(vector1, vector2)
elif score_type == "l1":
score = get_l1_score(vector1, vector2)
elif score_type == "l2":
score = get_l2_score(vector1, vector2)
return score
def get_links_scores(embeds, links, score_type):
"""
Calculate link score for a list of links (node pairs).
"""
features = []
num_links = 0
for l in links:
num_links = num_links + 1
# if num_links % 1000 == 0:
# print("get_links_score, num of edges processed: {}".format(num_links))
node1, node2 = l[0], l[1]
f = get_link_score(embeds, node1, node2, score_type)
features.append(f)
return features
def evaluate_classifier(embeds, train_pos_edges, train_neg_edges, test_pos_edges, test_neg_edges, score_type):
"""
Use Logistic Regression to do link prediction.
"""
train_pos_feats = np.array(get_links_scores(embeds, train_pos_edges, score_type))
train_neg_feats = np.array(get_links_scores(embeds, train_neg_edges, score_type))
train_pos_labels = np.ones(train_pos_feats.shape[0])
train_neg_labels = np.zeros(train_neg_feats.shape[0])
# train_data = np.vstack((train_pos_feats, train_neg_feats))
train_data = np.concatenate((train_pos_feats, train_neg_feats), axis=0)
train_labels = np.append(train_pos_labels, train_neg_labels)
test_pos_feats = np.array(get_links_scores(embeds, test_pos_edges, score_type))
test_neg_feats = np.array(get_links_scores(embeds, test_neg_edges, score_type))
test_pos_labels = np.ones(test_pos_feats.shape[0])
test_neg_labels = np.zeros(test_neg_feats.shape[0])
# test_data = np.vstack((test_pos_feats, test_neg_feats))
test_data = np.concatenate((test_pos_feats, test_neg_feats), axis=0)
test_labels = np.append(test_pos_labels, test_neg_labels)
train_data_indices_not_zero = train_data != 0
# train_data_indices_not_zero = np.prod(train_data, axis=1) == 0
train_data = train_data[train_data_indices_not_zero]
train_labels = train_labels[train_data_indices_not_zero]
test_data_indices_not_zero = test_data != 0
# test_data_indices_not_zero = np.prod(test_data, axis=1) == 0
test_data = test_data[test_data_indices_not_zero]
test_labels = test_labels[test_data_indices_not_zero]
# # training: eliminate the edges formed by new nodes. Their edge feats are 0s.
# train_data_filtered = train_data[(np.product(train_data, axis=1) + np.sum(train_data, axis=1)) != 0, :]
# train_labels_filtered = train_labels[(np.product(train_data, axis=1) + np.sum(train_data, axis=1)) != 0]
train_data_filtered = train_data
train_labels_filtered = train_labels
if len(train_data_filtered.shape) == 1:
train_data_filtered =
|
np.expand_dims(train_data_filtered, axis=1)
|
numpy.expand_dims
|
# Copyright (c) 2020 Mitsubishi Electric Research Laboratories (MERL). All rights reserved. The software, documentation and/or data in this file is provided on an "as is" basis, and MERL has no obligations to provide maintenance, support, updates, enhancements or modifications. MERL specifically disclaims any warranties, including, but not limited to, the implied warranties of merchantability and fitness for any particular purpose. In no event shall MERL be liable to any party for direct, indirect, special, incidental, or consequential damages, including lost profits, arising out of the use of this software and its documentation, even if MERL has been advised of the possibility of such damages. As more fully described in the license agreement that was required in order to download this software, documentation and/or data, permission to use, copy and modify this software without fee is granted, but only for educational, research and non-commercial purposes.
#################################################################################
# Note: The code requires PyTorch 1.1 #
#################################################################################
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import argparse
import numpy as np
import time
import sys
import os
from shutil import copytree, copy
from model import MotionNetMGDA, FeatEncoder
from data.nuscenes_dataloader import TrainDatasetMultiSeq
from min_norm_solvers import MinNormSolver
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self, name, fmt=':f'):
self.name = name
self.fmt = fmt
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def __str__(self):
fmtstr = '{name} {avg' + self.fmt + '}'
return fmtstr.format(**self.__dict__)
def check_folder(folder_path):
if not os.path.exists(folder_path):
os.mkdir(folder_path)
return folder_path
pred_adj_frame_distance = True # Whether to predict the relative offset between frames
height_feat_size = 13 # The size along the height dimension
cell_category_num = 5 # The number of object categories (including the background)
out_seq_len = 20 # The number of future frames we are going to predict
trans_matrix_idx = 1 # Among N transformation matrices (N=2 in our experiment), which matrix is used for alignment (see paper)
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--data', default=None, type=str, help='The path to the preprocessed sparse BEV training data')
parser.add_argument('--resume', default='', type=str, help='The path to the saved model that is loaded to resume training')
parser.add_argument('--batch', default=8, type=int, help='Batch size')
parser.add_argument('--nepoch', default=70, type=int, help='Number of epochs')
parser.add_argument('--nworker', default=4, type=int, help='Number of workers')
parser.add_argument('--reg_weight_bg_tc', default=0.1, type=float, help='Weight of background temporal consistency term')
parser.add_argument('--reg_weight_fg_tc', default=2.5, type=float, help='Weight of instance temporal consistency')
parser.add_argument('--reg_weight_sc', default=15.0, type=float, help='Weight of spatial consistency term')
parser.add_argument('--reg_weight_cls', default=2.0, type=float, help='The extra weight for grid cell classification term')
parser.add_argument('--use_bg_tc', action='store_true', help='Whether to use background temporal consistency loss')
parser.add_argument('--use_fg_tc', action='store_true', help='Whether to use foreground loss in st.')
parser.add_argument('--use_sc', action='store_true', help='Whether to use spatial consistency loss')
parser.add_argument('--nn_sampling', action='store_true', help='Whether to use nearest neighbor sampling in bg_tc loss')
parser.add_argument('--log', action='store_true', help='Whether to log')
parser.add_argument('--logpath', default='', help='The path to the output log file')
args = parser.parse_args()
print(args)
need_log = args.log
BATCH_SIZE = args.batch
num_epochs = args.nepoch
num_workers = args.nworker
reg_weight_bg_tc = args.reg_weight_bg_tc # The weight of background temporal consistency term
reg_weight_fg_tc = args.reg_weight_fg_tc # The weight of foreground temporal consistency term
reg_weight_sc = args.reg_weight_sc # The weight of spatial consistency term
reg_weight_cls = args.reg_weight_cls # The weight for grid cell classification term
use_bg_temporal_consistency = args.use_bg_tc
use_fg_temporal_consistency = args.use_fg_tc
use_spatial_consistency = args.use_sc
use_nn_sampling = args.nn_sampling
def main():
start_epoch = 1
# Whether to log the training information
if need_log:
logger_root = args.logpath if args.logpath != '' else 'logs'
time_stamp = time.strftime("%Y-%m-%d_%H-%M-%S")
if args.resume == '':
model_save_path = check_folder(logger_root)
model_save_path = check_folder(os.path.join(model_save_path, 'train_multi_seq'))
model_save_path = check_folder(os.path.join(model_save_path, time_stamp))
log_file_name = os.path.join(model_save_path, 'log.txt')
saver = open(log_file_name, "w")
saver.write("GPU number: {}\n".format(torch.cuda.device_count()))
saver.flush()
# Logging the details for this experiment
saver.write("command line: {}\n".format(" ".join(sys.argv[0:])))
saver.write(args.__repr__() + "\n\n")
saver.flush()
# Copy the code files as logs
copytree('nuscenes-devkit', os.path.join(model_save_path, 'nuscenes-devkit'))
copytree('data', os.path.join(model_save_path, 'data'))
python_files = [f for f in os.listdir('.') if f.endswith('.py')]
for f in python_files:
copy(f, model_save_path)
else:
model_save_path = args.resume # eg, "logs/train_multi_seq/1234-56-78-11-22-33"
log_file_name = os.path.join(model_save_path, 'log.txt')
saver = open(log_file_name, "a")
saver.write("GPU number: {}\n".format(torch.cuda.device_count()))
saver.flush()
# Logging the details for this experiment
saver.write("command line: {}\n".format(" ".join(sys.argv[1:])))
saver.write(args.__repr__() + "\n\n")
saver.flush()
# Specify gpu device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device_num = torch.cuda.device_count()
print("device number", device_num)
voxel_size = (0.25, 0.25, 0.4)
area_extents = np.array([[-32., 32.], [-32., 32.], [-3., 2.]])
trainset = TrainDatasetMultiSeq(dataset_root=args.data, future_frame_skip=0, voxel_size=voxel_size,
area_extents=area_extents, num_category=cell_category_num)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=BATCH_SIZE, shuffle=True, num_workers=num_workers)
print("Training dataset size:", len(trainset))
model_encoder = FeatEncoder(height_feat_size=height_feat_size)
model_head = MotionNetMGDA(out_seq_len=out_seq_len, motion_category_num=2)
model_encoder = nn.DataParallel(model_encoder)
model_encoder = model_encoder.to(device)
model_head = nn.DataParallel(model_head)
model_head = model_head.to(device)
criterion = nn.SmoothL1Loss(reduction='none')
encoder_optimizer = optim.Adam(model_encoder.parameters(), lr=0.002)
head_optimizer = optim.Adam(model_head.parameters(), lr=0.002)
encoder_scheduler = torch.optim.lr_scheduler.MultiStepLR(encoder_optimizer, milestones=[20, 40, 50, 60], gamma=0.5)
head_scheduler = torch.optim.lr_scheduler.MultiStepLR(head_optimizer, milestones=[20, 40, 50, 60], gamma=0.5)
if args.resume != '':
checkpoint = torch.load(args.resume)
start_epoch = checkpoint['epoch'] + 1
model_encoder.load_state_dict(checkpoint['encoder_state_dict'])
model_head.load_state_dict(checkpoint['head_state_dict'])
encoder_optimizer.load_state_dict(checkpoint['encoder_optimizer_state_dict'])
head_optimizer.load_state_dict(checkpoint['head_optimizer_state_dict'])
encoder_scheduler.load_state_dict(checkpoint['encoder_scheduler_state_dict'])
head_scheduler.load_state_dict(checkpoint['head_scheduler_state_dict'])
print("Load model from {}, at epoch {}".format(args.resume, start_epoch - 1))
for epoch in range(start_epoch, num_epochs + 1):
lr = encoder_optimizer.param_groups[0]['lr']
print("Epoch {}, learning rate {}".format(epoch, lr))
if need_log:
saver.write("epoch: {}, lr: {}\t".format(epoch, lr))
saver.flush()
encoder_scheduler.step()
head_scheduler.step()
model_encoder.train()
model_head.train()
models = [model_encoder, model_head]
optimizers = [encoder_optimizer, head_optimizer]
loss_disp, loss_class, loss_motion, loss_bg_tc, loss_sc, loss_fg_tc \
= train(models, criterion, trainloader, optimizers, device, epoch)
if need_log:
saver.write("{}\t{}\t{}\t{}\t{}\t{}\n".format(loss_disp, loss_class, loss_motion, loss_bg_tc,
loss_fg_tc, loss_sc))
saver.flush()
# save model
if need_log and (epoch % 5 == 0 or epoch == num_epochs or epoch == 1 or epoch > 40):
save_dict = {'epoch': epoch,
'encoder_state_dict': model_encoder.state_dict(),
'head_state_dict': model_head.state_dict(),
'encoder_optimizer_state_dict': encoder_optimizer.state_dict(),
'head_optimizer_state_dict': head_optimizer.state_dict(),
'encoder_scheduler_state_dict': encoder_scheduler.state_dict(),
'head_scheduler_state_dict': head_scheduler.state_dict(),
'loss': loss_disp.avg}
torch.save(save_dict, os.path.join(model_save_path, 'epoch_' + str(epoch) + '.pth'))
if need_log:
saver.close()
def train(models, criterion, trainloader, optimizers, device, epoch):
running_loss_bg_tc = AverageMeter('bg_tc', ':.7f') # background temporal consistency error
running_loss_fg_tc = AverageMeter('fg_tc', ':.7f') # foreground temporal consistency error
running_loss_sc = AverageMeter('sc', ':.7f') # spatial consistency error
running_loss_disp = AverageMeter('Disp', ':.6f') # for motion prediction error
running_loss_class = AverageMeter('Obj_Cls', ':.6f') # for cell classification error
running_loss_motion = AverageMeter('Motion_Cls', ':.6f') # for state estimation error
encoder = models[0]
pred_head = models[1]
for i, data in enumerate(trainloader, 0):
padded_voxel_points, all_disp_field_gt, all_valid_pixel_maps, non_empty_map, pixel_cat_map_gt, \
trans_matrices, motion_gt, pixel_instance_map, num_past_frames, num_future_frames = data
# Move to GPU/CPU
padded_voxel_points = padded_voxel_points.view(-1, num_past_frames[0].item(), 256, 256, height_feat_size)
padded_voxel_points = padded_voxel_points.to(device)
# Make prediction
# -- Prepare for computing coefficients of loss terms
with torch.no_grad():
shared_feats = encoder(padded_voxel_points)
# Compute loss coefficients
shared_feats_tensor = shared_feats.clone().detach().requires_grad_(True)
disp_pred_tensor, class_pred_tensor, motion_pred_tensor = pred_head(shared_feats_tensor)
scale = compute_loss_coeff(optimizers, device, num_future_frames[0].item(), all_disp_field_gt,
all_valid_pixel_maps, pixel_cat_map_gt, disp_pred_tensor, criterion,
non_empty_map, class_pred_tensor, motion_gt, motion_pred_tensor, shared_feats_tensor)
# Forward prediction
shared_feats = encoder(padded_voxel_points)
disp_pred, class_pred, motion_pred = pred_head(shared_feats)
# Compute and back-propagate the losses
loss_disp, loss_class, loss_motion, loss_bg_tc, loss_sc, loss_fg_tc = \
compute_and_bp_loss(optimizers, device, num_future_frames[0].item(), all_disp_field_gt, all_valid_pixel_maps,
pixel_cat_map_gt, disp_pred, criterion, non_empty_map, class_pred, motion_gt,
motion_pred, trans_matrices, pixel_instance_map, scale)
if not all((loss_disp, loss_class, loss_motion)):
print("{}, \t{}, \tat epoch {}, \titerations {} [empty occupy map]".
format(running_loss_disp, running_loss_class, epoch, i))
continue
running_loss_bg_tc.update(loss_bg_tc)
running_loss_fg_tc.update(loss_fg_tc)
running_loss_sc.update(loss_sc)
running_loss_disp.update(loss_disp)
running_loss_class.update(loss_class)
running_loss_motion.update(loss_motion)
print("[{}/{}]\t{}, \t{}, \t{}, \t{}, \t{}, \t{}".
format(epoch, i, running_loss_disp, running_loss_class, running_loss_motion, running_loss_bg_tc,
running_loss_sc, running_loss_fg_tc))
return running_loss_disp, running_loss_class, running_loss_motion, running_loss_bg_tc, \
running_loss_sc, running_loss_fg_tc
# Compute the loss coefficients adaptively
def compute_loss_coeff(optimizers, device, future_frames_num, all_disp_field_gt, all_valid_pixel_maps, pixel_cat_map_gt,
disp_pred, criterion, non_empty_map, class_pred, motion_gt, motion_pred, shared_feats_tensor):
encoder_optimizer = optimizers[0]
head_optimizer = optimizers[1]
encoder_optimizer.zero_grad()
head_optimizer.zero_grad()
grads = {}
# Compute the displacement loss
all_disp_field_gt = all_disp_field_gt.view(-1, future_frames_num, 256, 256, 2)
gt = all_disp_field_gt[:, -future_frames_num:, ...].contiguous()
gt = gt.view(-1, gt.size(2), gt.size(3), gt.size(4))
gt = gt.permute(0, 3, 1, 2).to(device)
all_valid_pixel_maps = all_valid_pixel_maps.view(-1, future_frames_num, 256, 256)
valid_pixel_maps = all_valid_pixel_maps[:, -future_frames_num:, ...].contiguous()
valid_pixel_maps = valid_pixel_maps.view(-1, valid_pixel_maps.size(2), valid_pixel_maps.size(3))
valid_pixel_maps = torch.unsqueeze(valid_pixel_maps, 1)
valid_pixel_maps = valid_pixel_maps.to(device)
valid_pixel_num = torch.nonzero(valid_pixel_maps).size(0)
if valid_pixel_num == 0:
return [None] * 3
# ---------------------------------------------------------------------
# -- Generate the displacement w.r.t. the keyframe
if pred_adj_frame_distance:
disp_pred = disp_pred.view(-1, future_frames_num, disp_pred.size(-3), disp_pred.size(-2), disp_pred.size(-1))
for c in range(1, disp_pred.size(1)):
disp_pred[:, c, ...] = disp_pred[:, c, ...] + disp_pred[:, c - 1, ...]
disp_pred = disp_pred.view(-1, disp_pred.size(-3), disp_pred.size(-2), disp_pred.size(-1))
# ---------------------------------------------------------------------
# -- Compute the gated displacement loss
pixel_cat_map_gt = pixel_cat_map_gt.view(-1, 256, 256, cell_category_num)
pixel_cat_map_gt_numpy = pixel_cat_map_gt.numpy()
pixel_cat_map_gt_numpy = np.argmax(pixel_cat_map_gt_numpy, axis=-1) + 1
cat_weight_map = np.zeros_like(pixel_cat_map_gt_numpy, dtype=np.float32)
weight_vector = [0.005, 1.0, 1.0, 1.0, 1.0] # [bg, car & bus, ped, bike, other]
for k in range(5):
mask = pixel_cat_map_gt_numpy == (k + 1)
cat_weight_map[mask] = weight_vector[k]
cat_weight_map = cat_weight_map[:, np.newaxis, np.newaxis, ...] # (batch, 1, 1, h, w)
cat_weight_map = torch.from_numpy(cat_weight_map).to(device)
map_shape = cat_weight_map.size()
loss_disp = criterion(gt * valid_pixel_maps, disp_pred * valid_pixel_maps)
loss_disp = loss_disp.view(map_shape[0], -1, map_shape[-3], map_shape[-2], map_shape[-1])
loss_disp = torch.sum(loss_disp * cat_weight_map) / valid_pixel_num
encoder_optimizer.zero_grad()
head_optimizer.zero_grad()
loss_disp.backward(retain_graph=True) # this operation is expensive
grads[0] = []
grads[0].append(shared_feats_tensor.grad.data.clone().detach())
shared_feats_tensor.grad.data.zero_()
# ---------------------------------------------------------------------
# -- Compute the classification loss
non_empty_map = non_empty_map.view(-1, 256, 256)
non_empty_map = non_empty_map.to(device)
pixel_cat_map_gt = pixel_cat_map_gt.permute(0, 3, 1, 2).to(device)
log_softmax_probs = F.log_softmax(class_pred, dim=1)
map_shape = cat_weight_map.size()
cat_weight_map = cat_weight_map.view(map_shape[0], map_shape[-2], map_shape[-1]) # (bs, h, w)
loss_class = torch.sum(- pixel_cat_map_gt * log_softmax_probs, dim=1) * cat_weight_map
loss_class = torch.sum(loss_class * non_empty_map) / torch.nonzero(non_empty_map).size(0)
encoder_optimizer.zero_grad()
head_optimizer.zero_grad()
loss_class.backward(retain_graph=True)
grads[1] = []
grads[1].append(shared_feats_tensor.grad.data.clone().detach())
shared_feats_tensor.grad.data.zero_()
# ---------------------------------------------------------------------
# -- Compute the speed level classification loss
motion_gt = motion_gt.view(-1, 256, 256, 2)
motion_gt_numpy = motion_gt.numpy()
motion_gt = motion_gt.permute(0, 3, 1, 2).to(device)
log_softmax_motion_pred = F.log_softmax(motion_pred, dim=1)
motion_gt_numpy = np.argmax(motion_gt_numpy, axis=-1) + 1
motion_weight_map = np.zeros_like(motion_gt_numpy, dtype=np.float32)
weight_vector = [0.005, 1.0]
for k in range(2):
mask = motion_gt_numpy == (k + 1)
motion_weight_map[mask] = weight_vector[k]
motion_weight_map = torch.from_numpy(motion_weight_map).to(device)
loss_speed = torch.sum(- motion_gt * log_softmax_motion_pred, dim=1) * motion_weight_map
loss_motion = torch.sum(loss_speed * non_empty_map) / torch.nonzero(non_empty_map).size(0)
encoder_optimizer.zero_grad()
head_optimizer.zero_grad()
loss_motion.backward(retain_graph=True)
grads[2] = []
grads[2].append(shared_feats_tensor.grad.data.clone().detach())
shared_feats_tensor.grad.data.zero_()
# ---------------------------------------------------------------------
# -- Frank-Wolfe iteration to compute scales.
scale = np.zeros(3, dtype=np.float32)
sol, min_norm = MinNormSolver.find_min_norm_element([grads[t] for t in range(3)])
for i in range(3):
scale[i] = float(sol[i])
return scale
# Compute and back-propagate the loss
def compute_and_bp_loss(optimizers, device, future_frames_num, all_disp_field_gt, all_valid_pixel_maps, pixel_cat_map_gt,
disp_pred, criterion, non_empty_map, class_pred, motion_gt, motion_pred, trans_matrices,
pixel_instance_map, scale):
encoder_optimizer = optimizers[0]
head_optimizer = optimizers[1]
encoder_optimizer.zero_grad()
head_optimizer.zero_grad()
# Compute the displacement loss
all_disp_field_gt = all_disp_field_gt.view(-1, future_frames_num, 256, 256, 2)
gt = all_disp_field_gt[:, -future_frames_num:, ...].contiguous()
gt = gt.view(-1, gt.size(2), gt.size(3), gt.size(4))
gt = gt.permute(0, 3, 1, 2).to(device)
all_valid_pixel_maps = all_valid_pixel_maps.view(-1, future_frames_num, 256, 256)
valid_pixel_maps = all_valid_pixel_maps[:, -future_frames_num:, ...].contiguous()
valid_pixel_maps = valid_pixel_maps.view(-1, valid_pixel_maps.size(2), valid_pixel_maps.size(3))
valid_pixel_maps = torch.unsqueeze(valid_pixel_maps, 1)
valid_pixel_maps = valid_pixel_maps.to(device)
valid_pixel_num = torch.nonzero(valid_pixel_maps).size(0)
if valid_pixel_num == 0:
return [None] * 6
# ---------------------------------------------------------------------
# -- Generate the displacement w.r.t. the keyframe
if pred_adj_frame_distance:
disp_pred = disp_pred.view(-1, future_frames_num, disp_pred.size(-3), disp_pred.size(-2), disp_pred.size(-1))
# Compute temporal consistency loss
if use_bg_temporal_consistency:
bg_tc_loss = background_temporal_consistency_loss(disp_pred, pixel_cat_map_gt, non_empty_map, trans_matrices)
if use_fg_temporal_consistency or use_spatial_consistency:
instance_spatio_temp_loss, instance_spatial_loss_value, instance_temporal_loss_value \
= instance_spatial_temporal_consistency_loss(disp_pred, pixel_instance_map)
for c in range(1, disp_pred.size(1)):
disp_pred[:, c, ...] = disp_pred[:, c, ...] + disp_pred[:, c - 1, ...]
disp_pred = disp_pred.view(-1, disp_pred.size(-3), disp_pred.size(-2), disp_pred.size(-1))
# ---------------------------------------------------------------------
# -- Compute the masked displacement loss
pixel_cat_map_gt = pixel_cat_map_gt.view(-1, 256, 256, cell_category_num)
# Note: have also tried focal loss, but did not observe noticeable improvement
pixel_cat_map_gt_numpy = pixel_cat_map_gt.numpy()
pixel_cat_map_gt_numpy = np.argmax(pixel_cat_map_gt_numpy, axis=-1) + 1
cat_weight_map = np.zeros_like(pixel_cat_map_gt_numpy, dtype=np.float32)
weight_vector = [0.005, 1.0, 1.0, 1.0, 1.0] # [bg, car & bus, ped, bike, other]
for k in range(len(weight_vector)):
mask = pixel_cat_map_gt_numpy == (k + 1)
cat_weight_map[mask] = weight_vector[k]
cat_weight_map = cat_weight_map[:, np.newaxis, np.newaxis, ...] # (batch, 1, 1, h, w)
cat_weight_map = torch.from_numpy(cat_weight_map).to(device)
map_shape = cat_weight_map.size()
loss_disp = criterion(gt * valid_pixel_maps, disp_pred * valid_pixel_maps)
loss_disp = loss_disp.view(map_shape[0], -1, map_shape[-3], map_shape[-2], map_shape[-1])
loss_disp = torch.sum(loss_disp * cat_weight_map) / valid_pixel_num
# ---------------------------------------------------------------------
# -- Compute the grid cell classification loss
non_empty_map = non_empty_map.view(-1, 256, 256)
non_empty_map = non_empty_map.to(device)
pixel_cat_map_gt = pixel_cat_map_gt.permute(0, 3, 1, 2).to(device)
log_softmax_probs = F.log_softmax(class_pred, dim=1)
map_shape = cat_weight_map.size()
cat_weight_map = cat_weight_map.view(map_shape[0], map_shape[-2], map_shape[-1]) # (bs, h, w)
loss_class = torch.sum(- pixel_cat_map_gt * log_softmax_probs, dim=1) * cat_weight_map
loss_class = torch.sum(loss_class * non_empty_map) / torch.nonzero(non_empty_map).size(0)
# ---------------------------------------------------------------------
# -- Compute the speed level classification loss
motion_gt = motion_gt.view(-1, 256, 256, 2)
motion_gt_numpy = motion_gt.numpy()
motion_gt = motion_gt.permute(0, 3, 1, 2).to(device)
log_softmax_motion_pred = F.log_softmax(motion_pred, dim=1)
motion_gt_numpy = np.argmax(motion_gt_numpy, axis=-1) + 1
motion_weight_map = np.zeros_like(motion_gt_numpy, dtype=np.float32)
weight_vector = [0.005, 1.0] # [static, moving]
for k in range(len(weight_vector)):
mask = motion_gt_numpy == (k + 1)
motion_weight_map[mask] = weight_vector[k]
motion_weight_map = torch.from_numpy(motion_weight_map).to(device)
loss_speed = torch.sum(- motion_gt * log_softmax_motion_pred, dim=1) * motion_weight_map
loss_motion = torch.sum(loss_speed * non_empty_map) / torch.nonzero(non_empty_map).size(0)
# ---------------------------------------------------------------------
# -- Sum up all the losses
if use_bg_temporal_consistency and (use_fg_temporal_consistency or use_spatial_consistency):
loss = scale[0] * loss_disp + reg_weight_cls * scale[1] * loss_class + scale[2] * loss_motion + \
reg_weight_bg_tc * bg_tc_loss + instance_spatio_temp_loss
elif use_bg_temporal_consistency:
loss = scale[0] * loss_disp + reg_weight_cls * scale[1] * loss_class + scale[2] * loss_motion + \
reg_weight_bg_tc * bg_tc_loss
elif use_spatial_consistency or use_fg_temporal_consistency:
loss = scale[0] * loss_disp + reg_weight_cls * scale[1] * loss_class + scale[2] * loss_motion + \
instance_spatio_temp_loss
else:
loss = scale[0] * loss_disp + reg_weight_cls * scale[1] * loss_class + scale[2] * loss_motion
loss.backward()
encoder_optimizer.step()
head_optimizer.step()
if use_bg_temporal_consistency:
bg_tc_loss_value = bg_tc_loss.item()
else:
bg_tc_loss_value = -1
if use_spatial_consistency or use_fg_temporal_consistency:
sc_loss_value = instance_spatial_loss_value
fg_tc_loss_value = instance_temporal_loss_value
else:
sc_loss_value = -1
fg_tc_loss_value = -1
return loss_disp.item(), loss_class.item(), loss_motion.item(), bg_tc_loss_value, \
sc_loss_value, fg_tc_loss_value
def background_temporal_consistency_loss(disp_pred, pixel_cat_map_gt, non_empty_map, trans_matrices):
"""
disp_pred: Should be relative displacement between adjacent frames. shape (batch * 2, sweep_num, 2, h, w)
pixel_cat_map_gt: Shape (batch, 2, h, w, cat_num)
non_empty_map: Shape (batch, 2, h, w)
trans_matrices: Shape (batch, 2, sweep_num, 4, 4)
"""
criterion = nn.SmoothL1Loss(reduction='sum')
non_empty_map_numpy = non_empty_map.numpy()
pixel_cat_maps = pixel_cat_map_gt.numpy()
max_prob = np.amax(pixel_cat_maps, axis=-1)
filter_mask = max_prob == 1.0
pixel_cat_maps = np.argmax(pixel_cat_maps, axis=-1) + 1 # category starts from 1 (background), etc
pixel_cat_maps = (pixel_cat_maps * non_empty_map_numpy * filter_mask) # (batch, 2, h, w)
trans_matrices = trans_matrices.numpy()
device = disp_pred.device
pred_shape = disp_pred.size()
disp_pred = disp_pred.view(-1, 2, pred_shape[1], pred_shape[2], pred_shape[3], pred_shape[4])
seq_1_pred = disp_pred[:, 0] # (batch, sweep_num, 2, h, w)
seq_2_pred = disp_pred[:, 1]
seq_1_absolute_pred_list = list()
seq_2_absolute_pred_list = list()
seq_1_absolute_pred_list.append(seq_1_pred[:, 1])
for i in range(2, pred_shape[1]):
seq_1_absolute_pred_list.append(seq_1_pred[:, i] + seq_1_absolute_pred_list[i - 2])
seq_2_absolute_pred_list.append(seq_2_pred[:, 0])
for i in range(1, pred_shape[1] - 1):
seq_2_absolute_pred_list.append(seq_2_pred[:, i] + seq_2_absolute_pred_list[i - 1])
# ----------------- Compute the consistency loss -----------------
# Compute the transformation matrices
# First, transform the coordinate
transformed_disp_pred_list = list()
trans_matrix_global = trans_matrices[:, 1] # (batch, sweep_num, 4, 4)
trans_matrix_global = trans_matrix_global[:, trans_matrix_idx, 0:3] # (batch, 3, 4) # <---
trans_matrix_global = trans_matrix_global[:, :, (0, 1, 3)] # (batch, 3, 3)
trans_matrix_global[:, 2] = np.array([0.0, 0.0, 1.0])
# --- Move pixel coord to global and rescale; then rotate; then move back to local pixel coord
translate_to_global = np.array([[1.0, 0.0, -120.0], [0.0, 1.0, -120.0], [0.0, 0.0, 1.0]], dtype=np.float32)
scale_global = np.array([[0.25, 0.0, 0.0], [0.0, 0.25, 0.0], [0.0, 0.0, 1.0]], dtype=np.float32)
trans_global = scale_global @ translate_to_global
inv_trans_global = np.linalg.inv(trans_global)
trans_global = np.expand_dims(trans_global, axis=0)
inv_trans_global = np.expand_dims(inv_trans_global, axis=0)
trans_matrix_total = inv_trans_global @ trans_matrix_global @ trans_global
# --- Generate grid transformation matrix, so as to use Pytorch affine_grid and grid_sample function
w, h = pred_shape[-2], pred_shape[-1]
resize_m = np.array([
[2 / w, 0.0, -1],
[0.0, 2 / h, -1],
[0.0, 0.0, 1]
], dtype=np.float32)
inverse_m = np.linalg.inv(resize_m)
resize_m =
|
np.expand_dims(resize_m, axis=0)
|
numpy.expand_dims
|
"""
Shared pytest fixtures for unit tests.
"""
import numpy as np
import pytest
from scipy.integrate import solve_ivp
from pysindy.differentiation import FiniteDifference
from pysindy.differentiation import SpectralDerivative
from pysindy.feature_library import CustomLibrary
from pysindy.feature_library import FourierLibrary
from pysindy.feature_library import GeneralizedLibrary
from pysindy.feature_library import PDELibrary
from pysindy.feature_library import PolynomialLibrary
from pysindy.feature_library import SINDyPILibrary
from pysindy.utils.odes import logistic_map
from pysindy.utils.odes import logistic_map_control
from pysindy.utils.odes import logistic_map_multicontrol
from pysindy.utils.odes import lorenz
from pysindy.utils.odes import lorenz_control
@pytest.fixture
def data_1d():
t = np.linspace(0, 5, 100)
x = 2 * t.reshape(-1, 1)
return x, t
@pytest.fixture
def data_1d_bad_shape():
t = np.linspace(0, 5, 100)
x = 2 * t
return x, t
@pytest.fixture
def data_lorenz():
t = np.linspace(0, 5, 500)
x0 = [8, 27, -7]
x = solve_ivp(lorenz, (t[0], t[-1]), x0, t_eval=t).y.T
return x, t
@pytest.fixture
def data_multiple_trajctories():
n_points = [100, 200, 500]
initial_conditions = [
[8, 27, -7],
[-10.9595724, 21.7346758, 24.5722540],
[-3.95406365, -9.21825124, 12.07459147],
]
x_list = []
t_list = []
for n, x0 in zip(n_points, initial_conditions):
t = np.linspace(0, 5, n)
t_list.append(t)
x_list.append(solve_ivp(lorenz, (t[0], t[-1]), x0, t_eval=t).y.T)
return x_list, t_list
@pytest.fixture
def diffuse_multiple_trajectories():
def diffuse(t, u, dx, nx):
u = np.reshape(u, nx)
du = SpectralDerivative(d=2, axis=0)._differentiate(u, dx)
return np.reshape(u * du, nx)
# Required for accurate solve_ivp results
integrator_keywords = {}
integrator_keywords["rtol"] = 1e-12
integrator_keywords["method"] = "LSODA"
integrator_keywords["atol"] = 1e-12
N = 200
h0 = 1.0
L = 5
T = 1
t = np.linspace(0, T, N)
x = np.arange(0, N) * L / N
ep = 0.5 * h0
y0 = np.reshape(
h0 + ep * np.cos(4 * np.pi / L * x) + ep * np.cos(2 * np.pi / L * x), N
)
y1 = np.reshape(
h0 + ep * np.cos(4 * np.pi / L * x) - ep * np.cos(2 * np.pi / L * x), N
)
dx = x[1] - x[0]
sol1 = solve_ivp(
diffuse, (t[0], t[-1]), y0=y0, t_eval=t, args=(dx, N), **integrator_keywords
)
sol2 = solve_ivp(
diffuse, (t[0], t[-1]), y0=y1, t_eval=t, args=(dx, N), **integrator_keywords
)
u = [np.reshape(sol1.y, (N, N, 1)), np.reshape(sol2.y, (N, N, 1))]
return t, x, u
@pytest.fixture
def data_discrete_time():
n_steps = 100
mu = 3.6
x = np.zeros((n_steps))
x[0] = 0.5
for i in range(1, n_steps):
x[i] = logistic_map(x[i - 1], mu)
return x
@pytest.fixture
def data_discrete_time_multiple_trajectories():
n_steps = 100
mus = [1, 2.3, 3.6]
x = [np.zeros((n_steps)) for mu in mus]
for i, mu in enumerate(mus):
x[i][0] = 0.5
for k in range(1, n_steps):
x[i][k] = logistic_map(x[i][k - 1], mu)
return x
@pytest.fixture
def data_1d_random_pde():
n = 100
t = np.linspace(0, 10, n)
dt = t[1] - t[0]
x = np.linspace(0, 10, n)
u = np.random.randn(n, n, 1)
u_dot = FiniteDifference(axis=1)._differentiate(u, t=dt)
return t, x, u, u_dot
@pytest.fixture
def data_2d_random_pde():
n = 4
t = np.linspace(0, 10, n)
dt = t[1] - t[0]
x = np.linspace(0, 10, n)
y = np.linspace(0, 10, n)
X, Y =
|
np.meshgrid(x, y)
|
numpy.meshgrid
|
import numpy as np
import scipy.sparse
from numpy import sin, cos, tan
import sys
import slepc4py
slepc4py.init(sys.argv)
from petsc4py import PETSc
from slepc4py import SLEPc
opts = PETSc.Options()
import pickle as pkl
class Model():
def __init__(self, model_variables, model_parameters, physical_constants):
self.model_variables = model_variables
self.model_parameters = model_parameters
self.physical_constants = physical_constants
for key in model_parameters:
exec('self.'+str(key)+' = model_parameters[\''+str(key)+'\']')
for key in physical_constants:
exec('self.'+str(key)+' = physical_constants[\''+str(key)+'\']')
self.calculate_nondimensional_parameters()
self.set_up_grid(self.R, self.h)
def set_up_grid(self, R, h):
"""
Creates the r and theta coordinate vectors
inputs:
R: radius of outer core in m
h: layer thickness in m
outputs: None
"""
self.R = R
self.h = h
self.Size_var = self.Nk*self.Nl
self.SizeM = len(self.model_variables)*self.Size_var
self.rmin = (R-h)/self.r_star
self.rmax = R/self.r_star
self.dr = (self.rmax-self.rmin)/(self.Nk)
ones = np.ones((self.Nk,self.Nl))
self.r = (ones.T*np.linspace(self.rmin+self.dr/2., self.rmax-self.dr/2.,num=self.Nk)).T # r value at center of each cell
self.rp = (ones.T*np.linspace(self.rmin+self.dr, self.rmax, num=self.Nk)).T # r value at plus border (top) of cell
self.rm = (ones.T*np.linspace(self.rmin, self.rmax-self.dr, num=self.Nk)).T # r value at minus border (bottom) of cell
self.dth = np.pi/(self.Nl)
self.th = ones*np.linspace(self.dth/2., np.pi-self.dth/2., num=self.Nl) # theta value at center of cell
self.thp = ones*np.linspace(self.dth, np.pi, num=self.Nl) # theta value at plus border (top) of cell
self.thm = ones*np.linspace(0,np.pi-self.dth, num=self.Nl)
return None
def calculate_nondimensional_parameters(self):
'''
Calculates the non-dimensional parameters in model from the physical
constants.
'''
self.t_star = 1/self.Omega # seconds
self.r_star = self.R # meters
self.P_star = self.rho*self.r_star**2/self.t_star**2
self.B_star = (self.eta*self.mu_0*self.rho/self.t_star)**0.5
self.u_star = self.r_star/self.t_star
self.E = self.nu*self.t_star/self.r_star**2
self.Pm = self.nu/self.eta
return None
def set_Br(self, BrT):
''' Sets the background phi magnetic field in Tesla
BrT = Br values for each cell in Tesla'''
if isinstance(BrT, (float, int)):
self.BrT = np.ones((self.Nk, self.Nl))*BrT
self.Br = self.BrT/self.B_star
elif isinstance(BrT, np.ndarray) and BrT.shape == (self.Nk, self.Nl):
self.BrT = BrT
self.Br = self.BrT/self.B_star
else:
raise TypeError("BrT must either be an int, float, or np.ndarray of correct size")
def set_Bth(self, BthT):
''' Sets the background phi magnetic field in Tesla
BthT = Bth values for each cell in Tesla'''
if isinstance(BthT, (float, int)):
self.BthT = np.ones((self.Nk, self.Nl))*BthT
self.Bth = self.BthT/self.B_star
elif isinstance(BthT, np.ndarray) and BthT.shape == (self.Nk, self.Nl) :
self.BthT = BthT
self.Bth = self.BthT/self.B_star
else:
raise TypeError("BthT must either be an int, float, or np.ndarray of correct size")
def set_Bph(self, BphT):
''' Sets the background phi magnetic field in Tesla
BphT = Bph values for each cell in Tesla'''
if isinstance(BphT, (float, int)):
self.BphT = np.ones((self.Nk, self.Nl))*BphT
self.Bph = self.BphT/self.B_star
elif isinstance(BphT, np.ndarray) and BphT.shape ==(self.Nk, self.Nl):
self.BphT = BphT
self.Bph = self.BphT/self.B_star
else:
raise TypeError("BphT must either be an int, float, or np.ndarray of correct size")
def set_Br_dipole(self, Bd, const=0):
''' Sets the background magnetic field to a dipole field with
Bd = dipole constant in Tesla '''
self.Bd = Bd
self.BrT = 2*cos(self.th)*Bd + const
self.Br = self.BrT/self.B_star
self.set_Bth(0.0)
self.set_Bph(0.0)
return None
def set_B_dipole(self, Bd, const=0):
''' Sets the background magnetic field to a dipole field with
Bd = dipole constant in Tesla '''
self.Bd = Bd
self.BrT = 2*cos(self.th)*Bd + const
self.Br = self.BrT/self.B_star
self.BthT = sin(self.th)*Bd + const
self.Bth = self.BthT/self.B_star
self.set_Bph(0.0)
return None
def set_B_abs_dipole(self, Bd, const=0):
''' Sets the background magnetic Br and Bth field to the absolute value of a
dipole field with Bd = dipole constant in Tesla '''
self.Bd = Bd
self.BrT = 2*abs(cos(self.th))*Bd + const
self.Br = self.BrT/self.B_star
self.BthT = abs(sin(self.th))*Bd + const
self.Bth = self.BthT/self.B_star
self.set_Bph(0.0)
return None
def set_B_dipole_absrsymth(self, Bd, const=0):
''' Sets the background magnetic Br and Bth field to the absolute value of a
dipole field with Bd = dipole constant in Tesla '''
self.Bd = Bd
self.BrT = 2*abs(cos(self.th))*Bd + const
self.Br = self.BrT/self.B_star
self.BthT = sin(self.th)*Bd + const
self.Bth = self.BthT/self.B_star
self.set_Bph(0.0)
return None
def set_Br_abs_dipole(self, Bd, const=0, noise=None, N=10000):
''' Sets the background Br magnetic field the absolute value of a
dipole with Bd = dipole constant in Tesla.
optionally, can offset the dipole by a constant with const or add numerical noise with noise '''
if noise:
from scipy.special import erf
def folded_mean(mu, s):
return s*(2/np.pi)**0.5*np.exp(-mu**2/(2*s**2)) - mu*erf(-mu/(2*s**2)**0.5)
self.Bd = Bd
Bdip = 2*Bd*np.abs(np.cos(self.th))
Bdip_noise = np.zeros_like(Bdip)
for (i,B) in enumerate(Bdip):
Bdip_noise[i] = folded_mean(Bdip[i], noise)
self.BrT = np.ones((self.Nk, self.Nl))*Bdip_noise
self.Br = self.BrT/self.B_star
else:
self.Bd = Bd
self.BrT = 2*abs(cos(self.th))*Bd + const
self.Br = self.BrT/self.B_star
self.set_Bth(0.0)
self.set_Bph(0.0)
return None
def set_Br_sinfunc(self, Bmin, Bmax, sin_exp=2.5):
self.BrT = ((1-sin(self.th)**sin_exp)*(Bmax-Bmin)+Bmin)
self.Br = self.BrT/self.B_star
self.set_Bth(0.0)
self.set_Bph(0.0)
return None
def set_B_by_type(self, B_type, Bd=0.0, Br=0.0, Bth=0.0, Bph=0.0, const=0.0, Bmin=0.0, Bmax=0.0, sin_exp=2.5, noise=0.0):
''' Sets the background magnetic field to given type.
B_type choices:
* dipole : Br, Bth dipole; specify scalar dipole constant Bd (T)
* abs_dipole : absolute value of dipole in Br and Bth, specify scalar Bd (T)
* dipole_Br : Br dipole, Bth=0; specify scalar dipole constant Bd (T)
* abs_dipole_Br : absolute value of dipole in Br, specify scalar Bd (T)
* constant_Br : constant Br, Bth=0; specify scalar Br (T)
* set : specify array Br, Bth, and Bph values in (T)
* dipole_absrsymth : absolute value of dipole in Br, symmetric in Bth, specify scalar Bd (T)
'''
if B_type == 'dipole':
self.set_B_dipole(Bd, const=const)
elif B_type == 'dipoleBr':
self.set_Br_dipole(Bd, const=const)
elif B_type == 'constantBr':
self.set_Br(Br*np.ones((self.Nk, self.Nl)))
self.set_Bth(0.0)
self.set_Bph(0.0)
elif B_type == 'set':
self.set_Br(Br)
self.set_Bth(Bth)
self.set_Bph(Bph)
elif B_type == 'absDipoleBr':
self.set_Br_abs_dipole(Bd, const=const, noise=noise)
elif B_type == 'absDipole':
self.set_B_abs_dipole(Bd, const=const)
elif B_type == 'dipoleAbsRSymTh':
self.set_B_dipole_absrsymth(Bd, const=const)
elif B_type == 'sinfuncBr':
self.set_Br_sinfunc(Bmin, Bmax, sin_exp=sin_exp)
else:
raise ValueError('B_type not valid')
def set_CC_skin_depth(self, period):
''' sets the magnetic skin depth for conducting core BC
inputs:
period = period of oscillation in years
returns:
delta_C = skin depth in (m)
'''
self.delta_C = np.sqrt(2*self.eta/(2*np.pi/(period*365.25*24*3600)))
self.physical_constants['delta_C'] = self.delta_C
return self.delta_C
def set_Uphi(self, Uphi):
'''Sets the background velocity field in m/s'''
if isinstance(Uphi, (float, int)):
self.Uphi = np.ones((self.Nk, self.Nl))*Uphi
elif isinstance(Uphi, np.ndarray):
self.Uphi = Uphi
else:
raise TypeError("The value passed for Uphi must be either an int, float, or np.ndarray")
self.U0 = self.Uphi*self.r_star/self.t_star
return None
def set_buoyancy(self, drho_dr):
'''Sets the buoyancy structure of the layer'''
self.omega_g = np.sqrt(-self.g/self.rho*drho_dr)
self.N = self.omega_g**2*self.t_star**2
def set_buoy_by_type(self, buoy_type, buoy_ratio):
self.omega_g0 = buoy_ratio*self.Omega
if buoy_type == 'constant':
self.omega_g = np.ones((self.Nk, self.Nl))*self.omega_g0
elif buoy_type == 'linear':
self.omega_g = (np.ones((self.Nk, self.Nl)).T*np.linspace(0, self.omega_g0, self.Nk)).T
self.N = self.omega_g**2*self.t_star**2
def get_index(self, k, l, var):
'''
Takes coordinates for a point, gives back index in matrix.
inputs:
k: k grid value from 0 to K-1
l: l grid value from 0 to L-1
var: variable name in model_variables
outputs:
index of location in matrix
'''
Nk = self.Nk
Nl = self.Nl
SizeM = self.SizeM
Size_var = self.Size_var
if (var not in self.model_variables):
raise RuntimeError('variable not in model_variables')
elif not (l >= 0 and l <= Nl-1):
raise RuntimeError('l index out of bounds')
elif not (k >= 0 and k <= Nk-1):
raise RuntimeError('k index out of bounds')
return Size_var*self.model_variables.index(var) + k + l*Nk
def get_variable(self, vector, var):
'''
Takes a flat vector and a variable name, returns the variable in a
np.matrix
inputs:
vector: flat vector array with len == SizeM
var: str of variable name in model
outputs:
variable in np.array
'''
Nk = self.Nk
Nl = self.Nl
if (var not in self.model_variables):
raise RuntimeError('variable not in model_variables')
elif len(vector) != self.SizeM:
raise RuntimeError('vector given is not correct length in this \
model')
else:
var_start = self.get_index(0, 0, var)
var_end = self.get_index(Nk-1, Nl-1, var)+1
variable = np.array(np.reshape(vector[var_start:var_end], (Nk, Nl), 'F'))
return variable
def create_vector(self, variables):
'''
Takes a set of variables and creates a vector out of
them.
inputs:
variables: list of (Nk x Nl) matrices or vectors for each model
variable
outputs:
vector of size (SizeM x 1)
'''
Nk = self.Nk
Nl = self.Nl
vector = np.array([1])
# Check Inputs:
if len(variables) != len(self.model_variables):
raise RuntimeError('Incorrect number of variable vectors passed')
for var in variables:
vector = np.vstack((vector, np.reshape(var, (Nk*Nl, 1))))
return np.array(vector[1:])
def add_gov_equation(self, name, variable):
setattr(self, name, GovEquation(self, variable))
def setup_SLEPc(self, nev=10, Target=None, Which='TARGET_MAGNITUDE'):
self.EPS = SLEPc.EPS().create()
self.EPS.setDimensions(10, PETSc.DECIDE)
self.EPS.setOperators(self.A_SLEPc, self.M_SLEPc)
self.EPS.setProblemType(SLEPc.EPS.ProblemType.PGNHEP)
self.EPS.setTarget(Target)
self.EPS.setWhichEigenpairs(eval('self.EPS.Which.'+Which))
self.EPS.setFromOptions()
self.ST = self.EPS.getST()
self.ST.setType(SLEPc.ST.Type.SINVERT)
return self.EPS
def solve_SLEPc(self, Target=None):
self.EPS.solve()
conv = self.EPS.getConverged()
vs, ws = PETSc.Mat.getVecs(self.A_SLEPc)
vals = []
vecs = []
for ind in range(conv):
vals.append(self.EPS.getEigenpair(ind, ws))
vecs.append(ws.getArray())
return vals, vecs
def save_mat_PETSc(self, filename, mat, type='Binary'):
''' Saves a Matrix in PETSc format '''
if type == 'Binary':
viewer = PETSc.Viewer().createBinary(filename, 'w')
elif type == 'ASCII':
viewer = PETSc.Viewer().createASCII(filename, 'w')
viewer(mat)
def load_mat_PETSc(self, filename, type='Binary'):
''' Loads and returns a Matrix stored in PETSc format '''
if type == 'Binary':
viewer = PETSc.Viewer().createBinary(filename, 'r')
elif type == 'ASCII':
viewer = PETSc.Viewer().createASCII(filename, 'r')
return PETSc.Mat().load(viewer)
def save_vec_PETSc(self, filename, vec, type='Binary'):
''' Saves a vector in PETSc format '''
if type == 'Binary':
viewer = PETSc.Viewer().createBinary(filename, 'w')
elif type == 'ASCII':
viewer = PETSc.Viewer().createASCII(filename, 'w')
viewer(vec)
def load_vec_PETSc(self, filename, type='Binary'):
''' Loads and returns a vector stored in PETSc format '''
if type == 'Binary':
viewer = PETSc.Viewer().createBinary(filename, 'r')
elif type == 'ASCII':
viewer = PETSc.Viewer().createASCII(filename, 'r')
return PETSc.Mat().load(viewer)
def save_model(self, filename):
''' Saves the model structure without the computed A and M matrices'''
try:
self.A
except:
pass
else:
A = self.A
del self.A
try:
self.M
except:
pass
else:
M = self.M
del self.M
pkl.dump(self, open(filename, 'wb'))
try:
A
except:
pass
else:
self.A = A
try:
M
except:
pass
else:
self.M = M
def make_d2Mat(self):
self.d2_rows = []
self.d2_cols = []
self.d2_vals = []
for var in self.model_variables:
self.add_gov_equation('d2_'+var, var)
exec('self.d2_'+var+'.add_d2_bd0(\''+var+'\','+str(self.m)+')')
exec('self.d2_rows = self.d2_'+var+'.rows')
exec('self.d2_cols = self.d2_'+var+'.cols')
exec('self.d2_vals = self.d2_'+var+'.vals')
self.d2Mat = coo_matrix((self.d2_vals, (self.d2_rows, self.d2_cols)),
shape=(self.SizeM, self.SizeM))
return self.d2Mat
def make_dthMat(self):
self.dth_rows = []
self.dth_cols = []
self.dth_vals = []
for var in self.model_variables:
self.add_gov_equation('dth_'+var, var)
exec('self.dth_'+var+'.add_dth(\''+var+'\','+str(self.m)+')')
exec('self.dth_rows += self.dth_'+var+'.rows')
exec('self.dth_cols += self.dth_'+var+'.cols')
exec('self.dth_vals += self.dth_'+var+'.vals')
self.dthMat = coo_matrix((self.dth_vals, (self.dth_rows, self.dth_cols)),
shape=(self.SizeM, self.SizeM))
return self.dthMat
def make_dphMat(self):
self.dph_rows = []
self.dph_cols = []
self.dph_vals = []
for var in self.model_variables:
self.add_gov_equation('dth_'+var, var)
exec('self.dph_'+var+'.add_dth(\''+var+'\','+str(self.m)+')')
exec('self.dph_rows += self.dth_'+var+'.rows')
exec('self.dph_cols += self.dth_'+var+'.cols')
exec('self.dph_vals += self.dth_'+var+'.vals')
self.dthMat = coo_matrix((self.dph_vals, (self.dph_rows, self.dph_cols)),
shape=(self.SizeM, self.SizeM))
return self.dphMat
def make_Bobs(self):
BrobsT = 2*np.ones((self.Nk, self.Nl))*cos(self.th)
self.Brobs = BrobsT/self.B_star
gradBrobsT = -2*np.ones((self.Nk, self.Nl))*sin(self.th)/self.R
self.gradBrobs = gradBrobsT/self.B_star*self.r_star
self.add_gov_equation('Bobs', self.model_variables[0])
self.Bobs.add_term('uth', self.gradBrobs)
self.Bobs.add_dth('uth', C= self.Brobs)
self.Bobs.add_dph('uph', C= self.Brobs)
self.BobsMat = coo_matrix((self.Bobs.vals, (self.Bobs.rows, self.Bobs.cols)),
shape=(self.SizeM, self.SizeM))
return self.BobsMat
def make_operators(self):
"""
:return:
"""
dr = self.dr
r = self.r
rp = self.rp
rm = self.rm
dth = self.dth
th = self.th
thm = self.thm
thp = self.thp
Nk = self.Nk
Nl = self.Nl
m = self.m
delta_C = self.delta_C/self.r_star
E = self.E
Pm = self.Pm
# ddr
self.ddr_kp1 = rp**2/(2*r**2*dr)
self.ddr_km1 = -rm**2/(2*r**2*dr)
self.ddr = 1/r
self.ddr_kp1_b0 = np.array(self.ddr_kp1)
self.ddr_km1_b0 = np.array(self.ddr_km1)
self.ddr_b0 = np.array(self.ddr)
self.ddr_kp1_b0[-1,:] = np.zeros(Nl)
self.ddr_b0[-1,:] = -rm[-1,:]**2/(2*r[-1,:]**2*dr)
self.ddr_km1_b0[0,:] = np.zeros(Nl)
self.ddr_b0[0,:] = rp[0,:]**2/(2*r[0,:]**2*dr)
self.ddr_kp1_bd0 = np.array(self.ddr_kp1)
self.ddr_km1_bd0 = np.array(self.ddr_km1)
self.ddr_bd0 = np.array(self.ddr)
self.ddr_kp1_bd0[-1,:] = np.zeros(Nl)
self.ddr_bd0[-1,:] = (2*rp[-1,:]**2 -rm[-1,:]**2)/(2*r[-1,:]**2*dr)
self.ddr_km1_bd0[0,:] = np.zeros(Nl)
self.ddr_bd0[0,:] = (rp[0,:]**2 - 2*rm[0,:]**2)/(2*r[0,:]**2*dr)
# ddr for Conducting core boundary conditions
self.ddr_kp1_ccb0 = np.array(self.ddr_kp1_b0)
self.ddr_kp1_ccb0[0,:] = rp[0,:]**2/(r[0,:]**2*2*dr)
self.ddr_km1_ccb0 = np.array(self.ddr_km1_b0)
self.ddr_km1_ccb0[0,:] = np.zeros(Nl)
self.ddr_ccb0 = np.array(self.ddr_b0)
self.ddr_ccb0[0,:] = rp[0,:]**2/(r[0,:]**2*2*dr)
self.ddr_u_ccb0 = -rm[0,:]**2/(r[0,:]**2*dr)
# ddth
self.ddth_lp1 = sin(thp)/(2*r*sin(th)*dth)
self.ddth_lm1 = -sin(thm)/(2*r*sin(th)*dth)
self.ddth = (sin(thp)-sin(thm))/(2*r*sin(th)*dth)
# ddph
self.ddph = 1j*m/(r*sin(th))
# drP
self.drP_kp1 = rp**2/(2*dr*r**2)
self.drP_km1 = -rm**2/(2*dr*r**2)
self.drP_lp1 = -sin(thp)/(4*r*sin(th))
self.drP_lm1 = -sin(thm)/(4*r*sin(th))
self.drP = -(sin(thp)+sin(thm))/(4*r*sin(th))
self.drP_kp1[-1,:] = np.zeros(Nl)
self.drP[-1,:] = rp[-1,:]**2/(2*dr*r[-1,:]**2) \
- (sin(thp[-1,:]) + sin(thm[-1,:]))/(4*r[-1,:]*sin(th[-1,:]))
self.drP_km1[0,:] = np.zeros(Nl)
self.drP[0,:] = -rm[0,:]**2/(2*dr*r[0,:]**2) \
- (sin(thp[0,:]) + sin(thm[0,:]))/(4*r[0,:]*sin(th[0,:]))
# dthP
self.dthP_lp1 = sin(thp)/(2*r*sin(th)*dth)
self.dthP_lm1 = -sin(thm)/(2*r*sin(th)*dth)
self.dthP = (sin(thp)-sin(thm))/(2*r*sin(th)*dth) - cos(th)/(r*sin(th))
# dphP
self.dphP = 1j*m/(r*sin(th))
# Laplacian
self.d2_kp1 = (rp/(r*dr))**2
self.d2_km1 = (rm/(r*dr))**2
self.d2_lp1 = sin(thp)/(sin(th)*(r*dth)**2)
self.d2_lm1 = sin(thm)/(sin(th)*(r*dth)**2)
self.d2 = -((rp**2+rm**2)/(r*dr)**2 + (sin(thp) + sin(thm))/(sin(th)*(r*dth)**2) + (m/(r*sin(th)))**2)
# Laplacian for B.C. var = 0
self.d2_kp1_b0 = np.array(self.d2_kp1)
self.d2_km1_b0 = np.array(self.d2_km1)
self.d2_lp1_b0 = self.d2_lp1
self.d2_lm1_b0 = self.d2_lm1
self.d2_b0 = np.array(self.d2)
self.d2_kp1_b0[-1,:] = np.zeros(Nl)
self.d2_b0[-1,:] = (-((2*rp**2+rm**2)/(r*dr)**2 + (sin(thp) + sin(thm))/(sin(th)*(r*dth)**2) + (m/(r*sin(th)))**2))[-1,:]
self.d2_km1_b0[0,:] = np.zeros(Nl)
self.d2_b0[0,:] = (-((rp**2+2*rm**2)/(r*dr)**2 + (sin(thp) + sin(thm))/(sin(th)*(r*dth)**2) + (m/(r*sin(th)))**2))[0,:]
# Laplacian for B.C. d(var)/dr = 0
self.d2_kp1_bd0 = np.array(self.d2_kp1)
self.d2_km1_bd0 = np.array(self.d2_km1)
self.d2_lp1_bd0 = self.d2_lp1
self.d2_lm1_bd0 = self.d2_lm1
self.d2_bd0 = np.array(self.d2)
self.d2_kp1_bd0[-1,:] = np.zeros(Nl)
self.d2_bd0[-1,:] = (-((rm**2)/(r*dr)**2 + (
|
sin(thp)
|
numpy.sin
|
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.2.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # OpenGLを用いたMCMCのリアルタイム可視化
# OpenGLとGLFWをインポートします
from OpenGL.GL import *
from OpenGL.GLUT import *
import glfw
import numpy as np
from math import gamma
class gibbs_random_chain():
def __init__(self, a, *, rho=0.5, diagonal_components=1):
self.a = np.array(a)
self.K = self.a.size
self.rho = rho
self.SIGMA = (np.ones((self.K,self.K))-np.eye(self.K))*rho + np.eye(self.K)*diagonal_components
self.L = np.linalg.cholesky(self.SIGMA)
self.z_t = self.L.dot(self.produce_vec_y())
self.z_t = np.ones(self.K)/self.K
# 区間(-1,1)の一様乱数ベクトルzを利用して独立なD個のサンプルベクトルyを得る関数
def produce_vec_y(self):
z_array = 2*np.random.rand(self.K) - 1
while (z_array**2).sum() > 1:
z_array = 2*np.random.rand(self.K) - 1
squared_r = (z_array**2).sum()
y = z_array * np.sqrt((-2*np.log(squared_r)/squared_r))
self.z_array = z_array
return y
def produce_z_k(self, z_not_k):
z_k_limit = 1 - (z_not_k**2).sum()
return np.random.rand()*np.sqrt(z_k_limit)*(2*np.random.randint(0,2)-1)
def generate_random(self):
z_array = np.array(self.z_array)
ind = np.ones(self.K, dtype=bool)
for k in range(self.K):
ind[k] = False
z_array[k] = self.produce_z_k(z_array[ind])
ind[k] = True
return self.z_t + self.L.dot(z_array), z_array
def set_z_t(self, z_t):
self.z_t = z_t
def set_z_array(self, z_array):
self.z_array = z_array
def alpha(self, z):
x = np.abs(np.array(z))
x /= x.sum()
x_t = np.abs(np.array(self.z_t))
x_t /= x_t.sum()
return min(1, p_tilde(x,self.a)/p_tilde(x_t,self.a))
class gibbs_over_relaxation():
def __init__(self, a, *, rho=0, diagonal_components=1, param_mu=0, param_sigma=1, param_alpha=0):
self.a = np.array(a)
self.K = self.a.size
self.rho = rho
self.SIGMA = (np.ones((self.K,self.K))-np.eye(self.K))*rho + np.eye(self.K)*diagonal_components
self.inv_SIGMA = np.linalg.inv(self.SIGMA)
self.L = np.linalg.cholesky(self.SIGMA)
self.z_t = self.L.dot(self.produce_vec_y())
self.z_t = np.ones(self.K)/self.K
if (type(param_mu) is int) or (type(param_mu) is float):
self.param_mu = np.ones(self.K)*param_mu
else:
self.param_mu = np.array(param_mu)
if (type(param_sigma) is int) or (type(param_sigma) is float):
self.param_sigma = np.ones(self.K)*param_sigma
else:
self.param_sigma = np.array(param_sigma)
if (type(param_alpha) is int) or (type(param_alpha) is float):
self.param_alpha = param_alpha
else:
raise ValueError("param_alpha is needed scalar")
# 区間(-1,1)の一様乱数ベクトルzを利用して独立なD個のサンプルベクトルyを得る関数
def produce_vec_y(self):
z_array = 2*np.random.rand(self.K) - 1
while (z_array**2).sum() > 1:
z_array = 2*np.random.rand(self.K) - 1
squared_r = (z_array**2).sum()
y = z_array * np.sqrt((-2*np.log(squared_r)/squared_r))
self.z_array = z_array
return y
def produce_z_k(self, z_not_k):
z_k_limit = 1 - (z_not_k**2).sum()
return np.random.rand()*np.sqrt(z_k_limit)*(2*np.random.randint(0,2)-1)
def generate_random(self):
z_array = np.array(self.z_array)
ind = np.ones(self.K, dtype=bool)
for k in range(self.K):
ind[k] = False
z_array[k] = self.produce_z_k(z_array[ind])
ind[k] = True
z_dash = (self.param_mu + self.param_alpha*(self.z_t-self.param_mu) + (self.param_sigma**2)*((1-self.param_alpha**2)**(1/2))*z_array)
return z_dash, z_array
def set_z_t(self, z_t):
self.z_t = z_t
def set_z_array(self, z_array):
self.z_array = z_array
def alpha(self, z):
x = np.abs(np.array(z))
x_t = np.abs(np.array(self.z_t))
x /= x.sum()
x_t /= x_t.sum()
return min(1, p_tilde(x,self.a)/p_tilde(x_t,self.a)*np.exp(((x-self.param_mu).dot(self.inv_SIGMA).dot(x-self.param_mu)-(x_t-self.param_mu).dot(self.inv_SIGMA).dot(x_t-self.param_mu))/2))
def draw():
global mcmc
global mean_point
global sigma_points
glClearColor(0.0, 0.5, 0.5, 0.0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
# 軸をプロット
glColor(1.0, 1.0, 1.0, 1.0)
glBegin(GL_TRIANGLES)
glVertex(p1)
glVertex(p2)
glVertex(p3)
glEnd()
# データ点をプロット
glPointSize(5)
glColor(0.7, 0.7, 0.2, 0.0)
glBegin(GL_POINTS)
for x in x_accepted:
glVertex(x)
glEnd()
# 分散をプロット
n_sigma = len(sigma_points)
colormap = np.linspace(0,1,n_sigma)
for n in range(n_sigma)[::-1]:
glColor(colormap[n_sigma-1-n], 0.0, colormap[n], 0.0)
glBegin(GL_TRIANGLES)
for x in sigma_points[n]:
glVertex(x)
glEnd()
# 重心をプロット
glPointSize(10)
glColor(0.0, 0.0, 0.0, 0.0)
glBegin(GL_POINTS)
glVertex(mean_point)
glEnd()
# 軸の説明文
glRasterPos(p1[0]-0.1, p1[1])
[glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(s)) for s in "theta_1"]
glRasterPos(p2)
[glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(s)) for s in "theta_2"]
glRasterPos(p3[0]-0.2, p3[1])
[glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(s)) for s in "theta_3"]
# 操作説明
glRasterPos(p1[0]-1.0, p1[1]+0.2)
[glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(s)) for s in " q:quit"]
glRasterPos(p1[0]-1.0, p1[1]+0.1)
[glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(s)) for s in "number key:run n times"]
glRasterPos(p1[0]+0.3, p1[1]+0.2)
[glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(s)) for s in "black dot:means"]
glRasterPos(p1[0]+0.3, p1[1]+0.1)
[glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(s)) for s in "green dot:samples"]
glRasterPos(p1[0]+0.3, p1[1])
[glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(s)) for s in "red triangle:1 sigma area"]
glRasterPos(p1[0]+0.3, p1[1]-0.1)
[glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(s)) for s in "purple triangle:2 sigma area"]
glRasterPos(p1[0]+0.3, p1[1]-0.2)
[glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(s)) for s in "blue triangle:3 sigma area"]
glRasterPos(p1[0]+0.3, p1[1]-0.3)
[glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(s)) for s in "parameter a:"+str(list(mcmc.a))]
glFlush()
glutSwapBuffers()
def resize(w, h):
glViewport(0, 0, w, h)
# +
# def mouse(button, state, x, y):
# print(x, y)
# +
# def motion(x, y):
# print("drag:", x, y)
# -
def keyboard(key, x, y, *, n_samples=10):
global mean_point
global sigma_points
key = key.decode('utf-8')
if key == 'q':
sys.exit()
elif key.isdigit():
n_samples = int(key)
for i in range(n_samples):
z_dash,z_array = mcmc.generate_random()
mcmc.set_z_t(z_dash)
mcmc.set_z_array(z_array)
x_dash = np.array(z_dash)
x_dash += np.abs(x_dash.min())*2
x_dash /= x_dash.sum()
z_accepted.append(z_dash)
x_accepted.append(p1 * x_dash[0] + p2 * x_dash[1] + p3 * x_dash[2])
mean_z_dash = np.mean(z_accepted, axis=0)
mean_point = mean_z_dash + np.abs(mean_z_dash.min())*2
mean_point /= mean_point.sum()
mean_point = p1 * mean_point[0] + p2 * mean_point[1] + p3 * mean_point[2]
var_z_dash = np.var(z_accepted, axis=0)
sigma_points = [np.array([mean_z_dash for i in mean_z_dash]) for n in range(3)]
for n in range(3):
for i in range(mean_z_dash.size):
sigma_points[n][i][i] += (n+1) * var_z_dash[i]
sigma_points[n][i] += np.abs(sigma_points[n][i].min())*2
sigma_points[n][i] /= sigma_points[n][i].sum()
sigma_points = [[p1 * s[0] + p2 * s[1] + p3 * s[2] for s in sigma] for sigma in sigma_points]
# 描画を更新
glutPostRedisplay()
# print(np.cov(np.array(z_accepted).T))
if __name__ == '__main__':
# ディリクレ分布の各次元とする頂点を指定
p1 =
|
np.array([0.0, (3.0**0.5) - 1.0])
|
numpy.array
|
# -*- coding: utf-8 -*-
"""
The module contains the Somoclu class that trains and visualizes
self-organizing maps and emergent self-organizing maps.
Created on Sun July 26 15:07:47 2015
@author: <NAME>
"""
from __future__ import division, print_function
import sys
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.collections as mcoll
import numpy as np
from scipy.spatial.distance import cdist
try:
import seaborn as sns
from sklearn.metrics.pairwise import pairwise_distances
have_heatmap = True
except ImportError:
have_heatmap = False
try:
from .somoclu_wrap import train as wrap_train
except ImportError:
print("Warning: the binary library cannot be imported. You cannot train "
"maps, but you can load and analyze ones that you have already saved.")
if sys.platform.startswith('win'):
print("If you installed Somoclu with pip on Windows, this typically "
"means missing DLLs. Please refer to the documentation.")
elif sys.platform.startswith('darwin'):
print("If you installed Somoclu with pip on macOS, this typically "
"means missing a linked library. If you compiled Somoclu with "
"GCC, please make sure you have set DYLD_LIBRARY_PATH to include "
"the GCC path. For more information, please refer to the "
"documentation.")
else:
print("The problem occurs because either compilation failed when you "
"installed Somoclu or a path is missing from the dependencies "
"when you are trying to import it. Please refer to the "
"documentation to see your options.")
def is_pos_real(s):
""" Returns True if s is a positive real.
"""
try:
return (float(s) > 0)
except ValueError:
return False
class Somoclu(object):
"""Class for training and visualizing a self-organizing map.
Attributes:
codebook The codebook of the self-organizing map.
bmus The BMUs corresponding to the data points.
:param n_columns: The number of columns in the map.
:type n_columns: int.
:param n_rows: The number of rows in the map.
:type n_rows: int.
:param initialcodebook: Optional parameter to start the training with a
given codebook.
:type initialcodebook: 2D numpy.array of float32.
:param kerneltype: Optional parameter to specify which kernel to use:
* 0: dense CPU kernel (default)
* 1: dense GPU kernel (if compiled with it)
:type kerneltype: int.
:param maptype: Optional parameter to specify the map topology:
* "planar": Planar map (default)
* "toroid": Toroid map
:type maptype: str.
:param gridtype: Optional parameter to specify the grid form of the nodes:
* "rectangular": rectangular neurons (default)
* "hexagonal": hexagonal neurons
:type gridtype: str.
:param compactsupport: Optional parameter to cut off map updates beyond the
training radius with the Gaussian neighborhood.
Default: True.
:type compactsupport: bool.
:param neighborhood: Optional parameter to specify the neighborhood:
* "gaussian": Gaussian neighborhood (default)
* "bubble": bubble neighborhood function
:type neighborhood: str.
:param vect_distance: Optional parameter to specify the vector distance function:
* "euclidean": Euclidean (default)
* "norm-inf": infinite norm (max absolute distance among components)
* "norm-p": p-th root of sum of absolute differences ^ p (only supported by kerneltype 0)
:type vect_distance: str.
:param std_coeff: Optional parameter to set the coefficient in the Gaussian
neighborhood function exp(-||x-y||^2/(2*(coeff*radius)^2))
Default: 0.5
:type std_coeff: float.
:param initialization: Optional parameter to specify the initalization:
* "random": random weights in the codebook
* "pca": codebook is initialized from the first
subspace spanned by the first two eigenvectors of
the correlation matrix
:type initialization: str.
:param verbose: Optional parameter to specify verbosity (0, 1, or 2).
:type verbose: int.
"""
def __init__(self, n_columns, n_rows, initialcodebook=None,
kerneltype=0, maptype="planar", gridtype="rectangular",
compactsupport=True, neighborhood="gaussian", std_coeff=0.5,
initialization=None, data=None, verbose=0, vect_distance="euclidean"):
"""Constructor for the class.
"""
self._n_columns, self._n_rows = n_columns, n_rows
self._kernel_type = kerneltype
self._map_type = maptype
self._grid_type = gridtype
self._compact_support = compactsupport
self._neighborhood = neighborhood
self._vect_distance = vect_distance
self._std_coeff = std_coeff
self._verbose = verbose
self._check_parameters()
self.activation_map = None
if initialcodebook is not None and initialization is not None:
raise Exception("An initial codebook is given but initilization"
" is also requested")
self.bmus = None
self.umatrix = np.zeros(n_columns * n_rows, dtype=np.float32)
self.codebook = initialcodebook
if initialization is None or initialization == "random":
self._initialization = "random"
elif initialization == "pca":
self._initialization = "pca"
else:
raise Exception("Unknown initialization method")
self.n_vectors = 0
self.n_dim = 0
self.clusters = None
self._data = None
if data is not None:
print("Warning: passing the data in the constructor is deprecated.")
self.update_data(data)
def load_bmus(self, filename):
"""Load the best matching units from a file to the Somoclu object.
:param filename: The name of the file.
:type filename: str.
"""
self.bmus = np.loadtxt(filename, comments='%', usecols=(1, 2))
if self.n_vectors != 0 and len(self.bmus) != self.n_vectors:
raise Exception("The number of best matching units does not match "
"the number of data instances")
else:
self.n_vectors = len(self.bmus)
tmp = self.bmus[:, 0].copy()
self.bmus[:, 0] = self.bmus[:, 1].copy()
self.bmus[:, 1] = tmp
if max(self.bmus[:, 0]) > self._n_columns - 1 or \
max(self.bmus[:, 1]) > self._n_rows - 1:
raise Exception("The dimensions of the best matching units do not "
"match that of the map")
def load_umatrix(self, filename):
"""Load the umatrix from a file to the Somoclu object.
:param filename: The name of the file.
:type filename: str.
"""
self.umatrix = np.loadtxt(filename, comments='%')
if self.umatrix.shape != (self._n_rows, self._n_columns):
raise Exception("The dimensions of the U-matrix do not "
"match that of the map")
def load_codebook(self, filename):
"""Load the codebook from a file to the Somoclu object.
:param filename: The name of the file.
:type filename: str.
"""
self.codebook = np.loadtxt(filename, comments='%')
if self.n_dim == 0:
self.n_dim = self.codebook.shape[1]
if self.codebook.shape != (self._n_rows * self._n_columns,
self.n_dim):
raise Exception("The dimensions of the codebook do not "
"match that of the map")
self.codebook.shape = (self._n_rows, self._n_columns, self.n_dim)
def train(self, data=None, epochs=10, radius0=0, radiusN=1,
radiuscooling="linear",
scale0=0.1, scaleN=0.01, scalecooling="linear"):
"""Train the map on the current data in the Somoclu object.
:param data: Optional parameter to provide training data. It is not
necessary if the data was added via the method
`update_data`.
:type data: 2D numpy.array of float32.
:param epochs: The number of epochs to train the map for.
:type epochs: int.
:param radius0: The initial radius on the map where the update happens
around a best matching unit. Default value of 0 will
trigger a value of min(n_columns, n_rows)/2.
:type radius0: float.
:param radiusN: The radius on the map where the update happens around a
best matching unit in the final epoch. Default: 1.
:type radiusN: float.
:param radiuscooling: The cooling strategy between radius0 and radiusN:
* "linear": Linear interpolation (default)
* "exponential": Exponential decay
:param scale0: The initial learning scale. Default value: 0.1.
:type scale0: float.
:param scaleN: The learning scale in the final epoch. Default: 0.01.
:type scaleN: float.
:param scalecooling: The cooling strategy between scale0 and scaleN:
* "linear": Linear interpolation (default)
* "exponential": Exponential decay
:type scalecooling: str.
"""
_check_cooling_parameters(radiuscooling, scalecooling)
if self._data is None and data is None:
raise Exception("No data was provided!")
elif data is not None:
self.update_data(data)
self._init_codebook()
self.umatrix.shape = (self._n_rows * self._n_columns, )
self.bmus.shape = (self.n_vectors * 2, )
wrap_train(
|
np.ravel(self._data)
|
numpy.ravel
|
import numpy as np
import torch
import os
import random
import bisect
import histogram
from tqdm import tqdm
class EarlyStopMonitor(object):
def __init__(self, max_round=5, higher_better=True, tolerance=1e-3):
self.max_round = max_round
self.num_round = 0
self.epoch_count = 0
self.best_epoch = 0
self.last_best = None
self.higher_better = higher_better
self.tolerance = tolerance
def early_stop_check(self, curr_val):
self.epoch_count += 1
if not self.higher_better:
curr_val *= -1
if self.last_best is None:
self.last_best = curr_val
elif (curr_val - self.last_best) / np.abs(self.last_best) > self.tolerance:
self.last_best = curr_val
self.num_round = 0
self.best_epoch = self.epoch_count
else:
self.num_round += 1
return self.num_round >= self.max_round
def roc_auc_score_me(y_true, y_score, multi_class='ovo'):
a = [roc_auc_score(y_true, y_score, multi_class='ovo')]
if len(y_true.shape) > 1:
pass
else:
nb_classes = max(y_true) + 1
one_hot_targets = np.eye(nb_classes)[y_true]
for i in range(len(y_score[0])):
a.append(roc_auc_score(one_hot_targets[:,i], y_score[:,i], average='weighted'))
return a
# preprocess dataset
def preprocess_dataset(ts_list, src_list, dst_list, node_max, edge_idx_list, label_list, time_window_factor=0.05, time_start_factor=0.4):
t_max = ts_list.max()
t_min = ts_list.min()
time_window = time_window_factor * (t_max - t_min)
time_start = t_min + time_start_factor * (t_max - t_min)
time_end = t_max - time_window_factor * (t_max - t_min)
edges = {} # edges dict: all the edges
edges_idx = {} # edges index dict: all the edges index, corresponding with edges
adj_list = {}
node_idx = {}
node_simplex = {}
ts_last = -1
simplex_idx = 0
simplex_ts = []
list_simplex = set()
node_first_time= {}
node2simplex = None
simplex_ts.append(ts_list[0])
print(max(label_list))
for i in tqdm(range(len(src_list))):
ts = ts_list[i]
src = src_list[i]
tgt = dst_list[i]
node_idx[src] = 1
node_idx[tgt] = 1
if (i>0) and (label_list[i] != label_list[i-1]):
simplex_ts.append(ts)
if (i>0) and (label_list[i] != label_list[i-1]):
for _i in list(list_simplex):
for _j in list(list_simplex):
for _l in list(list_simplex):
if (_i, _j, _l) in node_simplex:
continue
if len(set([_i, _j, _l])) != 3:
continue
if ((_i, _j) in edges) and (edges[(_i, _j)] <= time_end) and (node_first_time[_l] < edges[(_i, _j)]):
# assume w first appear at the same time as edge(u,v), then no previous information, no way to predict
timing = ts_list[i-1] - edges[(_i, _j)]
if (timing > 0) and (timing < time_window):
node_simplex[(_i, _j, _l)] = simplex_idx
simplex_idx += 1
list_simplex = set()
list_simplex.add(src)
list_simplex.add(tgt)
if src in node_first_time:
node_first_time[src] = min(node_first_time[src], ts)
else:
node_first_time[src] = ts
if tgt in node_first_time:
node_first_time[tgt] = min(node_first_time[tgt], ts)
else:
node_first_time[tgt] = ts
if (src, tgt) in edges:
if edges[(src, tgt)] > ts:
edges[(src, tgt)] = ts
edges_idx[(src, tgt)] = edge_idx_list[i]
else:
edges[(src, tgt)] = ts
edges_idx[(src, tgt)] = edge_idx_list[i]
if src in adj_list:
adj_list[src].append(tgt)
else:
adj_list[src] = [tgt]
# simplex, consider edge as undirected
src = dst_list[i]
tgt = src_list[i]
if (src, tgt) in edges:
if edges[(src, tgt)] > ts:
edges[(src, tgt)] = ts
edges_idx[(src, tgt)] = edge_idx_list[i]
else:
edges[(src, tgt)] = ts
edges_idx[(src, tgt)] = edge_idx_list[i]
if src in adj_list:
adj_list[src].append(tgt)
else:
adj_list[src] = [tgt]
print("node from ", min(node_idx), ' to ', max(node_idx))
print('total nodes out ', len(adj_list.keys()))
print('total nodes ', len(node_idx.keys()))
print('simplex time', len(simplex_ts))
print("close triangle", len(node_simplex.keys()))
return find_triangle_closure(ts_list, node_max, edges, adj_list, edges_idx, node_simplex, simplex_ts, node_first_time, node2simplex, time_window_factor, time_start_factor)
def find_triangle_closure(ts_list, node_max, edges, adj_list, edges_idx, node_simplex, simplex_ts, node_first_time, node2simplex, time_window_factor, time_start_factor=0.4):
positive_three_cycle = []
positive_two_cycle = []
positive_three_ffw = []
positive_two_ffw = []
negative = []
node_max = int(node_max)
t_max = ts_list.max()
t_min = ts_list.min()
time_window = time_window_factor * (t_max - t_min)
time_start = t_min + time_start_factor * (t_max - t_min)
time_end = t_max - time_window_factor * (t_max - t_min)
# close triangle
src_1_cls_tri = []
src_2_cls_tri = []
dst_cls_tri = []
ts_cls_tri_1 = []
ts_cls_tri_2 = []
ts_cls_tri_3 = []
edge_idx_cls_tri_1 = []
edge_idx_cls_tri_2 = []
edge_idx_cls_tri_3 = []
count_cls_tri = 0
# open triangle
src_1_opn_tri = [] # feed forward
src_2_opn_tri = []
dst_opn_tri = []
ts_opn_tri_1 = []
ts_opn_tri_2 = []
ts_opn_tri_3 = []
edge_idx_opn_tri_1 = []
edge_idx_opn_tri_2 = []
edge_idx_opn_tri_3 = []
count_opn_tri = 0
# wedge
src_1_wedge = []
src_2_wedge = []
dst_wedge = []
ts_wedge_1 = []
ts_wedge_2 = []
count_wedge = 0
edge_idx_wedge_1 = []
edge_idx_wedge_2 = []
# negative(only one edge between the first two nodes in three nodes)
src_1_neg = []
src_2_neg = []
dst_neg = []
ts_neg_1 = []
edge_idx_neg_1 = []
count_negative = 0 # <a,b>
set_all_node = set(adj_list.keys())
print(len(list(set_all_node)))
dict_processed_bool = {}
for k_idx, edge_i in enumerate(edges.keys()): # first edge
i = edge_i[0]
j = edge_i[1]
if not (j in adj_list): # exist second edge
continue
# second edge (j,l)
x1 = edges[edge_i]
if (x1 < time_start) or (x1 > time_end):
continue
x1_idx = edges_idx[edge_i]
"""
deal with no interaction with the third nodes
set_all_nodes - {(i, x)} - {(j,x)}
calculate the original situation (only one link between the first two nodes)
"""
if not ((i,j) in dict_processed_bool):
dict_processed_bool[(i,j)] = 1
dict_processed_bool[(j,i)] = 1
set_negative = list(set_all_node - set(adj_list[j]) - set(adj_list[i]))
for l in set_negative:
# (i,j,l)
if node_first_time[l] <= x1:
src_1_neg.append(i)
src_2_neg.append(j)
dst_neg.append(l)
ts_neg_1.append(x1)
edge_idx_neg_1.append(x1_idx)
count_negative += 1
for l in adj_list[j]:
if (l==j) or (l==i) or (node_first_time[l] >= x1):
continue
x2 = edges[(j,l)]
x2_idx = edges_idx[(j,l)]
if (x2 - x1 > time_window):
src_1_neg.append(i)
src_2_neg.append(j)
dst_neg.append(l)
ts_neg_1.append(x1)
edge_idx_neg_1.append(x1_idx)
count_negative += 1
continue
if (x1 > x2) or (x1 == x2 and x1_idx > x2_idx): # TODO: x1 >= x2
continue
l3 = 0
if (l,i) in edges:
x3 = edges[(l,i)]
x3_idx = edges_idx[(l,i)]
if x3 - x1 > time_window:
src_1_neg.append(i)
src_2_neg.append(j)
dst_neg.append(l)
ts_neg_1.append(x1)
edge_idx_neg_1.append(x1_idx)
count_negative += 1
continue
if ((x3 > x2) or (x3 == x2 and x3_idx > x2_idx)) and (x3 - x1 < time_window) and (x3 - x1 > 0): #TODO: x3 > x2
l3 = 1
l1 = (i, j, l) in node_simplex
if l1:
_ts = simplex_ts[node_simplex[(i, j, l)]]
# (i,j,l)
src_1_cls_tri.append(i)
src_2_cls_tri.append(j)
dst_cls_tri.append(l)
ts_cls_tri_1.append(x1)
ts_cls_tri_2.append(_ts) # changed
ts_cls_tri_3.append(_ts) # changed
edge_idx_cls_tri_1.append(x1_idx)
edge_idx_cls_tri_2.append(x2_idx)
edge_idx_cls_tri_3.append(x3_idx)
# total positive cycle
count_cls_tri += 1
elif l3 == 1: # Triangle
src_1_opn_tri.append(i)
src_2_opn_tri.append(j)
dst_opn_tri.append(l)
ts_opn_tri_1.append(x1)
ts_opn_tri_2.append(x2)
ts_opn_tri_3.append(x3)
edge_idx_opn_tri_1.append(x1_idx)
edge_idx_opn_tri_2.append(x2_idx)
edge_idx_opn_tri_3.append(x3_idx)
# total positive cycle
count_opn_tri += 1
elif l3 == 0: # Wedge
if (x2 - x1 > 0) and (x2 - x1 < time_window):
src_1_wedge.append(i)
src_2_wedge.append(j)
dst_wedge.append(l)
ts_wedge_1.append(x1)
ts_wedge_2.append(x2)
edge_idx_wedge_1.append(x1_idx)
edge_idx_wedge_2.append(x2_idx)
count_wedge += 1
cls_tri = [np.array(src_1_cls_tri), np.array(src_2_cls_tri), np.array(dst_cls_tri),
|
np.array(ts_cls_tri_1)
|
numpy.array
|
"""Provide a function for bounding node assignment costs with edgewise info."""
import numpy as np
import pandas as pd
import numba
import os
import tqdm
import time
def iter_adj_pairs(tmplt, world):
"""Generator for pairs of adjacency matrices.
Each pair of adjacency matrices corresponds to the same channel in both
the template and the world.
Parameters
----------
tmplt : Graph
Template graph to be matched.
world : Graph
World graph to be searched.
Yields
-------
(spmatrix, spmatrix)
A tuple of sparse adjacency matrices
"""
for channel, tmplt_adj in tmplt.ch_to_adj.items():
world_adj = world.ch_to_adj[channel]
yield (tmplt_adj, world_adj)
yield (tmplt_adj.T, world_adj.T)
def get_src_dst_weights(smp, src_idx, dst_idx):
""" Returns a tuple of src_weight, dst_weight indicating the weighting for
edge costs to node costs. Weights sum to 2, as they will later be divided by
2 in from_local_bounds.
"""
if isinstance(src_idx, list) or isinstance(dst_idx, list):
if len(src_idx) == 1:
return (2, 0)
elif len(dst_idx) == 1:
return (0, 2)
if not smp.use_monotone:
if hasattr(smp, "next_tmplt_idx") and smp.next_tmplt_idx in [src_idx, dst_idx]:
if src_idx == smp.next_tmplt_idx:
return (2, 0)
elif dst_idx == smp.next_tmplt_idx:
return (0, 2)
else:
assigned_tmplt_idxs = smp.assigned_tmplt_idxs
if src_idx in assigned_tmplt_idxs and dst_idx not in assigned_tmplt_idxs:
return (0, 2)
elif dst_idx in assigned_tmplt_idxs and src_idx not in assigned_tmplt_idxs:
return (2, 0)
else:
return (1, 1)
else:
return (1, 1)
def get_edgelist_iterator(edgelist, src_col, dst_col, attr_keys, node_as_str=True):
n_edges = len(edgelist.index)
srcs = edgelist[src_col]
dsts = edgelist[dst_col]
if node_as_str:
srcs = srcs.astype(str)
dsts = dsts.astype(str)
attr_cols = [edgelist[key] for key in attr_keys]
return zip(range(n_edges), srcs, dsts, *attr_cols)
from numba import float64, int64, void
@numba.njit(void(float64[:,:], int64, int64[:], float64[:]))
def set_assignment_costs(assignment_costs, tmplt_idx, cand_idxs, attr_costs):
for cand_idx, attr_cost in zip(cand_idxs, attr_costs):
if attr_cost < assignment_costs[tmplt_idx, cand_idx]:
assignment_costs[tmplt_idx, cand_idx] = attr_cost
def get_edge_to_unique_attr(edgelist, src_col, dst_col):
"""Get a map from edge indexes to unique attribute indexes.
Parameters
----------
edgelist : DataFrame
Each row of the dataframe should contain the source, destination, and attributes of an edge.
src_col : str
Column name for the source of each edge in `edgelist`.
dst_col : str
Column name for the destination of each edge in `edgelist`.
Returns
-------
edge_to_attr_idx : dict(int, int)
Map edge indexes to the indexes of the attributes in a uniquified list of attributes
unique_attrs : array_like(str)
The unique attributes for the edges of `graph`
"""
attr_names = [a for a in edgelist.columns if a not in [src_col, dst_col, 'id', 'template_id']]
attrs = edgelist[attr_names].to_numpy()
# attrs1d = [str(attr_row) for attr_row in attrs]
str_array = np.frompyfunc(str, 1, 1)
_, index, inverse = np.unique(str_array(attrs).astype(str), axis=0, return_index=True, return_inverse=True)
unique_attrs = attrs[index]
# Do we need to turn unique_attrs back into a dataframe?
return unique_attrs, inverse
def edgewise_no_attrs(smp, changed_cands=None):
"""Compute edgewise costs in the case where no attribute distance function
is provided.
Parameters
----------
smp : MatchingProblem
A subgraph matching problem on which to compute edgewise cost bounds.
changed_cands : ndarray(bool)
Boolean array indicating which template nodes have candidates that have
changed since the last run of the edgewise filter. Only these nodes and
their neighboring template nodes have to be reevaluated.
"""
new_local_costs = np.zeros(smp.shape)
candidates = smp.candidates()
for src_idx, dst_idx in smp.tmplt.nbr_idx_pairs:
if changed_cands is not None:
# If neither the source nor destination has changed, there is no
# point in filtering on this pair of nodes
if not (changed_cands[src_idx] or changed_cands[dst_idx]):
continue
# get indicators of candidate nodes in the world adjacency matrices
src_is_cand = candidates[src_idx]
dst_is_cand = candidates[dst_idx]
if ~np.any(src_is_cand) or ~np.any(dst_is_cand):
print("No candidates for given nodes, skipping edge")
continue
# This sparse matrix stores the number of supported template edges
# between each pair of candidates for src and dst
# i.e. the number of template edges between src and dst that also exist
# between their candidates in the world
supported_edges = None
# Number of total edges in the template between src and dst
total_tmplt_edges = 0
for tmplt_adj, world_adj in iter_adj_pairs(smp.tmplt, smp.world):
tmplt_adj_val = tmplt_adj[src_idx, dst_idx]
total_tmplt_edges += tmplt_adj_val
# if there are no edges in this channel of the template, skip it
if tmplt_adj_val == 0:
continue
# sub adjacency matrix corresponding to edges from the source
# candidates to the destination candidates
world_sub_adj = world_adj[:, dst_is_cand][src_is_cand, :]
# Edges are supported up to the number of edges in the template
if supported_edges is None:
supported_edges = world_sub_adj.minimum(tmplt_adj_val)
else:
supported_edges += world_sub_adj.minimum(tmplt_adj_val)
src_support = supported_edges.max(axis=1)
src_least_cost = total_tmplt_edges - src_support.A
# Different algorithm from REU
# Main idea: assigning u' to u and v' to v causes cost for u to increase
# based on minimum between cost of v and missing edges between u and v
# src_least_cost = np.maximum(total_tmplt_edges - supported_edges.A,
# local_costs[dst_idx][dst_is_cand]).min(axis=1)
src_least_cost = np.array(src_least_cost).flatten()
# Update the local cost bound
new_local_costs[src_idx][src_is_cand] += src_least_cost
if src_idx != dst_idx:
dst_support = supported_edges.max(axis=0)
dst_least_cost = total_tmplt_edges - dst_support.A
dst_least_cost = np.array(dst_least_cost).flatten()
new_local_costs[dst_idx][dst_is_cand] += dst_least_cost
return new_local_costs
def generate_edgewise_cost_cache(smp, cache_by_unique_attrs=True):
"""Generate a cache of edgewise costs for later use.
Parameters
----------
cache_by_unique_attrs : bool
Cache the edgewise costs between edges with unique attributes, and
generate the mapping from edges to unique attribute indices.
"""
src_col = smp.tmplt.source_col
dst_col = smp.tmplt.target_col
tmplt_attr_keys = [attr for attr in smp.tmplt.edgelist.columns if attr not in [src_col, dst_col, 'id', 'template_id']]
if cache_by_unique_attrs:
print('Calculating edge to unique attr map')
start_time = time.time()
if 'importance' not in smp.tmplt.edgelist.columns:
# Template edges with the same attributes could still be different if they have different importances
# For now, prevent the code from removing them as duplicates
tmplt_attr_keys = [attr for attr in smp.tmplt.edgelist.columns if attr not in ['id', 'template_id']]
tmplt_unique_attrs, tmplt_edge_to_attr_idx = get_edge_to_unique_attr(smp.tmplt.edgelist, None, None)
else:
tmplt_unique_attrs, tmplt_edge_to_attr_idx = get_edge_to_unique_attr(smp.tmplt.edgelist, smp.tmplt.source_col, smp.tmplt.target_col)
world_unique_attrs, world_edge_to_attr_idx = get_edge_to_unique_attr(smp.world.edgelist, smp.world.source_col, smp.world.target_col)
print('Edge to unique attr map calculated in {} seconds'.format(time.time()-start_time))
smp.tmplt_edge_to_attr_idx = np.array(tmplt_edge_to_attr_idx)
smp.world_edge_to_attr_idx = np.array(world_edge_to_attr_idx)
smp._edgewise_costs_cache = np.zeros((len(tmplt_unique_attrs), len(world_unique_attrs)))
pbar = tqdm.tqdm(total=len(tmplt_unique_attrs), position=0, leave=True, ascii=True)
for tmplt_unique_idx, tmplt_attrs in enumerate(tmplt_unique_attrs):
tmplt_attrs_dict = dict(zip(tmplt_attr_keys, tmplt_attrs))
if 'importance' in tmplt_attr_keys:
edge_key = None
else:
# Retrieve the source and destination, and reconstruct the edge key
edge_key = (str(tmplt_attrs_dict[smp.tmplt.source_col]), str(tmplt_attrs_dict[smp.tmplt.target_col]))
del tmplt_attrs_dict[smp.tmplt.source_col]
del tmplt_attrs_dict[smp.tmplt.target_col]
src_col_world = smp.world.source_col
dst_col_world = smp.world.target_col
cand_attr_keys = [attr for attr in smp.world.edgelist.columns if attr not in [src_col_world, dst_col_world, 'id']]
for world_unique_idx, cand_attrs in enumerate(world_unique_attrs):
cand_attrs_dict = dict(zip(cand_attr_keys, cand_attrs))
if 'importance' in tmplt_attr_keys:
importance = tmplt_attrs_dict['importance']
else:
importance = None
attr_cost = smp.edge_attr_fn(edge_key, None, tmplt_attrs_dict, cand_attrs_dict, importance_value=importance)
smp._edgewise_costs_cache[tmplt_unique_idx, world_unique_idx] = attr_cost
pbar.update(1)
pbar.close()
else:
n_tmplt_edges = len(smp.tmplt.edgelist.index)
n_world_edges = len(smp.world.edgelist.index)
smp._edgewise_costs_cache = np.zeros((n_tmplt_edges, n_world_edges))
pbar = tqdm.tqdm(total=len(smp.tmplt.edgelist.index), position=0, leave=True, ascii=True)
for tmplt_edge_idx, src_node, dst_node, *tmplt_attrs in get_edgelist_iterator(smp.tmplt.edgelist, src_col, dst_col, tmplt_attr_keys):
tmplt_attrs_dict = dict(zip(tmplt_attr_keys, tmplt_attrs))
src_col_world = smp.world.source_col
dst_col_world = smp.world.target_col
cand_attr_keys = [attr for attr in smp.world.edgelist.columns if attr not in [src_col_world, dst_col_world]]
for world_edge_idx, src_cand, dst_cand, *cand_attrs in get_edgelist_iterator(smp.world.edgelist, src_col_world, dst_col_world, cand_attr_keys):
cand_attrs_dict = dict(zip(cand_attr_keys, cand_attrs))
if 'importance' in tmplt_attr_keys:
attr_cost = smp.edge_attr_fn((src_node, dst_node), (src_cand, dst_cand), tmplt_attrs_dict, cand_attrs_dict, importance_value=tmplt_attrs_dict['importance'])
else:
attr_cost = smp.edge_attr_fn((src_node, dst_node), (src_cand, dst_cand), tmplt_attrs_dict, cand_attrs_dict)
smp._edgewise_costs_cache[tmplt_edge_idx, world_edge_idx] = attr_cost
pbar.update(1)
pbar.close()
if smp.cache_path is not None:
np.save(os.path.join(smp.cache_path, "edgewise_costs_cache.npy"), smp._edgewise_costs_cache)
if cache_by_unique_attrs:
np.save(os.path.join(smp.cache_path, "tmplt_edge_to_attr_idx.npy"), smp.tmplt_edge_to_attr_idx)
np.save(os.path.join(smp.cache_path, "world_edge_to_attr_idx.npy"), smp.world_edge_to_attr_idx)
try:
os.chmod(smp.cache_path, 0o770)
except:
pass
print("Edge-to-edge costs saved to cache")
def verify_edgewise_cost_cache(smp, cache_by_unique_attrs=True):
"""Check that the edgewise cost cache was successfully loaded and generate
edge to attr maps if none are found.
Parameters
----------
smp : MatchingProblem
A subgraph matching problem on which to compute edgewise cost bounds.
"""
n_tmplt_edges = len(smp.tmplt.edgelist.index)
n_world_edges = len(smp.world.edgelist.index)
if cache_by_unique_attrs:
if not hasattr(smp, 'tmplt_edge_to_attr_idx'):
try:
smp.tmplt_edge_to_attr_idx = np.load(os.path.join(smp.cache_path, "tmplt_edge_to_attr_idx.npy"))
smp.world_edge_to_attr_idx = np.load(os.path.join(smp.cache_path, "world_edge_to_attr_idx.npy"))
print('Edge to attr maps loaded from cache')
except:
print('Edge to attr cache not found')
print('Calculating edge to unique attr map')
start_time = time.time()
if 'importance' not in smp.tmplt.edgelist.columns:
tmplt_unique_attrs, tmplt_edge_to_attr_idx = get_edge_to_unique_attr(smp.tmplt.edgelist, None, None)
else:
tmplt_unique_attrs, tmplt_edge_to_attr_idx = get_edge_to_unique_attr(smp.tmplt.edgelist, smp.tmplt.source_col, smp.tmplt.target_col)
world_unique_attrs, world_edge_to_attr_idx = get_edge_to_unique_attr(smp.world.edgelist, smp.world.source_col, smp.world.target_col)
smp.tmplt_edge_to_attr_idx = tmplt_edge_to_attr_idx
smp.world_edge_to_attr_idx = world_edge_to_attr_idx
print('Edge to unique attr map calculated in {} seconds'.format(time.time()-start_time))
if len(smp.tmplt_edge_to_attr_idx) != n_tmplt_edges or len(smp.world_edge_to_attr_idx) != n_world_edges:
raise Exception("Edgewise costs cache not properly computed!")
# TODO: implement a more effective check here
else:
if smp._edgewise_costs_cache.shape != (n_tmplt_edges, n_world_edges):
raise Exception("Edgewise costs cache not properly computed!")
def edgewise_local_costs(smp, changed_cands=None, use_cost_cache=True,
cache_by_unique_attrs=True):
"""Compute edge disagreements between candidates.
Computes a lower bound on the local cost of assignment by iterating
over template edges and comparing candidates for the endpoints.
The lower bound for an assignment (u, u') is the sum over all neighbors
v of u of the minimum number of missing edges between (u', v') over
all v' where v' is a candidate for v.
TODO: Cite paper from REU.
Parameters
----------
smp : MatchingProblem
A subgraph matching problem on which to compute edgewise cost bounds.
changed_cands : ndarray(bool)
Boolean array indicating which template nodes have candidates that have
changed since the last run of the edgewise filter. Only these nodes and
their neighboring template nodes have to be reevaluated.
"""
if smp.edge_attr_fn is None:
return edgewise_no_attrs(smp, changed_cands=changed_cands)
else:
new_local_costs = np.zeros(smp.shape)
candidates = smp.candidates()
# Iterate over template edges and consider best matches for world edges
if use_cost_cache:
# Edge index -> unique attribute idx
# Avoid recalculating edge distance for identical attribute tuples
src_col = smp.tmplt.source_col
dst_col = smp.tmplt.target_col
tmplt_attr_keys = [attr for attr in smp.tmplt.edgelist.columns if attr not in [src_col, dst_col, 'id', 'template_id']]
n_tmplt_edges = len(smp.tmplt.edgelist.index)
n_world_edges = len(smp.world.edgelist.index)
if smp._edgewise_costs_cache is None:
generate_edgewise_cost_cache(smp, cache_by_unique_attrs=cache_by_unique_attrs)
else:
verify_edgewise_cost_cache(smp, cache_by_unique_attrs=cache_by_unique_attrs)
for tmplt_edge_idx, src_node, dst_node, *tmplt_attrs in get_edgelist_iterator(smp.tmplt.edgelist, src_col, dst_col, tmplt_attr_keys, node_as_str=False):
tmplt_attrs_dict = dict(zip(tmplt_attr_keys, tmplt_attrs))
if isinstance(src_node, list) or isinstance(dst_node, list):
# Handle templates with multiple alternatives
if len(src_node) > 1 and len(dst_node) > 1:
raise Exception("Edgewise cost bound cannot handle template edges with both multiple sources and multiple destinations.")
elif len(src_node) == 1 and len(dst_node) == 1:
src_node = src_node[0]
dst_node = dst_node[0]
src_idx = smp.tmplt.node_idxs[src_node]
dst_idx = smp.tmplt.node_idxs[dst_node]
src_node, dst_node = str(src_node), str(dst_node)
else:
src_idx = [smp.tmplt.node_idxs[src_node_i] for src_node_i in src_node]
dst_idx = [smp.tmplt.node_idxs[dst_node_i] for dst_node_i in dst_node]
else:
# Get candidates for src and dst
src_idx = smp.tmplt.node_idxs[src_node]
dst_idx = smp.tmplt.node_idxs[dst_node]
src_node, dst_node = str(src_node), str(dst_node)
# Matrix of costs of assigning template node src_idx and dst_idx
# to candidates row_idx and col_idx
assignment_costs = np.zeros(smp.shape)
if 'importance' in tmplt_attr_keys:
missing_edge_cost = smp.missing_edge_cost_fn((src_node, dst_node), tmplt_attrs_dict['importance'])
else:
missing_edge_cost = smp.missing_edge_cost_fn((src_node, dst_node))
# Put the weight of assignments on the unassigned nodes, when possible
# Only works if monotone is disabled
src_weight, dst_weight = get_src_dst_weights(smp, src_idx, dst_idx)
if src_weight > 0:
assignment_costs[src_idx, :] = src_weight * missing_edge_cost
if dst_weight > 0:
assignment_costs[dst_idx, :] = dst_weight * missing_edge_cost
# TODO: add some data to the graph classes to store the node indexes
# of the source and destination of each edge. You can then use this
# to efficiently get your masks by:
# >>> candidates[src_idx, smp.world.src_idxs]
world_edge_src_idxs = smp.world.edge_src_idxs
if isinstance(src_idx, list):
cand_edge_src_mask = np.sum(candidates[src_idx, :][:, world_edge_src_idxs], axis=0)
else:
cand_edge_src_mask = candidates[src_idx, world_edge_src_idxs]
world_edge_dst_idxs = smp.world.edge_dst_idxs
if isinstance(dst_idx, list):
cand_edge_dst_mask = np.sum(candidates[dst_idx, :][:, world_edge_dst_idxs], axis=0)
else:
cand_edge_dst_mask = candidates[dst_idx, world_edge_dst_idxs]
cand_edge_mask =
|
np.logical_and(cand_edge_src_mask, cand_edge_dst_mask)
|
numpy.logical_and
|
import numpy as n
from kde.cudakde import bootstrap_kde, gaussian_kde
from .qfakde.code.common import Point
from .qfakde.code.quadtree import DynamicQuadTree
__license__ = """
MIT License
Copyright (c) 2020 <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.
"""
class quadtree_kde(gaussian_kde):
def __init__(self, data,
quadtree_granularity=20,
quadtree_max_depth=10,
bandwidth_factor_power=0.5,
use_cuda=False):
gaussian_kde.__init__(self, data, use_cuda=use_cuda)
x_max = n.max(data[0, :])
x_min = n.min(data[0, :])
y_max = n.max(data[1, :])
y_min = n.min(data[1, :])
x_center = (x_max - x_min) / 2 + x_min
y_center = (y_max - y_min) / 2 + y_min
dimension = max((x_max - x_min) / 2, (y_max - y_min) / 2)
num_data_points = len(data[0])
max_points_per_node = pow(num_data_points, 1 / 2)
qt = DynamicQuadTree(centerPt=Point(x_center, y_center, 'center'),
dimension=dimension, max_points=max_points_per_node / quadtree_granularity, max_depth=quadtree_max_depth)
for i in range(len(data[0])):
qt.insert(Point(data[0,i], data[1,i], i))
bandwidth_scale_factor = {}
bandwidth_scale_factor = self.get_lambdas_from_quadtree(
qt.root,
bandwidth_scale_factor)
self.lambdas = pow(n.array([bandwidth_scale_factor[k] for k
in sorted(bandwidth_scale_factor)]),
bandwidth_factor_power)
def get_lambdas_from_quadtree(self, node, lambdas):
d = node.boundary.dimension
pts = list(node._points)
for pt in pts:
lambdas[pt.key] = d
for region in node._nodes:
lambdas = self.get_lambdas_from_quadtree(
node._nodes[region],
lambdas)
return lambdas
def __call__(self, grid_points):
return gaussian_kde.__call__(self, grid_points)
class quadtree_bootstrap_kde(bootstrap_kde):
def __init__(self, data, num_bootstraps, **kwargs):
assert int(num_bootstraps) == float(num_bootstraps)
num_bootstraps = int(num_bootstraps)
self.kernels = []
self.bootstrap_indices = []
self.data =
|
n.atleast_2d(data)
|
numpy.atleast_2d
|
#
# Author: <NAME> 2013
#
from __future__ import division, print_function, absolute_import
import math
import numpy as np
from numpy import asarray_chkfinite, asarray
import scipy.linalg
from scipy._lib import doccer
from scipy.special import gammaln, psi, multigammaln, xlogy, entr
from scipy._lib._util import check_random_state
from scipy.linalg.blas import drot
from scipy.linalg.misc import LinAlgError
from scipy.linalg.lapack import get_lapack_funcs
from ._discrete_distns import binom
from . import mvn
__all__ = ['multivariate_normal',
'matrix_normal',
'dirichlet',
'wishart',
'invwishart',
'multinomial',
'special_ortho_group',
'ortho_group',
'random_correlation',
'unitary_group']
_LOG_2PI = np.log(2 * np.pi)
_LOG_2 = np.log(2)
_LOG_PI = np.log(np.pi)
_doc_random_state = """\
random_state : {None, int, np.random.RandomState, np.random.Generator}, optional
Used for drawing random variates.
If `seed` is `None` the `~np.random.RandomState` singleton is used.
If `seed` is an int, a new ``RandomState`` instance is used, seeded
with seed.
If `seed` is already a ``RandomState`` or ``Generator`` instance,
then that object is used.
Default is None.
"""
def _squeeze_output(out):
"""
Remove single-dimensional entries from array and convert to scalar,
if necessary.
"""
out = out.squeeze()
if out.ndim == 0:
out = out[()]
return out
def _eigvalsh_to_eps(spectrum, cond=None, rcond=None):
"""
Determine which eigenvalues are "small" given the spectrum.
This is for compatibility across various linear algebra functions
that should agree about whether or not a Hermitian matrix is numerically
singular and what is its numerical matrix rank.
This is designed to be compatible with scipy.linalg.pinvh.
Parameters
----------
spectrum : 1d ndarray
Array of eigenvalues of a Hermitian matrix.
cond, rcond : float, optional
Cutoff for small eigenvalues.
Singular values smaller than rcond * largest_eigenvalue are
considered zero.
If None or -1, suitable machine precision is used.
Returns
-------
eps : float
Magnitude cutoff for numerical negligibility.
"""
if rcond is not None:
cond = rcond
if cond in [None, -1]:
t = spectrum.dtype.char.lower()
factor = {'f': 1E3, 'd': 1E6}
cond = factor[t] * np.finfo(t).eps
eps = cond * np.max(abs(spectrum))
return eps
def _pinv_1d(v, eps=1e-5):
"""
A helper function for computing the pseudoinverse.
Parameters
----------
v : iterable of numbers
This may be thought of as a vector of eigenvalues or singular values.
eps : float
Values with magnitude no greater than eps are considered negligible.
Returns
-------
v_pinv : 1d float ndarray
A vector of pseudo-inverted numbers.
"""
return np.array([0 if abs(x) <= eps else 1/x for x in v], dtype=float)
class _PSD(object):
"""
Compute coordinated functions of a symmetric positive semidefinite matrix.
This class addresses two issues. Firstly it allows the pseudoinverse,
the logarithm of the pseudo-determinant, and the rank of the matrix
to be computed using one call to eigh instead of three.
Secondly it allows these functions to be computed in a way
that gives mutually compatible results.
All of the functions are computed with a common understanding as to
which of the eigenvalues are to be considered negligibly small.
The functions are designed to coordinate with scipy.linalg.pinvh()
but not necessarily with np.linalg.det() or with np.linalg.matrix_rank().
Parameters
----------
M : array_like
Symmetric positive semidefinite matrix (2-D).
cond, rcond : float, optional
Cutoff for small eigenvalues.
Singular values smaller than rcond * largest_eigenvalue are
considered zero.
If None or -1, suitable machine precision is used.
lower : bool, optional
Whether the pertinent array data is taken from the lower
or upper triangle of M. (Default: lower)
check_finite : bool, optional
Whether to check that the input matrices contain only finite
numbers. Disabling may give a performance gain, but may result
in problems (crashes, non-termination) if the inputs do contain
infinities or NaNs.
allow_singular : bool, optional
Whether to allow a singular matrix. (Default: True)
Notes
-----
The arguments are similar to those of scipy.linalg.pinvh().
"""
def __init__(self, M, cond=None, rcond=None, lower=True,
check_finite=True, allow_singular=True):
# Compute the symmetric eigendecomposition.
# Note that eigh takes care of array conversion, chkfinite,
# and assertion that the matrix is square.
s, u = scipy.linalg.eigh(M, lower=lower, check_finite=check_finite)
eps = _eigvalsh_to_eps(s, cond, rcond)
if np.min(s) < -eps:
raise ValueError('the input matrix must be positive semidefinite')
d = s[s > eps]
if len(d) < len(s) and not allow_singular:
raise np.linalg.LinAlgError('singular matrix')
s_pinv = _pinv_1d(s, eps)
U = np.multiply(u, np.sqrt(s_pinv))
# Initialize the eagerly precomputed attributes.
self.rank = len(d)
self.U = U
self.log_pdet = np.sum(np.log(d))
# Initialize an attribute to be lazily computed.
self._pinv = None
@property
def pinv(self):
if self._pinv is None:
self._pinv = np.dot(self.U, self.U.T)
return self._pinv
class multi_rv_generic(object):
"""
Class which encapsulates common functionality between all multivariate
distributions.
"""
def __init__(self, seed=None):
super(multi_rv_generic, self).__init__()
self._random_state = check_random_state(seed)
@property
def random_state(self):
""" Get or set the RandomState object for generating random variates.
This can be either None, int, a RandomState instance, or a
np.random.Generator instance.
If None (or np.random), use the RandomState singleton used by
np.random.
If already a RandomState or Generator instance, use it.
If an int, use a new RandomState instance seeded with seed.
"""
return self._random_state
@random_state.setter
def random_state(self, seed):
self._random_state = check_random_state(seed)
def _get_random_state(self, random_state):
if random_state is not None:
return check_random_state(random_state)
else:
return self._random_state
class multi_rv_frozen(object):
"""
Class which encapsulates common functionality between all frozen
multivariate distributions.
"""
@property
def random_state(self):
return self._dist._random_state
@random_state.setter
def random_state(self, seed):
self._dist._random_state = check_random_state(seed)
_mvn_doc_default_callparams = """\
mean : array_like, optional
Mean of the distribution (default zero)
cov : array_like, optional
Covariance matrix of the distribution (default one)
allow_singular : bool, optional
Whether to allow a singular covariance matrix. (Default: False)
"""
_mvn_doc_callparams_note = \
"""Setting the parameter `mean` to `None` is equivalent to having `mean`
be the zero-vector. The parameter `cov` can be a scalar, in which case
the covariance matrix is the identity times that value, a vector of
diagonal entries for the covariance matrix, or a two-dimensional
array_like.
"""
_mvn_doc_frozen_callparams = ""
_mvn_doc_frozen_callparams_note = \
"""See class definition for a detailed description of parameters."""
mvn_docdict_params = {
'_mvn_doc_default_callparams': _mvn_doc_default_callparams,
'_mvn_doc_callparams_note': _mvn_doc_callparams_note,
'_doc_random_state': _doc_random_state
}
mvn_docdict_noparams = {
'_mvn_doc_default_callparams': _mvn_doc_frozen_callparams,
'_mvn_doc_callparams_note': _mvn_doc_frozen_callparams_note,
'_doc_random_state': _doc_random_state
}
class multivariate_normal_gen(multi_rv_generic):
r"""
A multivariate normal random variable.
The `mean` keyword specifies the mean. The `cov` keyword specifies the
covariance matrix.
Methods
-------
``pdf(x, mean=None, cov=1, allow_singular=False)``
Probability density function.
``logpdf(x, mean=None, cov=1, allow_singular=False)``
Log of the probability density function.
``cdf(x, mean=None, cov=1, allow_singular=False, maxpts=1000000*dim, abseps=1e-5, releps=1e-5)``
Cumulative distribution function.
``logcdf(x, mean=None, cov=1, allow_singular=False, maxpts=1000000*dim, abseps=1e-5, releps=1e-5)``
Log of the cumulative distribution function.
``rvs(mean=None, cov=1, size=1, random_state=None)``
Draw random samples from a multivariate normal distribution.
``entropy()``
Compute the differential entropy of the multivariate normal.
Parameters
----------
x : array_like
Quantiles, with the last axis of `x` denoting the components.
%(_mvn_doc_default_callparams)s
%(_doc_random_state)s
Alternatively, the object may be called (as a function) to fix the mean
and covariance parameters, returning a "frozen" multivariate normal
random variable:
rv = multivariate_normal(mean=None, cov=1, allow_singular=False)
- Frozen object with the same methods but holding the given
mean and covariance fixed.
Notes
-----
%(_mvn_doc_callparams_note)s
The covariance matrix `cov` must be a (symmetric) positive
semi-definite matrix. The determinant and inverse of `cov` are computed
as the pseudo-determinant and pseudo-inverse, respectively, so
that `cov` does not need to have full rank.
The probability density function for `multivariate_normal` is
.. math::
f(x) = \frac{1}{\sqrt{(2 \pi)^k \det \Sigma}}
\exp\left( -\frac{1}{2} (x - \mu)^T \Sigma^{-1} (x - \mu) \right),
where :math:`\mu` is the mean, :math:`\Sigma` the covariance matrix,
and :math:`k` is the dimension of the space where :math:`x` takes values.
.. versionadded:: 0.14.0
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from scipy.stats import multivariate_normal
>>> x = np.linspace(0, 5, 10, endpoint=False)
>>> y = multivariate_normal.pdf(x, mean=2.5, cov=0.5); y
array([ 0.00108914, 0.01033349, 0.05946514, 0.20755375, 0.43939129,
0.56418958, 0.43939129, 0.20755375, 0.05946514, 0.01033349])
>>> fig1 = plt.figure()
>>> ax = fig1.add_subplot(111)
>>> ax.plot(x, y)
The input quantiles can be any shape of array, as long as the last
axis labels the components. This allows us for instance to
display the frozen pdf for a non-isotropic random variable in 2D as
follows:
>>> x, y = np.mgrid[-1:1:.01, -1:1:.01]
>>> pos = np.dstack((x, y))
>>> rv = multivariate_normal([0.5, -0.2], [[2.0, 0.3], [0.3, 0.5]])
>>> fig2 = plt.figure()
>>> ax2 = fig2.add_subplot(111)
>>> ax2.contourf(x, y, rv.pdf(pos))
"""
def __init__(self, seed=None):
super(multivariate_normal_gen, self).__init__(seed)
self.__doc__ = doccer.docformat(self.__doc__, mvn_docdict_params)
def __call__(self, mean=None, cov=1, allow_singular=False, seed=None):
"""
Create a frozen multivariate normal distribution.
See `multivariate_normal_frozen` for more information.
"""
return multivariate_normal_frozen(mean, cov,
allow_singular=allow_singular,
seed=seed)
def _process_parameters(self, dim, mean, cov):
"""
Infer dimensionality from mean or covariance matrix, ensure that
mean and covariance are full vector resp. matrix.
"""
# Try to infer dimensionality
if dim is None:
if mean is None:
if cov is None:
dim = 1
else:
cov = np.asarray(cov, dtype=float)
if cov.ndim < 2:
dim = 1
else:
dim = cov.shape[0]
else:
mean = np.asarray(mean, dtype=float)
dim = mean.size
else:
if not np.isscalar(dim):
raise ValueError("Dimension of random variable must be "
"a scalar.")
# Check input sizes and return full arrays for mean and cov if
# necessary
if mean is None:
mean = np.zeros(dim)
mean = np.asarray(mean, dtype=float)
if cov is None:
cov = 1.0
cov = np.asarray(cov, dtype=float)
if dim == 1:
mean.shape = (1,)
cov.shape = (1, 1)
if mean.ndim != 1 or mean.shape[0] != dim:
raise ValueError("Array 'mean' must be a vector of length %d." %
dim)
if cov.ndim == 0:
cov = cov * np.eye(dim)
elif cov.ndim == 1:
cov = np.diag(cov)
elif cov.ndim == 2 and cov.shape != (dim, dim):
rows, cols = cov.shape
if rows != cols:
msg = ("Array 'cov' must be square if it is two dimensional,"
" but cov.shape = %s." % str(cov.shape))
else:
msg = ("Dimension mismatch: array 'cov' is of shape %s,"
" but 'mean' is a vector of length %d.")
msg = msg % (str(cov.shape), len(mean))
raise ValueError(msg)
elif cov.ndim > 2:
raise ValueError("Array 'cov' must be at most two-dimensional,"
" but cov.ndim = %d" % cov.ndim)
return dim, mean, cov
def _process_quantiles(self, x, dim):
"""
Adjust quantiles array so that last axis labels the components of
each data point.
"""
x = np.asarray(x, dtype=float)
if x.ndim == 0:
x = x[np.newaxis]
elif x.ndim == 1:
if dim == 1:
x = x[:, np.newaxis]
else:
x = x[np.newaxis, :]
return x
def _logpdf(self, x, mean, prec_U, log_det_cov, rank):
"""
Parameters
----------
x : ndarray
Points at which to evaluate the log of the probability
density function
mean : ndarray
Mean of the distribution
prec_U : ndarray
A decomposition such that np.dot(prec_U, prec_U.T)
is the precision matrix, i.e. inverse of the covariance matrix.
log_det_cov : float
Logarithm of the determinant of the covariance matrix
rank : int
Rank of the covariance matrix.
Notes
-----
As this function does no argument checking, it should not be
called directly; use 'logpdf' instead.
"""
dev = x - mean
maha = np.sum(np.square(np.dot(dev, prec_U)), axis=-1)
return -0.5 * (rank * _LOG_2PI + log_det_cov + maha)
def logpdf(self, x, mean=None, cov=1, allow_singular=False):
"""
Log of the multivariate normal probability density function.
Parameters
----------
x : array_like
Quantiles, with the last axis of `x` denoting the components.
%(_mvn_doc_default_callparams)s
Returns
-------
pdf : ndarray or scalar
Log of the probability density function evaluated at `x`
Notes
-----
%(_mvn_doc_callparams_note)s
"""
dim, mean, cov = self._process_parameters(None, mean, cov)
x = self._process_quantiles(x, dim)
psd = _PSD(cov, allow_singular=allow_singular)
out = self._logpdf(x, mean, psd.U, psd.log_pdet, psd.rank)
return _squeeze_output(out)
def pdf(self, x, mean=None, cov=1, allow_singular=False):
"""
Multivariate normal probability density function.
Parameters
----------
x : array_like
Quantiles, with the last axis of `x` denoting the components.
%(_mvn_doc_default_callparams)s
Returns
-------
pdf : ndarray or scalar
Probability density function evaluated at `x`
Notes
-----
%(_mvn_doc_callparams_note)s
"""
dim, mean, cov = self._process_parameters(None, mean, cov)
x = self._process_quantiles(x, dim)
psd = _PSD(cov, allow_singular=allow_singular)
out = np.exp(self._logpdf(x, mean, psd.U, psd.log_pdet, psd.rank))
return _squeeze_output(out)
def _cdf(self, x, mean, cov, maxpts, abseps, releps):
"""
Parameters
----------
x : ndarray
Points at which to evaluate the cumulative distribution function.
mean : ndarray
Mean of the distribution
cov : array_like
Covariance matrix of the distribution
maxpts: integer
The maximum number of points to use for integration
abseps: float
Absolute error tolerance
releps: float
Relative error tolerance
Notes
-----
As this function does no argument checking, it should not be
called directly; use 'cdf' instead.
.. versionadded:: 1.0.0
"""
lower = np.full(mean.shape, -np.inf)
# mvnun expects 1-d arguments, so process points sequentially
func1d = lambda x_slice: mvn.mvnun(lower, x_slice, mean, cov,
maxpts, abseps, releps)[0]
out = np.apply_along_axis(func1d, -1, x)
return _squeeze_output(out)
def logcdf(self, x, mean=None, cov=1, allow_singular=False, maxpts=None,
abseps=1e-5, releps=1e-5):
"""
Log of the multivariate normal cumulative distribution function.
Parameters
----------
x : array_like
Quantiles, with the last axis of `x` denoting the components.
%(_mvn_doc_default_callparams)s
maxpts: integer, optional
The maximum number of points to use for integration
(default `1000000*dim`)
abseps: float, optional
Absolute error tolerance (default 1e-5)
releps: float, optional
Relative error tolerance (default 1e-5)
Returns
-------
cdf : ndarray or scalar
Log of the cumulative distribution function evaluated at `x`
Notes
-----
%(_mvn_doc_callparams_note)s
.. versionadded:: 1.0.0
"""
dim, mean, cov = self._process_parameters(None, mean, cov)
x = self._process_quantiles(x, dim)
# Use _PSD to check covariance matrix
_PSD(cov, allow_singular=allow_singular)
if not maxpts:
maxpts = 1000000 * dim
out = np.log(self._cdf(x, mean, cov, maxpts, abseps, releps))
return out
def cdf(self, x, mean=None, cov=1, allow_singular=False, maxpts=None,
abseps=1e-5, releps=1e-5):
"""
Multivariate normal cumulative distribution function.
Parameters
----------
x : array_like
Quantiles, with the last axis of `x` denoting the components.
%(_mvn_doc_default_callparams)s
maxpts: integer, optional
The maximum number of points to use for integration
(default `1000000*dim`)
abseps: float, optional
Absolute error tolerance (default 1e-5)
releps: float, optional
Relative error tolerance (default 1e-5)
Returns
-------
cdf : ndarray or scalar
Cumulative distribution function evaluated at `x`
Notes
-----
%(_mvn_doc_callparams_note)s
.. versionadded:: 1.0.0
"""
dim, mean, cov = self._process_parameters(None, mean, cov)
x = self._process_quantiles(x, dim)
# Use _PSD to check covariance matrix
_PSD(cov, allow_singular=allow_singular)
if not maxpts:
maxpts = 1000000 * dim
out = self._cdf(x, mean, cov, maxpts, abseps, releps)
return out
def rvs(self, mean=None, cov=1, size=1, random_state=None):
"""
Draw random samples from a multivariate normal distribution.
Parameters
----------
%(_mvn_doc_default_callparams)s
size : integer, optional
Number of samples to draw (default 1).
%(_doc_random_state)s
Returns
-------
rvs : ndarray or scalar
Random variates of size (`size`, `N`), where `N` is the
dimension of the random variable.
Notes
-----
%(_mvn_doc_callparams_note)s
"""
dim, mean, cov = self._process_parameters(None, mean, cov)
random_state = self._get_random_state(random_state)
out = random_state.multivariate_normal(mean, cov, size)
return _squeeze_output(out)
def entropy(self, mean=None, cov=1):
"""
Compute the differential entropy of the multivariate normal.
Parameters
----------
%(_mvn_doc_default_callparams)s
Returns
-------
h : scalar
Entropy of the multivariate normal distribution
Notes
-----
%(_mvn_doc_callparams_note)s
"""
dim, mean, cov = self._process_parameters(None, mean, cov)
_, logdet = np.linalg.slogdet(2 * np.pi * np.e * cov)
return 0.5 * logdet
multivariate_normal = multivariate_normal_gen()
class multivariate_normal_frozen(multi_rv_frozen):
def __init__(self, mean=None, cov=1, allow_singular=False, seed=None,
maxpts=None, abseps=1e-5, releps=1e-5):
"""
Create a frozen multivariate normal distribution.
Parameters
----------
mean : array_like, optional
Mean of the distribution (default zero)
cov : array_like, optional
Covariance matrix of the distribution (default one)
allow_singular : bool, optional
If this flag is True then tolerate a singular
covariance matrix (default False).
seed : {None, int, `~np.random.RandomState`, `~np.random.Generator`}, optional
This parameter defines the object to use for drawing random
variates.
If `seed` is `None` the `~np.random.RandomState` singleton is used.
If `seed` is an int, a new ``RandomState`` instance is used, seeded
with seed.
If `seed` is already a ``RandomState`` or ``Generator`` instance,
then that object is used.
Default is None.
maxpts: integer, optional
The maximum number of points to use for integration of the
cumulative distribution function (default `1000000*dim`)
abseps: float, optional
Absolute error tolerance for the cumulative distribution function
(default 1e-5)
releps: float, optional
Relative error tolerance for the cumulative distribution function
(default 1e-5)
Examples
--------
When called with the default parameters, this will create a 1D random
variable with mean 0 and covariance 1:
>>> from scipy.stats import multivariate_normal
>>> r = multivariate_normal()
>>> r.mean
array([ 0.])
>>> r.cov
array([[1.]])
"""
self._dist = multivariate_normal_gen(seed)
self.dim, self.mean, self.cov = self._dist._process_parameters(
None, mean, cov)
self.cov_info = _PSD(self.cov, allow_singular=allow_singular)
if not maxpts:
maxpts = 1000000 * self.dim
self.maxpts = maxpts
self.abseps = abseps
self.releps = releps
def logpdf(self, x):
x = self._dist._process_quantiles(x, self.dim)
out = self._dist._logpdf(x, self.mean, self.cov_info.U,
self.cov_info.log_pdet, self.cov_info.rank)
return _squeeze_output(out)
def pdf(self, x):
return np.exp(self.logpdf(x))
def logcdf(self, x):
return np.log(self.cdf(x))
def cdf(self, x):
x = self._dist._process_quantiles(x, self.dim)
out = self._dist._cdf(x, self.mean, self.cov, self.maxpts, self.abseps,
self.releps)
return _squeeze_output(out)
def rvs(self, size=1, random_state=None):
return self._dist.rvs(self.mean, self.cov, size, random_state)
def entropy(self):
"""
Computes the differential entropy of the multivariate normal.
Returns
-------
h : scalar
Entropy of the multivariate normal distribution
"""
log_pdet = self.cov_info.log_pdet
rank = self.cov_info.rank
return 0.5 * (rank * (_LOG_2PI + 1) + log_pdet)
# Set frozen generator docstrings from corresponding docstrings in
# multivariate_normal_gen and fill in default strings in class docstrings
for name in ['logpdf', 'pdf', 'logcdf', 'cdf', 'rvs']:
method = multivariate_normal_gen.__dict__[name]
method_frozen = multivariate_normal_frozen.__dict__[name]
method_frozen.__doc__ = doccer.docformat(method.__doc__,
mvn_docdict_noparams)
method.__doc__ = doccer.docformat(method.__doc__, mvn_docdict_params)
_matnorm_doc_default_callparams = """\
mean : array_like, optional
Mean of the distribution (default: `None`)
rowcov : array_like, optional
Among-row covariance matrix of the distribution (default: `1`)
colcov : array_like, optional
Among-column covariance matrix of the distribution (default: `1`)
"""
_matnorm_doc_callparams_note = \
"""If `mean` is set to `None` then a matrix of zeros is used for the mean.
The dimensions of this matrix are inferred from the shape of `rowcov` and
`colcov`, if these are provided, or set to `1` if ambiguous.
`rowcov` and `colcov` can be two-dimensional array_likes specifying the
covariance matrices directly. Alternatively, a one-dimensional array will
be be interpreted as the entries of a diagonal matrix, and a scalar or
zero-dimensional array will be interpreted as this value times the
identity matrix.
"""
_matnorm_doc_frozen_callparams = ""
_matnorm_doc_frozen_callparams_note = \
"""See class definition for a detailed description of parameters."""
matnorm_docdict_params = {
'_matnorm_doc_default_callparams': _matnorm_doc_default_callparams,
'_matnorm_doc_callparams_note': _matnorm_doc_callparams_note,
'_doc_random_state': _doc_random_state
}
matnorm_docdict_noparams = {
'_matnorm_doc_default_callparams': _matnorm_doc_frozen_callparams,
'_matnorm_doc_callparams_note': _matnorm_doc_frozen_callparams_note,
'_doc_random_state': _doc_random_state
}
class matrix_normal_gen(multi_rv_generic):
r"""
A matrix normal random variable.
The `mean` keyword specifies the mean. The `rowcov` keyword specifies the
among-row covariance matrix. The 'colcov' keyword specifies the
among-column covariance matrix.
Methods
-------
``pdf(X, mean=None, rowcov=1, colcov=1)``
Probability density function.
``logpdf(X, mean=None, rowcov=1, colcov=1)``
Log of the probability density function.
``rvs(mean=None, rowcov=1, colcov=1, size=1, random_state=None)``
Draw random samples.
Parameters
----------
X : array_like
Quantiles, with the last two axes of `X` denoting the components.
%(_matnorm_doc_default_callparams)s
%(_doc_random_state)s
Alternatively, the object may be called (as a function) to fix the mean
and covariance parameters, returning a "frozen" matrix normal
random variable:
rv = matrix_normal(mean=None, rowcov=1, colcov=1)
- Frozen object with the same methods but holding the given
mean and covariance fixed.
Notes
-----
%(_matnorm_doc_callparams_note)s
The covariance matrices specified by `rowcov` and `colcov` must be
(symmetric) positive definite. If the samples in `X` are
:math:`m \times n`, then `rowcov` must be :math:`m \times m` and
`colcov` must be :math:`n \times n`. `mean` must be the same shape as `X`.
The probability density function for `matrix_normal` is
.. math::
f(X) = (2 \pi)^{-\frac{mn}{2}}|U|^{-\frac{n}{2}} |V|^{-\frac{m}{2}}
\exp\left( -\frac{1}{2} \mathrm{Tr}\left[ U^{-1} (X-M) V^{-1}
(X-M)^T \right] \right),
where :math:`M` is the mean, :math:`U` the among-row covariance matrix,
:math:`V` the among-column covariance matrix.
The `allow_singular` behaviour of the `multivariate_normal`
distribution is not currently supported. Covariance matrices must be
full rank.
The `matrix_normal` distribution is closely related to the
`multivariate_normal` distribution. Specifically, :math:`\mathrm{Vec}(X)`
(the vector formed by concatenating the columns of :math:`X`) has a
multivariate normal distribution with mean :math:`\mathrm{Vec}(M)`
and covariance :math:`V \otimes U` (where :math:`\otimes` is the Kronecker
product). Sampling and pdf evaluation are
:math:`\mathcal{O}(m^3 + n^3 + m^2 n + m n^2)` for the matrix normal, but
:math:`\mathcal{O}(m^3 n^3)` for the equivalent multivariate normal,
making this equivalent form algorithmically inefficient.
.. versionadded:: 0.17.0
Examples
--------
>>> from scipy.stats import matrix_normal
>>> M = np.arange(6).reshape(3,2); M
array([[0, 1],
[2, 3],
[4, 5]])
>>> U = np.diag([1,2,3]); U
array([[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])
>>> V = 0.3*np.identity(2); V
array([[ 0.3, 0. ],
[ 0. , 0.3]])
>>> X = M + 0.1; X
array([[ 0.1, 1.1],
[ 2.1, 3.1],
[ 4.1, 5.1]])
>>> matrix_normal.pdf(X, mean=M, rowcov=U, colcov=V)
0.023410202050005054
>>> # Equivalent multivariate normal
>>> from scipy.stats import multivariate_normal
>>> vectorised_X = X.T.flatten()
>>> equiv_mean = M.T.flatten()
>>> equiv_cov = np.kron(V,U)
>>> multivariate_normal.pdf(vectorised_X, mean=equiv_mean, cov=equiv_cov)
0.023410202050005054
"""
def __init__(self, seed=None):
super(matrix_normal_gen, self).__init__(seed)
self.__doc__ = doccer.docformat(self.__doc__, matnorm_docdict_params)
def __call__(self, mean=None, rowcov=1, colcov=1, seed=None):
"""
Create a frozen matrix normal distribution.
See `matrix_normal_frozen` for more information.
"""
return matrix_normal_frozen(mean, rowcov, colcov, seed=seed)
def _process_parameters(self, mean, rowcov, colcov):
"""
Infer dimensionality from mean or covariance matrices. Handle
defaults. Ensure compatible dimensions.
"""
# Process mean
if mean is not None:
mean = np.asarray(mean, dtype=float)
meanshape = mean.shape
if len(meanshape) != 2:
raise ValueError("Array `mean` must be two dimensional.")
if np.any(meanshape == 0):
raise ValueError("Array `mean` has invalid shape.")
# Process among-row covariance
rowcov = np.asarray(rowcov, dtype=float)
if rowcov.ndim == 0:
if mean is not None:
rowcov = rowcov * np.identity(meanshape[0])
else:
rowcov = rowcov * np.identity(1)
elif rowcov.ndim == 1:
rowcov = np.diag(rowcov)
rowshape = rowcov.shape
if len(rowshape) != 2:
raise ValueError("`rowcov` must be a scalar or a 2D array.")
if rowshape[0] != rowshape[1]:
raise ValueError("Array `rowcov` must be square.")
if rowshape[0] == 0:
raise ValueError("Array `rowcov` has invalid shape.")
numrows = rowshape[0]
# Process among-column covariance
colcov = np.asarray(colcov, dtype=float)
if colcov.ndim == 0:
if mean is not None:
colcov = colcov * np.identity(meanshape[1])
else:
colcov = colcov * np.identity(1)
elif colcov.ndim == 1:
colcov = np.diag(colcov)
colshape = colcov.shape
if len(colshape) != 2:
raise ValueError("`colcov` must be a scalar or a 2D array.")
if colshape[0] != colshape[1]:
raise ValueError("Array `colcov` must be square.")
if colshape[0] == 0:
raise ValueError("Array `colcov` has invalid shape.")
numcols = colshape[0]
# Ensure mean and covariances compatible
if mean is not None:
if meanshape[0] != numrows:
raise ValueError("Arrays `mean` and `rowcov` must have the "
"same number of rows.")
if meanshape[1] != numcols:
raise ValueError("Arrays `mean` and `colcov` must have the "
"same number of columns.")
else:
mean = np.zeros((numrows, numcols))
dims = (numrows, numcols)
return dims, mean, rowcov, colcov
def _process_quantiles(self, X, dims):
"""
Adjust quantiles array so that last two axes labels the components of
each data point.
"""
X = np.asarray(X, dtype=float)
if X.ndim == 2:
X = X[np.newaxis, :]
if X.shape[-2:] != dims:
raise ValueError("The shape of array `X` is not compatible "
"with the distribution parameters.")
return X
def _logpdf(self, dims, X, mean, row_prec_rt, log_det_rowcov,
col_prec_rt, log_det_colcov):
"""
Parameters
----------
dims : tuple
Dimensions of the matrix variates
X : ndarray
Points at which to evaluate the log of the probability
density function
mean : ndarray
Mean of the distribution
row_prec_rt : ndarray
A decomposition such that np.dot(row_prec_rt, row_prec_rt.T)
is the inverse of the among-row covariance matrix
log_det_rowcov : float
Logarithm of the determinant of the among-row covariance matrix
col_prec_rt : ndarray
A decomposition such that np.dot(col_prec_rt, col_prec_rt.T)
is the inverse of the among-column covariance matrix
log_det_colcov : float
Logarithm of the determinant of the among-column covariance matrix
Notes
-----
As this function does no argument checking, it should not be
called directly; use 'logpdf' instead.
"""
numrows, numcols = dims
roll_dev = np.rollaxis(X-mean, axis=-1, start=0)
scale_dev = np.tensordot(col_prec_rt.T,
np.dot(roll_dev, row_prec_rt), 1)
maha = np.sum(np.sum(np.square(scale_dev), axis=-1), axis=0)
return -0.5 * (numrows*numcols*_LOG_2PI + numcols*log_det_rowcov
+ numrows*log_det_colcov + maha)
def logpdf(self, X, mean=None, rowcov=1, colcov=1):
"""
Log of the matrix normal probability density function.
Parameters
----------
X : array_like
Quantiles, with the last two axes of `X` denoting the components.
%(_matnorm_doc_default_callparams)s
Returns
-------
logpdf : ndarray
Log of the probability density function evaluated at `X`
Notes
-----
%(_matnorm_doc_callparams_note)s
"""
dims, mean, rowcov, colcov = self._process_parameters(mean, rowcov,
colcov)
X = self._process_quantiles(X, dims)
rowpsd = _PSD(rowcov, allow_singular=False)
colpsd = _PSD(colcov, allow_singular=False)
out = self._logpdf(dims, X, mean, rowpsd.U, rowpsd.log_pdet, colpsd.U,
colpsd.log_pdet)
return _squeeze_output(out)
def pdf(self, X, mean=None, rowcov=1, colcov=1):
"""
Matrix normal probability density function.
Parameters
----------
X : array_like
Quantiles, with the last two axes of `X` denoting the components.
%(_matnorm_doc_default_callparams)s
Returns
-------
pdf : ndarray
Probability density function evaluated at `X`
Notes
-----
%(_matnorm_doc_callparams_note)s
"""
return np.exp(self.logpdf(X, mean, rowcov, colcov))
def rvs(self, mean=None, rowcov=1, colcov=1, size=1, random_state=None):
"""
Draw random samples from a matrix normal distribution.
Parameters
----------
%(_matnorm_doc_default_callparams)s
size : integer, optional
Number of samples to draw (default 1).
%(_doc_random_state)s
Returns
-------
rvs : ndarray or scalar
Random variates of size (`size`, `dims`), where `dims` is the
dimension of the random matrices.
Notes
-----
%(_matnorm_doc_callparams_note)s
"""
size = int(size)
dims, mean, rowcov, colcov = self._process_parameters(mean, rowcov,
colcov)
rowchol = scipy.linalg.cholesky(rowcov, lower=True)
colchol = scipy.linalg.cholesky(colcov, lower=True)
random_state = self._get_random_state(random_state)
std_norm = random_state.standard_normal(size=(dims[1], size, dims[0]))
roll_rvs = np.tensordot(colchol, np.dot(std_norm, rowchol.T), 1)
out = np.rollaxis(roll_rvs.T, axis=1, start=0) + mean[np.newaxis, :, :]
if size == 1:
out = out.reshape(mean.shape)
return out
matrix_normal = matrix_normal_gen()
class matrix_normal_frozen(multi_rv_frozen):
def __init__(self, mean=None, rowcov=1, colcov=1, seed=None):
"""
Create a frozen matrix normal distribution.
Parameters
----------
%(_matnorm_doc_default_callparams)s
seed : {None, int, `~np.random.RandomState`, `~np.random.Generator`}, optional
This parameter defines the object to use for drawing random
variates.
If `seed` is `None` the `~np.random.RandomState` singleton is used.
If `seed` is an int, a new ``RandomState`` instance is used, seeded
with seed.
If `seed` is already a ``RandomState`` or ``Generator`` instance,
then that object is used.
Default is None.
Examples
--------
>>> from scipy.stats import matrix_normal
>>> distn = matrix_normal(mean=np.zeros((3,3)))
>>> X = distn.rvs(); X
array([[-0.02976962, 0.93339138, -0.09663178],
[ 0.67405524, 0.28250467, -0.93308929],
[-0.31144782, 0.74535536, 1.30412916]])
>>> distn.pdf(X)
2.5160642368346784e-05
>>> distn.logpdf(X)
-10.590229595124615
"""
self._dist = matrix_normal_gen(seed)
self.dims, self.mean, self.rowcov, self.colcov = \
self._dist._process_parameters(mean, rowcov, colcov)
self.rowpsd = _PSD(self.rowcov, allow_singular=False)
self.colpsd = _PSD(self.colcov, allow_singular=False)
def logpdf(self, X):
X = self._dist._process_quantiles(X, self.dims)
out = self._dist._logpdf(self.dims, X, self.mean, self.rowpsd.U,
self.rowpsd.log_pdet, self.colpsd.U,
self.colpsd.log_pdet)
return _squeeze_output(out)
def pdf(self, X):
return np.exp(self.logpdf(X))
def rvs(self, size=1, random_state=None):
return self._dist.rvs(self.mean, self.rowcov, self.colcov, size,
random_state)
# Set frozen generator docstrings from corresponding docstrings in
# matrix_normal_gen and fill in default strings in class docstrings
for name in ['logpdf', 'pdf', 'rvs']:
method = matrix_normal_gen.__dict__[name]
method_frozen = matrix_normal_frozen.__dict__[name]
method_frozen.__doc__ = doccer.docformat(method.__doc__,
matnorm_docdict_noparams)
method.__doc__ = doccer.docformat(method.__doc__, matnorm_docdict_params)
_dirichlet_doc_default_callparams = """\
alpha : array_like
The concentration parameters. The number of entries determines the
dimensionality of the distribution.
"""
_dirichlet_doc_frozen_callparams = ""
_dirichlet_doc_frozen_callparams_note = \
"""See class definition for a detailed description of parameters."""
dirichlet_docdict_params = {
'_dirichlet_doc_default_callparams': _dirichlet_doc_default_callparams,
'_doc_random_state': _doc_random_state
}
dirichlet_docdict_noparams = {
'_dirichlet_doc_default_callparams': _dirichlet_doc_frozen_callparams,
'_doc_random_state': _doc_random_state
}
def _dirichlet_check_parameters(alpha):
alpha = np.asarray(alpha)
if np.min(alpha) <= 0:
raise ValueError("All parameters must be greater than 0")
elif alpha.ndim != 1:
raise ValueError("Parameter vector 'a' must be one dimensional, "
"but a.shape = %s." % (alpha.shape, ))
return alpha
def _dirichlet_check_input(alpha, x):
x = np.asarray(x)
if x.shape[0] + 1 != alpha.shape[0] and x.shape[0] != alpha.shape[0]:
raise ValueError("Vector 'x' must have either the same number "
"of entries as, or one entry fewer than, "
"parameter vector 'a', but alpha.shape = %s "
"and x.shape = %s." % (alpha.shape, x.shape))
if x.shape[0] != alpha.shape[0]:
xk = np.array([1 - np.sum(x, 0)])
if xk.ndim == 1:
x = np.append(x, xk)
elif xk.ndim == 2:
x = np.vstack((x, xk))
else:
raise ValueError("The input must be one dimensional or a two "
"dimensional matrix containing the entries.")
if np.min(x) < 0:
raise ValueError("Each entry in 'x' must be greater than or equal "
"to zero.")
if np.max(x) > 1:
raise ValueError("Each entry in 'x' must be smaller or equal one.")
# Check x_i > 0 or alpha_i > 1
xeq0 = (x == 0)
alphalt1 = (alpha < 1)
if x.shape != alpha.shape:
alphalt1 = np.repeat(alphalt1, x.shape[-1], axis=-1).reshape(x.shape)
chk = np.logical_and(xeq0, alphalt1)
if np.sum(chk):
raise ValueError("Each entry in 'x' must be greater than zero if its "
"alpha is less than one.")
if (np.abs(np.sum(x, 0) - 1.0) > 10e-10).any():
raise ValueError("The input vector 'x' must lie within the normal "
"simplex. but np.sum(x, 0) = %s." % np.sum(x, 0))
return x
def _lnB(alpha):
r"""
Internal helper function to compute the log of the useful quotient
.. math::
B(\alpha) = \frac{\prod_{i=1}{K}\Gamma(\alpha_i)}
{\Gamma\left(\sum_{i=1}^{K} \alpha_i \right)}
Parameters
----------
%(_dirichlet_doc_default_callparams)s
Returns
-------
B : scalar
Helper quotient, internal use only
"""
return np.sum(gammaln(alpha)) - gammaln(np.sum(alpha))
class dirichlet_gen(multi_rv_generic):
r"""
A Dirichlet random variable.
The `alpha` keyword specifies the concentration parameters of the
distribution.
.. versionadded:: 0.15.0
Methods
-------
``pdf(x, alpha)``
Probability density function.
``logpdf(x, alpha)``
Log of the probability density function.
``rvs(alpha, size=1, random_state=None)``
Draw random samples from a Dirichlet distribution.
``mean(alpha)``
The mean of the Dirichlet distribution
``var(alpha)``
The variance of the Dirichlet distribution
``entropy(alpha)``
Compute the differential entropy of the Dirichlet distribution.
Parameters
----------
x : array_like
Quantiles, with the last axis of `x` denoting the components.
%(_dirichlet_doc_default_callparams)s
%(_doc_random_state)s
Alternatively, the object may be called (as a function) to fix
concentration parameters, returning a "frozen" Dirichlet
random variable:
rv = dirichlet(alpha)
- Frozen object with the same methods but holding the given
concentration parameters fixed.
Notes
-----
Each :math:`\alpha` entry must be positive. The distribution has only
support on the simplex defined by
.. math::
\sum_{i=1}^{K} x_i \le 1
The probability density function for `dirichlet` is
.. math::
f(x) = \frac{1}{\mathrm{B}(\boldsymbol\alpha)} \prod_{i=1}^K x_i^{\alpha_i - 1}
where
.. math::
\mathrm{B}(\boldsymbol\alpha) = \frac{\prod_{i=1}^K \Gamma(\alpha_i)}
{\Gamma\bigl(\sum_{i=1}^K \alpha_i\bigr)}
and :math:`\boldsymbol\alpha=(\alpha_1,\ldots,\alpha_K)`, the
concentration parameters and :math:`K` is the dimension of the space
where :math:`x` takes values.
Note that the dirichlet interface is somewhat inconsistent.
The array returned by the rvs function is transposed
with respect to the format expected by the pdf and logpdf.
Examples
--------
>>> from scipy.stats import dirichlet
Generate a dirichlet random variable
>>> quantiles = np.array([0.2, 0.2, 0.6]) # specify quantiles
>>> alpha = np.array([0.4, 5, 15]) # specify concentration parameters
>>> dirichlet.pdf(quantiles, alpha)
0.2843831684937255
The same PDF but following a log scale
>>> dirichlet.logpdf(quantiles, alpha)
-1.2574327653159187
Once we specify the dirichlet distribution
we can then calculate quantities of interest
>>> dirichlet.mean(alpha) # get the mean of the distribution
array([0.01960784, 0.24509804, 0.73529412])
>>> dirichlet.var(alpha) # get variance
array([0.00089829, 0.00864603, 0.00909517])
>>> dirichlet.entropy(alpha) # calculate the differential entropy
-4.3280162474082715
We can also return random samples from the distribution
>>> dirichlet.rvs(alpha, size=1, random_state=1)
array([[0.00766178, 0.24670518, 0.74563305]])
>>> dirichlet.rvs(alpha, size=2, random_state=2)
array([[0.01639427, 0.1292273 , 0.85437844],
[0.00156917, 0.19033695, 0.80809388]])
"""
def __init__(self, seed=None):
super(dirichlet_gen, self).__init__(seed)
self.__doc__ = doccer.docformat(self.__doc__, dirichlet_docdict_params)
def __call__(self, alpha, seed=None):
return dirichlet_frozen(alpha, seed=seed)
def _logpdf(self, x, alpha):
"""
Parameters
----------
x : ndarray
Points at which to evaluate the log of the probability
density function
%(_dirichlet_doc_default_callparams)s
Notes
-----
As this function does no argument checking, it should not be
called directly; use 'logpdf' instead.
"""
lnB = _lnB(alpha)
return - lnB + np.sum((xlogy(alpha - 1, x.T)).T, 0)
def logpdf(self, x, alpha):
"""
Log of the Dirichlet probability density function.
Parameters
----------
x : array_like
Quantiles, with the last axis of `x` denoting the components.
%(_dirichlet_doc_default_callparams)s
Returns
-------
pdf : ndarray or scalar
Log of the probability density function evaluated at `x`.
"""
alpha = _dirichlet_check_parameters(alpha)
x = _dirichlet_check_input(alpha, x)
out = self._logpdf(x, alpha)
return _squeeze_output(out)
def pdf(self, x, alpha):
"""
The Dirichlet probability density function.
Parameters
----------
x : array_like
Quantiles, with the last axis of `x` denoting the components.
%(_dirichlet_doc_default_callparams)s
Returns
-------
pdf : ndarray or scalar
The probability density function evaluated at `x`.
"""
alpha = _dirichlet_check_parameters(alpha)
x = _dirichlet_check_input(alpha, x)
out = np.exp(self._logpdf(x, alpha))
return _squeeze_output(out)
def mean(self, alpha):
"""
Compute the mean of the dirichlet distribution.
Parameters
----------
%(_dirichlet_doc_default_callparams)s
Returns
-------
mu : ndarray or scalar
Mean of the Dirichlet distribution.
"""
alpha = _dirichlet_check_parameters(alpha)
out = alpha / (np.sum(alpha))
return _squeeze_output(out)
def var(self, alpha):
"""
Compute the variance of the dirichlet distribution.
Parameters
----------
%(_dirichlet_doc_default_callparams)s
Returns
-------
v : ndarray or scalar
Variance of the Dirichlet distribution.
"""
alpha = _dirichlet_check_parameters(alpha)
alpha0 =
|
np.sum(alpha)
|
numpy.sum
|
#%%
import random
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow.keras as keras
from itertools import product
import pandas as pd
import seaborn as sns
import numpy as np
import pickle
def unpickle(file):
with open(file, 'rb') as fo:
dict = pickle.load(fo, encoding='bytes')
return dict
# %%
file_to_load = 'result/res.pickle'
res = unpickle(file_to_load)
reps = len(res)
task_acc_single = np.zeros((10,reps),dtype=float)
task_acc_uf = np.zeros((10,reps),dtype=float)
task_acc_rf = np.zeros((10,reps),dtype=float)
task_acc_l2f= np.zeros((10,reps),dtype=float)
for i in range(reps):
task_acc_single[:,i], task_acc_uf[:,i], task_acc_rf[:,i], task_acc_l2f[:,i] = res[i]
#%%
fontsize = 24
ticksize = 20
fig, ax = plt.subplots(1,1, figsize=(8,8))
colors = sns.color_palette('Set1', n_colors=4)
mean_acc = np.mean(task_acc_l2f,axis=1)
std_acc = np.std(task_acc_l2f,axis=1,ddof=1)
ax.plot(np.arange(1, 11), mean_acc, c=colors[0], label='L2F')
ax.fill_between(np.arange(1, 11),
mean_acc+ 1.96*np.array(std_acc),
mean_acc - 1.96*np.array(std_acc),
where=mean_acc + 1.96*np.array(std_acc) >= mean_acc - 1.96*np.array(std_acc),
facecolor=colors[0],
alpha=0.15,
interpolate=False)
mean_acc = np.mean(task_acc_single,axis=1)
std_acc = np.std(task_acc_single,axis=1,ddof=1)
ax.plot(np.arange(1, 11), mean_acc, c=colors[1], label='UF fixed tree')
ax.fill_between(np.arange(1, 11),
mean_acc+ 1.96*np.array(std_acc),
mean_acc - 1.96*np.array(std_acc),
where=mean_acc + 1.96*np.array(std_acc) >= mean_acc - 1.96*np.array(std_acc),
facecolor=colors[1],
alpha=0.15,
interpolate=False)
mean_acc = np.mean(task_acc_uf,axis=1)
std_acc = np.std(task_acc_uf,axis=1,ddof=1)
ax.plot(np.arange(1, 11), mean_acc, c=colors[2], label='UF increasing tree')
ax.fill_between(np.arange(1, 11),
mean_acc+ 1.96*np.array(std_acc),
mean_acc - 1.96*np.array(std_acc),
where=mean_acc + 1.96*np.array(std_acc) >= mean_acc - 1.96*np.array(std_acc),
facecolor=colors[2],
alpha=0.15,
interpolate=False)
mean_acc = np.mean(task_acc_rf,axis=1)
std_acc = np.std(task_acc_rf,axis=1,ddof=1)
ax.plot(
|
np.arange(1, 11)
|
numpy.arange
|
"""
"""
import ConfigParser
import os
import pdb
import sys
import projects
import numpy as np
from netCDF4 import Dataset
class ESMValProject(object):
"""
class to easily retrieve informations for ESMVal project_info
in alphabetical order (mixed general and diagnostics specific)
"""
def __init__(self, project_info):
"""
Parameters
----------
project_info : dict
project information like provided by the launcher
"""
self.project_info = project_info
self.firstime = True
self.oldvar = ""
# self.version = os.environ['0_ESMValTool_version']
def _get_path_with_sep(self, p):
""" ensure that a pathname has the path separator at the end """
if p[-1] == os.sep:
return p
else:
return p + os.sep
def average_data(self, data, dim_index):
"""Returns the mean values over certain dimensions. """
# Usually the input array is three dimensional (time, lats, lons)
if (type(dim_index) == int):
means = np.zeros(data.shape[dim_index])
for mean in xrange(len(means)):
if (dim_index == 0):
means[mean] = np.mean(data[mean, :, :])
if (dim_index == 1):
means[mean] = np.mean(data[:, mean, :])
if (dim_index == 2):
means[mean] = np.mean(data[:, :, mean])
elif (dim_index == 'monthly'):
means = np.zeros(12)
for month in xrange(12):
means[month] = np.mean(data[month::12, :, :])
elif (dim_index == 'annual'):
new_shape = data.shape
new_shape = list(new_shape)
new_shape[0] = 12
means = np.zeros((new_shape))
for month in xrange(12):
for lat in xrange(means.shape[1]):
for lon in xrange(means.shape[2]):
means[month, lat, lon] = np.mean(data[month::12, lat, lon])
elif (dim_index == 'annual'):
new_shape = data.shape
new_shape = list(new_shape)
new_shape[0] = 12
means = np.zeros((new_shape))
for month in xrange(12):
for lat in xrange(means.shape[1]):
for lon in xrange(means.shape[2]):
means[month, lat, lon] = np.mean(data[month::12, lat, lon])
return means
def check_model_instances(self, first_set, second_set):
"""Checks that two model sets have same elemenents. """
# Not pretty but effective: we do a loop for both sets
for model in first_set:
try:
second_set[model]
except KeyError:
print("PY ERROR: I am getting inconsistent model sets for " +
"precipitation and temperature")
print("PY ERROR: All models must have both variables present.")
print("PY ERROR: This error is caused by " + model)
print("PY ERROR: Stopping the script and exiting")
sys.exit()
for model in second_set:
try:
first_set[model]
except KeyError:
print("PY ERROR: I am getting inconsistent model sets for " +
"precipitation and temperature")
print("PY ERROR: All models must have both variables present.")
print("PY ERROR: This error is caused by " + model)
print("PY ERROR: Stopping the script and exiting")
sys.exit()
def ensure_directory(self, path):
""" Checks if a given directory exists and creates it if necessary. """
if not (os.path.exists(path)):
os.makedirs(path)
def ensure_looping(self, array):
""" Checks the first and last element of array,
currently only done for lons. FIXME if you need lats as well. """
array.flags.writeable = True
if (array[0] > array[-1]):
for i in xrange(len(array) - 1):
if (array[i + 1] < array[i]):
array[i + 1] += 360
return array
def extract_seasonal_mean_values(self,
modelconfig,
data,
experiment,
season,
monthly=False):
"""Returns the season specific mean values for each lat, lon from data.
We assume the usual indexing of time, lat, lon"""
season_key = experiment + '_season_' + season
data_shape = data.shape
if (season == 'annual'):
# For annual season we merely copy the data
masked_values = data
else:
# For a specific season we mask the undesired values
season_months = modelconfig.get(season_key, 'season_months').split()
mask = np.ones((data_shape))
for month in season_months:
month_loc = int(month) - 1
mask[month_loc::12, :, :] = 0
masked_values = np.ma.masked_array(data, mask)
if (monthly):
return masked_values
mean_values = np.zeros((data_shape[1], data_shape[2]))
# Seasonal mean values
for lat in xrange(data_shape[1]):
for lon in xrange(data_shape[2]):
mean_values[lat, lon] = masked_values[:, lat, lon].mean()
return mean_values
def find_nearest_value(self, array, value):
""" Finds the nearest value in an array. """
return
|
np.abs(array - value)
|
numpy.abs
|
from __future__ import absolute_import
import math
from math import acos
from math import asin
from math import atan2
from math import cos
from math import pi
from math import sin
import numpy as np
# epsilon for testing whether a number is close to zero
_EPS = np.finfo(float).eps * 4.0
def _wrap_axis(axis):
"""Convert axis to float vector.
Parameters
----------
axis : list or numpy.ndarray or str or bool or None
rotation axis indicated by number or string.
Returns
-------
axis : numpy.ndarray
conveted axis
Examples
--------
>>> from skrobot.coordinates.math import _wrap_axis
>>> _wrap_axis('x')
array([1, 0, 0])
>>> _wrap_axis('y')
array([0, 1, 0])
>>> _wrap_axis('z')
array([0, 0, 1])
>>> _wrap_axis('xy')
array([1, 1, 0])
>>> _wrap_axis([1, 1, 1])
array([1, 1, 1])
>>> _wrap_axis(True)
array([0, 0, 0])
>>> _wrap_axis(False)
array([1, 1, 1])
"""
if isinstance(axis, str):
if axis in ['x', 'xx']:
axis = np.array([1, 0, 0])
elif axis in ['y', 'yy']:
axis = np.array([0, 1, 0])
elif axis in ['z', 'zz']:
axis = np.array([0, 0, 1])
elif axis == '-x':
axis = np.array([-1, 0, 0])
elif axis == '-y':
axis = np.array([0, -1, 0])
elif axis == '-z':
axis = np.array([0, 0, -1])
elif axis in ['xy', 'yx']:
axis = np.array([1, 1, 0])
elif axis in ['yz', 'zy']:
axis = np.array([0, 1, 1])
elif axis in ['zx', 'xz']:
axis = np.array([1, 0, 1])
else:
raise NotImplementedError
elif isinstance(axis, list):
if not len(axis) == 3:
raise ValueError
axis = np.array(axis)
elif isinstance(axis, np.ndarray):
if not axis.shape == (3,):
raise ValueError
elif isinstance(axis, bool):
if axis is True:
return np.array([0, 0, 0])
else:
return np.array([1, 1, 1])
elif axis is None:
return np.array([1, 1, 1])
else:
raise ValueError
return axis
def _check_valid_rotation(rotation):
"""Checks that the given rotation matrix is valid."""
rotation = np.array(rotation)
if not isinstance(
rotation,
np.ndarray) or not np.issubdtype(
rotation.dtype,
np.number):
raise ValueError('Rotation must be specified as numeric numpy array')
if len(rotation.shape) != 2 or \
rotation.shape[0] != 3 or rotation.shape[1] != 3:
raise ValueError('Rotation must be specified as a 3x3 ndarray')
if np.abs(np.linalg.det(rotation) - 1.0) > 1e-3:
raise ValueError('Illegal rotation. Must have determinant == 1.0, '
'get {}'.format(np.linalg.det(rotation)))
return rotation
def _check_valid_translation(translation):
"""Checks that the translation vector is valid."""
if not isinstance(
translation,
np.ndarray) or not np.issubdtype(
translation.dtype,
np.number):
raise ValueError(
'Translation must be specified as numeric numpy array')
t = translation.squeeze()
if len(t.shape) != 1 or t.shape[0] != 3:
raise ValueError(
'Translation must be specified as a 3-vector, '
'3x1 ndarray, or 1x3 ndarray')
def wxyz2xyzw(quat):
"""Convert quaternion [w, x, y, z] to [x, y, z, w] order.
Parameters
----------
quat : list or numpy.ndarray
quaternion [w, x, y, z]
Returns
-------
quaternion : numpy.ndarray
quaternion [x, y, z, w]
Examples
--------
>>> from skrobot.coordinates.math import wxyz2xyzw
>>> wxyz2xyzw([1, 2, 3, 4])
array([2, 3, 4, 1])
"""
if isinstance(quat, list):
quat = np.array(quat)
return np.roll(quat, -1)
def xyzw2wxyz(quat):
"""Convert quaternion [x, y, z, w] to [w, x, y, z] order.
Parameters
----------
quat : list or numpy.ndarray
quaternion [x, y, z, w]
Returns
-------
quaternion : numpy.ndarray
quaternion [w, x, y, z]
Examples
--------
>>> from skrobot.coordinates.math import xyzw2wxyz
>>> xyzw2wxyz([1, 2, 3, 4])
array([4, 1, 2, 3])
"""
if isinstance(quat, list):
quat = np.array(quat)
return np.roll(quat, 1)
def triple_product(a, b, c):
"""Returns Triple Product
See https://en.wikipedia.org/wiki/Triple_product.
Geometrically, the scalar triple product
:math:`a\\cdot(b \\times c)`
is the (signed) volume of the parallelepiped defined
by the three vectors given.
Parameters
----------
a : numpy.ndarray
vector a
b : numpy.ndarray
vector b
c : numpy.ndarray
vector c
Returns
-------
triple product : float
calculated triple product
Examples
--------
>>> from skrobot.math import triple_product
>>> triple_product([1, 1, 1], [1, 1, 1], [1, 1, 1])
0
>>> triple_product([1, 0, 0], [0, 1, 0], [0, 0, 1])
1
"""
return np.dot(a, np.cross(b, c))
def sr_inverse(J, k=1.0, weight_vector=None):
"""Returns SR-inverse of given Jacobian.
Calculate Singularity-Robust Inverse
See: `Inverse Kinematic Solutions With Singularity Robustness \
for Robot Manipulator Control`
Parameters
----------
J : numpy.ndarray
jacobian
k : float
coefficients
weight_vector : None or numpy.ndarray
weight vector
Returns
-------
ret : numpy.ndarray
result of SR-inverse
"""
r, _ = J.shape
# without weight
if weight_vector is None:
return sr_inverse_org(J, k)
# k=0 => sr-inverse = pseudo-inverse
if k == 0.0:
return np.linalg.pinv(J)
# with weight
weight_matrix = np.diag(weight_vector)
# umat = J W J^T + kI
# ret = W J^T (J W J^T + kI)^(-1)
weight_J = np.matmul(weight_matrix, J.T)
umat = np.matmul(J, weight_J) + k * np.eye(r)
ret = np.matmul(weight_J, np.linalg.inv(umat))
return ret
def sr_inverse_org(J, k=1.0):
"""Return SR-inverse of given J
Definition of SR-inverse is following.
:math:`J^* = J^T(JJ^T + kI_m)^{-1}`
Parameters
----------
J : numpy.ndarray
jacobian
k : float
coefficients
Returns
-------
sr_inverse : numpy.ndarray
calculated SR-inverse
"""
r, _ = J.shape
return np.matmul(J.T,
np.linalg.inv(np.matmul(J, J.T) + k * np.eye(r)))
def manipulability(J):
"""Return manipulability of given matrix.
Definition of manipulability is following.
:math:`w = \\sqrt{\\det J(\\theta)J^T(\\theta)}`
Parameters
----------
J : numpy.ndarray
jacobian
Returns
-------
w : float
manipulability
"""
return np.sqrt(max(0.0, np.linalg.det(np.matmul(J, J.T))))
def midpoint(p, a, b):
"""Return midpoint
Parameters
----------
p : float
ratio of a:b
a : numpy.ndarray
vector
b : numpy.ndarray
vector
Returns
-------
midpoint : numpy.ndarray
midpoint
Examples
--------
>>> import numpy as np
>>> from skrobot.coordinates.math import midpoint
>>> midpoint(0.5, np.ones(3), np.zeros(3))
>>> array([0.5, 0.5, 0.5])
"""
return a + (b - a) * p
def midrot(p, r1, r2):
"""Returns mid (or p) rotation matrix of given two matrix r1 and r2.
Parameters
----------
p : float
ratio of r1:r2
r1 : numpy.ndarray
3x3 rotation matrix
r2 : numpy.ndarray
3x3 rotation matrix
Returns
-------
r : numpy.ndarray
3x3 rotation matrix
Examples
--------
>>> import numpy as np
>>> from skrobot.coordinates.math import midrot
>>> midrot(0.5,
np.eye(3),
np.array([[0, 0, 1], [0, 1, 0], [-1, 0, 0]]))
array([[ 0.70710678, 0. , 0.70710678],
[ 0. , 1. , 0. ],
[-0.70710678, 0. , 0.70710678]])
>>> from skrobot.coordinates.math import rpy_angle
>>> np.rad2deg(rpy_angle(midrot(0.5,
np.eye(3),
np.array([[0, 0, 1], [0, 1, 0], [-1, 0, 0]])))[0])
array([ 0., 45., 0.])
"""
r1 = _check_valid_rotation(r1)
r2 = _check_valid_rotation(r2)
r = np.matmul(r1.T, r2)
omega = matrix_log(r)
r = matrix_exponent(omega, p)
return np.matmul(r1, r)
def transform(m, v):
"""Return transform m v
Parameters
----------
m : numpy.ndarray
3 x 3 rotation matrix.
v : numpy.ndarray or list
input vector.
Returns
-------
np.matmul(m, v) : numpy.ndarray
transformed vector.
"""
m = np.array(m)
v = np.array(v)
return np.matmul(m, v)
def rotation_matrix(theta, axis):
"""Return the rotation matrix.
Return the rotation matrix associated with counterclockwise rotation
about the given axis by theta radians.
Parameters
----------
theta : float
radian
axis : str or list or numpy.ndarray
rotation axis such that 'x', 'y', 'z'
[0, 0, 1], [0, 1, 0], [1, 0, 0]
Returns
-------
rot : numpy.ndarray
rotation matrix about the given axis by theta radians.
Examples
--------
>>> import numpy as np
>>> from skrobot.coordinates.math import rotation_matrix
>>> rotation_matrix(np.pi / 2.0, [1, 0, 0])
array([[ 1.00000000e+00, 0.00000000e+00, 0.00000000e+00],
[ 0.00000000e+00, 2.22044605e-16, -1.00000000e+00],
[ 0.00000000e+00, 1.00000000e+00, 2.22044605e-16]])
>>> rotation_matrix(np.pi / 2.0, 'y')
array([[ 2.22044605e-16, 0.00000000e+00, 1.00000000e+00],
[ 0.00000000e+00, 1.00000000e+00, 0.00000000e+00],
[-1.00000000e+00, 0.00000000e+00, 2.22044605e-16]])
"""
axis = _wrap_axis(axis)
axis = axis / np.sqrt(np.dot(axis, axis))
a = np.cos(theta / 2.0)
b, c, d = -axis * np.sin(theta / 2.0)
aa, bb, cc, dd = a * a, b * b, c * c, d * d
bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d
return np.array([[aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)],
[2 * (bc - ad), aa + cc - bb - dd, 2 * (cd + ab)],
[2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc]])
def rotate_vector(vec, theta, axis):
"""Rotate vector.
Rotate vec with respect to axis.
Parameters
----------
vec : list or numpy.ndarray
target vector
theta : float
rotation angle
axis : list or numpy.ndarray or str
axis of rotation.
Returns
-------
rotated_vec : numpy.ndarray
rotated vector.
Examples
--------
>>> from numpy import pi
>>> from skrobot.coordinates.math import rotate_vector
>>> rotate_vector([1, 0, 0], pi / 6.0, [1, 0, 0])
array([1., 0., 0.])
>>> rotate_vector([1, 0, 0], pi / 6.0, [0, 1, 0])
array([ 0.8660254, 0. , -0.5 ])
>>> rotate_vector([1, 0, 0], pi / 6.0, [0, 0, 1])
array([0.8660254, 0.5 , 0. ])
"""
rot = rotation_matrix(theta, axis)
rotated_vec = transform(rot, vec)
return rotated_vec
def rotate_matrix(matrix, theta, axis, world=None):
if world is False or world is None:
return np.dot(matrix, rotation_matrix(theta, axis))
return np.dot(rotation_matrix(theta, axis), matrix)
def rpy_matrix(az, ay, ax):
"""Return rotation matrix from yaw-pitch-roll
This function creates a new rotation matrix which has been
rotated ax radian around x-axis in WORLD, ay radian around y-axis in WORLD,
and az radian around z axis in WORLD, in this order. These angles can be
extracted by the rpy function.
Parameters
----------
az : float
rotated around z-axis(yaw) in radian.
ay : float
rotated around y-axis(pitch) in radian.
ax : float
rotated around x-axis(roll) in radian.
Returns
-------
r : numpy.ndarray
rotation matrix
Examples
--------
>>> import numpy as np
>>> from skrobot.coordinates.math import rpy_matrix
>>> yaw = np.pi / 2.0
>>> pitch = np.pi / 3.0
>>> roll = np.pi / 6.0
>>> rpy_matrix(yaw, pitch, roll)
array([[ 1.11022302e-16, -8.66025404e-01, 5.00000000e-01],
[ 5.00000000e-01, 4.33012702e-01, 7.50000000e-01],
[-8.66025404e-01, 2.50000000e-01, 4.33012702e-01]])
"""
r = rotation_matrix(ax, 'x')
r = rotate_matrix(r, ay, 'y', world=True)
r = rotate_matrix(r, az, 'z', world=True)
return r
def rpy_angle(matrix):
"""Decomposing a rotation matrix to yaw-pitch-roll.
Parameters
----------
matrix : list or numpy.ndarray
3x3 rotation matrix
Returns
-------
rpy : tuple(numpy.ndarray, numpy.ndarray)
pair of rpy in yaw-pitch-roll order.
Examples
--------
>>> import numpy as np
>>> from skrobot.coordinates.math import rpy_matrix
>>> from skrobot.coordinates.math import rpy_angle
>>> yaw = np.pi / 2.0
>>> pitch = np.pi / 3.0
>>> roll = np.pi / 6.0
>>> rot = rpy_matrix(yaw, pitch, roll)
>>> rpy_angle(rot)
(array([1.57079633, 1.04719755, 0.52359878]),
array([ 4.71238898, 2.0943951 , -2.61799388]))
"""
if np.sqrt(matrix[1, 0] ** 2 + matrix[0, 0] ** 2) < _EPS:
a = 0.0
else:
a = np.arctan2(matrix[1, 0], matrix[0, 0])
sa = np.sin(a)
ca = np.cos(a)
b = np.arctan2(-matrix[2, 0], ca * matrix[0, 0] + sa * matrix[1, 0])
c = np.arctan2(sa * matrix[0, 2] - ca * matrix[1, 2],
-sa * matrix[0, 1] + ca * matrix[1, 1])
rpy = np.array([a, b, c])
a = a + np.pi
sa = np.sin(a)
ca = np.cos(a)
b = np.arctan2(-matrix[2, 0], ca * matrix[0, 0] + sa * matrix[1, 0])
c = np.arctan2(sa * matrix[0, 2] - ca * matrix[1, 2],
-sa * matrix[0, 1] + ca * matrix[1, 1])
return rpy, np.array([a, b, c])
def normalize_vector(v, ord=2):
"""Return normalized vector
Parameters
----------
v : list or numpy.ndarray
vector
ord : int (optional)
ord of np.linalg.norm
Returns
-------
v : numpy.ndarray
normalized vector
Examples
--------
>>> from skrobot.coordinates.math import normalize_vector
>>> normalize_vector([1, 1, 1])
array([0.57735027, 0.57735027, 0.57735027])
>>> normalize_vector([0, 0, 0])
array([0., 0., 0.])
"""
v = np.array(v, dtype=np.float64)
norm = np.linalg.norm(v, ord=ord)
if norm == 0:
return v
return v / norm
def matrix2quaternion(m):
"""Returns quaternion of given rotation matrix.
Parameters
----------
m : list or numpy.ndarray
3x3 rotation matrix
Returns
-------
quaternion : numpy.ndarray
quaternion [w, x, y, z] order
Examples
--------
>>> import numpy
>>> from skrobot.coordinates.math import matrix2quaternion
>>> matrix2quaternion(np.eye(3))
array([1., 0., 0., 0.])
"""
m = np.array(m, dtype=np.float64)
tr = m[0, 0] + m[1, 1] + m[2, 2]
if tr > 0:
S = math.sqrt(tr + 1.0) * 2
qw = 0.25 * S
qx = (m[2, 1] - m[1, 2]) / S
qy = (m[0, 2] - m[2, 0]) / S
qz = (m[1, 0] - m[0, 1]) / S
elif (m[0, 0] > m[1, 1]) and (m[0, 0] > m[2, 2]):
S = math.sqrt(1. + m[0, 0] - m[1, 1] - m[2, 2]) * 2
qw = (m[2, 1] - m[1, 2]) / S
qx = 0.25 * S
qy = (m[0, 1] + m[1, 0]) / S
qz = (m[0, 2] + m[2, 0]) / S
elif m[1, 1] > m[2, 2]:
S = math.sqrt(1. + m[1, 1] - m[0, 0] - m[2, 2]) * 2
qw = (m[0, 2] - m[2, 0]) / S
qx = (m[0, 1] + m[1, 0]) / S
qy = 0.25 * S
qz = (m[1, 2] + m[2, 1]) / S
else:
S = math.sqrt(1. + m[2, 2] - m[0, 0] - m[1, 1]) * 2
qw = (m[1, 0] - m[0, 1]) / S
qx = (m[0, 2] + m[2, 0]) / S
qy = (m[1, 2] + m[2, 1]) / S
qz = 0.25 * S
return np.array([qw, qx, qy, qz])
def quaternion2matrix(q, normalize=False):
"""Returns matrix of given quaternion.
Parameters
----------
quaternion : list or numpy.ndarray
quaternion [w, x, y, z] order
normalize : bool
if normalize is True, input quaternion is normalized.
Returns
-------
rot : numpy.ndarray
3x3 rotation matrix
Examples
--------
>>> import numpy
>>> from skrobot.coordinates.math import quaternion2matrix
>>> quaternion2matrix([1, 0, 0, 0])
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
"""
q = np.array(q)
if normalize:
q = quaternion_normalize(q)
else:
norm = quaternion_norm(q)
if not np.allclose(norm, 1.0):
raise ValueError("quaternion q's norm is not 1")
if q.ndim == 1:
q0 = q[0]
q1 = q[1]
q2 = q[2]
q3 = q[3]
m = np.zeros((3, 3))
m[0, 0] = q0 * q0 + q1 * q1 - q2 * q2 - q3 * q3
m[0, 1] = 2 * (q1 * q2 - q0 * q3)
m[0, 2] = 2 * (q1 * q3 + q0 * q2)
m[1, 0] = 2 * (q1 * q2 + q0 * q3)
m[1, 1] = q0 * q0 - q1 * q1 + q2 * q2 - q3 * q3
m[1, 2] = 2 * (q2 * q3 - q0 * q1)
m[2, 0] = 2 * (q1 * q3 - q0 * q2)
m[2, 1] = 2 * (q2 * q3 + q0 * q1)
m[2, 2] = q0 * q0 - q1 * q1 - q2 * q2 + q3 * q3
elif q.ndim == 2:
m = np.zeros((q.shape[0], 3, 3), dtype=np.float64)
m[:, 0, 0] = q[:, 0] * q[:, 0] + \
q[:, 1] * q[:, 1] - q[:, 2] * q[:, 2] - q[:, 3] * q[:, 3]
m[:, 0, 1] = 2 * (q[:, 1] * q[:, 2] - q[:, 0] * q[:, 3])
m[:, 0, 2] = 2 * (q[:, 1] * q[:, 3] + q[:, 0] * q[:, 2])
m[:, 1, 0] = 2 * (q[:, 1] * q[:, 2] + q[:, 0] * q[:, 3])
m[:, 1, 1] = q[:, 0] * q[:, 0] - \
q[:, 1] * q[:, 1] + q[:, 2] * q[:, 2] - q[:, 3] * q[:, 3]
m[:, 1, 2] = 2 * (q[:, 2] * q[:, 3] - q[:, 0] * q[:, 1])
m[:, 2, 0] = 2 * (q[:, 1] * q[:, 3] - q[:, 0] * q[:, 2])
m[:, 2, 1] = 2 * (q[:, 2] * q[:, 3] + q[:, 0] * q[:, 1])
m[:, 2, 2] = q[:, 0] * q[:, 0] - \
q[:, 1] * q[:, 1] - q[:, 2] * q[:, 2] + q[:, 3] * q[:, 3]
return m
def matrix_log(m):
"""Returns matrix log of given rotation matrix, it returns [-pi, pi]
Parameters
----------
m : list or numpy.ndarray
3x3 rotation matrix
Returns
-------
matrixlog : numpy.ndarray
vector of shape (3, )
Examples
--------
>>> import numpy as np
>>> from skrobot.coordinates.math import matrix_log
>>> matrix_log(np.eye(3))
array([0., 0., 0.])
"""
# calc logarithm of quaternion
q = matrix2quaternion(m)
q_w = q[0]
q_xyz = q[1:]
theta = 2.0 * np.arctan(np.linalg.norm(q_xyz) / q_w)
if theta > np.pi:
theta = theta - 2.0 * np.pi
elif theta < - np.pi:
theta = theta + 2.0 * np.pi
return theta * normalize_vector(q_xyz)
def matrix_exponent(omega, p=1.0):
"""Returns exponent of given omega.
This function is similar to cv2.Rodrigues.
Convert rvec (which is log quaternion) to rotation matrix.
Parameters
----------
omega : list or numpy.ndarray
vector of shape (3,)
Returns
-------
rot : numpy.ndarray
exponential matrix of given omega
Examples
--------
>>> import numpy as np
>>> from skrobot.coordinates.math import matrix_exponent
>>> matrix_exponent([1, 1, 1])
array([[ 0.22629564, -0.18300792, 0.95671228],
[ 0.95671228, 0.22629564, -0.18300792],
[-0.18300792, 0.95671228, 0.22629564]])
>>> matrix_exponent([1, 0, 0])
array([[ 1. , 0. , 0. ],
[ 0. , 0.54030231, -0.84147098],
[ 0. , 0.84147098, 0.54030231]])
"""
w = np.linalg.norm(omega)
amat = outer_product_matrix(normalize_vector(omega))
return np.eye(3) + np.sin(w * p) * amat + \
(1.0 - np.cos(w * p)) * np.matmul(amat, amat)
def outer_product_matrix(v):
"""Returns outer product matrix of given v.
Returns following outer product matrix.
.. math::
\\left(
\\begin{array}{ccc}
0 & -v_2 & v_1 \\\\
v_2 & 0 & -v_0 \\\\
-v_1 & v_0 & 0
\\end{array}
\\right)
Parameters
----------
v : numpy.ndarray or list
[x, y, z]
Returns
-------
matrix : numpy.ndarray
3x3 rotation matrix.
Examples
--------
>>> from skrobot.coordinates.math import outer_product_matrix
>>> outer_product_matrix([1, 2, 3])
array([[ 0, -3, 2],
[ 3, 0, -1],
[-2, 1, 0]])
"""
return np.array([[0, -v[2], v[1]],
[v[2], 0, -v[0]],
[-v[1], v[0], 0]])
def cross_product(a, b):
"""Return cross product.
Parameters
----------
a : numpy.ndarray
3-dimensional vector.
b : numpy.ndarray
3-dimensional vector.
Returns
-------
cross_prod : numpy.ndarray
calculated cross product
"""
return np.dot(outer_product_matrix(a), b)
def quaternion2rpy(q):
"""Returns Roll-pitch-yaw angles of a given quaternion.
Parameters
----------
q : numpy.ndarray or list
Quaternion in [w x y z] format.
Returns
-------
rpy : numpy.ndarray
Array of yaw-pitch-roll angles, in radian.
Examples
--------
>>> from skrobot.coordinates.math import quaternion2rpy
>>> quaternion2rpy([1, 0, 0, 0])
(array([ 0., -0., 0.]), array([3.14159265, 3.14159265, 3.14159265]))
>>> quaternion2rpy([0, 1, 0, 0])
(array([ 0. , -0. , 3.14159265]),
array([3.14159265, 3.14159265, 0. ]))
"""
roll = atan2(
2 * q[2] * q[3] + 2 * q[0] * q[1],
q[3] ** 2 - q[2] ** 2 - q[1] ** 2 + q[0] ** 2)
pitch = -asin(
2 * q[1] * q[3] - 2 * q[0] * q[2])
yaw = atan2(
2 * q[1] * q[2] + 2 * q[0] * q[3],
q[1] ** 2 + q[0] ** 2 - q[3] ** 2 - q[2] ** 2)
rpy = np.array([yaw, pitch, roll])
return rpy, np.pi - rpy
def rpy2quaternion(rpy):
"""Return Quaternion from yaw-pitch-roll angles.
Parameters
----------
rpy : numpy.ndarray or list
Vector of yaw-pitch-roll angles in radian.
Returns
-------
quat : numpy.ndarray
Quaternion in [w x y z] format.
Examples
--------
>>> import numpy as np
>>> from skrobot.coordinates.math import rpy2quaternion
>>> rpy2quaternion([0, 0, 0])
array([1., 0., 0., 0.])
>>> yaw = np.pi / 3.0
>>> rpy2quaternion([yaw, 0, 0])
array([0.8660254, 0. , 0. , 0.5 ])
>>> rpy2quaternion([np.pi * 2 - yaw, 0, 0])
array([-0.8660254, -0. , 0. , 0.5 ])
"""
yaw, pitch, roll = rpy
cr, cp, cy = cos(roll / 2.), cos(pitch / 2.), cos(yaw / 2.)
sr, sp, sy = sin(roll / 2.), sin(pitch / 2.), sin(yaw / 2.)
return np.array([
cr * cp * cy + sr * sp * sy,
-cr * sp * sy + cp * cy * sr,
cr * cy * sp + sr * cp * sy,
cr * cp * sy - sr * cy * sp])
def rotation_matrix_from_rpy(rpy):
"""Returns Rotation matrix from yaw-pitch-roll angles.
Parameters
----------
rpy : numpy.ndarray or list
Vector of yaw-pitch-roll angles in radian.
Returns
-------
rot : numpy.ndarray
3x3 rotation matrix
Examples
--------
>>> import numpy as np
>>> from skrobot.coordinates.math import rotation_matrix_from_rpy
>>> rotation_matrix_from_rpy([0, np.pi / 3, 0])
array([[ 0.5 , 0. , 0.8660254],
[ 0. , 1. , 0. ],
[-0.8660254, 0. , 0.5 ]])
"""
return quaternion2matrix(quat_from_rpy(rpy))
def rotation_matrix_from_axis(
first_axis=(1, 0, 0), second_axis=(0, 1, 0), axes='xy'):
"""Return rotation matrix orienting first_axis
Parameters
----------
first_axis : list or tuple or numpy.ndarray
direction of first axis
second_axis : list or tuple or numpy.ndarray
direction of second axis.
This input axis is normalized using Gram-Schmidt.
axes : str
valid inputs are 'xy', 'yx', 'xz', 'zx', 'yz', 'zy'.
first index indicates first_axis's axis.
Returns
-------
rotation_matrix : numpy.ndarray
Rotation matrix
Examples
--------
>>> from skrobot.coordinates.math import rotation_matrix_from_axis
>>> rotation_matrix_from_axis((1, 0, 0), (0, 1, 0))
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
>>> rotation_matrix_from_axis((1, 1, 1), (0, 1, 0))
array([[ 0.57735027, -0.40824829, -0.70710678],
[ 0.57735027, 0.81649658, 0. ],
[ 0.57735027, -0.40824829, 0.70710678]])
"""
if axes not in ['xy', 'yx', 'xz', 'zx', 'yz', 'zy']:
raise ValueError("Valid axes are 'xy', 'yx', 'xz', 'zx', 'yz', 'zy'.")
e1 = normalize_vector(first_axis)
e2 = normalize_vector(second_axis - np.dot(second_axis, e1) * e1)
if axes in ['xy', 'zx', 'yz']:
third_axis = cross_product(e1, e2)
else:
third_axis = cross_product(e2, e1)
e3 = normalize_vector(
third_axis - np.dot(third_axis, e1) * e1 -
|
np.dot(third_axis, e2)
|
numpy.dot
|
"""
This file contains utilities to set up hexagonal convolution and pooling
kernels in PyTorch. The size of the input is abitrary, whereas the layout
from top to bottom (along tensor index 2) has to be of zig-zag-edge shape
and from left to right (along tensor index 3) of armchair-edge shape as
shown below.
__ __ __ __ __ __
/11\__/31\__ . . . |11|21|31|41| . . .
\__/21\__/41\ |__|__|__|__|
/12\__/32\__/ . . . _______|\ |12|22|32|42| . . .
\__/22\__/42\ | \ |__|__|__|__|
\__/ \__/ |_______ /
. . . . . |/ . . . . .
. . . . . . . . . .
. . . . . . . . . .
For more information visit https://github.com/ai4iacts/hexagdly
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
import numpy as np
class HexBase():
def __init__(self):
super(HexBase, self).__init__()
self.hexbase_size = None
self.depth_size = None
self.hexbase_stride = None
self.depth_stride = None
self.input_size_is_known = False
self.odd_columns_slices = []
self.odd_columns_pads = []
self.even_columns_slices = []
self.even_columns_pads = []
self.dimensions = None
self.combine = None
self.process = None
self.kwargs = dict()
def shape_for_odd_columns(self, input_size, kernel_number):
slices = [None, None, None, None]
pads = [0, 0, 0, 0]
# left
pads[0] = kernel_number
# right
pads[1] = max(0, kernel_number - ((input_size[-1] - 1) % (2 * self.hexbase_stride)))
# top
pads[2] = self.hexbase_size - int(kernel_number / 2)
# bottom
constraint = input_size[-2] - 1 - int((input_size[-2] - 1 - int(self.hexbase_stride / 2)) / self.hexbase_stride) * self.hexbase_stride
bottom = (self.hexbase_size - int((kernel_number + 1) / 2)) - constraint
if bottom >= 0:
pads[3] = bottom
else:
slices[1] = bottom
return slices, pads
def shape_for_even_columns(self, input_size, kernel_number):
slices = [None, None, None, None]
pads = [0, 0, 0, 0]
# left
left = kernel_number - self.hexbase_stride
if left >= 0:
pads[0] = left
else:
slices[2] = -left
# right
pads[1] = max(0, kernel_number - ((input_size[-1] - 1 - self.hexbase_stride) % (2 * self.hexbase_stride)))
# top
top_shift = -(kernel_number % 2) if (self.hexbase_stride % 2) == 1 else 0
top = (self.hexbase_size - int(kernel_number / 2)) + top_shift - int(self.hexbase_stride / 2)
if top >= 0:
pads[2] = top
else:
slices[0] = -top
# bottom
bottom_shift = 0 if (self.hexbase_stride % 2) == 1 else -(kernel_number % 2)
pads[3] = max(0, self.hexbase_size - int(kernel_number / 2) + bottom_shift - ((input_size[-2] - int(self.hexbase_stride / 2) - 1) % self.hexbase_stride))
return slices, pads
def get_padded_input(self, input, pads):
if self.dimensions == 2:
return nn.ZeroPad2d(tuple(pads))(input)
elif self.dimensions == 3:
return nn.ConstantPad3d(tuple(pads+[0,0]), 0)(input)
def get_sliced_input(self, input, slices):
if self.dimensions == 2:
return input[:, :, slices[0]:slices[1], slices[2]:slices[3]]
elif self.dimensions == 3:
return input[:, :, :, slices[0]:slices[1], slices[2]:slices[3]]
def get_dilation(self, dilation_2d):
if self.dimensions == 2:
return dilation_2d
elif self.dimensions == 3:
return tuple([1] + list(dilation_2d))
def get_stride(self):
if self.dimensions == 2:
return (self.hexbase_stride, 2 * self.hexbase_stride)
elif self.dimensions == 3:
return (self.depth_stride, self.hexbase_stride, 2 * self.hexbase_stride)
def get_ordered_output(self, input, order):
if self.dimensions == 2:
return input[:, :, :, order]
elif self.dimensions == 3:
return input[:, :, :, :, order]
# general implementation of an operation with a hexagonal kernel
def operation_with_arbitrary_stride(self, input):
assert (input.size(-2) - (self.hexbase_stride // 2) >= 0), 'Too few rows to apply hex conv with the stide that is set'
odd_columns = None
even_columns = None
for i in range(self.hexbase_size + 1):
dilation_base = (1, 1) if i == 0 else (1, 2 * i)
if not self.input_size_is_known:
slices, pads = self.shape_for_odd_columns(input.size(), i)
self.odd_columns_slices.append(slices)
self.odd_columns_pads.append(pads)
slices, pads = self.shape_for_even_columns(input.size(), i)
self.even_columns_slices.append(slices)
self.even_columns_pads.append(pads)
if i == self.hexbase_size:
self.input_size_is_known = True
if odd_columns is None:
odd_columns = self.process(self.get_padded_input(self.get_sliced_input(input,
self.odd_columns_slices[i]),
self.odd_columns_pads[i]),
getattr(self, 'kernel' + str(i)),
dilation=self.get_dilation(dilation_base),
stride=self.get_stride(),
**self.kwargs)
else:
odd_columns = self.combine(odd_columns,
self.process(self.get_padded_input(self.get_sliced_input(input,
self.odd_columns_slices[i]),
self.odd_columns_pads[i]),
getattr(self, 'kernel' + str(i)),
dilation=self.get_dilation(dilation_base),
stride=self.get_stride()))
if even_columns is None:
even_columns = self.process(self.get_padded_input(self.get_sliced_input(input,
self.even_columns_slices[i]),
self.even_columns_pads[i]),
getattr(self, 'kernel' + str(i)),
dilation=self.get_dilation(dilation_base),
stride=self.get_stride(),
**self.kwargs)
else:
even_columns = self.combine(even_columns,
self.process(self.get_padded_input(self.get_sliced_input(input,
self.even_columns_slices[i]),
self.even_columns_pads[i]),
getattr(self, 'kernel' + str(i)),
dilation=self.get_dilation(dilation_base),
stride=self.get_stride()))
concatenated_columns = torch.cat((odd_columns, even_columns), 1+self.dimensions)
n_odd_columns = odd_columns.size(-1)
n_even_columns = even_columns.size(-1)
if n_odd_columns == n_even_columns:
order = [int(i + x * n_even_columns) for i in range(n_even_columns) for x in range(2)]
else:
order = [int(i + x * n_odd_columns) for i in range(n_even_columns) for x in range(2)]
order.append(n_even_columns)
return self.get_ordered_output(concatenated_columns, order)
# a slightly faster, case specific implementation of the hexagonal convolution
def operation_with_single_hexbase_stride(self, input):
columns_mod2 = input.size(-1) % 2
odd_kernels_odd_columns = []
odd_kernels_even_columns = []
even_kernels_all_columns = []
even_kernels_all_columns = self.process(self.get_padded_input(input,
[0, 0, self.hexbase_size, self.hexbase_size]),
self.kernel0,
stride=(1, 1) if self.dimensions == 2 else (self.depth_stride, 1, 1),
**self.kwargs)
if self.hexbase_size >= 1:
odd_kernels_odd_columns = self.process(self.get_padded_input(input,
[1, columns_mod2, self.hexbase_size, self.hexbase_size - 1]),
self.kernel1,
dilation=self.get_dilation((1, 2)),
stride=self.get_stride())
odd_kernels_even_columns = self.process(self.get_padded_input(input,
[0, 1 - columns_mod2, self.hexbase_size - 1, self.hexbase_size]),
self.kernel1,
dilation=self.get_dilation((1, 2)),
stride=self.get_stride())
if self.hexbase_size > 1:
for i in range(2, self.hexbase_size + 1):
if i % 2 == 0:
even_kernels_all_columns = self.combine(even_kernels_all_columns,
self.process(self.get_padded_input(input,
[i, i, self.hexbase_size - int(i / 2), self.hexbase_size - int(i / 2)]),
getattr(self, 'kernel' + str(i)),
dilation=self.get_dilation((1, 2 * i)),
stride=(1, 1) if self.dimensions == 2 else (self.depth_stride, 1, 1)))
else:
x = self.hexbase_size + int((1 - i) / 2)
odd_kernels_odd_columns = self.combine(odd_kernels_odd_columns,
self.process(self.get_padded_input(input,
[i, i - 1 + columns_mod2, x, x - 1]),
getattr(self, 'kernel' + str(i)),
dilation=self.get_dilation((1, 2 * i)),
stride=self.get_stride()))
odd_kernels_even_columns = self.combine(odd_kernels_even_columns,
self.process(self.get_padded_input(input,
[i - 1, i - columns_mod2, x - 1, x]),
getattr(self, 'kernel' + str(i)),
dilation=self.get_dilation((1, 2 * i)),
stride=self.get_stride()))
odd_kernels_concatenated_columns = torch.cat((odd_kernels_odd_columns, odd_kernels_even_columns), 1+self.dimensions)
n_odd_columns = odd_kernels_odd_columns.size(-1)
n_even_columns = odd_kernels_even_columns.size(-1)
if n_odd_columns == n_even_columns:
order = [int(i + x * n_even_columns) for i in range(n_even_columns) for x in range(2)]
else:
order = [int(i + x * n_odd_columns) for i in range(n_even_columns) for x in range(2)]
order.append(n_even_columns)
return self.combine(even_kernels_all_columns , self.get_ordered_output(odd_kernels_concatenated_columns, order))
class Conv2d(HexBase, nn.Module):
r"""Applies a 2D hexagonal convolution`
Args:
in_channels: int: number of input channels
out_channels: int: number of output channels
kernel_size: int: number of layers with neighbouring pixels
covered by the pooling kernel
stride: int: length of strides
bias: bool: add bias if True (default)
debug: bool: switch to debug mode
False: weights are initalised with
kaiming normal, bias with 0.01 (default)
True: weights / bias are set to 1.
Examples::
>>> conv2d = hexagdly.Conv2d(1,3,2,1)
>>> input = torch.randn(1, 1, 4, 2)
>>> output = conv2d(input)
>>> print(output)
"""
def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, bias=True, debug=False):
super(Conv2d, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.hexbase_size = kernel_size
self.hexbase_stride = stride
self.debug = debug
self.bias = bias
self.dimensions = 2
self.process = F.conv2d
self.combine = torch.add
for i in range(self.hexbase_size + 1):
setattr(self, 'kernel' + str(i),
Parameter(torch.Tensor(out_channels, in_channels, 1 + 2 * self.hexbase_size - i, 1 if i==0 else 2)))
if self.bias:
self.bias_tensor = Parameter(torch.Tensor(out_channels))
self.kwargs = {'bias': self.bias_tensor}
else:
self.kwargs = {'bias': None}
self.init_parameters(self.debug)
def init_parameters(self, debug):
if debug:
for i in range(self.hexbase_size + 1):
nn.init.constant_(getattr(self, 'kernel' + str(i)), 1)
if self.bias:
nn.init.constant_(getattr(self, 'kwargs')['bias'], 1.)
else:
for i in range(self.hexbase_size + 1):
nn.init.kaiming_normal_(getattr(self, 'kernel' + str(i)))
if self.bias:
nn.init.constant_(getattr(self, 'kwargs')['bias'], 0.01)
def forward(self, input):
if self.hexbase_stride == 1:
return self.operation_with_single_hexbase_stride(input)
else:
return self.operation_with_arbitrary_stride(input)
def __repr__(self):
s = ('{name}({in_channels}, {out_channels}, kernel_size={hexbase_size}'
', stride={hexbase_stride}')
if self.bias is False:
s += ', bias=False'
if self.debug is True:
s += ', debug=True'
s += ')'
return s.format(name=self.__class__.__name__, **self.__dict__)
class Conv2d_CustomKernel(HexBase, nn.Module):
r"""Applies a 2D hexagonal convolution with custom kernels`
Args:
sub_kernels: list: list containing sub-kernels as numpy arrays
stride: int: length of strides
bias: array: numpy array with biases (default: None)
requires_grad: bool: trainable parameters if True (default: False)
debug: bool: If True a kernel of size one with all values
set to 1 will be applied as well as no bias
(default: False)
Examples::
Given in the online repository https://github.com/ai4iacts/hexagdly
"""
def __init__(self, sub_kernels=[], stride=1, bias=None, requires_grad=False, debug=False):
super(Conv2d_CustomKernel, self).__init__()
self.sub_kernels = sub_kernels
self.bias_array = bias
self.hexbase_stride = stride
self.requires_grad = requires_grad
self.debug = debug
self.dimensions = 2
self.process = F.conv2d
self.combine = torch.add
self.init_parameters(self.debug)
def init_parameters(self, debug):
if debug or len(self.sub_kernels)==0:
print('The debug kernel is used for {name}!'.format(name=self.__class__.__name__))
self.sub_kernels = [np.array([[[[1],[1],[1]]]]),
|
np.array([[[[1,1],[1,1]]]])
|
numpy.array
|
"""Generate halfway phase shifted ring.
TODO[Faruk]: I need to revisit and seriously cleanup this script once revision
rush is over.
"""
import os
import numpy as np
import matplotlib.pyplot as plt
OUTDIR = "/home/faruk/gdrive/paper-350_micron/paper_figures/revision-distortions"
DIMS = 900, 900
RADIUS_OUTER = 450
RADIUS_INNER = 150
SEGMENTS_INNER = 25
NR_LAYERS = 11
KAYCUBE_FACTOR = 32
DPI = 192
plt.style.use('dark_background')
# =============================================================================
# Generate coordinates
coords = np.zeros((DIMS[0], DIMS[1], 2))
center = DIMS[0]/2, DIMS[1]/2
for i in range(DIMS[0]):
for j in range(DIMS[1]):
coords[i, j, 0] = i
coords[i, j, 1] = j
coords[:, :, 0] -= center[0]
coords[:, :, 1] -= center[1]
# -----------------------------------------------------------------------------
# Generate ring
mag = np.linalg.norm(coords, axis=-1)
data = np.zeros(DIMS)
data[mag < RADIUS_OUTER] = 200
data[mag < RADIUS_INNER] = 0
# Extend horizontally
DIMS2 = DIMS[0], DIMS[1]+DIMS[1]*2//3
data2 = np.zeros((DIMS2[0], DIMS2[1]))
data2[0:DIMS[0]//2, 0:DIMS[1]] = data[0:DIMS[0]//2, :]
data2[DIMS[0]//2:, DIMS[1]*2//3:] = data[DIMS[0]//2:, :]
# Add notebook texture
lines = np.zeros(data2.shape)
lines[::KAYCUBE_FACTOR, :] = 100
lines[:, ::KAYCUBE_FACTOR] = 100
lines[data2 == 0] = 0
data3 = np.copy(data2)
data3[lines != 0] = 100
# -----------------------------------------------------------------------------
# Compute circumference ratio of equal line segments
circum_ratio = (2 * np.pi * RADIUS_OUTER) / (2 * np.pi * RADIUS_INNER)
SEGMENTS_OUTER = int(SEGMENTS_INNER / circum_ratio)
circum_ratio2 = (2 * np.pi * ((RADIUS_OUTER+RADIUS_INNER)/2)) / (2 * np.pi * RADIUS_INNER)
SEGMENTS_MIDDLE = int((SEGMENTS_INNER + circum_ratio) // 2)
nr_segments_outer = 360 // SEGMENTS_OUTER
nr_segments_inner = 360 // SEGMENTS_INNER
nr_segments_middle = 360 // SEGMENTS_MIDDLE
rhos = np.linspace(RADIUS_INNER, RADIUS_OUTER, NR_LAYERS)
# =============================================================================
# Generate points
def pol2cart(rho, phi):
x = rho * np.cos(phi)
y = rho * np.sin(phi)
return(x, y)
def cart2pol(x, y):
rho = np.sqrt(x**2 + y**2)
phi = np.arctan2(y, x)
return(rho, phi)
# =============================================================================
# Deep surface mesh
# =============================================================================
# Part 1
points1 = np.zeros((NR_LAYERS, nr_segments_outer, 2))
phis = np.linspace(np.pi, 2*np.pi, nr_segments_outer)
for k, r in enumerate(rhos):
for i, j in enumerate(phis):
points1[k, i, :] = pol2cart(r, j)
# Adjust point coordinates to array grid coordinates
points1[k, :, :] += center
# Part 2
points2 = np.zeros((NR_LAYERS, nr_segments_inner, 2))
phis = np.linspace(0, np.pi, nr_segments_inner)
for k, r in enumerate(rhos):
for i, j in enumerate(phis):
points2[k, i, :] = pol2cart(r, j)
# Adjust point coordinates to array grid coordinates
points2[k, :, :] += center
points2[k, :, 0] += RADIUS_OUTER + RADIUS_INNER
points_d = np.zeros((NR_LAYERS, nr_segments_outer + nr_segments_inner, 2))
points_d[:, :nr_segments_outer, :] = points1
points_d[:, nr_segments_outer:, :] = points2[::-1, ::-1, :]
# =============================================================================
fig = plt.figure(figsize=(1920/DPI, 1080/DPI), dpi=DPI)
plt.imshow(data2, cmap="gray", origin="lower")
for i in range(NR_LAYERS):
if i == NR_LAYERS-1:
plt.plot(points_d[i, :, 0], points_d[i, :, 1], marker="o",
markersize=6,
linewidth=2,
color=[1, 0, 0])
else:
plt.plot(points_d[i, :, 0], points_d[i, :, 1], marker="o",
markersize=3, linewidth=1,
color=[0.5, 0.5, 0.5])
plt.xlim([0, DIMS2[1]])
plt.ylim([0, DIMS2[0]])
plt.axis('off')
plt.ioff()
plt.savefig(os.path.join(OUTDIR, "1_deep_mesh.png"), bbox_inches='tight')
plt.clf()
# -----------------------------------------------------------------------------
# Notebook texture plot
plt.imshow(data3, cmap="gray", origin="lower")
for i in range(NR_LAYERS):
if i == NR_LAYERS-1:
plt.plot(points_d[i, :, 0], points_d[i, :, 1], marker="o",
markersize=2, linestyle='None',
color=[1, 0, 0])
else:
plt.plot(points_d[i, :, 0], points_d[i, :, 1], marker="o",
markersize=2, linestyle='None',
color=[0.5, 0.5, 0.5])
plt.xlim([0, DIMS2[1]])
plt.ylim([0, DIMS2[0]])
plt.axis('off')
plt.ioff()
plt.savefig(os.path.join(OUTDIR, "1_deep_mesh_alt.png"), bbox_inches='tight')
plt.clf()
# =============================================================================
# Superficial surface mesh
# =============================================================================
points1 = np.zeros((NR_LAYERS, nr_segments_inner, 2))
phis = np.linspace(np.pi, 2*np.pi, nr_segments_inner)
for k, r in enumerate(rhos):
for i, j in enumerate(phis):
points1[k, i, :] = pol2cart(r, j)
# Adjust point coordinates to array grid coordinates
points1[k, :, :] += center
# -----------------------------------------------------------------------------
points2 = np.zeros((NR_LAYERS, nr_segments_outer, 2))
phis = np.linspace(0, np.pi, nr_segments_outer)
for k, r in enumerate(rhos):
for i, j in enumerate(phis):
points2[k, i, :] = pol2cart(r, j)
# Adjust point coordinates to array grid coordinates
points2[k, :, :] += center
points2[k, :, 0] += RADIUS_OUTER + RADIUS_INNER
points_s = np.zeros((NR_LAYERS, nr_segments_outer + nr_segments_inner, 2))
points_s[:, :nr_segments_inner, :] = points1
points_s[:, nr_segments_inner:, :] = points2[::-1, ::-1, :]
# =============================================================================
fig = plt.figure(figsize=(1920/DPI, 1080/DPI), dpi=DPI)
plt.imshow(data2, cmap="gray", origin="lower")
for i in range(NR_LAYERS):
if i == 0:
plt.plot(points_s[i, :, 0], points_s[i, :, 1], marker="o",
markersize=6,
linewidth=2, color=[0, 0.5, 1])
else:
plt.plot(points_s[i, :, 0], points_s[i, :, 1], marker="o",
markersize=3, color=[0.5, 0.5, 0.5])
plt.xlim([0, DIMS2[1]])
plt.ylim([0, DIMS2[0]])
plt.axis('off')
plt.ioff()
plt.savefig(os.path.join(OUTDIR, "2_sup_mesh.png"), bbox_inches='tight')
plt.clf()
# -----------------------------------------------------------------------------
# Notebook texture plot
plt.imshow(data3, cmap="gray", origin="lower")
for i in range(NR_LAYERS):
if i == 0:
plt.plot(points_s[i, :, 0], points_s[i, :, 1], marker="o",
markersize=2, linestyle='None',
color=[0, 0.5, 1])
else:
plt.plot(points_s[i, :, 0], points_s[i, :, 1], marker="o",
markersize=2, linestyle='None',
color=[0.5, 0.5, 0.5])
plt.xlim([0, DIMS2[1]])
plt.ylim([0, DIMS2[0]])
plt.axis('off')
plt.ioff()
plt.savefig(os.path.join(OUTDIR, "2_sup_mesh_alt.png"), bbox_inches='tight')
plt.clf()
# =============================================================================
# Middle surface mesh
# =============================================================================
points_m = np.zeros((NR_LAYERS, nr_segments_middle*2, 2))
phis = np.linspace(-np.pi, np.pi, nr_segments_middle*2)
for k, r in enumerate(rhos):
for i, j in enumerate(phis):
points_m[k, i, :] = pol2cart(r, j)
# Adjust point coordinates to array grid coordinates
points_m[k, :, :] += center
points_m[:, nr_segments_middle:, 0] *= -1
points_m[:, nr_segments_middle:, 0] += RADIUS_OUTER*3 + RADIUS_INNER
points_m[:, nr_segments_middle:, :] = points_m[::-1, nr_segments_middle:, :]
# -----------------------------------------------------------------------------
fig = plt.figure(figsize=(1920/DPI, 1080/DPI), dpi=DPI)
plt.imshow(data2, cmap="gray", origin="lower")
for i in range(NR_LAYERS):
if i == NR_LAYERS//2:
plt.plot(points_m[i, :, 0], points_m[i, :, 1], marker="o",
markersize=6,
linewidth=2, color=[0, 220/255, 0])
else:
plt.plot(points_m[i, :, 0], points_m[i, :, 1], marker="o",
markersize=3, color=[0.5, 0.5, 0.5])
plt.xlim([0, DIMS2[1]])
plt.ylim([0, DIMS2[0]])
plt.axis('off')
plt.ioff()
plt.savefig(os.path.join(OUTDIR, "3_middle_mesh.png"), bbox_inches='tight')
plt.clf()
# -----------------------------------------------------------------------------
# Notebook texture plot
plt.imshow(data3, cmap="gray", origin="lower")
for i in range(NR_LAYERS):
if i == NR_LAYERS//2:
plt.plot(points_m[i, :, 0], points_m[i, :, 1], marker="o",
markersize=2, linestyle='None',
color=[1, 0, 0])
else:
plt.plot(points_m[i, :, 0], points_m[i, :, 1], marker="o",
markersize=2, linestyle='None',
color=[1, 0, 0])
plt.xlim([0, DIMS2[1]])
plt.ylim([0, DIMS2[0]])
plt.axis('off')
plt.ioff()
plt.savefig(os.path.join(OUTDIR, "3_middle_mesh_alt.png"), bbox_inches='tight')
plt.clf()
# =============================================================================
# Point cloud
# =============================================================================
x = np.arange(KAYCUBE_FACTOR//2, DIMS2[1]-1, KAYCUBE_FACTOR, dtype="int")
y =
|
np.arange(KAYCUBE_FACTOR//2, DIMS2[0]-1, KAYCUBE_FACTOR, dtype="int")
|
numpy.arange
|
import numpy as np
import random
import copy
import time
t = time.time() # Stopwatch started
puzzle = [] # Created an empty list
# puzzle = np.array([[1, 0, 3], [4, 2, 5], [7, 8, 6]])
# puzzle = np.arange(9)
# np.random.shuffle(puzzle)
# puzzle.shape = (3, 3)
# Created class for back tracing the path
class Tree:
def __init__(self, child, parent=None, index=0):
self.child = child
self.parent = parent
self.index = index
# function to find blank tile's location
def BlankTileLocation(p):
for m in range(3):
for n in range(3):
if p[m, n] == 0:
pos = m+1, n+1
return pos
# function to backtrace the path
def backtrace(strate):
street = []
current_state = strate
while current_state is not None:
street.append(current_state)
current_state = current_state.parent
street.reverse()
# Create a empty file
with open('nodePath.txt', 'w') as nPath:
for current_state in street:
# Writing path in the text file
nPath.writelines(str(current_state.child.flatten('F')).strip('[]')+'\n')
# function to move the blank tile left
def ActionMoveLeft(puzL):
#m, n = BlankTileLocation(puzL)
m, n = BlankTileLocation(puzL.child)
if n > 1:
puzL.child[m-1, n-1] = puzL.child[m-1, n-1-1]
puzL.child[m-1, n-1-1] = 0
stat = 1
# print(puzL, 'Inside function')
# print('Moving left.')
else:
# print('Cannot move left.')
stat = 0
return stat, puzL
# function to move the blank tile right
def ActionMoveRight(puzR):
m, n = BlankTileLocation(puzR.child)
if n < 3:
puzR.child[m-1, n-1] = puzR.child[m-1, n-1+1]
puzR.child[m-1, n-1+1] = 0
stat = 1
# print(puzR, 'Inside Function')
# print('Moving right.')
else:
# print('Cannot move right!!')
stat = 0
return stat, puzR
# function to move the blank tile up
def ActionMoveUp(puzU):
m, n = BlankTileLocation(puzU.child)
if m > 1:
puzU.child[m-1, n-1] = puzU.child[m-1-1, n-1]
puzU.child[m-1-1, n-1] = 0
stat = 1
# print(puzU, 'Inside Function')
# print('Moving up.')
else:
# print('Cannot move up!!')
stat = 0
return stat, puzU
# function to move the blank tile down
def ActionMoveDown(puzD):
m, n = BlankTileLocation(puzD.child)
if m < 3:
puzD.child[m-1, n-1] = puzD.child[m-1+1, n-1]
puzD.child[m-1+1, n-1] = 0
stat = 1
# print(puzD, 'Inside Function')
# print('Moving down.')
else:
# print('Cannot move down!!')
stat = 0
return stat, puzD
# function to check the solvability of the puzzle
def solvable(puzS):
ctr = 0
puzS = puzS.flatten()
for m in range(9):
for n in range(m+1, 9):
if puzS[n] and puzS[m] and puzS[m] > puzS[n]:
ctr += 1
return ctr
# function to check goal achieved or not
def goalTest(puzG):
goal =
|
np.array([[1, 2, 3], [4, 5, 6], [7, 8, 0]])
|
numpy.array
|
#!/usr/bin/env python3
# coding: utf-8
__author__ = '<NAME>'
__version__ = '0.1'
__email__ = '<EMAIL>'
__status__ = 'Development'
import os
import csv
import logging
import argparse
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backend_bases import MouseButton
logging.basicConfig(level=logging.INFO, format='%(message)s')
logger = logging.getLogger(__name__)
# Global variables
fig, ax = plt.subplots()
points = None
dataset = None
output = None
def onclick(event):
global dataset
global points
# clear the plot
ax.cla()
# redraw the points
x = points[:,0]
y = points[:,1]
ax.plot(x, y)
# get the x coordinate from the clicked point
ex = event.xdata
# add or remove the point from the dataset
if event.button is MouseButton.LEFT:
# find the closest point to the original points, using the X axis
x_distances = np.abs(x - ex)
closest_idx = np.argmin(x_distances)
cx = x[closest_idx]
cy = y[closest_idx]
dataset.append([cx, cy])
logger.info('Add a Point %s', [cx, cy])
elif event.button is MouseButton.RIGHT:
# find the closest point to the selected points, using the X axis
if len(dataset) > 0:
d =
|
np.array(dataset)
|
numpy.array
|
#!/usr/bin/env python
import argparse
import os
import sys
import logging
import numpy as np
import re
import time
import scipy.io
import glob
import unet
import tensorflow as tf
import keras
from keras import backend as K
import scipy.stats
import pyBigWig
print('tf-' + tf.__version__, 'keras-' + keras.__version__)
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.07
set_session(tf.Session(config=config))
K.set_image_data_format('channels_last') # TF dimension ordering in this code
def score(x1,x2):
mse=((x1-x2) ** 2.).mean()
pearson=np.corrcoef((x1,x2))[0,1]
y1=scipy.stats.rankdata(x1)
y2=scipy.stats.rankdata(x2)
spearman=np.corrcoef((y1,y2))[0,1]
return mse,pearson,spearman
###### PARAMETER ###############
size25=128
size=size25*25
write_pred=True # whether generate .vec prediction file
size_edge=int(10) # chunk edges to be excluded
batch=200
path0='../../data/bigwig_all/'
#path1='../../data/bigwig_cv2/'
chr_all=['chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrX']
#num_bp=[248956422,242193529,198295559,190214555,181538259,170805979,159345973,145138636,138394717,133797422,135086622,133275309,114364328,107043718,101991189,90338345,83257441,80373285,58617616,64444167,46709983,50818468,156040895]
num_bp=[249250621,243199373,198022430,191154276,180915260,171115067,159138663,146364022,141213431,135534747,135006516,133851895,115169878,107349540,102531392,90354753,81195210,78077248,59128983,63025520,48129895,51304566,155270560]
chr_len_cut={}
for i in np.arange(len(chr_all)):
chr_len_cut[chr_all[i]]=int(np.floor(num_bp[i]/25.0)*25) # HERE I cut tails
chr_len={}
for i in np.arange(len(chr_all)):
chr_len[chr_all[i]]=num_bp[i]
chr_len_bin={}
for i in np.arange(len(chr_all)):
chr_len_bin[chr_all[i]]=int(np.ceil(num_bp[i]/25.0))
## test cell
exclude_all=[]
list_dna=['A','C','G','T']
# argv
def get_args():
parser = argparse.ArgumentParser(description="globe prediction")
parser.add_argument('-f', '--feature', default='H3K4me1', nargs='+', type=str,
help='feature assay')
parser.add_argument('-t', '--target', default='H3K9ac',type=str,
help='target assay')
parser.add_argument('-c', '--cell', default='E002', nargs='+',type=str,
help='cell lines as common and specific features')
parser.add_argument('-s', '--seed', default='0', type=int,
help='seed for common - specific partition')
parser.add_argument('-ct', '--cell_test', default='E002', type=str,
help='the testing cell line')
parser.add_argument('-m', '--model', default='epoch01/weights_1.h5', type=str,
help='model')
args = parser.parse_args()
return args
args=get_args()
print(args)
assay_target = args.target
assay_feature = args.feature
cell_all = args.cell
seed_partition = args.seed
cell_test = args.cell_test
list_label_test=[cell_test + '_' + assay_target]
## parition common & specific cell types
np.random.seed(seed_partition)
np.random.shuffle(cell_all)
ratio=[0.5,0.5]
num = int(len(cell_all)*ratio[0])
cell_common = cell_all[:num]
cell_tv = cell_all[num:]
cell_all.sort()
cell_common.sort()
cell_tv.sort()
## partition train-vali cell types
np.random.seed(0) #TODO
np.random.shuffle(cell_tv)
ratio=[0.75,0.25]
num = int(len(cell_tv)*ratio[0])
cell_train = cell_tv[:num]
cell_vali = cell_tv[num:]
cell_tv.sort()
cell_train.sort()
cell_vali.sort()
# model
num_class = 1
num_channel = 4 + len(assay_feature)*2 + len(cell_common)*2
model1 = unet.get_unet(num_class=num_class,num_channel=num_channel,size=size)
model1.load_weights(args.model)
#model1.summary()
# load pyBigWig
#dict_label={}
#for the_cell in cell_tv:
# the_id = the_cell + '_' + assay_target
# dict_label[the_id]=pyBigWig.open(path0 + 'gt_' + the_id + '.bigwig')
dict_dna={}
for the_id in list_dna:
dict_dna[the_id]=pyBigWig.open(path0 + the_id + '.bigwig')
dict_feature_common={}
for the_cell in cell_common:
the_id = the_cell + '_' + assay_target
dict_feature_common[the_id]=pyBigWig.open(path0 + the_id + '.bigwig')
dict_feature_specific={}
for the_cell in [cell_test]:
dict_feature_specific[the_cell]={}
for the_assay in assay_feature:
the_id = the_cell + '_' + the_assay
dict_feature_specific[the_cell][the_id]=pyBigWig.open(path0 + the_id + '.bigwig')
dict_avg={}
dict_avg[assay_target]=pyBigWig.open(path0 + 'avg_' + assay_target + '.bigwig')
for the_assay in assay_feature:
dict_avg[the_assay]=pyBigWig.open(path0 + 'avg_' + the_assay + '.bigwig')
print('assay_target', assay_target)
print('assay_feature', len(assay_feature), assay_feature)
print('cell_common', len(cell_common), cell_common)
print('cell_tv', len(cell_tv), cell_tv)
print('cell_train', len(cell_train), cell_train)
print('cell_vali', len(cell_vali), cell_vali)
print('cell_test', len(cell_test), cell_test)
list_chr=chr_all
#list_chr=['chr21'] # TODO
path_pred='/'.join(args.model.split('/')[:-1]) + '/'
id_label_test = cell_test + '_' + assay_target
bw_output = pyBigWig.open(path_pred + 'pred_' + id_label_test + '_seed' + str(seed_partition) + '.bigwig','w')
bw_output.addHeader(list(zip(chr_all , np.ceil(np.array(num_bp)/25).astype('int').tolist())), maxZooms=0)
#file_score=open(path_pred + 'score_' + id_label_test + '_' + cell_train + '_' + cell_vali + '.txt','w')
#mse_all=[]
#pearson_all=[]
#spearman_all=[]
for the_chr in list_chr:
print(the_chr)
output_all=np.zeros((len(list_label_test), int(chr_len_cut[the_chr]/25.0)))
count_all=np.zeros((len(list_label_test), int(chr_len_cut[the_chr]/25.0)))
## 2. batch prediction ##########################
phase=0.5
tmp=int(size*batch)
index=np.arange(0,int(np.floor(chr_len_cut[the_chr]/tmp))*tmp, tmp)
index=np.concatenate((index,np.arange(int(size*phase),int(np.floor(chr_len_cut[the_chr]/tmp))*tmp, tmp)))
index=np.concatenate((index,np.array([chr_len_cut[the_chr]-tmp])))
index=np.concatenate((index,np.array([chr_len_cut[the_chr]-tmp-int(size*phase)])))
index.sort()
print(index)
for i in index: # all start positions
start = i
end = i + size*batch
## 2. image
image=np.zeros((num_channel, size*batch), dtype='float32')
# 2.1 dna
num=0
for j in np.arange(len(list_dna)):
the_id=list_dna[j]
image[num,:] = dict_dna[the_id].values(the_chr,start,end)
num+=1
# 2.2 feature & diff
the_avg=dict_avg[assay_target].values(the_chr,start,end)
for j in np.arange(len(cell_common)):
the_id=cell_common[j] + '_' + assay_target
# feature
image[num,:] = dict_feature_common[the_id].values(the_chr,start,end)
# diff
image[num+1,:]=image[num,:] - the_avg
num+=2
for j in np.arange(len(assay_feature)):
the_assay = assay_feature[j]
the_id=cell_test + '_' + the_assay
# feature
image[num,:] = dict_feature_specific[cell_test][the_id].values(the_chr,start,end)
# diff
the_assay=the_id.split('_')[1]
image[num+1,:]=image[num,:] - dict_avg[the_assay].values(the_chr,start,end)
num+=2
## make predictions ################
input_pred=
|
np.reshape(image.T,(batch,size,num_channel))
|
numpy.reshape
|
#!/usr/bin/python
# coding=utf-8
import numpy as np
from scipy.interpolate import Rbf
import matplotlib.pyplot as plt
import sys
from math import pi, sqrt, degrees, acos
import os
import pandas as pd
import warnings
from scipy.constants import physical_constants
from shapely.geometry import LineString, Point
m_p = physical_constants['proton mass'][0]
def isnamedtupleinstance(x):
"""
:param x:
:return:
"""
t = type(x)
b = t.__bases__
if len(b) != 1 or b[0] != tuple:
return False
f = getattr(t, '_fields', None)
if not isinstance(f, tuple):
return False
return all(type(n) == str for n in f)
def iterate_namedtuple(object, df):
if isnamedtupleinstance(object):
for key, item in object._asdict().items():
if isnamedtupleinstance(item):
iterate_namedtuple(item, df)
else:
df[key] = pd.Series(item.flatten(), name=key)
else:
pass
return df
# isclose is included in python3.5+, so you can delete this if the code ever gets ported into python3.5+
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
def print_progress(iteration, total, prefix='', suffix='', decimals=0, bar_length=50):
"""creates a progress bar
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
bar_length - Optional : character length of bar (Int)
"""
str_format = "{0:." + str(decimals) + "f}"
percents = str_format.format(100 * ((iteration + 1) / float(total)))
filled_length = int(round(bar_length * (iteration + 1) / float(total)))
bar = '█' * filled_length + '-' * (bar_length - filled_length)
sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix))
def calc_cell_pts(neut):
sys.setrecursionlimit(100000)
def loop(neut, oldcell, curcell, cellscomplete, xcoords, ycoords):
beta[curcell, :neut.nSides[curcell]] = np.cumsum(
np.roll(neut.angles[curcell, :neut.nSides[curcell]], 1) - 180) + 180
# if first cell:
if oldcell == 0 and curcell == 0:
# rotate cell by theta0 value (specified)
beta[curcell, :neut.nSides[curcell]] = beta[curcell, :neut.nSides[curcell]] + neut.cell1_theta0
x_comp = np.cos(np.radians(beta[curcell, :neut.nSides[curcell]])) * neut.lsides[curcell,
:neut.nSides[curcell]]
y_comp = np.sin(np.radians(beta[curcell, :neut.nSides[curcell]])) * neut.lsides[curcell,
:neut.nSides[curcell]]
xcoords[curcell, :neut.nSides[curcell]] = np.roll(np.cumsum(x_comp), 1) + neut.cell1_ctr_x
ycoords[curcell, :neut.nSides[curcell]] = np.roll(np.cumsum(y_comp), 1) + neut.cell1_ctr_y
# for all other cells:
else:
# adjust all values in beta for current cell such that the side shared
# with oldcell has the same beta as the oldcell side
oldcell_beta = beta[oldcell, :][np.where(neut.adjCell[oldcell, :] == curcell)][0]
delta_beta = beta[curcell, np.where(neut.adjCell[curcell, :] == oldcell)] + 180 - oldcell_beta
beta[curcell, :neut.nSides[curcell]] = beta[curcell, :neut.nSides[curcell]] - delta_beta
# calculate non-shifted x- and y- coordinates
x_comp = np.cos(np.radians(beta[curcell, :neut.nSides[curcell]])) * neut.lsides[curcell,
:neut.nSides[curcell]]
y_comp = np.sin(np.radians(beta[curcell, :neut.nSides[curcell]])) * neut.lsides[curcell,
:neut.nSides[curcell]]
xcoords[curcell, :neut.nSides[curcell]] = np.roll(np.cumsum(x_comp),
1) # xcoords[oldcell,np.where(neut.adjCell[oldcell,:]==curcell)[0][0]]
ycoords[curcell, :neut.nSides[curcell]] = np.roll(np.cumsum(y_comp),
1) # ycoords[oldcell,np.where(neut.adjCell[oldcell,:]==curcell)[0][0]]
cur_in_old = np.where(neut.adjCell[oldcell, :] == curcell)[0][0]
old_in_cur = np.where(neut.adjCell[curcell, :] == oldcell)[0][0]
mdpt_old_x = (xcoords[oldcell, cur_in_old] + np.roll(xcoords[oldcell, :], -1)[cur_in_old]) / 2
mdpt_old_y = (ycoords[oldcell, cur_in_old] + np.roll(ycoords[oldcell, :], -1)[cur_in_old]) / 2
mdpt_cur_x = (xcoords[curcell, old_in_cur] + np.roll(xcoords[curcell, :], -1)[old_in_cur]) / 2
mdpt_cur_y = (ycoords[curcell, old_in_cur] + np.roll(ycoords[curcell, :], -1)[old_in_cur]) / 2
xshift = mdpt_old_x - mdpt_cur_x
yshift = mdpt_old_y - mdpt_cur_y
xcoords[curcell, :] = xcoords[curcell,
:] + xshift # xcoords[oldcell,np.where(neut.adjCell[oldcell,:]==curcell)[0][0]]
ycoords[curcell, :] = ycoords[curcell,
:] + yshift # ycoords[oldcell,np.where(neut.adjCell[oldcell,:]==curcell)[0][0]]
# continue looping through adjacent cells
for j, newcell in enumerate(neut.adjCell[curcell, :neut.nSides[curcell]]):
# if the cell under consideration is a normal cell (>3 sides) and not complete, then move into that cell and continue
if neut.nSides[newcell] >= 3 and cellscomplete[newcell] == 0:
cellscomplete[newcell] = 1
loop(neut, curcell, newcell, cellscomplete, xcoords, ycoords)
return xcoords, ycoords
xcoords = np.zeros(neut.adjCell.shape)
ycoords = np.zeros(neut.adjCell.shape)
beta = np.zeros(neut.adjCell.shape) # beta is the angle of each side with respect to the +x axis.
## Add initial cell to the list of cells that are complete
cellscomplete = np.zeros(neut.nCells)
cellscomplete[0] = 1
xs, ys = loop(neut, 0, 0, cellscomplete, xcoords, ycoords)
return xs, ys
class NeutpyTools:
def __init__(self, neut=None):
# get vertices in R, Z geometry
self.xs, self.ys = self.calc_cell_pts(neut)
# localize densities, ionization rates, and a few other parameters that might be needed.
self.n_n_slow = neut.nn.s
self.n_n_thermal = neut.nn.t
self.n_n_total = neut.nn.tot
self.izn_rate_slow = neut.izn_rate.s
self.izn_rate_thermal = neut.izn_rate.t
self.izn_rate_total = neut.izn_rate.tot
self.flux_in_s = neut.flux.inc.s
self.flux_in_t = neut.flux.inc.t
self.flux_in_tot = self.flux_in_s + self.flux_in_t
self.flux_out_s = neut.flux.out.s
self.flux_out_t = neut.flux.out.t
self.flux_out_tot = self.flux_out_s + self.flux_out_t
self.create_flux_outfile()
self.create_cell_outfile()
flux_s_xcomp, flux_s_ycomp, flux_s_mag = self.calc_flow('slow', norm=True)
flux_t_xcomp, flux_t_ycomp, flux_t_mag = self.calc_flow('thermal', norm=True)
flux_tot_xcomp, flux_tot_ycomp, flux_tot_mag = self.calc_flow('total', norm=True)
self.vars = {}
self.vars['n_n_slow'] = neut.nn.s
self.vars['n_n_thermal'] = neut.nn.t
self.vars['n_n_total'] = neut.nn.tot
self.vars['flux_s_xcomp'] = flux_s_xcomp
self.vars['flux_s_ycomp'] = flux_s_ycomp
self.vars['flux_s_mag'] = flux_s_mag
self.vars['flux_t_xcomp'] = flux_t_xcomp
self.vars['flux_t_ycomp'] = flux_t_ycomp
self.vars['flux_t_mag'] = flux_t_mag
self.vars['flux_tot_xcomp'] = flux_tot_xcomp
self.vars['flux_tot_ycomp'] = flux_tot_ycomp
self.vars['flux_tot_mag'] = flux_tot_mag
print('attempting to start plot_cell_vals')
self.plot_cell_vals()
def create_cell_outfile(self):
df = pd.DataFrame()
df['R'] = pd.Series(np.mean(self.xs, axis=1), name='R')
df['Z'] = pd.Series(np.mean(self.ys, axis=1), name='Z')
df['n_n_slow'] = pd.Series(self.n_n_slow, name='n_n_slow')
df['n_n_thermal'] = pd.Series(self.n_n_thermal, name='n_n_thermal')
df['n_n_total'] = pd.Series(self.n_n_total, name='n_n_total')
df['izn_rate_slow'] = pd.Series(self.izn_rate_slow, name='izn_rate_slow')
df['izn_rate_thermal'] = pd.Series(self.izn_rate_thermal, name='izn_rate_thermal')
df['izn_rate_total'] = pd.Series(self.izn_rate_thermal, name='izn_rate_total')
#cell_df = iterate_namedtuple(neut.cell, df)
df.to_csv(os.getcwd() + '/outputs/neutpy_cell_values.txt')
def interp_RZ(self, var):
x = np.average(self.xs, axis=1)
y = np.average(self.ys, axis=1)
d = self.vars[var]
return Rbf(x, y, d)
def calc_flow(self, ntrl_pop='tot', norm=True):
"""Creates interpolation functions for net flux directions and magnitudes
flux_in: fluxes coming into cells. Can be slow, thermal, total or any other fluxes. Array of size (nCells, 3)
flux_in: fluxes leaving cells. Can be slow, thermal, total or any other fluxes. Array of size (nCells, 3)
norm: returns normalized x- and y-component interpolation functions. Useful for plotting quiver plots
with equally sized arrows or if you only care about the direction of the flux (You can still get
the magnitude from "flux_net_av_mag" interpolation object.)
"""
if ntrl_pop == 'slow':
flux_in = self.flux_in_s[:, :-1]
flux_out = self.flux_out_s[:, :-1]
elif ntrl_pop == 'thermal':
flux_in = self.flux_in_t[:, :-1]
flux_out = self.flux_out_t[:, :-1]
elif ntrl_pop == 'total':
flux_in = self.flux_in_tot[:, :-1]
flux_out = self.flux_out_tot[:, :-1]
flux_net = flux_out - flux_in
cent_pts_x = np.average(self.xs, axis=1)
cent_pts_y = np.average(self.ys, axis=1)
x_comp = np.roll(self.xs, -1, axis=1) - self.xs
y_comp = np.roll(self.ys, -1, axis=1) - self.ys
lside = np.sqrt(x_comp**2 + y_comp**2)
perim = np.sum(lside, axis=1).reshape((-1, 1))
l_frac = lside / perim
side_angles = np.arctan2(y_comp, x_comp)
side_angles = np.where(side_angles < 0, side_angles+2*pi, side_angles)
outwd_nrmls = side_angles + pi/2
outwd_nrmls = np.where(outwd_nrmls < 0, outwd_nrmls+2*pi, outwd_nrmls)
outwd_nrmls = np.where(outwd_nrmls >= 2*pi, outwd_nrmls-2*pi, outwd_nrmls)
flux_net_dir = np.where(flux_net < 0, outwd_nrmls+pi, outwd_nrmls)
flux_net_dir = np.where(flux_net_dir < 0, flux_net_dir+2*pi, flux_net_dir)
flux_net_dir = np.where(flux_net_dir >= 2*pi, flux_net_dir-2*pi, flux_net_dir)
# x- and y-component of fluxes
flux_net_xcomp =
|
np.abs(flux_net)
|
numpy.abs
|
import jax.numpy as np
import numpy as onp
import tensorflow_datasets as tfds
import tensorflow as tf
from enum import Enum
def _one_hot(x, k, dtype=np.float32):
"""Create a one-hot encoding of x of size k."""
return onp.array(x[:, None] == onp.arange(k), dtype)
CIFAR_ANIMAL_IDS = [2,3,4,5,6,7]
CIFAR_VEHICLE_IDS = [0,1,8,9]
Dataset = Enum('Dataset', ['cifar10','cifar6','cifar4','cifar2', 'mnist'])
ImageNoise = Enum('ImageNoise',['none','gaussian'])
BackgroundNoise = Enum('BackgroundNoise',['none','gaussian','blocks','imagenet'])
BlockNoiseDataset = Enum('BlockNoiseDataset',['cifar10','cifar6','cifar4'])
Placement = Enum('Placement', ['fixed_corner','random_corner','random_loc'])
for e in [Dataset,ImageNoise,BackgroundNoise,BlockNoiseDataset,Placement]:
e.__str__ = lambda self: self.name
def load_data(dataset=Dataset.cifar10,
image_size=32, background_size=32,
image_noise=ImageNoise.none, background_noise=BackgroundNoise.none,
block_noise_data = BlockNoiseDataset.cifar6,
image_noise_scalar=1.0, background_noise_scalar=1.0,
placement=Placement.fixed_corner, num_train=-1, num_test=-1):
if dataset == Dataset.mnist:
train_images, train_ys, test_images, test_ys =mnist(num_train, num_test) # TODO: not passing image size for mnist
else:
c10_train_xs, c10_train_ys, c10_test_xs, c10_test_ys = cifar_with_size(image_size) # TODO: not passing num examples for cifar
if dataset == Dataset.cifar10:
train_images, train_ys, test_images, test_ys = c10_train_xs, c10_train_ys, c10_test_xs, c10_test_ys
elif dataset == Dataset.cifar2:
train_ys = onp.vectorize(lambda label: 1 if label in CIFAR_ANIMAL_IDS else 0)(c10_train_ys)
test_ys = onp.vectorize(lambda label: 1 if label in CIFAR_ANIMAL_IDS else 0)(c10_test_ys)
train_images, test_images = c10_train_xs, c10_test_xs
elif dataset == Dataset.cifar4:
train_images, train_ys, test_images, test_ys = cifar_with_only(CIFAR_VEHICLE_IDS, c10_train_xs, c10_train_ys, c10_test_xs, c10_test_ys)
elif dataset == Dataset.cifar6:
train_images, train_ys, test_images, test_ys = cifar_with_only(CIFAR_ANIMAL_IDS, c10_train_xs, c10_train_ys, c10_test_xs, c10_test_ys)
if image_noise==ImageNoise.gaussian:
train_images += onp.random.normal(scale=image_noise_scalar,size=train_images.shape)
test_images += onp.random.normal(scale=image_noise_scalar,size=test_images.shape)
if image_size == background_size:
train_xs, test_xs = train_images, test_images
else:
if background_noise == BackgroundNoise.none:
background_train = onp.zeros((train_images.shape[0], background_size, background_size, train_images.shape[-1]))
background_test = onp.zeros((test_images.shape[0], background_size, background_size, train_images.shape[-1]))
elif background_noise == BackgroundNoise.gaussian:
background_train = onp.random.normal(scale=background_noise_scalar,size=(train_images.shape[0], background_size, background_size, train_images.shape[-1]))
background_test = onp.random.normal(scale=background_noise_scalar,size=(test_images.shape[0], background_size, background_size, train_images.shape[-1]))
elif background_noise == BackgroundNoise.blocks:
c10_train_xs, _, c10_test_xs, _ = cifar_with_size(background_size//2)
if block_noise_data == BlockNoiseDataset.cifar4:
background_images,_,_,_ = cifar_with_only(CIFAR_VEHICLE_IDS, c10_train_xs, c10_train_ys, c10_test_xs, c10_test_ys)
elif block_noise_data == BlockNoiseDataset.cifar6:
background_images,_,_,_ = cifar_with_only(CIFAR_ANIMAL_IDS, c10_train_xs, c10_train_ys, c10_test_xs, c10_test_ys)
background_train = blocks(background_images, train_images.shape[0])
background_test = blocks(background_images, test_images.shape[0])
elif background_noise == BackgroundNoise.imagenet:
background_train = load_imagenet_plants(train_images.shape[0])
background_test = load_imagenet_plants(test_images.shape[0])
background_train *= background_noise_scalar
background_test *= background_noise_scalar
train_xs, test_xs = place_images(placement, train_images, background_train), place_images(placement, test_images, background_test)
k = max(train_ys) + 1
print('There are {:} categories'.format(k))
train_ys, test_ys = _one_hot(train_ys, k), _one_hot(test_ys, k)
return train_xs, train_ys, test_xs, test_ys
def mnist(num_train=-1, num_test=-1, size=28):
ds_train, ds_test = tfds.load('mnist', split=['train','test'],data_dir='data/')
if size != 28:
ds_train = ds_train.map(lambda ex: {'image':tf.image.resize(ex['image'], [size,size])/255.,
'label':ex['label']})
ds_test = ds_test.map(lambda ex: {'image':tf.image.resize(ex['image'], [size,size])/255.,
'label':ex['label']})
ds_train = ds_train.batch(60000).as_numpy_iterator()
ds_train = next(ds_train)
ds_test = ds_test.batch(10000).as_numpy_iterator()
ds_test = next(ds_test)
train_xs, train_ys, test_xs, test_ys = (ds_train["image"], ds_train["label"], ds_test["image"], ds_test["label"])
if size == 28:
train_xs = train_xs / 255.
test_xs = test_xs / 255.
num_train = num_train if num_train > 0 else 60000
num_test = num_test if num_test > 0 else 10000
keep_idx_train = onp.random.choice(train_xs.shape[0],size=num_train)
keep_idx_test = onp.random.choice(test_xs.shape[0],size=num_test)
return train_xs[keep_idx_train], train_ys[keep_idx_train], test_xs[keep_idx_test], test_ys[keep_idx_test]
def cifar_with_size(size):
ds_train, ds_test = tfds.load('cifar10', split=['train','test'],data_dir='data/')
if size != 32:
ds_train = ds_train.map(lambda ex: {'id': ex['id'],
'image':tf.image.resize(ex['image'], [size,size])/255.,
'label':ex['label']})
ds_test = ds_test.map(lambda ex: {'id': ex['id'],
'image':tf.image.resize(ex['image'], [size,size])/255.,
'label':ex['label']})
ds_train = ds_train.batch(50000).as_numpy_iterator()
ds_train = next(ds_train)
ds_test = ds_test.batch(10000).as_numpy_iterator()
ds_test = next(ds_test)
train_xs, train_ys, test_xs, test_ys = (ds_train["image"], ds_train["label"], ds_test["image"], ds_test["label"])
if size == 32:
# otherwise this had to be done above during resizing, per tf.image api
train_xs = train_xs / 255.
test_xs = test_xs / 255.
return train_xs, train_ys, test_xs, test_ys
def cifar_with_only(class_ids, train_xs, train_ys, test_xs, test_ys):
is_allowed_train = onp.equal(train_ys.reshape(-1,1),onp.array(class_ids).reshape(1,-1)).any(axis=-1)
is_allowed_test = onp.equal(test_ys.reshape(-1,1),onp.array(class_ids).reshape(1,-1)).any(axis=-1)
train_xs, train_ys = train_xs[is_allowed_train], train_ys[is_allowed_train]
test_xs, test_ys = test_xs[is_allowed_test], test_ys[is_allowed_test]
train_ys = onp.vectorize(lambda label: class_ids.index(label))(train_ys)
test_ys = onp.vectorize(lambda label: class_ids.index(label))(test_ys)
return train_xs, train_ys, test_xs, test_ys
def blocks(dataset, num_examples):
num_images = dataset.shape[0]
out = onp.concatenate([onp.concatenate([dataset[
|
onp.random.choice(num_images, size=num_examples)
|
numpy.random.choice
|
import sys
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from torch.optim import Adam, AdamW, SGD, RMSprop
from .base import TrainerBase
class AssistTrainer(TrainerBase):
def __init__(self, args):
super(AssistTrainer, self).__init__(args)
self.args = args
self.data = args.data
self.loader = args.loader
self.model = None
def dataloader(self):
"""
load data and build dataset -> loaders
"""
# load / split data
train_data = self.data.get_train_data()
if self.args.use_dev:
train_data, dev_data = self.data.split_data(train_data)
test_data = self.data.get_test_data()
#print(train_data[0])
#print(dev_data[0])
#print(test_data[0])
# build dataset
train_dataset = self.loader.build_dataset(
train_data,
self.args.train_max_seq_len)
train_loader = self.loader.build_dataloader(
train_dataset, 'train')
test_dataset = self.loader.build_dataset(
test_data,
self.args.eval_max_seq_len)
test_loader = self.loader.build_dataloader(
test_dataset, 'test')
if self.args.use_dev:
dev_dataset = self.loader.build_dataset(
dev_data,
self.args.eval_max_seq_len)
dev_loader = self.loader.build_dataloader(
dev_dataset, 'dev')
return train_loader, dev_loader, test_loader
else:
return train_loader, test_loader
def process_batch(self, batch, max_seq_len):
qid, correct, mask, n_questions = batch
# qid : [args.train_batch_size, args.max_seq_len], float
# correct : [args.train_batch_size, args.max_seq_len], float
# mask : [args.train_batch_size, args.max_seq_len], bool (for each example, mask length is n_questions -1)
# n_questions : [args.max_seq_len], int
# 0. actual sequence -1 masks
mask = mask.type(torch.FloatTensor)
# 1. build input_X (~2q dim)
# [incorrect 0 0 0 0 0 correct 0 0 0 0 0]
input_index = correct * self.args.n_questions + qid
max_input_index = 2 * self.args.n_questions
inputX = F.one_hot(
input_index,
max_input_index)[:,:max_seq_len,:]
inputX = inputX.type(torch.FloatTensor) * mask.unsqueeze(2)
#print(inputX.size())
# 2. build inputY (q dim) : answer one-hot ids
inputY = F.one_hot(
qid,
self.args.n_questions)[:,1:,:]
inputY = inputY.type(torch.FloatTensor) * mask.unsqueeze(2)
#print(inputY.size())
# 3. build correct (q dim) : answer 1/0
correct = inputY * correct[:,1:].unsqueeze(2) * mask.unsqueeze(2)
#print(correct.size())
#print(mask)
#print(inputX[0][:4])
#print(inputY[0][:4])
#print(correct[0][:4])
inputX = inputX.to(self.args.device)
inputY = inputY.to(self.args.device)
correct = correct.to(self.args.device)
mask = mask.to(self.args.device)
return inputX, inputY, correct, mask
def compute_loss(self, logit, correct, mask):
"""
input :
logit : (batch_size, max_seq_len, n_questions)
correct : (batch_size, max_seq_len, n_questions)
mask : (batch_size, max_seq_len)
output :
loss
"""
loss = self.loss_function(
logit,
correct) * mask.unsqueeze(2) #
loss = torch.sum(loss, dim=2) # masked dim
loss = torch.mean(loss)
return loss
def update_params(self, loss):
"""
update self.model.parameters()
# TODO : gradient accumulation
"""
loss.backward()
torch.nn.utils.clip_grad_norm_(
self.model.parameters(),
self.args.clip_grad)
self.optimizer.step()
self.optimizer.zero_grad()
self.n_updates += 1
def set_model(self):
self.model = self.args.model(self.args)
self.model.to(self.args.device) # load model to target device
def train(self):
# load dataloadrers
if self.args.use_dev:
train_loader, dev_loader, test_loader = self.dataloader()
else:
train_loader, test_loader = self.dataloader()
# set trainer components
if self.model is None:
self.set_model()
# set loss / optim
self.loss_function = self.set_loss()
self.set_optimizer(self.model.parameters())
self.optimizer.zero_grad()
# train model
for i in range(self.args.n_epochs):
print("Start Training: Epoch", str(i+1))
self.model.train()
for train_batch in train_loader:
# process inputs
inputX, inputY, correct, mask = self.process_batch(
train_batch,
self.args.train_max_seq_len)
# forward step
logits = self.model(inputX, inputY)
# compute loss
loss = self.compute_loss(logits, correct, mask)
# backward params
self.update_params(loss)
if self.n_updates % self.args.log_steps == 0:
print("Training steps:", str(self.n_updates), "Loss:", str(loss.item()))
self.n_epochs += 1
if self.args.save_model:
if self.n_epochs % self.args.save_epochs == 0 and self.n_epochs != 0:
self.save_model(self.model, self.optimizer)
# eval model
if self.args.use_dev:
dev_tp, dev_tc, dev_tm = self.predict(dev_loader)
dev_predict, dev_correct = self.metrics.flatten(dev_tp, dev_tc, dev_tm)
dev_auc = self.metrics.auc(dev_predict, dev_correct)
print("Dev AUC:", dev_auc)
tst_tp, tst_tc, tst_tm = self.predict(test_loader)
tst_predict, tst_correct = self.metrics.flatten(tst_tp, tst_tc, tst_tm)
tst_auc = self.metrics.auc(tst_predict, tst_correct)
print("Test AUC:", tst_auc)
def predict(self, eval_loader):
total_predictions = []
total_correct = []
total_mask = []
if self.model is None: self.set_model()
self.model.eval()
for eval_batch in eval_loader:
# process inputs
inputX, inputY, correct, mask = self.process_batch(
eval_batch,
self.args.eval_max_seq_len)
# forward step
logits = self.model(inputX, inputY)
# predictions
# product with mask because of logit=0 is sigm(0) != 0
predictions = torch.mean(
self.model.activation(logits) * mask.unsqueeze(2),
2)
correct = torch.sum(correct, 2)
# if using GPU, move every batch predictions to CPU
# to not consume GPU memory for all prediction results
if self.args.device == 'cuda':
predictions = predictions.to('cpu').detach().numpy()
correct = correct.to('cpu').detach().numpy()
mask = mask.to('cpu').detach().numpy()
else: # cpu
predictions = predictions.detach().numpy()
correct = correct.detach().numpy()
mask = mask.detach().numpy()
total_predictions.append(predictions)
total_correct.append(correct)
total_mask.append(mask)
total_predictions = np.concatenate(total_predictions) # (total eval examples, max_sequence_length)
total_correct = np.concatenate(total_correct) # (total eval examples, max_sequence_length)
total_mask =
|
np.concatenate(total_mask)
|
numpy.concatenate
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.