prompt
stringlengths 19
879k
| completion
stringlengths 3
53.8k
| api
stringlengths 8
59
|
---|---|---|
""" This file provides is an example of the application of geomstats
on the space of SDP matrices. The goal here is to classify a set of 86
brain connectomes represented by their SPD regularized Laplacian
(with parameter GAMMA) into two classes: control vs people suffering
from schizophrenia.
"""
import geomstats.spd_matrices_space as spd_space
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.cluster.hierarchy as hc
import seaborn as sb
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.metrics import f1_score, precision_score, recall_score
from sklearn.model_selection import KFold
from sklearn.svm import SVC
import time
N_NODES = 28
RAND_SEED = 2018
SPACE = spd_space.SPDMatricesSpace(n=N_NODES)
CORR_THRESH = 0.1
GAMMA = 1.0
N_GRAPHS = 86
SIGMAS = list(np.arange(0.5, 20, 0.5))
DISTANCES = ['log_euclidean', 'frobenius', 'riemannian']
TRAIN_SIZE = 0.85
def import_data():
graphs = pd.read_csv('data/train_fnc.csv')
map_functional = pd.read_csv('add_info/comp_ind_fmri.csv',
index_col=None)
map_functional = map_functional['fMRI_comp_ind'].to_dict()
map_functional_r = {v: k for k, v
in map_functional.items()}
mapping = pd.read_csv('add_info/' +
'rs_fmri_fnc_mapping.csv')
graph_labels = pd.read_csv('data/train_labels.csv')
all_graphs = [None] * N_GRAPHS
all_targets = np.zeros(N_GRAPHS)
def create_connectome(graph_id, mapping):
u = np.zeros((N_NODES, N_NODES))
nb_edges = mapping.shape[0]
for edge in range(nb_edges):
e0, e1 = (mapping.iloc[edge]['mapA'], mapping.iloc[edge]['mapB'])
region0, region1 = map_functional_r[e0], map_functional_r[e1]
u[region0, region1] = graphs.iloc[graph_id][edge]
u = np.multiply(u, (u > CORR_THRESH))
return np.abs(u + u.T)
for graph_id in range(N_GRAPHS):
all_graphs[graph_id] = create_connectome(graph_id, mapping)
all_targets[graph_id] = int(graph_labels.loc[graphs.index[graph_id], 'Class'])
all_targets = np.array(all_targets)
np.random.seed(RAND_SEED)
index_train = list(range(N_GRAPHS))
np.random.shuffle(index_train)
stop = int(TRAIN_SIZE * N_GRAPHS)
labels = all_targets[index_train]
return (graphs.iloc[:, index_train], [all_graphs[t] for t in index_train],
labels, stop, index_train)
def laplacian(a):
d = np.diag(np.array(a.sum(1)).flatten())
return d-a
def frobenius(hat_l1, hat_l2):
return np.linalg.norm(spd_space.group_log(hat_l1).squeeze(0)
- spd_space.group_log(hat_l2).squeeze(0),
'fro')
def riemannian(inv_l1, hat_l2):
return np.linalg.norm(inv_l1.dot(spd_space.group_log(hat_l2).squeeze(0).dot(inv_l1)),
'fro')
def log_euclidean(hat_l1, hat_l2):
return np.linalg.norm(spd_space.group_log(hat_l1).squeeze(0)
- spd_space.group_log(hat_l2).squeeze(0),
'fro')
def fit_kernel_cv(log_euclidean_distance, labels,
sigma=None, verbose=False):
kf = KFold(n_splits=10)
perf = {}
conf = {}
nb_train = len(labels)
if sigma is not None:
distance = np.exp(- np.square(log_euclidean_distance)/(sigma**2))
else:
distance = log_euclidean_distance
k = 0
for train_index, test_index in kf.split(range(nb_train)):
train_index = np.array(train_index)
test_index = np.array(test_index)
x = np.array(distance)[train_index, :][:, train_index]
x_test = np.array(distance[test_index, :])[:, train_index]
clf = SVC(kernel='precomputed')
clf.fit(x, labels[train_index])
y_train = clf.predict(x)
if verbose:
print("Training accuracy:",
accuracy_score(labels[train_index], y_train))
y_test = clf.predict(x_test)
perf[k] = {'acc': accuracy_score(labels[test_index], y_test),
'prec': precision_score(labels[test_index], y_test),
'f1': f1_score(labels[test_index], y_test),
'recall': recall_score(labels[test_index], y_test)}
conf[k] = confusion_matrix(labels[test_index], y_test)
k += 1
return perf, conf
def compute_similarities(all_graphs, type_dist):
distance = np.zeros((N_GRAPHS, N_GRAPHS))
for c, g in enumerate(all_graphs):
hat_l1 = laplacian(g) + GAMMA * np.eye(N_NODES)
lambda2, u = np.linalg.eigh(hat_l1)
inv_l1 = u.dot(np.diag(1.0/ | np.sqrt(lambda2) | numpy.sqrt |
"""
defines:
- PLOADv
- PLOAD1v
- PLOAD2v
- PLOAD4v
"""
from __future__ import print_function
from collections import defaultdict
from itertools import count
import numpy as np
from pyNastran.bdf.bdf_interface.assign_type import (
integer, integer_or_blank, double, double_or_blank, string_or_blank,
integer_string_or_blank, string, fields, components_or_blank)
from pyNastran.bdf.field_writer_8 import (
print_float_8, print_card_8, set_blank_if_default, set_string8_blank_if_default)
from pyNastran.bdf.field_writer_16 import (
print_float_16, set_string16_blank_if_default)
from pyNastran.bdf.field_writer_double import print_scientific_double
from pyNastran.bdf.cards.base_card import _format_comment
from pyNastran.bdf.cards.base_card import expand_thru
from pyNastran.dev.bdf_vectorized2.cards.loads.loads import BaseLoad
class PLOADv(BaseLoad):
"""
Static Pressure Load
Defines a uniform static pressure load on a triangular or quadrilateral surface
comprised of surface elements and/or the faces of solid elements.
+-------+-----+------+----+----+----+----+
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
+=======+=====+======+====+====+====+====+
| PLOAD | SID | P | G1 | G2 | G3 | G4 |
+-------+-----+------+----+----+----+----+
| PLOAD | 1 | -4.0 | 16 | 32 | 11 | |
+-------+-----+------+----+----+----+----+
"""
card_name = 'PLOAD'
def __init__(self, model):
BaseLoad.__init__(self, model)
self.pressure = np.array([], dtype='float64')
self.nids = | np.array([], dtype='int32') | numpy.array |
"""Standard library imports"""
import numpy as np # 1.19.4
import pandas as pd # 1.2.0
import scipy as sp #
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from scipy.optimize import fsolve
"""Local modules"""
from pyloads.blade_data import BladeFeatures
from pyloads.aerodynamic_profiles import AeroProfiles
from pyloads.operation_dtu10mw import Operation
class Rotor(Operation):
"""Create a Rotor object (by Default is the DTU 10 MW) by defining the blade geometry (cord, twist and
thickness), as well as the aerodynamic profiles (i.e as output from XFOIL interactive program for design).
- Calculate the Normal and Tangential loads for given operational conditions.
- Calculate the Power and Thrust coefficient.
- Calculate and plot the Rotor Power Curve.
Parameters
----------
radio : array , default=None
twist : array , default=None
cord : array , default=None
t_c : array , default=None
profiles : array , default='Default'"""
# class attributes
number_of_blades = 3
radio = 89.17 # [m]
rho = 1.225 # [km/m3]
operation = pd.DataFrame(
{'u': [4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21.,
22., 23., 24., 25., ],
'pitch': [2.751, 1.966, 0.896, 0., 0., 0., 0., 0., 4.502, 7.266,
9.292, 10.958, 12.499, 13.896, 15.2, 16.432, 17.618, 18.758, 19.86,
20.927,
21.963, 22.975],
'RPM': [6., 6., 6., 6., 6.426, 7.229, 8.032, 8.836, 9.6, 9.6, 9.6, 9.6,
9.6, 9.6, 9.6, 9.6, 9.6, 9.6, 9.6, 9.6, 9.6, 9.6, ]
})
# blade_data = pd.read_csv('bladedat.txt', sep='\t', names=['r', 'twist', 'c', 't/c'])
# class constructor
def __init__(self, radio='DTU_10MW', twist='DTU_10MW', cord='DTU_10MW', t_c='DTU_10MW', profiles='DTU_10MW'):
super().__init__()
bld = BladeFeatures()
# Take the parameters from BladeFeatures corresponding to DTU 10MW
if radio == 'DTU_10MW':
self.radio = bld.radio
if twist == 'DTU_10MW':
self.twist = bld.twist
if cord == 'DTU_10MW':
self.cord = bld.cord
if t_c == 'DTU_10MW':
self.t_c = bld.t_c
"""Load the aerodynamics profiles."""
# TODO:
# This should be in a child class from Rotor called DTU-10MW
if profiles == 'DTU_10MW':
aero_prof = AeroProfiles()
ffa_241 = aero_prof.ffa_241
ffa_301 = aero_prof.ffa_301
ffa_360 = aero_prof.ffa_360
ffa_480 = aero_prof.ffa_480
ffa_600 = aero_prof.ffa_600
cylinder = aero_prof.cylinder
self.ffa_dict = dict(zip(np.arange(6), [ffa_241, ffa_301, ffa_360, ffa_480, ffa_600, cylinder]))
# TODO:
# check that the len of the features is the same
# check that the data has valid ranges..
@staticmethod
def integrate(y, r):
"""Useful function for numerical integration.
parameters
----------
y : array
function to be integrated
r : array
integrate over r radial positions.
"""
M = 0 # dummy assignment before loop
for k in range(len(y) - 1):
A_k = (y[k + 1] - y[k]) / (r[k + 1] - r[k])
B_k = (y[k] * r[k + 1] - y[k + 1] * r[k]) / (r[k + 1] - r[k])
M += 1 / 3 * A_k * ((r[k + 1]) ** 3 - (r[k]) ** 3) + 0.5 * B_k * ((r[k + 1]) ** 2 - (r[k]) ** 2)
return M
@staticmethod
def thruster(pN, r):
"""Compute the total Thrust (T * num_blades) for the Rotor.
parameter
---------
pN : array
normal loads vector (i.e as returned by norma_tangential_loads method.
r : array
vector with radial position [m]"""
# [r] m
T = 0
B = Rotor.number_of_blades
for i in range(len(pN) - 1):
T += (pN[i + 1] + pN[i]) * 0.5 * (r[i + 1] - r[i])
# print(f'thrust {T} for item num {i}')
return T * B
def lift_drag_coeff(self, alpha, t_c):
# TODO:
# raise exceptions for thick and alpha
# read how to write docstring in Python PEP-8
"""Interpolation for drag and lift coefficients.
Returns: (Cl, Cd)
--------------parameters:
t_c: float (ie. 24.1)
alpha: int or float (rad)
"""
t = t_c
cdthick, clthick = np.zeros(6), np.zeros(6)
for k in range(6):
f1cl = interp1d(self.ffa_dict[k].iloc[:, 0], self.ffa_dict[k].iloc[:, 1])
f1cd = interp1d(self.ffa_dict[k].iloc[:, 0], self.ffa_dict[k].iloc[:, 2])
clthick[k] = f1cl(alpha * 180 / np.pi) # must convert into degrees
cdthick[k] = f1cd(alpha * 180 / np.pi)
thick_prof = | np.array([24.1, 30.1, 36., 48., 60., 100.]) | numpy.array |
from __future__ import print_function
from .base import Problem
from keras.models import Sequential
from keras.layers import Dense, LSTM, SimpleRNN
from keras.optimizers import Adam
from keras import backend as K
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
import numpy as np
import os
import pandas as pd
from datetime import datetime
from pygrn import RGRN
class Prediction(Problem):
def __init__(self, log_file, seed=0, learn=True, batch_size=1,
epochs=1, data_dir='./', lamarckian=False, unsupervised=True,
stateful=True, model='RGRN', ntrain=6*24*60, ntest=24*60,
shift=1, lag=60):
rawvals = pd.read_csv(os.path.join(data_dir, 'kliens_raw.csv'))
self.df = rawvals
if shift != 0:
self.df = rawvals - rawvals.shift(-1)
self.df['target'] = rawvals['close'] - rawvals['close'].shift(-shift-lag)
self.df.dropna(inplace=True)
train = self.df.tail(ntrain+ntest).head(ntrain)
test = self.df.tail(ntest)
self.scaler = MinMaxScaler(feature_range=(0, 1))
self.scaler = self.scaler.fit(train)
train = self.scaler.transform(train)
test = self.scaler.transform(test)
self.x_train = train[:, 0:-1]
self.x_train = self.x_train.reshape(self.x_train.shape[0], 1, self.x_train.shape[1])
self.y_train = train[:, -1]
self.x_test = test[:, 0:-1]
self.x_test = self.x_test.reshape(self.x_test.shape[0], 1, self.x_test.shape[1])
self.y_test = test[:, -1]
self.batch_size = batch_size
self.epochs = epochs
self.learn = learn
self.generation = 0
self.ntrain = ntrain
self.ntest = ntest
self.shift = shift
self.lag = lag
self.seed = seed
self.lamarckian = lamarckian
self.unsupervised = unsupervised
self.stateful = stateful
self.model_type = eval(model)
if self.unsupervised:
i = np.random.randint(self.x_train.shape[2])
self.y_train = 0.5*self.x_train[:,0,i] + 0.5*np.random.rand(len(self.y_train))
self.nin = self.x_train.shape[2]
self.nout = 10
self.cacheable = False
self.logfile = log_file
def generation_function(self, grneat, generation):
self.generation = generation
if self.unsupervised:
i = np.random.randint(self.x_train.shape[2])
self.y_train = 0.5*self.x_train[:,0,i] + 0.5*np.random.rand(len(self.y_train))
def eval(self, grn):
seed = np.random.randint(1e5)
model = Sequential()
batch_input_shape=(self.batch_size, self.x_train.shape[1], self.x_train.shape[2])
start_time = datetime.now()
if self.model_type == LSTM or self.model_type == SimpleRNN:
np.random.seed(int(np.round(grn.identifiers[0]*100)))
layer = self.model_type(self.nout, stateful=self.stateful,
batch_input_shape=batch_input_shape)
model.add(layer)
else:
np.random.seed(self.seed)
layer = self.model_type(str(grn), stateful=self.stateful,
batch_input_shape=batch_input_shape)
model.add(layer)
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
error = []
if self.learn:
for i in range(self.epochs):
history = model.fit(self.x_train, self.y_train,
batch_size=self.batch_size,
epochs=1, verbose=0, shuffle=False)
model.reset_states()
with open(self.logfile, 'a') as f:
for l in range(len(history.history['loss'])):
train_fit = history.history['loss'][l]
error += [train_fit]
f.write('L,%e,%d,%s,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%e\n' % (
(datetime.now()-start_time).total_seconds(),
self.seed, self.model_type.__name__, self.epochs,
self.lamarckian, self.unsupervised, self.stateful,
self.ntrain, self.ntest, self.shift, self.lag,
self.generation, i, train_fit))
# lamarckian evolution
if self.lamarckian:
layer.set_learned_genes(grn)
start_error = error[0]
end_error = error[-1]
fit = start_error - end_error
total_error = np.sum(np.abs(error))
if not self.unsupervised:
# predict and return unscaled difference
ntest = len(self.y_test)
yhat = model.predict(self.x_test, batch_size=self.batch_size, verbose=0)
final = np.concatenate((
np.reshape(self.x_test, (self.x_test.shape[0], self.x_test.shape[2])),
np.reshape(yhat, (ntest,1))), axis=1)
inverted = self.scaler.inverse_transform(final)
yhatp = inverted[:, -1]
target = self.df['target'].tail(ntest)
fit = np.sqrt(mean_squared_error(yhatp, target))
total_error = np.sum( | np.abs(yhatp - target) | numpy.abs |
# from __future__ import division
#-------------------------------------
#
# Started at 06/08/2018 (YuE)
#
# This script based on the previous script
# threeApproachesComparison_v6.py
#
## Upgraded version of python (python3.4): script was rewritten to take into
# account some differences in the descriptions and using of some functions
# (version cma_v3 and more earlier scripts are written under python2).
#
# 07/24/2018: IT IS NOT FINISHED:
#
# Which are still unsatisfactory:
# 1) the absolute values of frictional forces for all methods of calculation,
# 2) their dependence on the ion velocity.
#
# But nevertheless, the dependences of the transmitted energy on the impact
# parameter are close to the inverse quadratic (as it should be!) at all velocities.
#
# 07/27/2018: IT IS NOT FINISHED:
#
# Which are still unsatisfactory:
# 1) the absolute values of frictional forces for all methods of calculation,
# 2) their dependence on the ion velocity.
# The investigation of that is in progress.
#
# Some features were improved, some figures were corrected.
#
#-------------------------------------
#========================================================
#
# This code compairs two approaches: "classical" (from [1]) and
# "magnus" (from [2]).
#
# For "classical" approach the magnetized interaction between ion
# and electron is considered for ion velocities V_i > rmsTrnsvVe.
#
# References:
#
# [1] <NAME>, <NAME>, <NAME>, <NAME>.
# "Physics guide of BETACOOL code. Version 1.1". C-A/AP/#262, November
# 2006, Brookhaven National Laboratory, Upton, NY 11973.
# [2] <NAME>, <NAME>. "New Algorithm for Dynamical Friction
# of Ions in a Magnetized Electron Beam". AIP Conf. Proc. 1812, 05006 (2017).
#
#========================================================
#########################################################
#
# Main issues of the calculations:
#
# 1) Friction force (FF) is calculated in the (P)article (R)est (F)rame,
# i.e. in the frame moving together with both (cooled and cooling)
# beams at a velocity V0;
# 2) Friction force is calculated for each value of ion velocity
# in the interval from .1*rmsTrnsvVe till 10*rmsTrnsvVe;
# 3) Initially assumped that all electrons have a logitudinal
# velocity rmsLongVe and transversal velocity rmsTrnsvVe;
# 4) For each ion velocity the minimal and maximal values of the
# impact parameter are defined. Radius of the shielding of the
# electric field of the ion equals to the value of the maximal
# impact parameter;
# 5) For each impact parameter in the interval from minimal till
# maximal values the transfered momenta deltap_x,y,z are
# calculated;
# 6) Founded transfered momenta allow to calculate the transfered
# energy delta_E =deltap^2/(2*m_e) and to integrate it over
# impact parameter; then (expressions (3.4), (3.5) from [1]):
# FF =-2*pi*n_e*integral_rhoMin^rhoMax delta_E*rho*drho;
# 7) For taking into account the velocity distribution of the
# electrons it is necessary to repeat these calculations for
# each value of the electron's velocity and then integrate result
# over distribution of the velocities.
#
# 10/26/2018:
#
# 8) Item 6 is wrong and correct expression for transfered
# energy delta_E will be used;
# 9) Method (my own) Least Squares Method - LSM is used to fit the
# dependence of transferred momenta on impact parameter;
#
#
# 11/08/2018:
#
# 10) Two functions ('fitting' and 'errFitAB' are defined to realize
# my LSM to find the parameters of the fitting end error of this
# fitting;
#
# 11) Analys of different dependeces between values; graphical
# presentation of these dependences;
#
#########################################################
import os, sys
import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import LogNorm
from matplotlib import ticker
from matplotlib import markers
import matplotlib as mpl
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D
import scipy.integrate as integrate
from scipy.integrate import quad, nquad, dblquad
from scipy.constants import pi
from scipy import optimize
from statistics import mean
from array import array
#
# All physical constants have its dimension in units in the system CI.
# This code uses units in the system CGS!
#
from scipy.constants import speed_of_light as clight
from scipy.constants import epsilon_0 as eps0
from scipy.constants import mu_0 as mu0
from scipy.constants import elementary_charge as qe
from scipy.constants import electron_mass as me
from scipy.constants import proton_mass as mp
from scipy.constants import Boltzmann as kB
pi=3.14159265358
#
# Physical constants:
#
m_e=9.10938356e-28 # electron mass, g
m_elec=m_e # to keep variable from previous script
m_p=1.672621898e-24 # electron mass, g
M_ion = m_p # to keep variable from previous script
q_e=4.803204673e-10 # electron charge, CGSE unit: sqrt(g*cm^3/sec^2)
q_elec=q_e # to keep variable from previous script
Z_ion = q_e # to keep variable from previous script
cLight=2.99792458e10 # speed of light, cm/sec
eVtoErg=1.6021766208e-12 # 1 eV = 1.6...e-12 erg
CtoPart=2.99792458e9 # 1 C = 1 A*sec = 2.9...e9 particles
m_e_eV = m_e*cLight**2/eVtoErg
#
# Electron beam parameters:
#
Ekin=3.0e4 # kinetic energy, eV
curBeam=0.5 # current density, A/cm^2
dBeam=3.0 # beam diameter, cm
angSpread=3.0 # angular spread, mrad
trnsvT=0.5 # transversal temperature, eV
longT=2.0e-4 # longitudinal temperature, eV (was 2.0e-4)
nField=1 # number ov values of the magnetic field
fieldB=np.zeros(nField) # magnetic field
fieldB[0]=3.e3 # Gs
omega_p=1.0e9 # plasma frequency, 1/sec
n_e=omega_p**2*m_e/(4.*pi*q_e**2) # plasma density, 3.1421e+08 cm-3
n_e1=8.e7 # plasma density, cm-3
omega_p1=np.sqrt(4.*pi*n_e1*q_e**2/m_e) # plasma frequency, 5.0459e+08 1/s
#
# Cooling system parameter:
#
coolLength=150.0 # typical length of the coolong section, cm
#
# HESR:
#
Ekin=90.8e4 # HESR kinetic energy, eV
curBeam=0.5 # HESR current beam, A
dBeam=2.0 # HESR beam diameter, cm
angSpread=0.0 # HESR angular spread, mrad
trnsvT=0.2 # HESR transversal temperature, eV
longT=1.0e-2 # HESR longitudinal temperature, eV (was 2.0e-4)
fieldB[0]=1.e3 # HESR, Gs
coolLength=270.0 # HESR typical length of the coolong section, cm
#
# EIC:
#
angSpread=0.0 # EIC angular spread, mrad
fieldB[0]=5.e4 # EIC, Gs
coolLength=300.0 # EIC typical length of the coolong section, cm
#
# Calculated parameters of the electron beam:
#
V0 = cLight*np.sqrt(Ekin/m_e_eV*(Ekin/m_e_eV+2.))/(Ekin/m_e_eV+1.)
print ('V0 =%e' % V0)
tetaV0=0. # angle between V0 and magnetic field, rad
B_mag=fieldB[0]*np.cos(tetaV0) # magnetic field acting on an electron, Gs
rmsTrnsvVe=np.sqrt(2.*trnsvT*eVtoErg/m_e) # RMS transversal velocity, cm/s
rmsLongVe=np.sqrt(2.*longT*eVtoErg/m_e) # RMS longitudinal velocity, cm/s
# HESR:
dens=curBeam*(CtoPart/q_e)/(pi*(.5*dBeam)**2*V0) # density, 1/cm^3
omega=np.sqrt(4.*pi*dens*q_e**2/m_e) # plasma frequency, 1/s
n_e=dens
omega_p=omega
print ('HESR: dens = %e,omega_p = %e' % (dens,omega_p))
# EIC:
rmsLongVe = 1.0e+7 # cm/s
longT = .5*m_e*rmsLongVe**2/eVtoErg
rmsTrnsvVe = 4.2e+7 # cm/s
trnsvT = .5*m_e*rmsTrnsvVe**2/eVtoErg
print ('EIC: rmsLongVe = %e, longT = %e, rmsTrnsvVe = %e, trnsvT = %e' % \
(rmsLongVe,longT,rmsTrnsvVe,trnsvT))
dens=2.e9 # density, 1/cm^3
omega=np.sqrt(4.*pi*dens*q_e**2/m_e) # plasma frequency, 1/s
n_e=dens
omega_p=omega
print ('EIC: dens = %e,omega_p = %e' % (dens,omega_p))
cyclFreq=q_e*B_mag/(m_e*cLight) # cyclotron frequency, 1/s
rmsRoLarm=rmsTrnsvVe*cyclFreq**(-1) # RMS Larmor radius, cm
dens=omega_p**2*m_e/(4.*pi*q_e**2) # density, 1/cm^3
likeDebyeR=(3./dens)**(1./3.) # "Debye" sphere with 3 electrons, cm
eTempTran=trnsvT # to keep variable from previous script
eTempLong=longT # to keep variable from previous script
coolPassTime=coolLength/V0 # time pass through cooling section, cm
thetaVi=0. # polar angle ion and cooled electron beams, rad
phiVi=0. # azimuth angle ion and cooled electron beams, rad
powV0=round(np.log10(V0))
mantV0=V0/(10**powV0)
pow_n_e=round(np.log10(n_e))
mant_n_e=n_e/(10**pow_n_e)
#
# Formfactor ffForm for friction force:
#
# ffForm = 2*pi*dens*q_e**4/(m_e*V0**2)=
# = 0.5*omega_p**2*q_e**2/V0**2
#
# Dimension of ffForm is force: g*cm/sec**2=erg/cm
#
# 1 MeV/m = 1.e6*eVtoErg/100. g*cm/sec**2 = 1.e4*eVtoErg erg/cm
MeV_mToErg_cm=1.e4*eVtoErg
# ffForm=-.5*omega_p**2*q_e**2/V0**2/MeV_mToErg_cm # MeV/m
eV_mToErg_m=100.*eVtoErg
# ffForm=-.5*omega_p**2*q_e**2/V0**2/eV_mToErg_m # =-6.8226e-12 eV/m
eV_mInErg_cm=100.*eVtoErg
ffForm=-.5*omega_p**2*q_e**2/V0**2/eVtoErg # =-6.8226e-10 eV/cm
ffForm=100.*ffForm # =-6.8226e-08 eV/m
ergToEV = 1./1.60218e-12
#
# Relative velocities of electrons:
#
relVeTrnsv=rmsTrnsvVe/V0
relVeLong=rmsLongVe/V0
print ('V0=%e cm/s, rmsTrnsvVe=%e cm/s (rel = %e), rmsLongVe=%e cm/s (rel = %e)' % \
(V0,rmsTrnsvVe,relVeTrnsv,rmsLongVe,relVeLong))
# Indices:
(Ix, Ipx, Iy, Ipy, Iz, Ipz) = range(6)
stepsNumberOnGyro = 25 # number of the steps on each Larmour period
'''
#
# Opening the input file:
#
inputFile='areaOfImpactParameter_tAC-v6_fig110.data'
print ('Open input file "%s"...' % inputFile)
inpfileFlag=0
try:
inpfile = open(inputFile,'r')
inpfileFlag=1
except:
print ('Problem to open input file "%s"' % inputFile)
if inpfileFlag == 1:
print ('No problem to open input file "%s"' % inputFile)
lines=0 # Number of current line from input file
dataNumber=0 # Number of current value of any types of Data
xAboundary=np.zeros(100)
xBboundary=np.zeros(100)
while True:
lineData=inpfile.readline()
# print ('line=%d: %s' % (lines,lineData))
if not lineData:
break
lines += 1
if lines > 4:
words=lineData.split()
nWords=len(words)
# print ('Data from %d: words=%s, number of entries = %d' % (lines,words,nWords))
xAboundary[dataNumber]=float(words[0])
xBboundary[dataNumber]=float(words[1])
dataNumber += 1
inpfile.close()
print ('Close input file "%s"' % inputFile)
'''
#====================================================================
#
#------------------ Begin of defined functions -----------------------
#
# Larmor frequency electron:
#
def omega_Larmor(mass,B_mag):
return (q_elec)*B_mag/(mass*clight*1.e+2) # rad/sec
#
# Derived quantities:
#
omega_L = omega_Larmor(m_elec,B_mag) # rad/sec
T_larm = 2*pi/omega_L # sec
timeStep = T_larm/stepsNumberOnGyro # time step, sec
print ('omega_Larmor= %e rad/sec, T_larm = %e sec, timeStep = %e sec' % \
(omega_L,T_larm,timeStep))
nLarmorAvrgng=10 # number of averaged Larmor rotations
#
# Data to integrate transferred momemta over the track:
#
timeStep_c=nLarmorAvrgng*stepsNumberOnGyro*timeStep # sec
print ('timeStep_c = %e s' % timeStep_c)
eVrmsTran = np.sqrt(2.*eTempTran*eVtoErg/m_elec) # cm/sec
eVrmsLong = np.sqrt(2.*eTempLong*eVtoErg/m_elec) # cm/sec
kinEnergy = m_elec*(eVrmsTran**2+eVrmsLong**2)/2. # kinetic energy; erg
print ('eVrmsTran = %e cm/sec, eVrmsLong = %e cm/sec, kinEnergy = %e eV' % \
(eVrmsTran,eVrmsLong,ergToEV*kinEnergy))
ro_larmRMS = eVrmsTran/omega_L # cm
print ('ro_larmRMS =%e mkm' % (1.e4*ro_larmRMS))
#
# Electrons are magnetized for impact parameter >> rhoCrit:
#
rhoCrit=math.pow(q_elec**2/(m_elec*omega_L**2),1./3) # cm
print ('rhoCrit (mkm) = ' , 1.e+4*rhoCrit)
#
# Convertion from 6-vector of relectron's "coordinates" to 6-vector
# of guiding-center coordinates:
# z_e=(x_e,px_e,y_e,py_e,z_e,pz_e) --> zgc_e=(phi,p_phi,y_gc,p_gc,z_e,pz_e);
#
def toGuidingCenter(z_e):
mOmega=m_elec*omega_L # g/sec
zgc_e=z_e.copy() # 6-vector
zgc_e[Ix] = np.arctan2(z_e[Ipx]+mOmega*z_e[Iy],z_e[Ipy]) # radians
zgc_e[Ipx]= (((z_e[Ipx]+mOmega*z_e[Iy])**2+z_e[Ipy]**2)/(2.*mOmega)) # g*cm**2/sec
zgc_e[Iy] =-z_e[Ipx]/mOmega # cm
zgc_e[Ipy]= z_e[Ipy]+mOmega*z_e[Ix] # g/sec
return zgc_e
#
# Convertion from 6-vector of guiding-center coordinates to 6-vector
# of electron's "coordinates":
# zgc_e=(phi,p_phi,y_gc,p_gc,z_e,pz_e) --> z_e=(x_e,px_e,y_e,py_e,z_e,pz_e);
#
def fromGuidingCenter(zgc_e):
mOmega=m_elec*omega_L # g/sec
rho_larm=np.sqrt(2.*zgc_e[Ipx]/mOmega) # cm
z_e = zgc_e.copy() # 6-vector
z_e[Ix] = zgc_e[Ipy]/mOmega-rho_larm*np.cos(zgc_e[Ix]) # cm
z_e[Ipx]=-mOmega*zgc_e[Iy] # g*cm/sec
z_e[Iy] = zgc_e[Iy]+rho_larm*np.sin(zgc_e[Ix]) # cm
z_e[Ipy]= mOmega*rho_larm*np.cos(zgc_e[Ix]) # g*cm/sec
return z_e
#
# Matrix to dragg electron through the solenoid with field 'B_mag'
# during time interval 'deltaT':
#
def solenoid_eMatrix(B_mag,deltaT):
slndMtrx=np.identity(6)
omega_L=omega_Larmor(m_elec,B_mag) # rad/sec
mOmega= m_elec*omega_L # g/sec
phi=omega_L*deltaT # phase, rad
cosPhi=math.cos(phi) # dimensionless
sinPhi=math.sin(phi) # dimensionless
cosPhi_1=2.*math.sin(phi/2.)**2 # dimensionless
slndMtrx[Iy, Iy ]= cosPhi # dimensionless
slndMtrx[Ipy,Ipy]= cosPhi # dimensionless
slndMtrx[Iy, Ipy]= sinPhi/mOmega # sec/g
slndMtrx[Ipy,Iy ]=-mOmega*sinPhi # g/sec
slndMtrx[Iz, Ipz]= deltaT/m_elec # sec/g
slndMtrx[Ix, Ipx]= sinPhi/mOmega # sec/g
slndMtrx[Ix, Iy ]= sinPhi # dimensionless
slndMtrx[Ix, Ipy]= cosPhi_1/mOmega # sec/g
slndMtrx[Iy, Ipx]=-cosPhi_1/mOmega # sec/g
slndMtrx[Ipy,Ipx]=-sinPhi # dimensionless
return slndMtrx
#
# Matrix to dragg particle through the drift during time interval 'deltaT':
#
def drift_Matrix(M_prtcl,deltaT):
driftMtrx = np.identity(6)
for i in (Ix,Iy,Iz):
driftMtrx[i,i+1]=deltaT/M_prtcl # sec/g
return driftMtrx
#
# Matrix to dragg electron in the "guiding center" system during time interval 'deltaT':
#
def guidingCenter_Matrix(deltaT):
gcMtrx = np.identity(6)
gcMtrx[Iz,Ipz]=deltaT/m_elec # sec/g
return gcMtrx
#
# Description of the collision during time interval 'deltaT'
# in the system coordinates of "guiding center" of electron
# input - 6-vectors for electron and ion before collision and time step deltaT;
# output - transfered momenta to ion and electron:
#
def guidingCenterCollision(vectrElec_gc,vectrIon,deltaT):
dpIon=np.zeros(3)
dpElec=np.zeros(3)
mOmegaLarm=m_elec*omega_L # g/sec
dpFactor_gc=q_elec**2 # g*cm^3/sec^2
rhoLarm_gc=np.sqrt(2.*vectrElec_gc[1]/mOmegaLarm) # cm
sinOmega_gc=math.sin(vectrElec_gc[0])
cosOmega_gc=math.cos(vectrElec_gc[0])
x_gc=vectrElec_gc[3]/mOmegaLarm # cm
numer=(vectrIon[0]-x_gc)*cosOmega_gc- \
(vectrIon[2]-vectrElec_gc[2])*sinOmega_gc # cm
denom=((vectrIon[0]-x_gc)**2+(vectrIon[2]-vectrElec_gc[2])**2+ \
(vectrIon[4]-vectrElec_gc[4])**2+rhoLarm_gc**2)**(3/2) # cm^3
action=vectrElec_gc[1]+dpFactor_gc*numer*rhoLarm_gc/(omega_L*denom) # g*cm^2/sec
b_gc=np.sqrt((vectrIon[0]-x_gc)**2+ \
(vectrIon[2]-vectrElec_gc[2])**2+ \
(vectrIon[4]-vectrElec_gc[4])**2+2.*action/mOmegaLarm) # cm
# Dimensions of dpIon, deElec are g*cm/sec:
dpIon[0]=-dpFactor_gc*deltaT*(vectrIon[0]-x_gc)/b_gc**3
dpIon[1]=-dpFactor_gc*deltaT*(vectrIon[2]-vectrElec_gc[2])/b_gc**3
dpIon[2]=-dpFactor_gc*deltaT*(vectrIon[4]-vectrElec_gc[4])/b_gc**3
dpElec[0]=-dpIon[0]
dpElec[1]=-dpIon[1]
dpElec[2]=-dpIon[2]
# print ('dpIon[0]=%e, dpIon[1]=%e, dpIon[2]=%e' % \
# (dpIon[0],dpIon[1],dpIon[2]))
return dpIon,dpElec,action,b_gc
#
# "Magnus expansion" description of the collision during time interval 'deltaT'
# in the system coordinates of "guiding center" of electron
# input - 6-vectors for electron and ion before collision and time step deltaT;
# output - transfered momenta to ion and electron and electron y_gc coordinate
# as well calculated parameters C1,C2,C3,b,D1,D2,q for testing:
#
def MagnusExpansionCollision(vectrElec_gc,vectrIon,deltaT):
# print ('Ion: x=%e, y=%e, z=%e' % (vectrIon[0],vectrIon[2],vectrIon[4]))
# print ('Electron: x=%e, y=%e, z=%e' %
# (vectrElec_gc[0],vectrElec_gc[4],vectrElec_gc[4]))
dpIon=np.zeros(3)
dpElec=np.zeros(3)
mOmegaLarm=m_elec*omega_L # g/sec
dpFactor_gc=q_elec**2 # g*cm^3/sec^2
rhoLarm_gc=np.sqrt(2.*vectrElec_gc[1]/mOmegaLarm) # cm
sinOmega_gc=math.sin(vectrElec_gc[0])
cosOmega_gc=math.cos(vectrElec_gc[0])
x_gc=vectrElec_gc[3]/mOmegaLarm # cm
numer=(vectrIon[0]-x_gc)*cosOmega_gc- \
(vectrIon[2]-vectrElec_gc[2])*sinOmega_gc # cm
denom=((vectrIon[0]-x_gc)**2+(vectrIon[2]-vectrElec_gc[2])**2+ \
(vectrIon[4]-vectrElec_gc[4])**2+rhoLarm_gc**2)**(3./2.) # cm^3
action=vectrElec_gc[1]+dpFactor_gc*numer*rhoLarm_gc/(omega_L*denom) # g*cm^2/sec
# C1=np.sqrt((vectrIon[0]-x_gc)**2+ \
# (vectrIon[2]-vectrElec_gc[2])**2+ \
# (vectrIon[4]-vectrElec_gc[4])**2+2.*action/mOmegaLarm) # cm^2
C1=(vectrIon[0]-x_gc)**2+(vectrIon[2]-vectrElec_gc[2])**2+ \
(vectrIon[4]-vectrElec_gc[4])**2+2.*action/mOmegaLarm # cm^2
C2=2.*((vectrIon[0]-x_gc)*vectrIon[1]/M_ion+ \
(vectrIon[2]-vectrElec_gc[2])*vectrIon[3]/M_ion+ \
(vectrIon[4]-vectrElec_gc[4])* \
(vectrIon[5]/M_ion-vectrElec_gc[5]/m_elec)) # cm^2/sec
C3=(vectrIon[1]/M_ion)**2+(vectrIon[3]/M_ion)**2+ \
(vectrIon[5]/M_ion-vectrElec_gc[5]/m_elec)**2 # cm^2/sec^2
b=np.sqrt(C1+C2*deltaT+C3*deltaT**2) # cm
D1=(2.*C3*deltaT+C2)/b-C2/np.sqrt(C1) # cm/sec
D2=(C2*deltaT+2.*C1)/b-2.*np.sqrt(C1) # cm
q=4.*C1*C3-C2**2 # cm^4/sec^2
# Dimensions of dpIon, deElec are g*cm/sec:
dpIon[0]=-2.*dpFactor_gc/q*((vectrIon[0]-x_gc)*D1-vectrIon[1]/M_ion*D2)
dpIon[1]=-2.*dpFactor_gc/q*((vectrIon[2]-vectrElec_gc[2])*D1- \
vectrIon[3]/M_ion*D2)
dpIon[2]=-2.*dpFactor_gc/q*((vectrIon[4]-vectrElec_gc[4])*D1- \
(vectrIon[5]/M_ion-vectrElec_gc[5]/m_elec)*D2)
dpElec[0]=-dpIon[0]
dpElec[1]=-dpIon[1]
dpElec[2]=-dpIon[2]
dy_gc=dpIon[0]/mOmegaLarm # cm
# print ('dpIon[0]=%e, dpIon[1]=%e, dpIon[2]=%e' % \
# (dpIon[0],dpIon[1],dpIon[2]))
return dpIon,dpElec,action,dy_gc,C1,C2,C3,b,D1,D2,q
#
# Minimized functional (my own Least Squares Method - LSM;
# Python has own routine for LSM - see site
# http://scipy-cookbook.readthedocs.io/items/FittingData.html):
#
# Funcional = {log10(funcY) - [fitB*log10(argX) + fitA]}^2
#
def fitting(nPar1,nPar2,argX,funcY):
log10argX = np.zeros((nPar1,nPar2))
log10funcY = np.zeros((nPar1,nPar2))
for i in range(nVion):
for n in range(nPar1):
log10argX[n,i] = np.log10(argX[n,i])
log10funcY[n,i] = np.log10(funcY[n,i])
sumArgX = np.zeros(nPar2)
sumArgX2 = np.zeros(nPar2)
sumFuncY = np.zeros(nPar2)
sumArgXfuncY= np.zeros(nPar2)
fitA = np.zeros(nPar2)
fitB = np.zeros(nPar2)
for i in range(nPar2):
for n in range(nPar1):
sumArgX[i] += log10argX[n,i]
sumArgX2[i] += log10argX[n,i]**2
sumFuncY[i] += log10funcY[n,i]
sumArgXfuncY[i] += log10argX[n,i]*log10funcY[n,i]
delta = sumArgX[i]**2-nPar1*sumArgX2[i]
fitA[i] = (sumArgX[i]*sumArgXfuncY[i]-sumArgX2[i]*sumFuncY[i])/delta
fitB[i] = (sumArgX[i]*sumFuncY[i]-nPar1*sumArgXfuncY[i])/delta
# print ('fitA(%d) = %e, fitB(%d) = %e' % (i,fitA[i],i,fitB[i]))
argXfit = np.zeros((nPar1,nPar2))
funcYfit = np.zeros((nPar1,nPar2))
funcHi2 = np.zeros(nPar2)
for i in range(nPar2):
factorA = math.pow(10.,fitA[i])
for n in range(nPar1):
argXfit[n,i] = math.pow(10.,log10argX[n,i])
funcYfit[n,i] = factorA*math.pow(argXfit[n,i],fitB[i])
funcHi2[i] += (np.log10(abs(funcY[n,i])) - np.log10(abs(funcYfit[n,i])))**2
return fitA,fitB,funcHi2,argXfit,funcYfit
#
# +-Errors for fitied parameters fitA and fitB:
#
def errFitAB(nPar1,nPar2,argX,funcY,fitA,fitB,funcHi2,errVar,errType):
log10argX = np.zeros((nPar1,nPar2))
log10funcY = np.zeros((nPar1,nPar2))
sumArgX = np.zeros(nPar2)
sumArgX2 = np.zeros(nPar2)
posErrFit = np.zeros(nPar2)
negErrFit = np.zeros(nPar2)
# return posErrFit,negErrFit
stepA = 5.e-4*mean(funcHi2)
stepB = 1.e-4*mean(funcHi2)
# print ('errFitAB: mean(funcHi2) = %e, stepA = %e, stepB = %e' % (mean(funcHi2),stepA,stepB))
for i in range(nPar2):
for n in range(nPar1):
log10argX[n,i] = np.log10(argX[n,i])
log10funcY[n,i] = np.log10(funcY[n,i])
sumArgX[i] += log10argX[n,i]
sumArgX2[i] += log10argX[n,i]**2
for i in range(nPar2):
k = 0
deltaFuncHi2 = 0.
while (deltaFuncHi2 < 1.):
k += 1
if k > 2000:
print ('Break in errFitAB (Fit funcY: case %d); positive error) for %d' % (errVar,i))
break
# print ('i=%d: fitParamtr = %e, funcHi2 = %e' % (i,fitParamtr[i], funcHi2[i]))
curFitA = fitA[i]
if (int(errVar) == 1):
curFitA = fitA[i] + k*stepA
curFuncHi2 = 0.
factorA = math.pow(10.,curFitA)
curFitB = fitB[i]
if (int(errVar) == 2):
curFitB = fitB[i] + k*stepB
curFuncHi2 = 0.
for n in range(nPar1):
curArgX = math.pow(10.,log10argX[n,i])
curFuncYfit = factorA*math.pow(curArgX,curFitB)
curFuncHi2 += (np.log10(abs(curFuncYfit)) - log10funcY[n,i])**2
deltaFuncHi2 = curFuncHi2 - funcHi2[i]
if (int(errVar) == 1):
posErrFit[i] = abs(curFitA - fitA[i])
else:
posErrFit[i] = abs(curFitB - fitB[i])
func1sigma2 = funcHi2[i]/(nPar2-3)
if (int(errVar) == 1):
fitSigma = np.sqrt(sumArgX2[i]/(nPar2*sumArgX2[i]-sumArgX[i]**2)*func1sigma2)
else:
fitSigma = np.sqrt(nPar2/(nPar2*sumArgX2[i]-sumArgX[i]**2)*func1sigma2)
if (int(errType) == 2):
posErrFit[i] = fitSigma
# if (int(errVar) == 1):
# print ('i=%d: fitA = %e + %e (%e), funcHi2 = %e (for %d steps curFuncHi2 = %e)' % \
# (i,fitA[i],posErrFit[i],fitSigma,funcHi2[i],k,curFuncHi2))
# else:
# print ('i=%d: fitB = %e + %e (%e), funcHi2 = %e (for %d steps curFuncHi2 = %e)' % \
# (i,fitB[i],posErrFit[i],fitSigma,funcHi2[i],k,curFuncHi2))
for i in range(nPar2):
k = 0
deltaFuncHi2 = 0.
while (deltaFuncHi2 < 1.):
k += 1
if k > 2000:
print ('Break in errFitAB (Fit funcY: case %d); negative error) for %d' % (errVar,i))
break
curFitA = fitA[i]
if (int(errVar) == 1):
curFitA = fitA[i] - k*stepA
factorA = math.pow(10.,curFitA)
curFitB = fitB[i]
if (int(errVar) == 2):
curFitB = fitB[i] - k*stepB
curFuncHi2 = 0.
for n in range(nPar1):
curArgX = math.pow(10.,log10argX[n,i])
curFuncYfit = factorA*math.pow(curArgX,curFitB)
curFuncHi2 += (np.log10(abs(curFuncYfit)) - log10funcY[n,i])**2
deltaFuncHi2 = curFuncHi2 - funcHi2[i]
if (int(errVar) == 1):
negErrFit[i] = abs(curFitA - fitA[i])
else:
negErrFit[i] = abs(curFitB - fitB[i])
if (int(errType) == 2):
negErrFit[i] = posErrFit[i]
# if (errVar == 1):
# print ('i=%d: fitA = %e - %e, funcHi2 = %e (for %d steps curFuncHi2 = %e)' % \
# (i,fitA[i],posErrFit[i],funcHi2[i],k,curFuncHi2))
# else:
# print ('i=%d: fitB = %e - %e, funcHi2 = %e (for %d steps curFuncHi2 = %e)' % \
# (i,fitB[i],negErrFit[i],funcHi2[i],k,curFuncHi2))
return posErrFit,negErrFit
def fittedGKintegration(xMin,xMax,fitA,fitB):
#
# "Gauss-Kronrod" method of integration (GK)
#
#
# Points (psi_i) and weigths (w_i) to integrate for interval from -1 to 1;
# These data are from <NAME>. "Handbook of Mathematical Science".
# 5th Edition, CRC Press, Inc, 1978.
#
# To integrate for interval from 0 to 1 it is necessary to change points
# psi_i with points ksi_i=(1+psi_i)/2;
#
# For method with order N for function F(x):
# int_(-1)^1 = sum_1^N [w_i* F(psi_i)];
#
# In case of integration over interval from a to b:
# int_(a)^b = (b-a)/2 * sum_1^N [w_i* F(x_i)], where
# x_i = (b-a)*psi_i/2+(a+b)/2.
#
#----------------------------------------------------
#
# Data for GK:
#
#----------------------------------------------------
nPoints_GK = 16
psi_16=np.array([-0.9894009, -0.9445750, -0.8656312, -0.7554044, -0.6178762, \
-0.4580168, -0.2816036, -0.0950125, 0.0950125, 0.2816036, \
0.4580168, 0.6178762, 0.7554044, 0.8656312, 0.9445750, \
0.9894009])
w_16 =np.array([ 0.0271525, 0.0622535, 0.0951585, 0.1246290, 0.1495960, \
0.1691565, 0.1826034, 0.1894506, 0.1894506, 0.1826034, \
0.1691565, 0.1495960, 0.1246290, 0.0951585, 0.0622535, \
0.0271525])
y = np.zeros(nPoints_GK)
yIntegrated = 0.
for n in range(nPoints_GK):
xCrrnt = psi_16[n]*(xMax-xMin)/2 + (xMax+xMin)/2.
factorA = math.pow(10.,fitA)
y[n] = factorA*math.pow(xCrrnt,fitB)
yIntegrated += (xMax-xMin)*w_16[n]*y[n]*xCrrnt
return y,yIntegrated
#------------------ End of defined functions -----------------------
#
#====================================================================
sphereNe=3.
R_e=math.pow(sphereNe/n_e,1./3) # cm
print ('R_e (cm)=%e' % R_e)
ro_Larm = eVrmsTran/omega_L # cm
print ('ro_Larm (cm)=%e' % ro_Larm)
impctPrmtrMin=2.*ro_Larm
# rhoDependenceFlag = 1 # skip calculation of rho dependence if = 0!
#============ Important flags ===========================
#
# Taking into account the transfer of momenta for both particles
# (for "classical" only):
dpTransferFlag = 1 # no taking into account if = 0!
#
saveFilesFlag = 0 # no saving if = 0!
#
plotFigureFlag = 1 # plot if = 1!
#
#========================================================
nVion=50
Vion=np.zeros(nVion)
VionLong=np.zeros(nVion)
VionTrnsv=np.zeros(nVion)
VionRel=np.zeros(nVion)
vIonMin=4.e-3*eVrmsTran
vIonMax=10.*eVrmsTran
vIonMinRel=vIonMin/V0
vIonMaxRel=vIonMax/V0
print ('VionMin=%e (vIonMinRel=%e), vIonMax=%e (vIonMaxRel=%e)' % \
(vIonMin,vIonMinRel,vIonMax,vIonMaxRel))
vIonLogStep=math.log10(vIonMax/vIonMin)/(nVion-1)
R_debye=np.zeros(nVion)
R_pass=np.zeros(nVion)
R_pass_1=np.zeros(nVion) # for longT=0. --> eVrmsLong=0.
impctPrmtrMax=np.zeros(nVion)
impctPrmtrMax_1=np.zeros(nVion) # for longT=0. --> eVrmsLong=0.
for i in range(nVion):
crrntLogVionRel=math.log10(vIonMinRel)+i*vIonLogStep
VionRel[i]=math.pow(10.,crrntLogVionRel)
Vion[i]=VionRel[i]*V0
VionLong[i]=Vion[i]*np.cos(thetaVi)
VionTrnsv[i]=Vion[i]*np.sin(thetaVi)
R_debye[i]=np.sqrt(Vion[i]**2+eVrmsTran**2+eVrmsLong**2)/omega_p
R_pass[i]=np.sqrt(Vion[i]**2+eVrmsLong**2)*coolPassTime
R_pass_1[i]=np.sqrt(Vion[i]**2+0.*eVrmsLong**2)*coolPassTime
help=max(R_debye[i],R_e)
impctPrmtrMax[i]=min(help,R_pass[i])
impctPrmtrMax_1[i]=min(help,R_pass_1[i])
#-----------------------------------------------------------------
# Checking of corection of the maximal impact parameter on depence
# of preset number of minimal Larmor turns
#
larmorTurnsMin=[10,20,30,40]
impctPrmtrMaxCrrctd=np.zeros((nVion,4))
impctPrmtrMaxCrrctdRel=np.zeros((nVion,4))
for n in range (4):
for i in range(nVion):
impctPrmtrMaxCrrctd[i,n]=impctPrmtrMax[i]* \
np.sqrt(1.- (pi*larmorTurnsMin[n]*eVrmsLong/omega_L/impctPrmtrMax[i])**2)
impctPrmtrMaxCrrctdRel[i,n]=impctPrmtrMaxCrrctd[i,n]/impctPrmtrMax[i]
#
# First plotting:
#
if (plotFigureFlag == 0):
fig10 = plt.figure(10)
plt.semilogx(impctPrmtrMax,impctPrmtrMaxCrrctdRel[:,0],'-r', \
impctPrmtrMax,impctPrmtrMaxCrrctdRel[:,1],'-b', \
impctPrmtrMax,impctPrmtrMaxCrrctdRel[:,2],'-g', \
impctPrmtrMax,impctPrmtrMaxCrrctdRel[:,3],'-m',linewidth=2)
plt.grid(True)
hold=True
plt.xlabel('Maximal Impact parameter $R_{max}$, cm',color='m',fontsize=16)
plt.ylabel('$R_{max}^{Crrctd}/R_{Max}$',color='m',fontsize=16)
# plt.xlim([.9*min(impctPrmtrMax),1.1*max(impctPrmtrMax)])
plt.xlim([1.e-2,1.1*max(impctPrmtrMax)])
plt.ylim([.986,1.001])
titleHeader='$R_{max}^{Crrctd}=R_{Max} \cdot [1-(\pi\cdot N_{Larm} \cdot'
titleHeader += '\Delta_{e||}/(\omega_{Larm} \cdot R_{max})]^{1/2}$'
plt.title(titleHeader,color='m',fontsize=16)
plt.legend([('$N_{Larm}=$%2d' % larmorTurnsMin[0]), \
('$N_{Larm}=$%2d' % larmorTurnsMin[1]), \
('$N_{Larm}=$%2d' % larmorTurnsMin[2]), \
('$N_{Larm}=$%2d' % larmorTurnsMin[3])],loc='lower center',fontsize=14)
if (saveFilesFlag == 1):
fig10.savefig('picturesCMA/correctedRmax_fig10cma.png')
print ('File "picturesCMA/correctedRmax_fig10cma.png" is written')
xLimit=[.9*VionRel[0],1.1*VionRel[nVion-1]]
#
# Typs of collisions:
#
if (plotFigureFlag == 0):
fig3151=plt.figure (3151)
plt.loglog(VionRel,impctPrmtrMax,'-r', VionRel,impctPrmtrMax_1,'--r', \
[VionRel[0],VionRel[nVion-1]],[impctPrmtrMin,impctPrmtrMin],'-b',linewidth=2)
plt.grid(True)
hold=True
plt.xlabel('Relative Ion Velocity, $V_i/V_{e0}$',color='m',fontsize=14)
plt.ylabel('Impact Parameter, cm',color='m',fontsize=14)
titleHeader= \
'Types of Collisions: $V_{e0}=%4.2f\cdot10^{%2d}$ cm/s, $B=%6.1f$ Gs'
plt.title(titleHeader % (mantV0,powV0,fieldB[0]),color='m',fontsize=16)
plt.xlim(xLimit)
yLimit=[8.e-4,.6]
plt.ylim(yLimit)
plt.plot([relVeTrnsv,relVeTrnsv],yLimit,'--m',linewidth=1)
plt.text(1.6e-3,5.e-4,'$ \Delta V_{e\perp}/ V_{e0}$',color='m',fontsize=14)
plt.plot([relVeLong,relVeLong],yLimit,'--m',linewidth=1)
plt.text(4.4e-5,.0018,'$ \Delta V_{e||}/ V_{e0}$',color='m',fontsize=14)
plt.text(3.e-4,1.75e-3,'$R_{min}=2\cdot<rho_\perp>$',color='k',fontsize=16)
plt.text(7.e-4,5.e-2,'$R_{max}$',color='k',fontsize=16)
plt.text(2.85e-5,3.3e-3,'$R_{max}$ $for$ $T_{e||}=0$',color='k',fontsize=16)
plt.plot([VionRel[0],VionRel[nVion-1]],[20.*rhoCrit,20.*rhoCrit],color='k')
plt.text(1.e-4,7.e-3,'Magnetized Collisions',color='r',fontsize=20)
plt.text(1.e-4,10.e-4,'Adiabatic or Fast Collisions',color='r',fontsize=20)
plt.text(2.25e-5,.275,'Collisions are Screened',color='r',fontsize=20)
plt.text(1.6e-5,1.e-3,'$ \cong 20\cdot R_{Crit}$',color='k',fontsize=16)
if (saveFilesFlag == 1):
fig3151.savefig('picturesCMA_v7/impctPrmtr_fig3151cma.png')
print ('File "picturesCMA_v7/impctPrmtr_fig3151cma.png" is written')
#
# Picture for HESR:
#
if (plotFigureFlag == 0):
fig3151=plt.figure (3151)
plt.loglog(VionRel,impctPrmtrMax,'-r', VionRel,impctPrmtrMax_1,'--r', \
[VionRel[0],VionRel[nVion-1]],[impctPrmtrMin,impctPrmtrMin],'-b',linewidth=2)
plt.grid(True)
hold=True
plt.xlabel('Relative Ion Velocity, $V_i/V_{e0}$',color='m',fontsize=14)
plt.ylabel('Impact Parameter, cm',color='m',fontsize=14)
titleHeader= \
'HESR Types of Collisions: $V_{e0}=%3.1f\cdot10^{%2d}$cm/s, $B=%3.1f$T'
plt.title(titleHeader % (mantV0,powV0,1.e-4*fieldB[0]),color='m',fontsize=16)
plt.xlim(xLimit)
yLimit=[8.e-4,.6]
plt.ylim(yLimit)
plt.plot([relVeTrnsv,relVeTrnsv],yLimit,'--m',linewidth=1)
plt.text(4.4e-4,8.4e-4,'$ \Delta V_{e\perp}/ V_{e0}$',color='m',fontsize=14)
plt.plot([relVeLong,relVeLong],yLimit,'--m',linewidth=1)
plt.text(1.e-4,8.4e-4,'$ \Delta V_{e||}/ V_{e0}$',color='m',fontsize=14)
plt.text(3.7e-6,3.4e-3,'$R_{min}=2\cdot<rho_\perp>$',color='b',fontsize=16)
plt.text(2.8e-4,.1,'$R_{max}$',color='k',fontsize=16)
plt.text(1.e-4,1.8e-2,'$R_{max}$ $for$ $T_{e||}=0$',color='k',fontsize=16)
plt.plot([VionRel[0],VionRel[nVion-1]],[20.*rhoCrit,20.*rhoCrit],color='k')
plt.text(6.8e-5,7.e-3,'Magnetized Collisions',color='r',fontsize=20)
plt.text(6.8e-5,1.2e-3,'Weak Collisions',color='r',fontsize=20)
plt.text(2.3e-5,1.95e-3,'Adiabatic or Fast Collisions',color='r',fontsize=20)
plt.text(2.e-5,.275,'Screened Collisions',color='r',fontsize=20)
plt.text(3.58e-6,2.05e-3,'$\cong$20$\cdot$$R_{Crit}$',color='k',fontsize=16)
if (saveFilesFlag == 1):
# fig3151.savefig('picturesCMA_v7/impctPrmtr_fig3151cma.png')
# print ('File "picturesCMA_v7/impctPrmtr_fig3151cma.png" is written')
fig3151.savefig('HESRimpctPrmtr_fig3151cma.png')
print ('File "HESRimpctPrmtr_fig3151cma.png" is written')
#
# Picture for EIC:
#
if (plotFigureFlag == 0):
fig3151=plt.figure (3151)
plt.loglog(VionRel,impctPrmtrMax,'-r', VionRel,impctPrmtrMax_1,'--r', \
[VionRel[0],VionRel[nVion-1]],[impctPrmtrMin,impctPrmtrMin],'-b',linewidth=2)
plt.grid(True)
hold=True
plt.xlabel('Relative Ion Velocity, $V_i/V_{e0}$',color='m',fontsize=14)
plt.ylabel('Impact Parameter, cm',color='m',fontsize=14)
titleHeader= \
'EIC Types of Collisions: $V_{e0}=%3.1f\cdot10^{%2d}$cm/s, $B=%3.1f$T'
plt.title(titleHeader % (mantV0,powV0,1.e-4*fieldB[0]),color='m',fontsize=16)
plt.xlim(xLimit)
yLimit=[5.e-5,.3]
plt.ylim(yLimit)
plt.plot([relVeTrnsv,relVeTrnsv],yLimit,'--m',linewidth=1)
plt.text(9.e-4,4.e-5,'$ \Delta V_{e\perp}/ V_{e0}$',color='m',fontsize=14)
plt.plot([relVeLong,relVeLong],yLimit,'--m',linewidth=1)
plt.text(1.7e-4,3.e-5,'$ \Delta V_{e||}/ V_{e0}$',color='m',fontsize=14)
plt.text(6.3e-6,1.1e-4,'$R_{min}=2\cdot<rho_\perp>$',color='b',fontsize=16)
plt.text(1.e-4,2.1e-2,'$R_{max}$',color='k',fontsize=16)
plt.text(2.57e-5,5.e-3,'$R_{max}$ $for$ $T_{e||}=0$',color='k',fontsize=16)
plt.plot([VionRel[0],VionRel[nVion-1]],[20.*rhoCrit,20.*rhoCrit],color='k')
plt.text(2.3e-5,1.e-3,'Magnetized Collisions',color='r',fontsize=20)
# plt.text(6.8e-5,1.2e-3,'Weak Collisions',color='r',fontsize=20)
plt.text(1.1e-5,5.7e-5,'Weak or Adiabatic or Fast Collisions',color='r',fontsize=16)
plt.text(2.e-5,.15,'Screened Collisions',color='r',fontsize=20)
plt.text(2.5e-3,1.7e-4,'$\cong$20$\cdot$$R_{Crit}$',color='k',fontsize=16)
if (saveFilesFlag == 1):
# fig3151.savefig('picturesCMA_v7/impctPrmtr_fig3151cma.png')
# print ('File "picturesCMA_v7/impctPrmtr_fig3151cma.png" is written')
fig3151.savefig('EICimpctPrmtr_fig3151cma.png')
print ('File "EICimpctPrmtr_fig3151cma.png" is written')
# plt.show()
# sys.exit()
#
# Magnetized collisions:
#
if (plotFigureFlag == 0):
fig209=plt.figure (209)
plt.loglog(VionRel,R_debye,'-r',VionRel,R_pass,'-b', \
VionRel,R_pass_1,'--b',linewidth=2)
plt.grid(True)
hold=True
plt.plot([VionRel[0],VionRel[nVion-1]],[R_e,R_e],color='m',linewidth=2)
plt.xlabel('Relative Ion Velocity, $V_i/V_{e0}$',color='m',fontsize=16)
plt.ylabel('$R_{Debye}$, $R_{Pass}$, $R_e$, cm',color='m',fontsize=16)
# titleHeader='Magnetized Collision: $R_{Debye}$, $R_{Pass}$, $R_e$: $V_{e0}=%5.3f\cdot10^{%2d}$cm/s'
# plt.title(titleHeader % (mantV0,powV0),color='m',fontsize=16)
plt.title('Magnetized Collisions: $R_{Debye}$, $R_{Pass}$, $R_e$',color='m',fontsize=16)
plt.xlim(xLimit)
yLimit=[1.e-3,10.]
plt.ylim(yLimit)
plt.plot([relVeTrnsv,relVeTrnsv],yLimit,'--m',linewidth=1)
plt.text(1.6e-3,5.5e-4,'$ \Delta V_{e\perp}/ V_{e0}$',color='m',fontsize=14)
plt.plot([relVeLong,relVeLong],yLimit,'--m',linewidth=1)
plt.text(4.4e-5,0.001175,'$ \Delta V_{e||}/ V_{e0}$',color='m',fontsize=14)
plt.text(3.e-5,2.45e-3,'$R_e$',color='k',fontsize=16)
plt.text(3.e-5,5.e-2,'$R_{Debye}$',color='k',fontsize=16)
plt.text(3.e-5,1.8e-2,'$R_{Pass}$',color='k',fontsize=16)
plt.text(4.5e-5,4.8e-3,'$R_{Pass}$ $for$ $T_{e||}=0$',color='k',fontsize=16)
plt.text(8.3e-5,4.0,('$V_{e0}=%5.3f\cdot10^{%2d}$cm/s' % (mantV0,powV0)), \
color='m',fontsize=16)
if (saveFilesFlag == 1):
fig209.savefig('picturesCMA/rDebye_rLikeDebye_rPass_fig209cma.png')
print ('File "picturesCMA/rDebye_rLikeDebye_rPass_fig209cma.png" is written')
#
# Coulomb logarithm evaluation:
#
clmbLog = np.zeros(nVion)
for i in range(nVion):
clmbLog[i] = math.log(impctPrmtrMax[i]/impctPrmtrMin)
# clmbLog[i] = math.log(impctPrmtrMax_1[i]/impctPrmtrMin)
if (plotFigureFlag == 0):
fig3155=plt.figure (3155)
plt.semilogx(VionRel,clmbLog,'-xr',linewidth=2)
plt.xlabel('Relative Ion Velocity, $V_i/V_{e0}$',color='m',fontsize=14)
plt.ylabel('Coulomb Logarithm $L_c$',color='m',fontsize=14)
plt.title('Coulomb Logarithm: $L_c$ = $ln(R_{max}/R_{min})$',color='m',fontsize=16)
yLimit=[min(clmbLog)-.1,max(clmbLog)+.1]
plt.ylim(yLimit)
plt.plot([relVeTrnsv,relVeTrnsv],yLimit,'--m',linewidth=1)
plt.text(1.6e-3,5.,'$ \Delta V_{e\perp}/ V_{e0}$',color='m',fontsize=14)
plt.plot([relVeLong,relVeLong],yLimit,'--m',linewidth=1)
plt.text(3.4e-5,5.,'$ \Delta V_{e||}/ V_{e0}$',color='m',fontsize=14)
if (saveFilesFlag == 1):
fig3155.savefig('picturesCMA_v7/coulombLogrthm_fig3155cma.png')
print ('File "picturesCMA_v7/coulombLogrthm_fig3155cma.png" is written')
#
# matrix for electron with .5*timeStep_c:
#
matr_elec_c=guidingCenter_Matrix(.5*timeStep_c)
#
# matrix for ion with mass M_ion and .5*timeStep_c:
#
matr_ion_c=drift_Matrix(M_ion,.5*timeStep_c)
larmorTurns = 10
nImpctPrmtr = 50
rhoMin = impctPrmtrMin
rhoMax = np.zeros(nVion)
log10rhoMin = math.log10(rhoMin)
crrntImpctPrmtr = np.zeros(nImpctPrmtr)
halfLintr = np.zeros((nImpctPrmtr,nVion))
pointAlongTrack = np.zeros((nImpctPrmtr,nVion))
totalPoints = 0
for i in range(nVion):
rhoMax[i] = impctPrmtrMax[i]* \
np.sqrt(1.- (pi*larmorTurns*eVrmsLong/omega_L/impctPrmtrMax[i])**2)
rhoMax[i] = impctPrmtrMax[i]
# rhoMax[i] = impctPrmtrMax_1[i] # for checking!
# print ('rhoMax(%d) = %e' % (i,rhoMax[i]))
log10rhoMax = math.log10(rhoMax[i])
log10rhoStep = (log10rhoMax-log10rhoMin)/(nImpctPrmtr)
# print ('Vion(%d) = %e, rhoMax = %e' % (i,Vion[i],rhoMax[i]))
for n in range(nImpctPrmtr):
log10rhoCrrnt = log10rhoMin+(n+0.5)*log10rhoStep
rhoCrrnt = math.pow(10.,log10rhoCrrnt)
# print (' rhoCrrnt(%d) = %e' % (n,rhoCrrnt))
halfLintr[n,i] = np.sqrt(rhoMax[i]**2-rhoCrrnt**2) # half length of interaction; cm
timeHalfPath = halfLintr[n,i]/eVrmsLong # 0.5 time of interaction; sec
numbLarmor = int(2.*timeHalfPath/T_larm)
pointAlongTrack[n,i] = int(2.*timeHalfPath/timeStep_c)
totalPoints += pointAlongTrack[n,i]
# print (' %d: rhoCrrnt = %e, numbLarmor = %d, pointAlongTrack = %d' % \
# (n,rhoCrrnt,numbLarmor,pointAlongTrack[n,i]))
# print ('totalPoints = %d' % totalPoints)
totalPoints = int(totalPoints)
nnTotalPoints=np.arange(0,2*totalPoints-1,1)
arrayA=np.zeros(2*totalPoints)
arrayB=np.zeros(2*totalPoints)
bCrrnt_c = np.zeros(2*totalPoints)
#
# Variables for different testing:
#
b_gc = np.zeros(totalPoints)
action_gc = np.zeros(totalPoints)
C1test = np.zeros(totalPoints)
C2test = np.zeros(totalPoints)
C3test = np.zeros(totalPoints)
b_ME = np.zeros(totalPoints)
D1test = np.zeros(totalPoints)
D2test = np.zeros(totalPoints)
qTest = np.zeros(totalPoints)
action_ME = np.zeros(totalPoints)
actn_gc_ME_rel = np.zeros(totalPoints)
indxTest = 0
rhoInit = np.zeros((nImpctPrmtr,nVion))
#
# "Classical" approach:
#
deltaPx_c = np.zeros((nImpctPrmtr,nVion))
deltaPy_c = np.zeros((nImpctPrmtr,nVion))
deltaPz_c = np.zeros((nImpctPrmtr,nVion))
ionVx_c = np.zeros((nImpctPrmtr,nVion))
ionVy_c = np.zeros((nImpctPrmtr,nVion))
ionVz_c = np.zeros((nImpctPrmtr,nVion))
deltaEnrgIon_c = np.zeros((nImpctPrmtr,nVion))
#
# "Magnus Expand" approach:
#
deltaPx_m = np.zeros((nImpctPrmtr,nVion))
deltaPy_m = np.zeros((nImpctPrmtr,nVion))
deltaPz_m = np.zeros((nImpctPrmtr,nVion))
ionVx_m = np.zeros((nImpctPrmtr,nVion))
ionVy_m = np.zeros((nImpctPrmtr,nVion))
ionVz_m = np.zeros((nImpctPrmtr,nVion))
deltaEnrgIon_m = np.zeros((nImpctPrmtr,nVion))
#
# Comparison of approaches (ratio deltaEnrgIon_c/deltaEnrgIon_m):
#
deltaPx_c_m = np.zeros((nImpctPrmtr,nVion))
deltaPy_c_m = np.zeros((nImpctPrmtr,nVion))
deltaPz_c_m = np.zeros((nImpctPrmtr,nVion))
dEion_c_m = np.zeros((nImpctPrmtr,nVion))
#
# Factor to calculate transferred energy to ion
# (the friction force is defined by this transfered energy):
#
deFactor = 0.5/M_ion # 1/g
frctnForce_cSM = np.zeros(nVion) # integration, using Simpson method
frctnForce_mSM = np.zeros(nVion) # integration, using Simpson method
numberWrongSign_c=0
numberWrongSign_m=0
posSignDeltaEnrgIon_c=0
negSignDeltaEnrgIon_c=0
posSignDeltaEnrgIon_m=0
negSignDeltaEnrgIon_m=0
timeRun = np.zeros(nVion)
totalTimeRun = 0.
indx = 0
# ----------------- Main simulation ---------------
#
for i in range(nVion):
# Taking into account the corection of the maximal impact parameter
# on depence of preset number of minimal Larmor turns:
rhoMax[i] = impctPrmtrMax[i]* \
np.sqrt(1.- (pi*larmorTurns*eVrmsLong/omega_L/impctPrmtrMax[i])**2)
# Without taking into account the corection of the maximal impact parameter
# on depence of preset number of minimal Larmor turns:
rhoMax[i] = impctPrmtrMax[i]
# rhoMax[i] = impctPrmtrMax_1[i] # for checking!
log10rhoMax = math.log10(rhoMax[i])
log10rhoStep = (log10rhoMax-log10rhoMin)/(nImpctPrmtr)
# print ('Vion(%d) = %e, rhoMax = %e' % (i,Vion[i],rhoMax[i]))
timeStart=os.times()
for n in range(nImpctPrmtr):
log10rhoCrrnt = log10rhoMin+(n+0.5)*log10rhoStep
rhoCrrnt = math.pow(10.,log10rhoCrrnt)
# rhoInit[i*nImpctPrmtr+n] = rhoCrrnt
rhoInit[n,i] = rhoCrrnt
halfLintr[n,i] = np.sqrt(rhoMax[i]**2-rhoCrrnt**2) # half length of interaction; cm
z_ionCrrnt_c = np.zeros(6) # Zeroing out of vector for ion ("GC"-approach)
z_elecCrrnt_c = np.zeros(6) # Zeroing out of vector for electron ("GC"-approach)
z_ionCrrnt_m = | np.zeros(6) | numpy.zeros |
import numpy as np
import xarray as xr
import gcpy
# Must have:
# 1. extract_grid (returns an xarray Dataset)
# 2. grid_area (returns a 6xNxN array)
# 3. gen_grid (returns an xarray Dataset)
def extract_grid(ds,src_var='Xdim'):
# Extract grid from xarray dataset but return a cubed-sphere grid
n_cs = ds[src_var].shape[-1]
return gen_grid(n_cs)
def face_area(lon_b, lat_b, r_sphere = 6.375e6):
"""Calculate area of cubed-sphere grid cells on one face
Inputs must be in degrees. Edge arrays must be
shaped [N+1 x N+1]
"""
# Convert inputs to radians
lon_b_rad = lon_b * np.pi / 180.0
lat_b_rad = lat_b * np.pi / 180.0
r_sq = r_sphere * r_sphere
n_cs = lon_b.shape[1] - 1
# Allocate output array
cs_area = np.zeros((n_cs,n_cs))
# Ordering
valid_combo = np.array([[1,2,4],[2,3,1],[3,2,4],[4,1,3]]) - 1
for i_lon in range(n_cs):
for i_lat in range(n_cs):
lon_corner = np.zeros(4)
lat_corner = np.zeros(4)
xyz_corner = np.zeros((4,3))
for i_vert in range(4):
x_lon = i_lon + (i_vert > 1)
x_lat = i_lat + (i_vert == 0 or i_vert == 3)
lon_corner[i_vert] = lon_b_rad[x_lon,x_lat]
lat_corner[i_vert] = lat_b_rad[x_lon,x_lat]
for i_vert in range(4):
xyz_corner[i_vert,:] = ll2xyz(lon_corner[i_vert],lat_corner[i_vert])
tot_ang = 0.0
for i_corner in range(4):
curr_combo = valid_combo[i_corner,:]
xyz_mini = np.zeros((3,3))
for i_mini in range(3):
xyz_mini[i_mini,:] = xyz_corner[curr_combo[i_mini],:]
curr_ang = sphere_angle(xyz_mini[0,:],xyz_mini[1,:],xyz_mini[2,:])
tot_ang += curr_ang
cs_area[i_lon,i_lat] = r_sq * (tot_ang - (2.0*np.pi))
return cs_area
def ll2xyz(lon_pt,lat_pt):
"""Converts a lon/lat pair (in radians) to cartesian co-ordinates
Vector should point to the surface of the unit sphere"""
xPt = np.cos(lat_pt) * np.cos(lon_pt)
yPt = np.cos(lat_pt) * | np.sin(lon_pt) | numpy.sin |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Tests for linear_model extensions."""
import numpy as np
import pytest
import unittest
import warnings
from econml.sklearn_extensions.ensemble import SubsampledHonestForest
class TestSubsampledHonestForest(unittest.TestCase):
"""Test SubsampledHonestForest."""
def test_y1d(self):
np.random.seed(123)
n = 5000
d = 5
x_grid = | np.linspace(-1, 1, 10) | numpy.linspace |
import numpy as np
def py_SurfStatInd2Coord(ind, surf):
"""Converts a vertex index to x,y,z coordinates
Parameters
----------
ind : 2D numpy array of shape (1,c)
indices of vertex, 1-based
surf : a dictionary with key 'coord' OR 'lat', 'vox', 'origin'
surf['coord'] : 2D numpy array of shape (3,v), the coordinates.
or
surf['lat'] : 3D numpy array of 1's and 0's (1=in, 0=out).
surf['vox'] : 2D numpy array of shape (1,3),
voxel sizes in mm, [1,1,1] by default.
surf['origin'] : 2D numpy array of shape (1,3),
position of the first voxel in mm, [0,0,0] by default.
Returns
-------
coord : 2D numpy array of shape (3,c)
array of coordinates
"""
ind = ind.astype(int)
if 'coord' in surf.keys():
coord = surf['coord'][:,ind-1].squeeze()
if 'lat' in surf.keys():
if not 'vox' in surf:
surf['vox'] = np.ones((1,3))
if not 'origin' in surf.keys():
surf['origin'] = np.zeros((1,3))
vid = np.cumsum(surf['lat'].T.flatten()) * surf['lat'].T.flatten()
# implement matlab-ismember
loc = []
for i in range(0, ind.shape[1]):
loc.append(np.where(vid == ind[0,i])[0].tolist())
loc_flat = [item for sublist in loc for item in sublist]
dim = np.shape(surf['lat'])
i, j, k = np.unravel_index(loc_flat, dim, order='F')
coord = np.zeros((3, ind.shape[1]))
coord[0,:] = surf['origin'][0,0] + np.multiply(i, surf['vox'][0,0])
coord[1,:] = surf['origin'][0,1] + | np.multiply(j, surf['vox'][0,1]) | numpy.multiply |
import numpy as np
import pandas as pd
from typing import Set, List, Optional
from collections.abc import Collection
from dae.pedigrees.family import FamiliesData
from dae.pheno.common import MeasureType
from dae.pheno.pheno_db import Measure, PhenotypeData
class PersonFilter():
def __init__(self, criteria: str, values: Collection):
self.criteria: str = criteria
self.values: str = values
def _apply_to_df(self, df: pd.DataFrame) -> pd.DataFrame:
raise NotImplementedError()
def apply(
self, families: FamiliesData, roles: Optional[List[str]] = None
) -> Set[str]:
ped_df = families.ped_df.copy()
if roles is not None:
ped_df = ped_df.loc[ped_df["role"].astype(str).isin(roles)]
ped_df[self.criteria] = ped_df[self.criteria].astype(str)
ped_df = self._apply_to_df(ped_df)
return set(ped_df["person_id"])
class PersonFilterSet(PersonFilter):
def __init__(self, criteria: str, values: Collection):
super(PersonFilterSet, self).__init__(criteria, values)
assert type(values) in (list, set, tuple)
def _apply_to_df(self, df: pd.DataFrame) -> pd.DataFrame:
return df[df[self.criteria].isin(self.values)]
class PersonFilterRange(PersonFilter):
def __init__(self, criteria: str, values: Collection):
super(PersonFilterRange, self).__init__(criteria, values)
assert isinstance(values, list) or \
isinstance(values, tuple) or \
isinstance(values, set), \
f"{values} ({type(values)})"
if len(values) == 2:
assert isinstance(values, list) or isinstance(values, tuple)
self.values_min, self.values_max = values
else:
assert len(values) == 1
self.values_min = self.values_max = list(values)[0]
def _apply_to_df(self, df: pd.DataFrame) -> pd.DataFrame:
if self.values_min is not None and self.values_max is not None:
return df[
np.logical_and(
df[self.criteria] >= self.values_min,
df[self.criteria] <= self.values_max,
)
]
elif self.values_min is not None:
return df[df[self.criteria] >= self.values_min]
elif self.values_max is not None:
return df[df[self.criteria] <= self.values_max]
else:
return df[- | np.isnan(df[self.criteria]) | numpy.isnan |
import pandas as pd
import numpy as np
from .groundtruthcomparison import GroundTruthComparison
from .comparisontools import make_collision_events
class CollisionGTComparison(GroundTruthComparison):
"""
This class is an extension of GroundTruthComparison by focusing
to benchmark spike in collision
collision_lag: float
Collision lag in ms.
"""
def __init__(self, gt_sorting, tested_sorting, collision_lag=2.0, nbins=11, **kwargs):
# Force compute labels
kwargs['compute_labels'] = True
GroundTruthComparison.__init__(self, gt_sorting, tested_sorting, **kwargs)
self.collision_lag = collision_lag
self.nbins = nbins
self.detect_gt_collision()
self.compute_all_pair_collision_bins()
def detect_gt_collision(self):
delta = int(self.collision_lag / 1000 * self.sampling_frequency)
self.collision_events = make_collision_events(self.sorting1, delta)
def get_label_for_collision(self, gt_unit_id1, gt_unit_id2):
gt_index1 = self.sorting1.id_to_index(gt_unit_id1)
gt_index2 = self.sorting1.id_to_index(gt_unit_id2)
if gt_index1 > gt_index2:
gt_unit_id1, gt_unit_id2 = gt_unit_id2, gt_unit_id1
reversed = True
else:
reversed = False
# events
mask = (self.collision_events['unit_id1'] == gt_unit_id1) & (self.collision_events['unit_id2'] == gt_unit_id2)
event = self.collision_events[mask]
score_label1 = self._labels_st1[gt_unit_id1][event['index1']]
score_label2 = self._labels_st1[gt_unit_id2][event['index2']]
delta = event['delta_frame']
if reversed:
score_label1, score_label2 = score_label2, score_label1
delta = -delta
return score_label1, score_label2, delta
def get_label_count_per_collision_bins(self, gt_unit_id1, gt_unit_id2, bins):
score_label1, score_label2, delta = self.get_label_for_collision(gt_unit_id1, gt_unit_id2)
tp_count1 = np.zeros(bins.size - 1)
fn_count1 = np.zeros(bins.size - 1)
tp_count2 = np.zeros(bins.size - 1)
fn_count2 = np.zeros(bins.size - 1)
for i in range(tp_count1.size):
l0, l1 = bins[i], bins[i + 1]
mask = (delta >= l0) & (delta < l1)
tp_count1[i] = np.sum(score_label1[mask] == 'TP')
fn_count1[i] = np.sum(score_label1[mask] == 'FN')
tp_count2[i] = np.sum(score_label2[mask] == 'TP')
fn_count2[i] = np.sum(score_label2[mask] == 'FN')
# inverse for unit_id2
tp_count2 = tp_count2[::-1]
fn_count2 = fn_count2[::-1]
return tp_count1, fn_count1, tp_count2, fn_count2
def compute_all_pair_collision_bins(self):
d = int(self.collision_lag / 1000 * self.sampling_frequency)
bins = np.linspace(-d, d, self.nbins+1)
self.bins = bins
unit_ids = self.sorting1.unit_ids
n = len(unit_ids)
all_tp_count1 = []
all_fn_count1 = []
all_tp_count2 = []
all_fn_count2 = []
self.all_tp = np.zeros((n, n, self.nbins), dtype='int64')
self.all_fn = np.zeros((n, n, self.nbins), dtype='int64')
for i in range(n):
for j in range(i+1, n):
u1 = unit_ids[i]
u2 = unit_ids[j]
tp_count1, fn_count1, tp_count2, fn_count2 = self.get_label_count_per_collision_bins(u1, u2, bins)
self.all_tp[i, j, :] = tp_count1
self.all_tp[j, i, :] = tp_count2
self.all_fn[i, j, :] = fn_count1
self.all_fn[j, i, :] = fn_count2
def compute_collision_by_similarity(self, similarity_matrix, unit_ids=None, good_only=False):
if unit_ids is None:
unit_ids = self.sorting1.unit_ids
n = len(unit_ids)
recall_scores = []
similarities = []
pair_names = []
for r in range(n):
for c in range(r + 1, n):
u1 = unit_ids[r]
u2 = unit_ids[c]
ind1 = self.sorting1.id_to_index(u1)
ind2 = self.sorting1.id_to_index(u2)
tp1 = self.all_tp[ind1, ind2, :]
fn1 = self.all_fn[ind1, ind2, :]
recall1 = tp1 / (tp1 + fn1)
recall_scores.append(recall1)
similarities.append(similarity_matrix[r, c])
pair_names.append(f'{u1} {u2}')
tp2 = self.all_tp[ind2, ind1, :]
fn2 = self.all_fn[ind2, ind1, :]
recall2 = tp2 / (tp2 + fn2)
recall_scores.append(recall2)
similarities.append(similarity_matrix[r, c])
pair_names.append(f'{u2} {u1}')
recall_scores = np.array(recall_scores)
similarities = np.array(similarities)
pair_names = np.array(pair_names)
order = | np.argsort(similarities) | numpy.argsort |
# Lint as: python3
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for lingvo Jax transformer layers."""
import itertools
from absl import logging
from absl.testing import absltest
from absl.testing import parameterized
import jax
from jax import numpy as jnp
from jax import test_util
from lingvo.core import batch_major_attention
from lingvo.jax import base_layer
from lingvo.jax import py_utils
from lingvo.jax import test_utils
from lingvo.jax.layers import attentions
from lingvo.jax.layers import transformers
import numpy as np
import tensorflow.compat.v2 as tf
class TransformersTest(test_util.JaxTestCase):
def setUp(self):
super().setUp()
np.random.seed(123456)
tf.random.set_seed(123)
@parameterized.parameters(*list(itertools.product([True, False], repeat=3)))
def test_transformer_layer(self, mask_self_attention, packed_input,
cross_attention):
p = transformers.TransformerLayer.Params().Set(
name='jax_transformer_layer',
input_dims=32,
hidden_dims=128,
num_heads=8,
mask_self_attention=mask_self_attention,
packed_input=packed_input,
cross_attention=cross_attention)
seq_len = np.random.randint(10, 32)
batch_size = 10
transformer_layer = p.Instantiate()
prng_key = jax.random.PRNGKey(seed=123)
initial_vars = transformer_layer.InstantiateVariables(prng_key)
npy_inputs = np.random.normal(
1.0, 0.5, [batch_size, seq_len, p.input_dims]).astype('float32')
inputs = jnp.asarray(npy_inputs)
npy_paddings = np.random.randint(0, 1,
[batch_size, seq_len]).astype('float32')
paddings = jnp.asarray(npy_paddings)
causal_mask = None
segment_mask = None
tf_segment_mask = None
attention_mask = attentions.ConvertPaddingsToMask(paddings)
if mask_self_attention:
causal_mask = attentions.CausalMask(inputs)
attention_mask = jnp.minimum(attention_mask, causal_mask)
if packed_input:
segment_ids = np.random.random_integers(0, 2, [batch_size, seq_len])
segment_mask = attentions.SegmentMask(segment_ids, dtype=np.float32)
attention_mask = jnp.minimum(attention_mask, segment_mask)
if mask_self_attention:
tf_segment_mask = batch_major_attention.CausalSegmentMask(
segment_ids, tf.float32)
else:
tf_segment_mask = batch_major_attention.SegmentMask(
segment_ids, segment_ids)
cross_inputs = None
cross_attention_mask = None
tf_cross_inputs = None
tf_cross_paddings = None
tf_cross_segment_mask = None
if cross_attention:
cross_seq_len = np.random.randint(10, 128)
npy_cross_inputs = np.random.normal(
1.0, 0.5, [batch_size, cross_seq_len, p.input_dims]).astype('float32')
cross_inputs = jnp.asarray(npy_cross_inputs)
tf_cross_inputs = tf.constant(npy_cross_inputs, dtype=tf.float32)
npy_cross_paddings = np.random.randint(
0, 1, [batch_size, cross_seq_len]).astype('float32')
cross_paddings = jnp.asarray(npy_cross_paddings)
cross_attention_mask = attentions.ConvertPaddingsToMask(cross_paddings)
tf_cross_paddings = tf.constant(npy_cross_paddings, dtype=tf.float32)
if packed_input:
source_segment_ids = np.random.random_integers(
0, 2, [batch_size, cross_seq_len])
cross_segment_mask = attentions.SegmentMask(
segment_ids, source_segment_ids, dtype=np.float32)
cross_attention_mask = jnp.minimum(cross_attention_mask,
cross_segment_mask)
tf_cross_segment_mask = batch_major_attention.SegmentMask(
segment_ids, source_segment_ids)
with base_layer.JaxContext.NewContext(
prng_key=prng_key, global_step=jnp.array(0, dtype=jnp.uint32)):
outputs, _ = transformer_layer.FProp(
initial_vars,
inputs,
paddings,
attention_mask=attention_mask,
cross_inputs=cross_inputs,
cross_attention_mask=cross_attention_mask)
logging.info('initial_vars in transformer layer = %s', initial_vars)
# Test whether tf Transformer layer returns same output
# Modify initial_vars to use TF compatible params
tf_initial_vars = test_utils.ReplaceJaxAttentionVarsToTf(
initial_vars, cross_attention)
tf_initial_vars = test_utils.ToTfNmap(tf_initial_vars)
logging.info('tf_initial_vars in transformer layer = %s', initial_vars)
tf_p = batch_major_attention.TransformerLayer.Params().Set(
name='tf_transformer_layer',
input_dim=p.input_dims,
num_heads=p.num_heads,
mask_self_atten=mask_self_attention,
packed_input=packed_input,
has_aux_atten=cross_attention)
tf_p.tr_fflayer_tpl.hidden_dim = p.hidden_dims
tf_p.tr_fflayer_tpl.fflayer_tpl.batch_norm = False
tf_p.tr_fflayer_tpl.fflayer_tpl.has_bias = True
tf_transformer_layer = tf_p.Instantiate()
tf_output, _ = tf_transformer_layer.FProp(
tf_initial_vars,
tf.constant(npy_inputs, dtype=tf.float32),
paddings=test_utils.ToTfNmap(npy_paddings),
segment_mask=tf_segment_mask,
aux_vec=tf_cross_inputs,
aux_paddings=tf_cross_paddings,
aux_segment_mask=test_utils.ToTfNmap(tf_cross_segment_mask))
np_outputs = test_utils.ToNp(outputs)
tf_np_outputs = test_utils.ToNp(tf_output)
self.assertAllClose(tf_np_outputs, np_outputs, atol=1e-5)
@parameterized.parameters((True, True), (False, True), (True, False),
(False, False))
def test_transformer_layer_extendstep(self, packed_input, cross_attention):
p = transformers.TransformerLayer.Params().Set(
name='jax_transformer_layer',
input_dims=8,
hidden_dims=32,
num_heads=4,
mask_self_attention=True,
packed_input=packed_input,
cross_attention=cross_attention)
seq_len = 5
batch_size = 4
transformer_layer = p.Instantiate()
prng_key = jax.random.PRNGKey(seed=123)
initial_vars = transformer_layer.InstantiateVariables(prng_key)
initial_states = transformer_layer.InitStates(initial_vars, batch_size,
seq_len)
npy_inputs = np.random.normal(
1.0, 0.5, [batch_size, seq_len, p.input_dims]).astype('float32')
inputs = jnp.asarray(npy_inputs)
npy_paddings = np.random.randint(0, 1,
[batch_size, seq_len]).astype('float32')
paddings = jnp.asarray(npy_paddings)
attention_mask = attentions.ConvertPaddingsToMask(paddings)
segment_mask = None
causal_mask = attentions.CausalMask(inputs)
attention_mask = jnp.minimum(causal_mask, attention_mask)
if packed_input:
segment_ids = np.random.random_integers(0, 2, [batch_size, seq_len])
segment_mask = attentions.SegmentMask(segment_ids, dtype=np.float32)
attention_mask = jnp.minimum(attention_mask, segment_mask)
cross_inputs = None
cross_paddings = None
cross_attention_mask = None
if cross_attention:
cross_seq_len = np.random.randint(10, 32)
npy_cross_inputs = np.random.normal(
1.0, 0.5, [batch_size, cross_seq_len, p.input_dims]).astype('float32')
cross_inputs = jnp.asarray(npy_cross_inputs)
npy_cross_paddings = np.random.randint(
0, 1, [batch_size, cross_seq_len]).astype('float32')
cross_paddings = jnp.asarray(npy_cross_paddings)
cross_attention_mask = attentions.ConvertPaddingsToMask(cross_paddings)
if packed_input:
source_segment_ids = np.random.random_integers(
0, 2, [batch_size, cross_seq_len])
cross_segment_mask = attentions.SegmentMask(
segment_ids, source_segment_ids, dtype=np.float32)
cross_attention_mask = jnp.minimum(cross_attention_mask,
cross_segment_mask)
with base_layer.JaxContext.NewContext(
prng_key=prng_key, global_step=jnp.array(0, dtype=jnp.uint32)):
fprop_outputs, _ = transformer_layer.FProp(
initial_vars,
inputs,
paddings,
attention_mask=attention_mask,
cross_inputs=cross_inputs,
cross_attention_mask=cross_attention_mask)
decoder_outputs = jnp.zeros(shape=[seq_len, batch_size, p.input_dims])
atten_states = initial_states
for t in range(seq_len):
attention_mask_t = attention_mask[:, :, t, :]
cross_attention_mask_t = cross_attention_mask
if cross_attention:
cross_attention_mask_t = cross_attention_mask[:, :, t, :]
cross_attention_mask_t = np.expand_dims(
cross_attention_mask_t, axis=2)
atten_states, encoded = transformer_layer.ExtendStep(
initial_vars,
atten_states,
inputs=inputs[:, t, :],
time_step=t,
attention_mask=attention_mask_t,
cross_inputs=cross_inputs,
cross_attention_mask=cross_attention_mask_t)
decoder_outputs = decoder_outputs.at[t].set(encoded)
decoder_out_transposed = jnp.transpose(decoder_outputs, [1, 0, 2])
logging.info('initial_vars in transformer layer = %s', initial_vars)
np_fprop_outputs = test_utils.ToNp(fprop_outputs)
np_decoder_outputs = test_utils.ToNp(decoder_out_transposed)
self.assertAllClose(np_fprop_outputs, np_decoder_outputs, atol=1e-5)
@parameterized.parameters((True, True, True), (True, False, True),
(True, True, False), (False, True, True),
(True, False, False), (False, True, False),
(False, False, True), (False, False, False))
def test_stacked_transformer_layer(self, mask_self_attention, packed_input,
cross_attention):
p = transformers.StackedTransformerLayers.Params().Set(
name='jax_stacked_transformer_layer',
model_dims=16,
hidden_dims=64,
num_heads=8,
mask_self_attention=mask_self_attention,
num_layers=4,
packed_input=packed_input,
cross_attention=cross_attention)
seq_len = np.random.randint(10, 32)
batch_size = 10
stacked_transformer_layer = p.Instantiate()
prng_key = jax.random.PRNGKey(seed=123)
initial_vars = stacked_transformer_layer.InstantiateVariables(prng_key)
npy_inputs = np.random.normal(
1.0, 0.5, [batch_size, seq_len, p.model_dims]).astype('float32')
inputs = jnp.asarray(npy_inputs)
npy_paddings = np.random.randint(0, 1,
[batch_size, seq_len]).astype('float32')
paddings = jnp.asarray(npy_paddings)
segment_mask = None
tf_segment_mask = None
if packed_input:
segment_ids = np.random.random_integers(0, 2, [batch_size, seq_len])
segment_mask = attentions.SegmentMask(segment_ids, dtype=np.float32)
if mask_self_attention:
tf_segment_mask = batch_major_attention.CausalSegmentMask(
segment_ids, tf.float32)
else:
tf_segment_mask = batch_major_attention.SegmentMask(
segment_ids, segment_ids)
cross_inputs = None
cross_paddings = None
cross_segment_mask = None
tf_cross_inputs = None
tf_cross_paddings = None
tf_cross_segment_mask = None
if cross_attention:
cross_seq_len = np.random.randint(10, 64)
npy_cross_inputs = np.random.normal(
1.0, 0.5, [batch_size, cross_seq_len, p.model_dims]).astype('float32')
cross_inputs = jnp.asarray(npy_cross_inputs)
tf_cross_inputs = tf.constant(npy_cross_inputs, dtype=tf.float32)
npy_cross_paddings = np.random.randint(
0, 1, [batch_size, cross_seq_len]).astype('float32')
cross_paddings = jnp.asarray(npy_cross_paddings)
tf_cross_paddings = tf.constant(npy_cross_paddings, dtype=tf.float32)
if packed_input:
source_segment_ids = np.random.random_integers(
0, 2, [batch_size, cross_seq_len])
cross_segment_mask = attentions.SegmentMask(
segment_ids, source_segment_ids, dtype=np.float32)
tf_cross_segment_mask = batch_major_attention.SegmentMask(
segment_ids, source_segment_ids)
with base_layer.JaxContext.NewContext(
prng_key=prng_key, global_step=jnp.array(0, dtype=jnp.uint32)):
outputs = stacked_transformer_layer.FProp(
initial_vars,
inputs,
paddings,
segment_mask=segment_mask,
cross_inputs=cross_inputs,
cross_paddings=cross_paddings,
cross_segment_mask=cross_segment_mask)
logging.info('initial_vars in transformer layer = %s', initial_vars)
# Test whether tf Transformer layer returns same output
# Modify initial_vars to use TF compatible params
tf_initial_vars = py_utils.NestedMap()
tf_initial_vars.x_layers = []
for jax_initial_vars in initial_vars.x_layers:
tf_layer_vars = test_utils.ReplaceJaxAttentionVarsToTf(
jax_initial_vars, cross_attention)
tf_initial_vars.x_layers.append(tf_layer_vars)
tf_initial_vars = test_utils.ToTfNmap(tf_initial_vars)
logging.info('tf_initial_vars in transformer layer = %s', initial_vars)
tf_p = batch_major_attention.StackedTransformerLayers.Params().Set(
name='tf_transformer_layer',
mdl_dim=p.model_dims,
hidden_dim=p.hidden_dims,
num_atten_heads=p.num_heads,
mask_self_atten=mask_self_attention,
num_layers=p.num_layers,
packed_input=packed_input,
has_aux_atten=cross_attention)
tf_p.transformer_layer_params_tpl.tr_fflayer_tpl.fflayer_tpl.batch_norm = (
False)
tf_p.transformer_layer_params_tpl.tr_fflayer_tpl.fflayer_tpl.has_bias = True
tf_stacked_transformer_layer = tf_p.Instantiate()
tf_output, _ = tf_stacked_transformer_layer.FProp(
tf_initial_vars,
test_utils.ToTfNmap(npy_inputs),
paddings=test_utils.ToTfNmap(npy_paddings),
segment_mask=test_utils.ToTfNmap(tf_segment_mask),
aux_vec=test_utils.ToTfNmap(tf_cross_inputs),
aux_paddings=test_utils.ToTfNmap(tf_cross_paddings),
aux_segment_mask=test_utils.ToTfNmap(tf_cross_segment_mask))
np_outputs = test_utils.ToNp(outputs)
tf_np_outputs = test_utils.ToNp(tf_output)
self.assertAllClose(tf_np_outputs, np_outputs, atol=1e-5)
@parameterized.parameters(*list(itertools.product([True, False], repeat=3)))
def test_repeated_stacked_xformer_layer(self, mask_self_attention,
packed_input, cross_attention):
model_dims = 16
p1 = transformers.StackedTransformerLayers.Params().Set(
name='jax_stacked_transformer_layer',
model_dims=model_dims,
hidden_dims=64,
num_heads=8,
mask_self_attention=mask_self_attention,
num_layers=4,
packed_input=packed_input,
cross_attention=cross_attention)
p2 = transformers.StackedTransformerLayersRepeated.Params().Set(
name='jax_stacked_transformer_layer_repeated',
model_dims=model_dims,
hidden_dims=64,
num_heads=8,
mask_self_attention=mask_self_attention,
num_layers=4,
packed_input=packed_input,
cross_attention=cross_attention)
seq_len = | np.random.randint(10, 32) | numpy.random.randint |
from __future__ import print_function
# Maintain a live constrained delaunay triangulation of the grid.
# designed as a mixin
from collections import defaultdict, Iterable
import logging
log = logging.getLogger('stompy.live_dt')
import pdb
import numpy as np
from numpy.linalg import norm,solve
from matplotlib import collections
import matplotlib.pyplot as plt
from .. import utils
from ..utils import array_append
from ..spatial import field,robust_predicates
from . import orthomaker,trigrid,exact_delaunay
def ray_intersection(p0,vec,pA,pB):
d1a = np.array([pA[0]-p0[0],pA[1]-p0[1]])
# alpha * vec + beta * ab = d1a
# | vec[0] ab[0] | | alpha | = | d1a[0] |
# | vec[1] ab[1] | | beta | = | d1a[1] |
A = np.array( [[vec[0], pB[0] - pA[0]],
[vec[1], pB[1] - pA[1]]] )
alpha_beta = solve(A,d1a)
return p0 + alpha_beta[0]*np.asarray(vec)
class MissingConstraint(Exception):
pass
def distance_left_of_line(pnt, qp1, qp2):
# return the signed distance for where pnt is located left of
# of the line qp1->qp2
# we don't necessarily get the real distance, but at least something
# with the right sign, and monotonicity
vec = qp2 - qp1
left_vec = np.array( [-vec[1],vec[0]] )
return (pnt[0] - qp1[0])*left_vec[0] + (pnt[1]-qp1[1])*left_vec[1]
class LiveDtGridNull(orthomaker.OrthoMaker):
""" absolute minimum, do-nothing stand-in for LiveDtGrid implementations.
probably not useful, and definitely not complete
"""
has_dt = 0
pending_conflicts = []
def hold(self):
pass
def release(self):
pass
def delaunay_neighbors(self,n):
return []
LiveDtGrid=LiveDtGridNull # will be set to the "best" implementation below
class LiveDtGridBase(orthomaker.OrthoMaker):
"""
A mixin which adds a live-updated constrained Delaunay
triangulation to shadow the grid, aiding in various geometric
queries. Similar in spirit to ShadowCDT, but this is an older
code designed explicitly for use with paver, and originally
only using CGAL for the triangulation.
This is the abstract base class, which can either use a CGAL
implementation or a pure-python implementation in subclasses
below.
This mixin maintains the mapping between nodes in self, and
the vertices in the shadow Delaunay triangulation.
self.vh[n] maps a trigrid node n to the "handle" for a Delaunay
vertex.
self.vh_info[vh] provides the reverse mapping, from a Delaunay
vertex handle to a node
"""
has_dt = 1
# if true, skips graph API handling
freeze=0
# if true, stores up modified nodes and edges, and
# updates all at once upon release
holding = 0
# queue of conflicting edges that have been un-constrained to allow for
# an add_edge() to proceed
pending_conflicts = []
edges_to_release = None
# triangles in the "medial axis" with a radius r < density/scale_ratio_for_cutoff
# will be removed.
# the meaning of this has changed slightly - 1/9/2013
# now it is roughly the number of cells across a channel to make room for.
# so at 1.0 it will retain channels which are one cell wide (actually there's a
# bit of slop - room for 1.3 cells or so).
# at 2.0, you should get 2-3 cells across.
scale_ratio_for_cutoff = 1.0
# even though in some cases the vertex handle type is more like int32,
# leave this as object so that None can be used as a special value.
vh_dtype='object' # used in allocating
def __init__(self,*args,**kwargs):
super(LiveDtGridBase,self).__init__(*args,**kwargs)
self.populate_dt()
check_i = 0
def check(self):
return
print(" --checkplot %05i--"%self.check_i)
plt.figure(10)
plt.clf()
self.plot_dt()
if self.default_clip is not None:
self.plot_nodes()
plt.axis(self.default_clip)
plt.title("--checkplot %05i--"%self.check_i)
plt.savefig('tmp/dtframe%05i.png'%self.check_i)
self.check_i += 1
plt.close(10)
def refresh_metadata(self):
""" Should be called when all internal state is changed outside
the mechanisms of add_X, delete_X, move_X, etc.
"""
super(LiveDtGridBase,self).refresh_metadata()
self.populate_dt()
def populate_dt(self):
""" Initialize a triangulation with all current edges and nodes.
"""
# print("populate_dt: top")
self.dt_allocate()
self.vh = np.zeros( (self.Npoints(),), self.vh_dtype)
self.vh[:]=None # 0 isn't actually a good mark for unused.
# sometimes CGAL creates vertices automatically, which are detected by
# having info == None
self.vh_info = defaultdict(lambda:None)
# print("populate_dt: adding points")
for n in range(self.Npoints()):
if n % 50000==0:
log.info("populate_dt: %d/%d"%(n,self.Npoints()))
# skip over deleted points:
if np.isfinite(self.points[n,0]):
self.dt_insert(n)
# print("populate_dt: add constraints")
for e in range(self.Nedges()):
if e % 50000==0:
log.info("populate_dt: %d/%d"%(e,self.Nedges()))
a,b = self.edges[e,:2]
if a>=0 and b>=0: # make sure we don't insert deleted edges
self.safe_insert_constraint(a,b)
# print("populate_dt: end")
def safe_insert_constraint(self,a,b):
""" adds a constraint to the DT, but does a few simple checks first
if it's not safe, raise an Exception
"""
if a < 0 or b < 0 or a==b:
raise Exception("invalid node indices: %d %d"%(a,b))
if all(self.points[a] == self.points[b]):
raise Exception("invalid constraint: points[%d]=%s and points[%d]=%s are identical"%(a,self.points[a],
b,self.points[b]))
if self.verbose > 2:
print(" Inserting constraint (populate_dt): %d %d %s %s"%(a,b,self.vh[a],self.vh[b]))
print(" node A=%s node B=%s"%(self.points[a],self.points[b]))
print(" A.point=%s B.point=%s"%(self.vh[a].point(), self.vh[b].point()))
self.dt_insert_constraint(a,b)
# double check to make sure that it's actually in there...
found_it=0
for edge in self.dt_incident_constraints(self.vh[a]):
v1,v2 = edge.vertices()
if v1==self.vh[b] or v2==self.vh[b]:
found_it = 1
break
if not found_it:
# we have a conflict - search from a to b
msg="Just tried to insert a constraint %d-%d (%s - %s), but it's not there!"%(a,b,
self.points[a],
self.points[b])
raise MissingConstraint(msg)
## Hold/release
def hold(self):
if self.holding == 0:
self.holding_nodes = {}
self.holding += 1
def release(self):
if self.holding == 0:
raise Exception("Tried to release, but holding is already 0")
self.holding -= 1
if self.holding == 0:
# First, make sure that we have enough room for new nodes:
while len(self.vh) < self.Npoints():
# This used to extend with 0, but None is a better option
self.vh = array_append(self.vh,None)
held_nodes = list(self.holding_nodes.keys())
# Remove all of the nodes that were alive when we started
# the hold:
for n in held_nodes:
# first, it was != 0.
# then it was "is not 0"
# but with exact_delaunay, 0 is a valid vertex handle.
if self.vh[n] is not None: # used to != 0
self.dt_remove_constraints(self.vh[n])
self.dt_remove(n) # that's correct, pass trigrid node index
# Add back the ones that are currently valid
for n in held_nodes:
if np.isfinite(self.points[n,0]):
self.dt_insert(n)
# Add back edges for each one
held_edges = {}
for n in held_nodes:
for e in self.pnt2edges(n):
held_edges[e] = 1
self.edges_to_release = list(held_edges.keys())
while len(self.edges_to_release) > 0:
e = self.edges_to_release.pop()
# call dt_add_edge to get all of the conflicting-edge-detecting
# functionality.
self.dt_add_edge(e)
self.edges_to_release = None
self.holding_nodes=0
return self.holding
def dt_update(self,n):
if self.verbose > 2:
print(" dt_update TOP: %d"%n)
self.check()
# have to remove any old constraints first:
n_removed = 0
to_remove = []
# probably unnecessary, but queue the deletions to avoid any possibility
# of confusing the iterator
for edge in self.dt_incident_constraints(self.vh[n]):
n_removed += 1
v1,v2 = edge.vertices()
vi1 = self.vh_info[v1]
vi2 = self.vh_info[v2]
to_remove.append( (edge, vi1, vi2) )
if self.verbose > 2:
# weird stuff is happening in here, so print out some extra
# info
print(" dt_update: found old constraint %s-%s"%(vi1,vi2))
if n_removed != len(self.pnt2edges(n)):
print(" WARNING: was going to remove them, but n_removed=%d, but pnt2edges shows"%n_removed)
# How many of this point's edges are in the queue to be added?
count_unreleased = 0
if self.edges_to_release:
for e in self.pnt2edges(n):
if e in self.edges_to_release:
count_unreleased += 1
if n_removed + count_unreleased != len(self.pnt2edges(n)):
print(self.edges[self.pnt2edges(n),:2])
print("Even after counting edges that are queued for release, still fails.")
raise Exception("Something terrible happened trying to update a node")
for edge,a,b in to_remove:
self.dt_remove_constrained_edge(edge)
self.dt_remove(n)
self.dt_insert(n)
# add back any of the constraints that we removed.
# This used to add all constraints involving n, but if we are in the middle
# of a release, pnt2edges() will not necessarily give the same edges as
# constraints
all_pairs = []
for edge,a,b in to_remove:
all_pairs.append( (a,b) )
self.safe_insert_constraint(a,b)
n_removed -= 1
if n_removed != 0:
print(" WARNING: in updating node %d, removed-added=%d"%(n,n_removed))
print(" Inserted edges were ",all_pairs)
raise Exception("why does this happen?")
if self.verbose > 2:
print(" dt_update END: %d"%n)
self.check()
def dt_add_edge(self,e):
""" Add the edge, indexed by integer e and assumed to exist in the grid,
to the Delaunay triangulation. This method is a bit sneaky, and in dire
situations tries to adjust the geometry to allow an otherwise invalid
edge to be inserted.
Not a good design, but this is old code.
"""
a,b = self.edges[e,:2]
#-#-# Try to anticipate unsafe connections
for i in range(3): # try a few times to adjust the conflicting nodes
constr_edges = self.check_line_is_clear(a,b)
if len(constr_edges)>0:
print("--=-=-=-=-=-= Inserting this edge %d-%d will cause an intersection -=-=-=-=-=-=-=--"%(a,b))
for v1,v2 in constr_edges:
# use %s formats as values could be None
print(" intersects constrained edge: %s - %s"%(self.vh_info[v1],self.vh_info[v2]))
if self.verbose > 1:
if i==0:
self.plot(plot_title="About to prepare_conflicting_edges")
plt.plot(self.points[[a,b],0],
self.points[[a,b],1],'m')
# Debugging:
# raise Exception,"Stopping before trying to fix conflicting edges"
self.prepare_conflicting_edges(e,constr_edges)
else:
break
#-#-#
self.safe_insert_constraint(a,b)
if a>b:
a,b=b,a
if self.verbose > 2:
print(" dt_add_edge: adding constraint %d->%d"%(a,b))
self.check()
def prepare_conflicting_edges(self,e,constr_edges):
"""
If an edge to be inserted is not valid, try to adjust one or more nodes
in a small way to make it clear. This approach is clearly stepping outside
the bounds of good program flow.
"""
# First figure out which side is "open"
# We should only be called when the data in self.edges has already
# been taken care of, so it should be safe to just consult our cell ids.
a,b = self.edges[e,:2]
# arrange for a -> b to have the open side to its right
if self.edges[e,3] >= 0 and self.edges[e,4] >= 0:
print("prepare_conflicting_edges: both sides are closed!")
return
if self.edges[e,3] == -1 and self.edges[e,4] != -1:
a,b = b,a
elif self.edges[e,4] == -1:
pass
elif self.edges[e,3] == -2 and self.edges[e,4] != -2:
a,b = b,a
# otherwise it's already in the correct orientation
print("prepare_conflicting_edges: proceeding for edge %d-%d"%(a,b))
AB = self.points[b] - self.points[a]
open_dir = np.array( [AB[1],-AB[0]] )
mag = np.sqrt(AB[0]**2+AB[1]**2)
AB /= mag
open_dir /= mag
to_move = [] # node index for nodes that need to be moved.
for cgal_edge in constr_edges:
vh_c,vh_d = cgal_edge
c = self.vh_info[vh_c]
d = self.vh_info[vh_d]
if c is None:
print("No node data for conflicting vertex %s"%vh_c)
continue
if d is None:
print("No node data for conflicting vertex %s"%vh_d)
continue
# 2. which one is on the closed side?
c_beta = np.dot( self.points[c] - self.points[a],
open_dir)
d_beta = np.dot( self.points[d] - self.points[a],
open_dir)
if c_beta < 0 and d_beta >= 0:
to_move.append(c)
elif d_beta < 0 and c_beta >= 0:
to_move.append(d)
else:
print("Neither node in conflicting edge appears to be on the closed side")
to_move = np.unique(to_move)
eps = mag / 50.0
for n in to_move:
beta = np.dot( self.points[n] - self.points[a], open_dir)
if beta >= 0:
raise Exception("Only nodes with beta<0 should be in this list!")
new_point = self.points[n] - (beta-eps)*open_dir
print("prepare_conflicting_edges: Moving node %d to %s"%(n,new_point))
self.move_node(n,new_point)
def dt_remove_edge(self,e,nodes=None):
""" Remove the given edge from the triangulation. In cases
where the edge e has already been updated with different nodes,
pass in nodes as [a,b] to remove the edge as it was.
"""
if nodes is not None:
a,b = nodes
else:
a,b = self.edges[e,:2]
#-# DBG
if a>b:
a,b=b,a
if self.verbose > 2:
print(" remove constraint %d->%d"%(a,b))
self.check()
#-# /DBG
# have to figure out the face,index for this edge
found_edge = 0
for edge in self.dt_incident_constraints(self.vh[a]):
v1,v2 = edge.vertices()
if self.vh[b] == v1 or self.vh[b] == v2:
self.dt_remove_constrained_edge(edge)
return
raise MissingConstraint("Tried to remove edge %i, but it wasn't in the constrained DT"%e)
#-#-# API for adding/moving/deleting
#-# NODES
def add_node(self,P):
n = super(LiveDtGridBase,self).add_node(P)
if self.freeze:
pass
elif self.holding:
self.holding_nodes[n] = 'add_node'
else:
self.vh = array_append(self.vh,None)
self.dt_insert(n)
# tricky - a new node may interrupt some existing
# constraint, but when the node is removed the
# constraint is not remembered - so check for that
# explicitly -
interrupted_edge = []
for edge in self.dt_incident_constraints(self.vh[n]):
a,b = edge.vertices()
if self.vh_info[a] != n:
interrupted_edge.append(self.vh_info[a])
else:
interrupted_edge.append(self.vh_info[b])
if len(interrupted_edge):
self.push_op(self.uninterrupt_constraint,interrupted_edge)
return n
def uninterrupt_constraint(self,ab):
print("Uninterrupting a constraint. Yes!")
self.safe_insert_constraint(ab[0],ab[1])
def unmodify_edge(self, e, old_data):
""" a bit unsure of this... I don't know exactly where this
gets done the first time
"""
a,b = self.edges[e,:2]
n = super(LiveDtGridBase,self).unmodify_edge(e,old_data)
if a!=old_data[0] or b!=old_data[1]:
print("unmodifying live_dt edge")
self.safe_insert_constraint(old_data[0],old_data[1])
def unadd_node(self,old_length):
if self.freeze:
pass
elif self.holding:
for i in range(old_length,len(self.points)):
self.holding_nodes[i] = 'unadd'
else:
for i in range(old_length,len(self.points)):
self.dt_remove(i)
self.vh = self.vh[:old_length]
super(LiveDtGridBase,self).unadd_node(old_length)
if not (self.freeze or self.holding):
print("HEY - this would be a good time to refresh the neighboring constraints")
def delete_node(self,i,*args,**kwargs):
# there is a keyword argument, remove_edges
# does that need to be interpreted here?
if self.freeze:
pass
elif self.holding:
self.holding_nodes[i] = 'delete_node'
super(LiveDtGridBase,self).delete_node(i,*args,**kwargs)
if not self.freeze and not self.holding:
self.dt_remove( i )
def undelete_node(self,i,p):
super(LiveDtGridBase,self).undelete_node(i,p)
if self.freeze:
pass
elif self.holding:
self.holding_nodes[i] = 'undelete'
else:
self.dt_insert(i)
def unmove_node(self,i,orig_val):
super(LiveDtGridBase,self).unmove_node(i,orig_val)
if self.freeze:
pass
elif self.holding:
self.holding_nodes[i] = 'unmove'
else:
self.dt_update(i)
def move_node(self,i,new_pnt,avoid_conflicts=True):
""" avoid_conflicts: if the new location would cause a
self-intersection, don't move it so far...
if the location is modified, return the actual location, otherwise
return None
"""
if not self.freeze and not self.holding:
# pre-emptively remove constraints and the vertex
# so that there aren't conflicts between the current
# edges and the probe point.
# See if the location will be okay -
to_remove = []
nbrs = [] # neighbor nodes, based only on constrained edges
for edge in self.dt_incident_constraints(self.vh[i]):
v1,v2 = edge.vertices()
vi1 = self.vh_info[v1]
vi2 = self.vh_info[v2]
to_remove.append( (edge, vi1, vi2) )
if vi1 == i:
nbrs.append(vi2)
else:
nbrs.append(vi1)
if len(to_remove) != len(self.pnt2edges(i)):
# why is this a warning here, but for unmove_node we bail out?
# I'm not really sure how this happens in the first place...
# this was a warning, but investigating...
# HERE: And now test_sine_sine is failing here.
pdb.set_trace()
raise Exception("WARNING: move_node len(DT constraints) != len(pnt2edges(i))")
for edge,a,b in to_remove:
self.dt_remove_constrained_edge(edge)
self.dt_remove(i)
# With the old edges and vertex out of the way, make sure the new location
# is safe, and adjust necessary
new_pnt = self.adjust_move_node(i,new_pnt,nbrs)
super(LiveDtGridBase,self).move_node(i,new_pnt)
if self.freeze:
pass
elif self.holding:
self.holding_nodes[i] = 'move'
else:
# put the node back in, and add back any edges that we removed.
# NB: safer to add only the constraints that were there before, since it
# could be that the DT is not perfectly in sync with self.edges[]
self.dt_insert(i)
for edge,a,b in to_remove:
self.safe_insert_constraint(a,b)
return new_pnt
def adjust_move_node(self,i,new_pnt,nbrs):
""" Check if it's okay to move the node i to the given point, and
if needed, return a different new_pnt location that won't make an
intersection
i: node index
new_pnt: the requested new location of the node
nbrs: list of neighbor node indices for checking edges
"""
# HERE -- not compatible with pure python code.
# find existing constrained edges
# for each constrained edge:
# will the updated edge still be valid?
# if not, update new_pnt to be halfway between the old and the new,
# and loop again.
for shorten in range(15): # maximum number of shortenings allowed
all_good = True
# Create a probe vertex so we can call check_line_is_clear()
# sort of winging it here for a measure of close things are.
if abs(self.points[i] - new_pnt).sum() / (1.0+abs(new_pnt).max()) < 1e-8:
log.warning("adjust_move_node: danger of roundoff issues")
all_good = False
break
all_good=self.check_line_is_clear_batch(p1=new_pnt,n2=nbrs)
if all_good:
break
else:
new_pnt = 0.5*(self.points[i]+new_pnt)
log.debug('adjust_move_node: adjusting')
if all_good:
return new_pnt
else:
return self.points[i]
## EDGES
def add_edge(self,nodeA,nodeB,*args,**kwargs):
e = super(LiveDtGridBase,self).add_edge(nodeA,nodeB,*args,**kwargs)
if self.freeze:
pass
elif self.holding:
self.holding_nodes[ self.edges[e,0] ] ='add_edge'
self.holding_nodes[ self.edges[e,1] ] ='add_edge'
else:
self.dt_add_edge(e)
return e
def unadd_edge(self,old_length):
if self.freeze:
pass
elif self.holding:
for e in range(old_length,len(self.edges)):
self.holding_nodes[ self.edges[e,0] ] ='unadd_edge'
self.holding_nodes[ self.edges[e,1] ] ='unadd_edge'
else:
for e in range(old_length,len(self.edges)):
self.dt_remove_edge(e)
super(LiveDtGridBase,self).unadd_edge(old_length)
def delete_edge(self,e,*args,**kwargs):
if self.freeze:
pass
elif self.holding:
self.holding_nodes[ self.edges[e,0] ] = 'delete_edge'
self.holding_nodes[ self.edges[e,1] ] = 'delete_edge'
else:
self.dt_remove_edge(e)
super(LiveDtGridBase,self).delete_edge(e,*args,**kwargs)
def undelete_edge(self,e,*args,**kwargs):
super(LiveDtGridBase,self).undelete_edge(e,*args,**kwargs)
if self.freeze:
pass
elif self.holding:
self.holding_nodes[ self.edges[e,0] ] = 'undelete_edge'
self.holding_nodes[ self.edges[e,1] ] = 'undelete_edge'
else:
self.dt_add_edge(e)
def merge_edges(self,e1,e2):
if self.verbose > 1:
print(" live_dt: merge edges %d %d"%(e1,e2))
# the tricky thing here is that we don't know which of
# these edges will be removed by merge_edges - one
# of them will get deleted, and then deleted by our
# delete handler.
# the other one will get modified, so by the time we get
# control again after trigrid, we won't know what to update
# so - save the nodes...
saved_nodes = self.edges[ [e1,e2],:2]
remaining = super(LiveDtGridBase,self).merge_edges(e1,e2)
if self.freeze:
pass
elif self.holding:
for n in saved_nodes.ravel():
self.holding_nodes[n] = 'merge_edges'
else:
if remaining == e1:
ab = saved_nodes[0]
else:
ab = saved_nodes[1]
# the one that is *not* remaining has already been deleted
# just update the other one.
try:
self.dt_remove_edge(remaining,nodes=ab)
except MissingConstraint:
print(" on merge_edges, may have an intervener")
raise
self.dt_add_edge(remaining)
return remaining
def unmerge_edges(self,e1,e2,*args,**kwargs):
check_dt_after = False
if self.freeze:
pass
elif self.holding:
pass
else:
# this can be problematic if the middle node is exactly on
# the line between them, because re-inserting that node
# will pre-emptively segment the constrained edge.
try:
self.dt_remove_edge(e1)
except MissingConstraint:
print(" got a missing constraint on merge edges - will verify that it's okay")
check_dt_after = True
#print " after pre-emptive remove_edge"
super(LiveDtGridBase,self).unmerge_edges(e1,e2,*args,**kwargs)
#print " after call to super()"
if self.freeze:
pass
elif self.holding:
n1,n2 = self.edges[e1,:2]
n3,n4 = self.edges[e2,:2]
for n in [n1,n2,n3,n4]:
self.holding_nodes[ n ] = 'unmerge_edges'
else:
if check_dt_after:
AB = self.edges[e1,:2]
BC = self.edges[e2,:2]
B = np.intersect1d(AB,BC)[0]
A = np.setdiff1d(AB,B)[0]
C = np.setdiff1d(BC,B)[0]
print("while unmerging edges, a constraint was pre-emptively created, but will verify that now %d-%d-%d."%(A,B,C))
for edge in self.dt_incident_constraints(self.vh[B]):
v1,v2 = edge.vertices()
if self.vh_info[v1] == A or self.vh_info[v2] == A:
A = None
elif self.vh_info[v1] == B or self.vh_info[v2] == B:
B = None
else:
print("while unmerging edge, the middle point has another constrained DT neighbor - surprising...")
if A is not None or B is not None:
raise MissingConstraint("Failed to verify that implicit constraint was there")
else:
#print " adding reverted edge e1 and e2"
self.dt_add_edge(e1)
# even though trigrid.merge_edges() calls delete_edge()
# on e2, it doesn't register an undelete_edge() b/c
# rollback=0.
self.dt_add_edge(e2)
# def unsplit_edge(...): # not supported by trigrid
def split_edge(self,nodeA,nodeB,nodeC):
""" per trigrid updates, nodeB may be a node index or a tuple (coords, **add_node_opts)
"""
if self.freeze:
pass
elif self.holding:
self.holding_nodes[nodeA] = 'split_edge'
if not isinstance(nodeB,Iterable):
self.holding_nodes[nodeB] = 'split_edge'
self.holding_nodes[nodeC] = 'split_edge'
else:
if self.verbose > 2:
print(" split_edge: %d %d %d"%(nodeA,nodeB,nodeC))
e1 = self.find_edge([nodeA,nodeC])
try:
self.dt_remove_edge(e1)
except MissingConstraint:
if isinstance(nodeB,Iterable):
print(" got a missing constraint on split edge, and node has not been created!")
raise
else:
print(" got a missing constraint on split edge, but maybe the edge has already been split")
self.dt_remove_edge(e1,[nodeA,nodeB])
self.dt_remove_edge(e1,[nodeB,nodeC])
print(" Excellent. The middle node had become part of the constraint")
e2 = super(LiveDtGridBase,self).split_edge(nodeA,nodeB,nodeC)
if self.freeze:
pass
elif self.holding:
pass
else:
self.dt_add_edge(e1)
self.dt_add_edge(e2)
return e2
def delete_node_and_merge(self,n):
if self.freeze:
return super(LiveDtGridBase,self).delete_node_and_merge(n)
if self.holding:
self.holding_nodes[n] = 'delete_node_and_merge'
else:
# remove any constraints going to n -
self.dt_remove_constraints(self.vh[n])
self.dt_remove(n)
# note that this is going to call merge_edges, before it
# calls delete_node() - and merge_edges will try to add the new
# constraint, which will fail if the middle node is collinear with
# the outside nodes. so freeze LiveDT updates, then here we clean up
self.freeze = 1
new_edge = super(LiveDtGridBase,self).delete_node_and_merge(n)
if self.verbose > 2:
print(" Got new_edge=%s from trigrid.delete_node_and_merge"%new_edge)
self.freeze=0
if self.holding:
for n in self.edges[new_edge,:2]:
self.holding_nodes[n] = 'delete_node_and_merge'
else:
# while frozen we missed a merge_edges and a delete node.
# we just want to do them in the opposite order of what trigrid does.
self.dt_add_edge(new_edge)
return new_edge
def renumber(self):
mappings = super(LiveDtGridBase,self).renumber()
self.vh = self.vh[ mappings['valid_nodes'] ]
for i in range(len(self.vh)):
self.vh_info[self.vh[i]] = i
return mappings
def dt_interior_cells(self):
"""
Only valid for a triangulation where all nodes lie on
the boundary. there will be some
cells which fall inside the domain, others outside the
domain.
returns cells which are properly inside the domain as
triples of nodes
"""
log.info("Finding interior cells from full Delaunay Triangulation")
interior_cells = []
for a,b,c in self.dt_cell_node_iter():
# going to be slow...
# How to test whether this face is internal:
# Arbitrarily choose a vertex: a
#
# Find an iter for which the face abc lies to the left of the boundary
internal = 0
for elt in self.all_iters_for_node(a):
d = self.points[elt.nxt.data] - self.points[a]
theta_afwd = np.arctan2(d[1],d[0])
d = self.points[b] - self.points[a]
theta_ab = np.arctan2(d[1],d[0])
d = self.points[elt.prv.data] - self.points[a]
theta_aprv = np.arctan2(d[1],d[0])
dtheta_b = (theta_ab - theta_afwd) % (2*np.pi)
dtheta_elt = (theta_aprv - theta_afwd) % (2*np.pi)
# if b==elt.nxt.data, then dtheta_b==0.0 - all good
if dtheta_b >= 0 and dtheta_b < dtheta_elt:
internal = 1
break
if internal:
interior_cells.append( [a,b,c] )
cells = np.array(interior_cells)
return cells
## DT-based "smoothing"
# First, make sure the boundary is sufficiently sampled
def subdivide(self,min_edge_length=1.0,edge_ids=None):
""" Like medial_axis::subdivide_iterate -
Add nodes along the boundary as needed to ensure that the boundary
is well represented in channels
[ from medial_axis ]
Find edges that need to be sampled with smaller
steps and divide them into two edges.
returns the number of new edges / nodes
method: calculate voronoi radii
iterate over edges in boundary
for each edge, find the voronoi point that they have
in common. So this edge should be part of a triangle,
and we are getting the center of that triangle.
the voronoi radius with the distance between the voronoi
point and the edge. If the edge is too long and needs to
be subdivided, it will be long (and the voronoi radius large)
compared to the distance between the edge and the vor. center.
"""
if edge_ids is None:
print("Considering all edges for subdividing")
edge_ids = list(range(self.Nedges()))
else:
print("Considering only %d supplied edges for subdividing"%len(edge_ids))
to_subdivide = []
# Also keep a list of constrained edges of DT cells for which another edge
# has been selected for subdivision.
neighbors_of_subdivide = {}
print("Choosing edges to subdivide")
for ni,i in enumerate(edge_ids): # range(self.Nedges()):
if ni%500==0:
log.debug('.')
if self.edges[i,0] == -37:
continue # edge has been deleted
# this only works when one side is unpaved and the other boundary -
if self.edges[i,3] != trigrid.UNMESHED or self.edges[i,4] != trigrid.BOUNDARY:
print("Skipping edge %d because it has weird cell ids"%i)
continue
a,b = self.edges[i,:2]
# consult the DT to find who the third node is:
a_nbrs = self.delaunay_neighbors(a)
b_nbrs = self.delaunay_neighbors(b)
abc = np.array([self.points[a],self.points[b],[0,0]])
c = None
for nbr in a_nbrs:
if nbr in b_nbrs:
# does it lie to the left of the edge?
abc[2,:] = self.points[nbr]
if trigrid.is_ccw(abc):
c = nbr
break
if c is None:
print("While looking at edge %d, %s - %s"%(i,self.points[a],self.points[b]))
raise Exception("Failed to find the third node that makes up an interior triangle")
pntV = trigrid.circumcenter(abc[0],abc[1],abc[2])
# compute the point-line distance between
# this edge and the v center, then compare to
# the distance from the endpoint to that
# vcenter
pntA = self.points[a]
pntB = self.points[b]
v_radius = np.sqrt( ((pntA-pntV)**2).sum() )
# This calculates unsigned distance - with Triangle, that's fine because
# it takes care of the Steiner points, but with CGAL we do it ourselves.
# line_clearance = np.sqrt( (( 0.5*(pntA+pntB) - pntV)**2).sum() )
ab = (pntB - pntA)
ab = ab / np.sqrt( np.sum(ab**2) )
pos_clearance_dir = np.array( [-ab[1],ab[0]] )
av = pntV - pntA
line_clearance = av[0]*pos_clearance_dir[0] + av[1]*pos_clearance_dir[1]
# Why do I get some bizarrely short edges?
ab = np.sqrt( np.sum( (pntA - pntB)**2 ) )
if v_radius > 1.2*line_clearance and v_radius > min_edge_length and ab>min_edge_length:
to_subdivide.append(i)
# Also make note of the other edges of this same DT triangle
for maybe_nbr in [ [a,c], [b,c] ]:
# could be an internal DT edge, or a real edge
try:
nbr_edge = self.find_edge(maybe_nbr)
neighbors_of_subdivide[nbr_edge] = 1
except trigrid.NoSuchEdgeError:
pass
print()
print("Will subdivide %d edges"%(len(to_subdivide)))
for ni,i in enumerate(to_subdivide):
if ni%500==0:
log.debug('.')
if i in neighbors_of_subdivide:
del neighbors_of_subdivide[i]
a,b = self.edges[i,:2]
elts = self.all_iters_for_node(a)
if len(elts) != 1:
raise Exception("How is there not exactly one iter for this node!?")
scale = 0.5*np.sqrt( np.sum( (self.points[a]-self.points[b])**2 ) )
# print "Subdividing edge %d with scale %f"%(i,scale)
new_elt = self.resample_boundary(elts[0],'forward',
local_scale=scale,
new_node_stat=self.node_data[a,0])
# keep track of any edges that change:
e1,e2 = self.pnt2edges(new_elt.data)
neighbors_of_subdivide[e1] = 1
neighbors_of_subdivide[e2] = 1
print("done")
subdivided = np.array( list(neighbors_of_subdivide.keys()) )
return subdivided
def subdivide_iterate(self,min_edge_length=1.0):
modified_edges = None
while 1:
# It wasn't enough to just test for no modified edges - rather than
# trying to be clever about checking exactly edges that may have
# been affected by a split, have nested iterations, and stop only
# when globally there are no modified edges
new_modified_edges = self.subdivide(min_edge_length=min_edge_length,
edge_ids = modified_edges)
print("Subdivide made %d new nodes"%(len(new_modified_edges)/2) )
if len(new_modified_edges) == 0:
if modified_edges is None:
# this means we considered all edges, and still found nobody
# to split
break
else:
# this means we were only considering likely offenders -
# step back and consider everyone
print("Will reconsider all edges...")
modified_edges = None
else:
modified_edges = new_modified_edges
def smoothed_poly(self,density,min_edge_length=1.0):
""" Returns a polygon for the boundary that has all 'small' concave features
removed. Modifies the boundary points, but only by adding new samples evenly
between originals.
"""
# Make sure that all edges are sufficiently sampled:
self.subdivide_iterate(min_edge_length=min_edge_length)
# The process (same as in smoother.py):
# For all _interior_ DT cells
# calculate circum-radius
# mark for deletion any cell with radius < scale/2,
# with scale calculated at circumcenter
# For all non-deleted cells, create an array of all edges
# The notes in smoother say that if an edge appears exactly once
# then it should be kept.
# Edges that appear twice are internal to the domain.
# If/when degenerate edges take part in this, they will have to be
# handled specially, since they *should* have two adjacent, valid, cells.
# What is faster?
# (a) iterate over known boundary edges, grabbing cells to the left,
# and checking against a hash to see that the cell hasn't been included
# already
# (b) iterate over DT faces, checking to see if it's an internal face or not
# by checking ab,bc,ca against the edge hash?
# probably (b), since we already have this hash built.
# Actually, (b) isn't sufficient - there are triangles that are internal, but
# have no boundary edges.
# And (a) isn't good either - it would skip over any triangles that are entirely
# internal _or_ entirely external (i.e. share no edges with the boundary).
# Is there a way to do this by tracing edges? Start at some vertex on a clist.
# check the next edge forward - is the radius of the DT face to its left big enough?
# If so, we move forward.
# If not, detour?
# That's not quite enough, though. Really need to be checking every triangle incident
# to the vertex, not just the ones incident to the edges.
# So for simplicity, why not use the traversal of the edges to enumerate internal cells,
# then proceed as before.
cells = self.dt_interior_cells()
print("Marking for deletion DT faces that are too small")
points = self.points[cells]
vcenters = trigrid.circumcenter(points[:,0],
points[:,1],
points[:,2])
# Threshold on the radius, squared -
#
r2_min = (density(vcenters)/2.0 * self.scale_ratio_for_cutoff)**2
# r^2 for each internal DT face
r2 = np.sum( (vcenters - points[:,0,:])**2,axis=1)
valid = r2 >= r2_min
# From here on out it follows smoother.py very closely...
print("Compiling valid edges")
# expands cells into edges
good_cells = cells[valid]
all_edges = good_cells[:,np.array([[0,1],[1,2],[2,0]])]
# cells is Nfaces x 3
# all_edges is then Nfaces x 3 x 2
# combine the first two dimensions, so we have a regular edges array
all_edges = all_edges.reshape( (-1,2) )
print("building hash of edges")
edge_hash = {}
for i in range(len(all_edges)):
k = all_edges[i,:]
if k[0] > k[1]:
k=k[::-1]
k = tuple(k)
if k not in edge_hash:
edge_hash[k] = 0
edge_hash[k] += 1
print("Selecting boundary edges")
# good edges are then edges that appear in exactly one face
good_edges = []
for k in edge_hash:
if edge_hash[k] == 1:
good_edges.append(k)
good_edges = np.array(good_edges)
print("Finding polygons from edges")
tgrid = trigrid.TriGrid(points=self.points,
edges =good_edges)
tgrid.verbose = 2
polygons = tgrid.edges_to_polygons(None) # none=> use all edges
self.smooth_all_polygons = polygons # for debugging..
print("done with smoothing")
return polygons[0]
def apollonius_scale(self,r,min_edge_length=1.0,process_islands=True):
""" Return an apollonius based field giving the scale subject to
the local feature size of geo and the telescoping rate r
"""
self.subdivide_iterate(min_edge_length=min_edge_length)
dt_cells = self.dt_interior_cells()
points = self.points[dt_cells]
vcenters = trigrid.circumcenter(points[:,0],
points[:,1],
points[:,2])
radii = np.sqrt( np.sum( (vcenters - points[:,0,:])**2,axis=1) )
diam = 2*radii
if process_islands:
print("Hang on. Adding scale points for islands")
island_centers = []
island_scales = []
for int_ring in self.poly.interiors:
p = int_ring.convex_hull
points = np.array(p.exterior.coords)
center = points.mean(axis=0)
# brute force - find the maximal distance between
# any two points. probably a smart way to do this,
# but no worries...
max_dsqr = 0
for i in range(len(points)):
pa = points[i]
for j in range(i,len(points)):
d = ((pa - points[j])**2).sum()
max_dsqr = max(d,max_dsqr)
feature_scale = np.sqrt( max_dsqr )
print("Ring has scale of ",feature_scale)
island_centers.append( center )
# this very roughly says that we want at least 4 edges
# for representing this thing.
# island_scales.append( feature_scale / 2.0)
# actually it's not too hard to have a skinny island
# 2 units long that gets reduced to a degenerate pair
# of edges, so go conservative here:
island_scales.append( feature_scale / 3.0 )
island_centers = np.array(island_centers)
island_scales = np.array(island_scales)
if len(island_centers) > 0:
vcenters = np.concatenate( (vcenters,island_centers) )
diam = np.concatenate( (diam,island_scales) )
print("Done with islands")
scale = field.ApolloniusField(vcenters,diam)
return scale
try:
# If CGAL gives import errors, it may be because gmp is outdated
# This got past conda because the build of mpfr isn't specific
# about the version of gmp, just says it depends on gmp.
# One fix in anaconda land is:
# conda update gmp to install 6.1.2
from CGAL.CGAL_Triangulation_2 import Constrained_Delaunay_triangulation_2
from CGAL.CGAL_Kernel import Point_2
class LiveDtCGAL(LiveDtGridBase):
class Edge(object):
def __init__(self,**kwargs):
self.__dict__.update(kwargs)
def vertices(self):
return self.f.vertex( (self.v+1)%3 ),self.f.vertex( (self.v+2)%3 )
def dt_allocate(self):
""" allocate both the triangulation and the vertex handle
"""
self.DT = Constrained_Delaunay_triangulation_2()
def dt_insert(self,n):
""" Given a point that is correctly in self.points, and vh that
is large enough, do the work of inserting the node and updating
the vertex handle.
"""
pnt = Point_2( self.points[n,0], self.points[n,1] )
self.vh[n] = self.DT.insert(pnt)
self.vh_info[self.vh[n]] = n
if self.verbose > 2:
print(" dt_insert node %d"%n)
self.check()
def dt_insert_constraint(self,a,b):
self.DT.insert_constraint( self.vh[a], self.vh[b] )
def dt_remove_constraints(self,vh):
self.DT.remove_incident_constraints(vh)
def dt_remove(self,n):
self.DT.remove( self.vh[n] )
del self.vh_info[self.vh[n]]
self.vh[n] = 0
if self.verbose > 2:
print(" dt_remove node %d"%n)
self.check()
def dt_remove_constrained_edge(self,edge):
self.DT.remove_constrained_edge(edge.f,edge.v)
def dt_incident_constraints(self,vh):
constraints = []
self.DT.incident_constraints(vh,constraints)
# maybe I should keep a reference to the Edge object, too?
# that gets through some early crashes.
return [self.Edge(f=e.first,v=e.second,keepalive=[e]) for e in constraints]
def dt_cell_node_iter(self):
""" generator for going over finite cells, returning
nodes as triples
"""
face_it = self.DT.finite_faces()
for f in face_it:
yield [self.vh_info[f.vertex(i)] for i in [0,1,2]]
def delaunay_face(self, pnt):
""" Returns node indices making up the face of the DT in which pnt lies.
Not explicitly tested, but this should return None for infinite nodes.
"""
f = self.DT.locate( Point_2(pnt[0],pnt[1]) )
n = [self.vh_info[f.vertex(i)] for i in [0,1,2]]
return n
def delaunay_neighbors(self, n):
""" returns an array of node ids that the DT connects the given node
to. Includes existing edges
"""
nbrs = []
# how do we stop on a circulator?
first_v = None
# somehow it fails HERE, with self.vh[n] being an int, rather
# than a vertex handle.
for v in self.DT.incident_vertices(self.vh[n]):
if first_v is None:
first_v = v
elif first_v == v:
break
if self.DT.is_infinite(v):
continue
# print "Looking for vertex at ",v.point()
# This is going to need something faster, or maybe the store info
# bits of cgal.
nbr_i = self.vh_info[v] # np.where( self.vh == v )[0]
if nbr_i is None:
print(" While looking for vertex at ",v.point())
raise Exception("expected vertex handle->node, but instead got %s"%nbr_i)
nbrs.append( nbr_i )
return np.array(nbrs)
def plot_dt(self,clip=None):
edges = []
colors = []
gray = (0.7,0.7,0.7,1.0)
magenta = (1.0,0.0,1.0,1.0)
e_iter = self.DT.finite_edges()
for e in e_iter:
face,vertex = e
v1 = face.vertex( (vertex + 1)%3 )
v2 = face.vertex( (vertex + 2)%3 )
edges.append( [ [v1.point().x(),v1.point().y()],
[v2.point().x(),v2.point().y()] ] )
if self.DT.is_constrained(e):
colors.append(magenta)
else:
colors.append(gray)
segments = np.array(edges)
colors = np.array(colors)
if clip is None:
clip = self.default_clip
if clip is not None:
points_visible = (segments[...,0] >= clip[0]) & (segments[...,0]<=clip[1]) \
& (segments[...,1] >= clip[2]) & (segments[...,1]<=clip[3])
# so now clip is a bool array of length Nedges
clip = np.any( points_visible, axis=1)
segments = segments[clip,...]
colors = colors[clip,...]
coll = collections.LineCollection(segments,colors=colors)
ax = plt.gca()
ax.add_collection(coll)
def dt_clearance(self,n):
"""POORLY TESTED
Returns the diameter of the smallest circumcircle (?) of a face
incident to the node n. Currently this doesn't work terribly well
because sliver triangles will create arbitrarily small clearances
at obtuse angles.
"""
diams = []
f_circ = self.DT.incident_faces( self.vh[n] )
first_f = next(f_circ)
f = first_f
for f in f_circ:
if f == first_f:
break
diams.append( self.face_diameter(f) )
return min(diams)
# Not 100% sure of these
def face_nodes(self,face):
return np.array( [self.vh_info[face.vertex(j)] for j in range(3)] )
def face_center(self,face):
points = self.points[self.face_nodes(face)]
return trigrid.circumcenter(points[0],points[1],points[2])
def face_diameter(self,face):
points = self.points[self.face_nodes(face)]
ccenter = trigrid.circumcenter(points[0],points[1],points[2])
return 2*norm(points[0] - ccenter)
#-# Detecting self-intersections
def face_in_direction(self,vh,vec):
"""
Starting at the vertex handle vh, look in the direction
of vec to choose a face adjacent to vh.
Used for the CGAL implementation of line_walk_edges and shoot_ray()
"""
# vh: vertex handle
# vec: search direction as array
theta = np.arctan2(vec[1],vec[0])
# choose a starting face
best_f = None
f_circ = self.DT.incident_faces(vh)
first_f = next(f_circ)
f = first_f
while 1:
# get the vertices of this face:
vlist=[f.vertex(i) for i in range(3)]
# rotate to make v1 first:
vh_index = vlist.index(vh)
vlist = vlist[vh_index:] + vlist[:vh_index]
# then check the relative angles of the other two - they are in CCW order
pnts = np.array( [ [v.point().x(),v.point().y()] for v in vlist] )
delta01 = pnts[1] - pnts[0]
delta02 = pnts[2] - pnts[0]
theta01 = np.arctan2( delta01[1], delta01[0] )
theta02 = np.arctan2( delta02[1], delta02[0] )
#
d01 = (theta - theta01)%(2*np.pi)
d02 = (theta02 - theta)%(2*np.pi)
#print "starting point:",pnts[0]
#print "Theta01=%f Theta=%f Theta02=%f"%(theta01,theta,theta02)
if (d01 < np.pi) and (d02 < np.pi):
best_f = f
break
f = next(f_circ)
if f == first_f:
# raise Exception("Went all the way around...")
# this can happen when starting from a vertex and aiming
# outside the convex hull
return None
return best_f
def next_face(self,f,p1,vec):
""" find the next face from f, along the line through v in the direction vec,
return the face and the edge that was crossed, where the edge is a face,i tuple
Used for the CGAL implementation of line_walk_edges() and shoot_ray()
"""
# First get the vertices that make up this face:
# look over the edges:
vlist=[f.vertex(i) for i in range(3)]
pnts = np.array( [ [v.point().x(),v.point().y()] for v in vlist] )
# check which side of the line each vertex is on:
left_vec = np.array( [-vec[1],vec[0]] )
left_distance = [ (pnts[i,0] - p1[0])*left_vec[0] + (pnts[i,1]-p1[1])*left_vec[1] for i in range(3)]
# And we want the edge that goes from a negative to positive left_distance.
# should end with i being the index of the start of the edge that we want
for i in range(3):
# This doesn't quite follow the same definitions as in CGAL -
# because we want to ensure that we get a consecutive list of edges
# The easy case - the query line exits through an edge that straddles
# the query line, that's the <
# the == part comes in where the query line exits through a vertex.
# in that case, we choose the edge to the left (arbitrary).
if left_distance[i] <= 0 and left_distance[(i+1)%3] > 0:
break
# so now the new edge is between vertex i,(i+1)%3, so in CGAL parlance
# that's
edge = (f,(i-1)%3)
new_face = f.neighbor( (i-1)%3 )
return edge,new_face
# N.B.: the svn (and original git) versions of live_dt included
# a new set of check_line_is_clear_new, line_walk_edges_new, and
# various helpers, which made more extensive use of CGAL primitives
#
##
def line_walk_edges(self,n1=None,n2=None,v1=None,v2=None,
include_tangent=False,
include_coincident=True):
""" for a line starting at node n1 or vertex handle v1 and
ending at node n2 or vertex handle v2, return all the edges
that intersect.
Used in the CGAL implementation of check_line_is_clear
"""
# this is a bit dicey in terms of numerical robustness -
# face_in_direction is liable to give bad results when multiple faces are
# indistinguishable (like a colinear set of points with many degenerate faces
# basically on top of each other).
# How can this be made more robust?
# When the query line exactly goes through one or more vertex stuff starts
# going nuts.
# So is it possible to handle this more intelligently?
# there are 3 possibilities for intersecting edges:
# (1) intersect only at an end point, i.e. endpoint lies on query line
# (2) intersect in interior of edge - one end point on one side, other endpoint
# on the other side of the query line
# (3) edge is coincident with query line
# so for a first cut - make sure that we aren't just directly connected:
if (n2 is not None) and (n1 is not None) and (n2 in self.delaunay_neighbors(n1)):
return []
if v1 is None:
v1 = self.vh[n1]
if v2 is None:
v2 = self.vh[n2]
# Get the points from the vertices, not self.points, because in some cases
# (adjust_move_node) we may be probing
p1 = np.array([ v1.point().x(), v1.point().y()] )
p2 = np.array([ v2.point().x(), v2.point().y()] )
# print "Walking the line: ",p1,p2
vec = p2 - p1
unit_vec = vec / norm(vec)
pnt = p1
# NB: this can be None - though not sure whether the context can
# ensure that it never would be.
f1 = self.face_in_direction(v1,vec)
f2 = self.face_in_direction(v2,-vec)
# do the search:
f_trav = f1
edges = []
while 1:
# print "line_walk_edges: traversing face:"
# print [f_trav.vertex(i).point() for i in [0,1,2]]
# Stop condition: we're in a face containing the final vertex
# check the vertices directly, rather than the face
still_close = 0
for i in range(3):
if f_trav.vertex(i) == v2:
return edges
if not still_close:
# Check to see if this vertex is beyond the vertex of interest
vertex_i_pnt = np.array( [f_trav.vertex(i).point().x(),f_trav.vertex(i).point().y()] )
if norm(vec) > np.dot( vertex_i_pnt - p1, unit_vec):
still_close = 1
if not still_close:
# We didn't find any vertices of this face that were as close to where we started
# as the destination was, so we must have passed it.
print("BAILING: n1=%s n2=%s v1=%s v2=%s"%(n1,n2,v1,v2))
raise Exception("Yikes - line_walk_edges exposed its numerical issues. We traversed too far.")
return edges
edge,new_face = self.next_face(f_trav,pnt,vec)
edges.append(edge)
f_trav = new_face
return edges
def shoot_ray(self,n1,vec,max_dist=None):
""" Shoot a ray from self.points[n] in the given direction vec
returns (e_index,pnt), the first edge that it encounters and the location
of the intersection
max_dist: stop checking beyond this distance -- currently doesn't make it faster
but will return None,None if the point that it finds is too far away
"""
v1 = self.vh[n1]
vec = vec / | norm(vec) | numpy.linalg.norm |
''' Functions to generate the set of endpoints for the time series
benchmark on the HiRID database'''
import glob
import logging
import math
import os
import os.path
import pickle
import random
import sys
import lightgbm as lgbm
import numpy as np
import pandas as pd
import skfda.preprocessing.smoothing.kernel_smoothers as skks
import skfda.representation.grid as skgrid
import sklearn.linear_model as sklm
import sklearn.metrics as skmetrics
import sklearn.preprocessing as skpproc
def load_pickle(fpath):
''' Given a file path pointing to a pickle file, yields the object pickled in this file'''
with open(fpath,'rb') as fp:
return pickle.load(fp)
SUPPOX_TO_FIO2={
0: 21,
1: 26,
2: 34,
3: 39,
4: 45,
5: 49,
6: 54,
7: 57,
8: 58,
9: 63,
10: 66,
11: 67,
12: 69,
13: 70,
14: 73,
15: 75 }
def mix_real_est_pao2(pao2_col, pao2_meas_cnt, pao2_est_arr, bandwidth=None):
''' Mix real PaO2 measurement and PaO2 estimates using a Gaussian kernel'''
final_pao2_arr=np.copy(pao2_est_arr)
sq_scale=57**2 # 1 hour has mass 1/3 approximately
for idx in range(final_pao2_arr.size):
meas_ref=pao2_meas_cnt[idx]
real_val=None
real_val_dist=None
# Search forward and backward with priority giving to backward if equi-distant
for sidx in range(48):
if not idx-sidx<0 and pao2_meas_cnt[idx-sidx]<meas_ref:
real_val=pao2_col[idx-sidx+1]
real_val_dist=5*sidx
break
elif not idx+sidx>=final_pao2_arr.size and pao2_meas_cnt[idx+sidx]>meas_ref:
real_val=pao2_col[idx+sidx]
real_val_dist=5*sidx
break
if real_val is not None:
alpha_mj=math.exp(-real_val_dist**2/sq_scale)
alpha_ej=1-alpha_mj
final_pao2_arr[idx]=alpha_mj*real_val+alpha_ej*pao2_est_arr[idx]
return final_pao2_arr
def perf_regression_model(X_list, y_list, aux_list, configs=None):
''' Initial test of a regression model to estimate the current Pao2 based
on 6 features of the past. Also pass FiO2 to calculate resulting mistakes in
the P/F ratio'''
logging.info("Testing regression model for PaO2...")
# Partition the data into 3 sets and run SGD regressor
X_train=X_list[:int(0.6*len(X_list))]
X_train=np.vstack(X_train)
y_train=np.concatenate(y_list[:int(0.6*len(y_list))])
X_val=X_list[int(0.6*len(X_list)):int(0.8*len(X_list))]
X_val=np.vstack(X_val)
y_val=np.concatenate(y_list[int(0.6*len(y_list)):int(0.8*len(y_list))])
X_test=X_list[int(0.8*len(X_list)):]
X_test=np.vstack(X_test)
y_test=np.concatenate(y_list[int(0.8*len(y_list)):])
fio2_test=np.concatenate(aux_list[int(0.8*len(aux_list)):])
if configs["sur_model_type"]=="linear":
scaler=skpproc.StandardScaler()
X_train_std=scaler.fit_transform(X_train)
X_val_std=scaler.transform(X_val)
X_test_std=scaler.transform(X_test)
if configs["sur_model_type"]=="linear":
alpha_cands=[0.0001,0.001,0.01,0.1,1.0]
elif configs["sur_model_type"]=="lgbm":
alpha_cands=[32]
best_alpha=None
best_score=np.inf
# Search for the best model on the validation set
for alpha in alpha_cands:
logging.info("Testing alpha: {}".format(alpha))
if configs["sur_model_type"]=="linear":
lmodel_cand=sklm.SGDRegressor(alpha=alpha, random_state=2021)
elif configs["sur_model_type"]=="lgbm":
lmodel_cand=lgbm.LGBMRegressor(num_leaves=alpha, learning_rate=0.05, n_estimators=1000,
random_state=2021)
if configs["sur_model_type"]=="linear":
lmodel_cand.fit(X_train_std,y_train)
elif configs["sur_model_type"]=="lgbm":
lmodel_cand.fit(X_train_std,y_train, eval_set=(X_val_std,y_val), early_stopping_rounds=20,
eval_metric="mae")
pred_y_val=lmodel_cand.predict(X_val_std)
mae_val=np.median(np.absolute(y_val-pred_y_val))
if mae_val<best_score:
best_score=mae_val
best_alpha=alpha
lmodel=sklm.SGDRegressor(alpha=best_alpha,random_state=2021)
lmodel.fit(X_train_std,y_train)
pred_y_test=lmodel.predict(X_test_std)
pred_pf_ratio_test=pred_y_test/fio2_test
true_pf_ratio_test=y_test/fio2_test
mae_test=skmetrics.mean_absolute_error(y_test, pred_y_test)
logging.info("Mean absolute error in test set: {:.3f}".format(mae_test))
def percentile_smooth(signal_col, percentile, win_scope_mins):
''' Window percentile smoother, where percentile is in the interval [0,100]'''
out_arr=np.zeros_like(signal_col)
mins_per_window=5
search_range=int(win_scope_mins/mins_per_window/2)
for jdx in range(out_arr.size):
search_arr=signal_col[max(0,jdx-search_range):min(out_arr.size,jdx+search_range)]
out_arr[jdx]=np.percentile(search_arr,percentile)
return out_arr
def subsample_blocked(val_arr, meas_arr=None, ss_ratio=None, block_length=None, normal_value=None):
''' Subsample blocked with ratio and block length'''
val_arr_out=np.copy(val_arr)
meas_arr_out=np.copy(meas_arr)
meas_idxs=[]
n_meas=0
for idx in range(meas_arr.size):
if meas_arr[idx]>n_meas:
meas_idxs.append(idx)
n_meas+=1
if len(meas_idxs)==0:
return (val_arr_out, meas_arr_out)
meas_select=int((1-ss_ratio)*len(meas_idxs))
begin_select=meas_select//block_length
feas_begins=[meas_idxs[idx] for idx in np.arange(0,len(meas_idxs),block_length)]
sel_meas_begins=sorted(random.sample(feas_begins, begin_select))
sel_meas_delete=[]
for begin in sel_meas_begins:
for add_idx in range(block_length):
sel_meas_delete.append(begin+add_idx)
# Rewrite the measuremnent array with deleted indices
for midx,meas_idx in enumerate(meas_idxs):
prev_cnt=0 if meas_idx==0 else meas_arr_out[meas_idx-1]
revised_cnt=prev_cnt if meas_idx in sel_meas_delete else prev_cnt+1
if midx<len(meas_idxs)-1:
for rewrite_idx in range(meas_idx,meas_idxs[midx+1]):
meas_arr_out[rewrite_idx]=revised_cnt
else:
for rewrite_idx in range(meas_idx,len(meas_arr_out)):
meas_arr_out[rewrite_idx]=revised_cnt
# Rewrite the value array with deleted indices, with assuming forward filling
for midx,meas_idx in enumerate(meas_idxs):
prev_val=normal_value if meas_idx==0 else val_arr_out[meas_idx-1]
cur_val=val_arr_out[meas_idx]
revised_value=prev_val if meas_idx in sel_meas_delete else cur_val
if midx<len(meas_idxs)-1:
for rewrite_idx in range(meas_idx,meas_idxs[midx+1]):
val_arr_out[rewrite_idx]=revised_value
else:
for rewrite_idx in range(meas_idx,len(meas_arr_out)):
val_arr_out[rewrite_idx]=revised_value
return (val_arr_out, meas_arr_out)
def subsample_individual(val_arr, meas_arr=None, ss_ratio=None, normal_value=None):
''' Subsample individual measurements completely randomly with random choice'''
val_arr_out=np.copy(val_arr)
meas_arr_out=np.copy(meas_arr)
meas_idxs=[]
n_meas=0
for idx in range(meas_arr.size):
if meas_arr[idx]>n_meas:
meas_idxs.append(idx)
n_meas+=1
if len(meas_idxs)==0:
return (val_arr_out, meas_arr_out)
meas_select=int((1-ss_ratio)*len(meas_idxs))
sel_meas_delete=sorted(random.sample(meas_idxs, meas_select))
# Rewrite the measuremnent array with deleted indices
for midx,meas_idx in enumerate(meas_idxs):
prev_cnt=0 if meas_idx==0 else meas_arr_out[meas_idx-1]
revised_cnt=prev_cnt if meas_idx in sel_meas_delete else prev_cnt+1
if midx<len(meas_idxs)-1:
for rewrite_idx in range(meas_idx,meas_idxs[midx+1]):
meas_arr_out[rewrite_idx]=revised_cnt
else:
for rewrite_idx in range(meas_idx,len(meas_arr_out)):
meas_arr_out[rewrite_idx]=revised_cnt
# Rewrite the value array with deleted indices, with assuming forward filling
for midx,meas_idx in enumerate(meas_idxs):
prev_val=normal_value if meas_idx==0 else val_arr_out[meas_idx-1]
cur_val=val_arr_out[meas_idx]
revised_value=prev_val if meas_idx in sel_meas_delete else cur_val
if midx<len(meas_idxs)-1:
for rewrite_idx in range(meas_idx,meas_idxs[midx+1]):
val_arr_out[rewrite_idx]=revised_value
else:
for rewrite_idx in range(meas_idx,len(meas_arr_out)):
val_arr_out[rewrite_idx]=revised_value
return (val_arr_out, meas_arr_out)
def merge_short_vent_gaps(vent_status_arr, short_gap_hours):
''' Merge short gaps in the ventilation status array'''
in_gap=False
gap_length=0
before_gap_status=np.nan
for idx in range(len(vent_status_arr)):
cur_state=vent_status_arr[idx]
if in_gap and (cur_state==0.0 or np.isnan(cur_state)):
gap_length+=5
elif not in_gap and (cur_state==0.0 or np.isnan(cur_state)):
if idx>0:
before_gap_status=vent_status_arr[idx-1]
in_gap=True
in_gap_idx=idx
gap_length=5
elif in_gap and cur_state==1.0:
in_gap=False
after_gap_status=cur_state
if gap_length/60.<=short_gap_hours:
vent_status_arr[in_gap_idx:idx]=1.0
return vent_status_arr
def kernel_smooth_arr(input_arr, bandwidth=None):
''' Kernel smooth an input array with a Nadaraya-Watson kernel smoother'''
output_arr=np.copy(input_arr)
fin_arr=output_arr[np.isfinite(output_arr)]
time_axis=5*np.arange(len(output_arr))
fin_time=time_axis[np.isfinite(output_arr)]
# Return the unsmoothed array if fewer than 2 observations
if fin_arr.size<2:
return output_arr
smoother=skks.NadarayaWatsonSmoother(smoothing_parameter=bandwidth)
fgrid=skgrid.FDataGrid([fin_arr], fin_time)
fd_smoothed=smoother.fit_transform(fgrid)
output_smoothed=fd_smoothed.data_matrix.flatten()
output_arr[np.isfinite(output_arr)]=output_smoothed
return output_arr
def delete_short_vent_events(vent_status_arr, short_event_hours):
''' Delete short events in the ventilation status array'''
in_event=False
event_length=0
for idx in range(len(vent_status_arr)):
cur_state=vent_status_arr[idx]
if in_event and cur_state==1.0:
event_length+=5
if not in_event and cur_state==1.0:
in_event=True
event_length=5
event_start_idx=idx
if in_event and (cur_state==0.0 or np.isnan(cur_state)):
in_event=False
if event_length/60.<short_event_hours:
vent_status_arr[event_start_idx:idx]=0.0
return vent_status_arr
def ellis(x_orig):
''' ELLIS model converting SpO2 in 100 % units into a PaO2 ABGA
estimate'''
x_orig[np.isnan(x_orig)]=98 # Normal value assumption
x=x_orig/100
x[x==1]=0.999
exp_base = (11700/((1/x)-1))
exp_sqrbracket = np.sqrt(pow(50,3)+(exp_base**2))
exp_first = np.cbrt(exp_base + exp_sqrbracket)
exp_second = np.cbrt(exp_base - exp_sqrbracket)
exp_full = exp_first + exp_second
return exp_full
def correct_left_edge_vent(vent_status_arr, etco2_meas_cnt, etco2_col):
''' Corrects the left edge of the ventilation status array, to pin-point the exact conditions'''
on_left_edge=False
in_event=False
# Correct left ventilation edges of the ventilation zone
for idx in range(len(vent_status_arr)):
if vent_status_arr[idx]==1.0 and not in_event:
in_event=True
on_left_edge=True
if on_left_edge and in_event:
if vent_status_arr[idx]==0.0:
in_event=False
on_left_edge=False
elif (idx==0 and etco2_meas_cnt[idx]>0 or etco2_meas_cnt[idx]-etco2_meas_cnt[idx-1]>=1) and etco2_col[idx]>0.5:
on_left_edge=False
else:
vent_status_arr[idx]=0.0
return vent_status_arr
def delete_small_continuous_blocks(event_arr,block_threshold=None):
''' Given an event array, deletes small contiguous blocks that are sandwiched between two other blocks, one of which
is longer, they both have the same label. For the moment we delete blocks smaller than 30 minutes. Note this
requires only a linear pass over the array'''
block_list=[]
active_block=None
# Build a block list
for jdx in range(event_arr.size):
new_block=event_arr[jdx]
# Start a new block at the beginning
if active_block is None:
active_block=new_block
left_block_idx=jdx
# Change to a new block
elif not active_block==new_block:
block_list.append((active_block,left_block_idx,jdx-1))
left_block_idx=jdx
active_block=new_block
# Same last block unconditionally
if jdx==event_arr.size-1:
block_list.append((new_block,left_block_idx,jdx))
# Merge blocks
while True:
all_clean=True
for bidx, block in enumerate(block_list):
block_label,lidx,ridx=block
block_len=ridx-lidx+1
# Candidate for merging
if block_len<=block_threshold:
if len(block_list)==1:
all_clean=True
break
# Only right block
elif bidx==0:
next_block=block_list[bidx+1]
nb_label,nb_lidx,nb_ridx=next_block
nb_len=nb_ridx-nb_lidx+1
# Merge blocks
if nb_len>block_len and nb_len>block_threshold:
block_list[bidx]=(nb_label,lidx,nb_ridx)
block_list.remove(next_block)
all_clean=False
break
# Only left block
elif bidx==len(block_list)-1:
prev_block=block_list[bidx-1]
pb_label,pb_lidx,pb_ridx=prev_block
pb_len=pb_ridx-pb_lidx+1
if pb_len>block_len and pb_len>block_threshold:
block_list[bidx]=(pb_label,pb_lidx,ridx)
block_list.remove(prev_block)
all_clean=False
break
# Interior block
else:
prev_block=block_list[bidx-1]
next_block=block_list[bidx+1]
pb_label,pb_lidx,pb_ridx=prev_block
nb_label,nb_lidx,nb_ridx=next_block
pb_len=pb_ridx-pb_lidx+1
nb_len=nb_ridx-nb_lidx+1
if pb_label==nb_label and (pb_len>block_threshold or nb_len>block_threshold):
block_list[bidx]=(pb_label,pb_lidx,nb_ridx)
block_list.remove(prev_block)
block_list.remove(next_block)
all_clean=False
break
# Traversed block list with no actions required
if all_clean:
break
# Now back-translate the block list to the list
out_arr=np.copy(event_arr)
for blabel,lidx,ridx in block_list:
out_arr[lidx:ridx+1]=blabel
# Additionally build an array where the two arrays are different
diff_arr=(out_arr!=event_arr).astype(np.bool)
return (out_arr,diff_arr)
def collect_regression_data(spo2_col, spo2_meas_cnt, pao2_col, pao2_meas_cnt, fio2_est_arr,
sao2_col, sao2_meas_cnt, ph_col, ph_meas_cnt ):
''' Collect regression data at time-stamps where we have a real PaO2 measurement, return
partial training X,y pairs for this patient'''
X_arr_collect=[]
y_arr_collect=[]
aux_collect=[]
cur_pao2_cnt=0
cur_spo2_cnt=0
cur_sao2_cnt=0
cur_ph_cnt=0
pao2_real_meas=[]
spo2_real_meas=[]
sao2_real_meas=[]
ph_real_meas=[]
for jdx in range(spo2_col.size):
if spo2_meas_cnt[jdx]>cur_spo2_cnt:
spo2_real_meas.append(jdx)
cur_spo2_cnt=spo2_meas_cnt[jdx]
if sao2_meas_cnt[jdx]>cur_sao2_cnt:
sao2_real_meas.append(jdx)
cur_sao2_cnt=sao2_meas_cnt[jdx]
if ph_meas_cnt[jdx]>cur_ph_cnt:
ph_real_meas.append(jdx)
cur_ph_cnt=ph_meas_cnt[jdx]
if pao2_meas_cnt[jdx]>cur_pao2_cnt:
pao2_real_meas.append(jdx)
cur_pao2_cnt=pao2_meas_cnt[jdx]
# Only start fitting the model from the 2nd measurement onwards
if len(pao2_real_meas)>=2 and len(spo2_real_meas)>=2 and len(sao2_real_meas)>=2 and len(ph_real_meas)>=2:
# Dimensions of features
# 0: Last real SpO2 measurement
# 1: Last real PaO2 measurement
# 2: Last real SaO2 measurement
# 3: Last real pH measurement
# 4: Time to last real SpO2 measurement
# 5: Time to last real PaO2 measurement
# 6: Closest SpO2 to last real PaO2 measurement
x_vect=np.array([spo2_col[jdx-1], pao2_col[jdx-1], sao2_col[jdx-1], ph_col[jdx-1],
jdx-spo2_real_meas[-2], jdx-pao2_real_meas[-2],spo2_col[pao2_real_meas[-2]]])
y_val=pao2_col[jdx]
aux_val=fio2_est_arr[jdx]
if np.isnan(x_vect).sum()==0 and np.isfinite(y_val) and np.isfinite(aux_val):
X_arr_collect.append(x_vect)
y_arr_collect.append(y_val)
aux_collect.append(aux_val)
if len(X_arr_collect)>0:
X_arr=np.vstack(X_arr_collect)
y_arr=np.array(y_arr_collect)
aux_arr=np.array(aux_collect)
assert(np.isnan(X_arr).sum()==0 and np.isnan(y_arr).sum()==0)
return (X_arr,y_arr,aux_arr)
else:
return (None,None,None)
def delete_low_density_hr_gap(vent_status_arr, hr_status_arr, configs=None):
''' Deletes gaps in ventilation which are caused by likely sensor dis-connections'''
in_event=False
in_gap=False
gap_idx=-1
for idx in range(len(vent_status_arr)):
# Beginning of new event, not from inside gap
if not in_event and not in_gap and vent_status_arr[idx]==1.0:
in_event=True
# Beginning of potential gap that needs to be closed
elif in_event and vent_status_arr[idx]==0.0:
in_gap=True
gap_idx=idx
in_event=False
# The gap is over, re-assign the status of ventilation to merge the gap, enter new event
if in_gap and vent_status_arr[idx]==1.0:
hr_sub_arr=hr_status_arr[gap_idx:idx]
# Close the gap if the density of HR is too low in between
if np.sum(hr_sub_arr)/hr_sub_arr.size<=configs["vent_hr_density_threshold"]:
vent_status_arr[gap_idx:idx]=1.0
in_gap=False
in_event=True
return vent_status_arr
def suppox_to_fio2(suppox_val):
''' Conversion of supplemental oxygen to FiO2 estimated value'''
if suppox_val>15:
return 75
else:
return SUPPOX_TO_FIO2[suppox_val]
def conservative_state(state1,state2):
''' Given two states, return the lower one '''
if state1==state2:
return state1
for skey in ["event_0","event_1","event_2"]:
if state1==skey or state2==skey:
return skey
return "event_3"
def endpoint_gen_benchmark(configs):
var_map=configs["VAR_IDS"]
raw_var_map=configs["RAW_VAR_IDS"]
sz_window=configs["length_fw_window"]
abga_window=configs["length_ABGA_window"]
missing_unm=0
# Threshold statistics
stat_counts_ready_and_failure=0
stat_counts_ready_and_success=0
stat_counts_nready_and_failure=0
stat_counts_nready_and_success=0
stat_counts_ready_nextube=0
stat_counts_nready_nextube=0
imputed_f=configs["imputed_path"]
merged_f=os.path.join(configs["merged_h5"])
out_folder=os.path.join(configs["endpoint_path"])
if not os.path.exists(out_folder):
os.mkdir(out_folder)
batch_id=configs["batch_idx"]
logging.info("Generating endpoints for batch {}".format(batch_id))
batch_fpath=os.path.join(imputed_f,"batch_{}.parquet".format(batch_id))
if not os.path.exists(batch_fpath):
logging.info("WARNING: Input file does not exist, exiting...")
sys.exit(1)
df_batch=pd.read_parquet(os.path.join(imputed_f,"batch_{}.parquet".format(batch_id)))
logging.info("Loaded imputed data done...")
cand_raw_batch=glob.glob(os.path.join(merged_f,"part-{}.parquet".format(batch_id)))
assert(len(cand_raw_batch)==1)
pids=list(df_batch.patientid.unique())
logging.info("Number of patients in batch: {}".format(len(df_batch.patientid.unique())))
first_write=True
out_fp=os.path.join(out_folder,"batch_{}.parquet".format(batch_id))
event_count={"FIO2_AVAILABLE": 0, "SUPPOX_NO_MEAS_12_HOURS_LIMIT": 0, "SUPPOX_MAIN_VAR": 0, "SUPPOX_HIGH_FLOW": 0,
"SUPPOX_NO_FILL_STOP": 0}
readiness_ext_count=0
not_ready_ext_count=0
readiness_and_extubated_cnt=0
extubated_cnt=0
df_static=pd.read_parquet(configs["general_data_table_path"])
X_reg_collect=[]
y_reg_collect=[]
aux_reg_collect=[]
out_dfs=[]
for pidx,pid in enumerate(pids):
df_pid=df_batch[df_batch["patientid"]==pid]
if df_pid.shape[0]==0:
logging.info("WARNING: No input data for PID: {}".format(pid))
continue
df_merged_pid=pd.read_parquet(cand_raw_batch[0],filters=[("patientid","=",pid)])
df_merged_pid.sort_values(by="datetime", inplace=True)
suppox_val={}
suppox_ts={}
# Main route of SuppOx
df_suppox_red_async=df_merged_pid[[var_map["SuppOx"], "datetime"]]
df_suppox_red_async = df_suppox_red_async.dropna(how="all",thresh=2)
suppox_async_red_ts=np.array(df_suppox_red_async["datetime"])
suppox_val["SUPPOX"]=np.array(df_suppox_red_async[var_map["SuppOx"]])
# Strategy is to create an imputed SuppOx column based on the spec using
# forward filling heuristics
# Relevant meta-variables
fio2_col=np.array(df_pid[var_map["FiO2"]])
pao2_col=np.array(df_pid[var_map["PaO2"]])
etco2_col=np.array(df_pid[var_map["etCO2"]])
paco2_col=np.array(df_pid[var_map["PaCO2"]])
gcs_a_col=np.array(df_pid[var_map["GCS_Antwort"]])
gcs_m_col=np.array(df_pid[var_map["GCS_Motorik"]])
gcs_aug_col=np.array(df_pid[var_map["GCS_Augen"]])
weight_col=np.array(df_pid[var_map["Weight"][0]])
noreph_col=np.array(df_pid[var_map["Norephenephrine"][0]])
epineph_col=np.array(df_pid[var_map["Epinephrine"][0]])
vaso_col=np.array(df_pid[var_map["Vasopressin"][0]])
milri_col=np.array(df_pid[var_map["Milrinone"][0]])
dobut_col=np.array(df_pid[var_map["Dobutamine"][0]])
levosi_col=np.array(df_pid[var_map["Levosimendan"][0]])
theo_col=np.array(df_pid[var_map["Theophyllin"][0]])
lactate_col=np.array(df_pid[var_map["Lactate"][0]])
peep_col=np.array(df_pid[var_map["PEEP"]])
# Heartrate
hr_col=np.array(df_pid[var_map["HR"]])
hr_meas_cnt=np.array(df_pid["{}_IMPUTED_STATUS_CUM_COUNT".format(var_map["HR"])])
# Temperature
temp_col=np.array(df_pid[var_map["Temp"]])
temp_meas_cnt=np.array(df_pid["{}_IMPUTED_STATUS_CUM_COUNT".format(var_map["Temp"])])
rrate_col=np.array(df_pid[var_map["RRate"]])
tv_col=np.array(df_pid[var_map["TV"]])
map_col=np.array(df_pid[var_map["MAP"][0]])
airway_col=np.array(df_pid[var_map["Airway"]])
# Ventilator mode group columns
vent_mode_col=np.array(df_pid[var_map["vent_mode"]])
spo2_col=np.array(df_pid[var_map["SpO2"]])
if configs["presmooth_spo2"]:
spo2_col=percentile_smooth(spo2_col,configs["spo2_smooth_percentile"],configs["spo2_smooth_window_size_mins"])
sao2_col=np.array(df_pid[var_map["SaO2"]])
ph_col=np.array(df_pid[var_map["pH"]])
fio2_meas_cnt=np.array(df_pid["{}_IMPUTED_STATUS_CUM_COUNT".format(var_map["FiO2"])])
pao2_meas_cnt=np.array(df_pid["{}_IMPUTED_STATUS_CUM_COUNT".format(var_map["PaO2"])])
etco2_meas_cnt=np.array(df_pid["{}_IMPUTED_STATUS_CUM_COUNT".format(var_map["etCO2"])])
peep_meas_cnt=np.array(df_pid["{}_IMPUTED_STATUS_CUM_COUNT".format(var_map["PEEP"])])
hr_meas_cnt=np.array(df_pid["{}_IMPUTED_STATUS_CUM_COUNT".format(var_map["HR"])])
spo2_meas_cnt=np.array(df_pid["{}_IMPUTED_STATUS_CUM_COUNT".format(var_map["SpO2"])])
sao2_meas_cnt=np.array(df_pid["{}_IMPUTED_STATUS_CUM_COUNT".format(var_map["SaO2"])])
ph_meas_cnt=np.array(df_pid["{}_IMPUTED_STATUS_CUM_COUNT".format(var_map["pH"])])
abs_dtime_arr=np.array(df_pid["datetime"])
event_status_arr=np.zeros(shape=(fio2_col.size),dtype="<S10")
# Status arrays
pao2_avail_arr=np.zeros(shape=(fio2_col.size))
fio2_avail_arr=np.zeros(shape=(fio2_col.size))
fio2_suppox_arr=np.zeros(shape=(fio2_col.size))
fio2_ambient_arr=np.zeros(shape=(fio2_col.size))
pao2_sao2_model_arr=np.zeros(shape=(fio2_col.size))
pao2_full_model_arr=np.zeros(shape=(fio2_col.size))
ratio_arr=np.zeros(shape=(fio2_col.size))
sur_ratio_arr=np.zeros(shape=(fio2_col.size))
pao2_est_arr=np.zeros(shape=(fio2_col.size))
fio2_est_arr=np.zeros(shape=(fio2_col.size))
vent_status_arr=np.zeros(shape=(fio2_col.size))
readiness_ext_arr=np.zeros(shape=(fio2_col.size))
readiness_ext_arr[:]=np.nan
# Votes arrays
vent_votes_arr=np.zeros(shape=(fio2_col.size))
vent_votes_etco2_arr=np.zeros(shape=(fio2_col.size))
vent_votes_ventgroup_arr=np.zeros(shape=(fio2_col.size))
vent_votes_tv_arr=np.zeros(shape=(fio2_col.size))
vent_votes_airway_arr=np.zeros(shape=(fio2_col.size))
peep_status_arr=np.zeros(shape=(fio2_col.size))
peep_threshold_arr=np.zeros(shape=(fio2_col.size))
hr_status_arr=np.zeros(shape=(fio2_col.size))
etco2_status_arr=np.zeros(shape=(fio2_col.size))
event_status_arr.fill("UNKNOWN")
# Array pointers tracking the current active value of each type
suppox_async_red_ptr=-1
# ======================== VENTILATION ================================================================================================
# Label each point in the 30 minute window with ventilation
in_vent_event=False
for jdx in range(0,len(ratio_arr)):
win_etco2=etco2_col[max(0,jdx-configs["etco2_vent_search_bw"]):min(len(ratio_arr),jdx+configs["etco2_vent_search_fw"])]
win_etco2_meas=etco2_meas_cnt[max(0,jdx-configs["etco2_vent_search_bw"]):min(len(ratio_arr),jdx+configs["etco2_vent_search_fw"])]
win_peep=peep_col[max(0,jdx-configs["peep_search_bw"]):min(len(ratio_arr),jdx+configs["peep_search_fw"])]
win_peep_meas=peep_meas_cnt[max(0,jdx-configs["peep_search_bw"]):min(len(ratio_arr),jdx+configs["peep_search_fw"])]
win_hr_meas=hr_meas_cnt[max(0,jdx-configs["hr_vent_search_bw"]):min(len(ratio_arr),jdx+configs["hr_vent_search_fw"])]
etco2_meas_win=win_etco2_meas[-1]-win_etco2_meas[0]>0
peep_meas_win=win_peep_meas[-1]-win_peep_meas[0]>0
hr_meas_win=win_hr_meas[-1]-win_hr_meas[0]>0
current_vent_group=vent_mode_col[jdx]
current_tv=tv_col[jdx]
current_airway=airway_col[jdx]
vote_score=0
# EtCO2 requirement (still needed)
if etco2_meas_win and (win_etco2>0.5).any():
vote_score+=2
vent_votes_etco2_arr[jdx]=2
# Ventilation group requirement (still needed)
if current_vent_group in [2.0,3.0,4.0,5.0,6.0,7.0,8.0,10.0]:
vote_score+=1
vent_votes_ventgroup_arr[jdx]+=1
elif current_vent_group in [1.0]:
vote_score-=1
vent_votes_ventgroup_arr[jdx]-=1
elif current_vent_group in [11.0,12.0,13.0,15.0,17.0]:
vote_score-=2
vent_votes_ventgroup_arr[jdx]-=2
# TV presence requirement (still needed)
if current_tv>0:
vote_score+=1
vent_votes_tv_arr[jdx]=1
# Airway requirement (still needed)
if current_airway in [1,2]:
vote_score+=2
vent_votes_airway_arr[jdx]=2
# No airway (still needed)
if current_airway in [3,4,5,6]:
vote_score-=1
vent_votes_airway_arr[jdx]=-1
vent_votes_arr[jdx]=vote_score
if vote_score>=configs["vent_vote_threshold"]:
in_vent_event=True
vent_status_arr[jdx]=1
else:
in_vent_event=False
if peep_meas_win:
peep_status_arr[jdx]=1
if (win_peep>=configs["peep_threshold"]).any():
peep_threshold_arr[jdx]=1
if etco2_meas_win:
etco2_status_arr[jdx]=1
if hr_meas_win:
hr_status_arr[jdx]=1
if configs["detect_hr_gaps"]:
vent_status_arr=delete_low_density_hr_gap(vent_status_arr, hr_status_arr, configs=configs)
if configs["merge_short_vent_gaps"]:
vent_status_arr=merge_short_vent_gaps(vent_status_arr, configs["short_gap_hours"])
if configs["delete_short_vent_events"]:
vent_status_arr=delete_short_vent_events(vent_status_arr, configs["short_event_hours"])
#vent_status_arr=correct_left_edge_vent(vent_status_arr, etco2_meas_cnt, etco2_col)
#vent_status_arr=correct_right_edge_vent(vent_status_arr, etco2_meas_cnt, etco2_col)
# Ventilation period array
vent_period_arr=np.copy(vent_status_arr)
# Delete short ventilation periods if no HR gap before
in_event=False
event_length=0
for idx in range(len(vent_period_arr)):
cur_state=vent_period_arr[idx]
if in_event and cur_state==1.0:
event_length+=5
if not in_event and cur_state==1.0:
in_event=True
event_length=5
event_start_idx=idx
if in_event and (np.isnan(cur_state) or cur_state==0.0):
in_event=False
# Short event at beginning of stay shall never be deleted...
if event_start_idx==0:
delete_event=False
else:
search_hr_idx=event_start_idx-1
while search_hr_idx>=0:
if hr_status_arr[search_hr_idx]==1.0:
hr_gap_length=5*(event_start_idx-search_hr_idx)
delete_event=True
break
search_hr_idx-=1
# Found no HR before event, do not delete event...
if search_hr_idx==-1:
delete_event=False
# Delete event in principle, then check if short enough...
if delete_event:
event_length+=hr_gap_length
if event_length/60.<=configs["short_event_hours_vent_period"]:
vent_period_arr[event_start_idx:idx]=0.0
# ============================== OXYGENATION ENDPOINTS ==================================================================
# Label each point in the 30 minute window (except ventilation)
for jdx in range(0,len(ratio_arr)):
# Advance to the last SuppOx infos before grid point
cur_time=abs_dtime_arr[jdx]
while True:
suppox_async_red_ptr=suppox_async_red_ptr+1
if suppox_async_red_ptr>=len(suppox_async_red_ts) or suppox_async_red_ts[suppox_async_red_ptr]>cur_time:
suppox_async_red_ptr=suppox_async_red_ptr-1
break
# Estimate the current FiO2 value
bw_fio2=fio2_col[max(0,jdx-configs["sz_fio2_window"]):jdx+1]
bw_fio2_meas=fio2_meas_cnt[max(0,jdx-configs["sz_fio2_window"]):jdx+1]
bw_etco2_meas=etco2_meas_cnt[max(0,jdx-configs["sz_etco2_window"]):jdx+1]
fio2_meas=bw_fio2_meas[-1]-bw_fio2_meas[0]>0
etco2_meas=bw_etco2_meas[-1]-bw_etco2_meas[0]>0
mode_group_est=vent_mode_col[jdx]
# FiO2 is measured since beginning of stay and EtCO2 was measured, we use FiO2 (indefinite forward filling)
# if ventilation is active or the current estimate of ventilation mode group is NIV.
if fio2_meas and (vent_status_arr[jdx]==1.0 or mode_group_est==4.0):
event_count["FIO2_AVAILABLE"]+=1
fio2_val=bw_fio2[-1]/100
fio2_avail_arr[jdx]=1
# Use supplemental oxygen or ambient air oxygen
else:
# No real measurements up to now, or the last real measurement
# was more than 8 hours away.
if suppox_async_red_ptr==-1 or (cur_time-suppox_async_red_ts[suppox_async_red_ptr])>np.timedelta64(configs["suppox_max_ffill"],'h'):
event_count["SUPPOX_NO_MEAS_12_HOURS_LIMIT"]+=1
fio2_val=configs["ambient_fio2"]
fio2_ambient_arr[jdx]=1
# Find the most recent source variable of SuppOx
else:
suppox=suppox_val["SUPPOX"][suppox_async_red_ptr]
# SuppOx information from main source
if np.isfinite(suppox):
event_count["SUPPOX_MAIN_VAR"]+=1
fio2_val=suppox_to_fio2(int(suppox))/100
fio2_suppox_arr[jdx]=1
else:
assert(False, "Impossible condition")
bw_pao2_meas=pao2_meas_cnt[max(0,jdx-configs["sz_pao2_window"]):jdx+1]
bw_pao2=pao2_col[max(0,jdx-configs["sz_pao2_window"]):jdx+1]
pao2_meas=bw_pao2_meas[-1]-bw_pao2_meas[0]>=1
# PaO2 was just measured, just use the value
if pao2_meas:
pao2_estimate=bw_pao2[-1]
pao2_avail_arr[jdx]=1
# Have to forecast PaO2 from a previous SpO2
else:
bw_spo2=spo2_col[max(0,jdx-abga_window):jdx+1]
bw_spo2_meas=spo2_meas_cnt[max(0,jdx-abga_window):jdx+1]
spo2_meas=bw_spo2_meas[-1]-bw_spo2_meas[0]>=1
# Standard case, take the last SpO2 measurement
if spo2_meas:
spo2_val=bw_spo2[-1]
pao2_estimate=ellis(np.array([spo2_val]))[0]
# Extreme edge case, there was SpO2 measurement in the last 24 hours
else:
spo2_val=98
pao2_estimate=ellis(np.array([spo2_val]))[0]
# Compute the individual components of the Horowitz index
pao2_est_arr[jdx]=pao2_estimate
fio2_est_arr[jdx]=fio2_val
pao2_est_arr_orig=np.copy(pao2_est_arr)
# Smooth individual components of the P/F ratio estimate
if configs["kernel_smooth_estimate_pao2"]:
pao2_est_arr=kernel_smooth_arr(pao2_est_arr, bandwidth=configs["smoothing_bandwidth"])
if configs["kernel_smooth_estimate_fio2"]:
fio2_est_arr=kernel_smooth_arr(fio2_est_arr, bandwidth=configs["smoothing_bandwidth"])
# Test2 data-set for surrogate model
pao2_sur_est=np.copy(pao2_est_arr)
assert(np.sum(np.isnan(pao2_sur_est))==0)
# Convex combination of the estimate
if configs["mix_real_estimated_pao2"]:
pao2_est_arr=mix_real_est_pao2(pao2_col, pao2_meas_cnt, pao2_est_arr, bandwidth=configs["smoothing_bandwidth"])
# Compute Horowitz indices (Kernel pipeline / Surrogate model pipeline)
for jdx in range(len(ratio_arr)):
ratio_arr[jdx]=pao2_est_arr[jdx]/fio2_est_arr[jdx]
# Post-smooth Horowitz index
if configs["post_smooth_pf_ratio"]:
ratio_arr=kernel_smooth_arr(ratio_arr, bandwidth=configs["post_smoothing_bandwidth"])
if configs["pao2_version"]=="ellis_basic":
pf_event_est_arr=np.copy(ratio_arr)
elif configs["pao2_version"]=="original":
assert(False)
# Now label based on the array of estimated Horowitz indices
for idx in range(0,len(event_status_arr)-configs["offset_back_windows"]):
est_idx=pf_event_est_arr[idx:min(len(ratio_arr),idx+sz_window)]
est_vent=vent_status_arr[idx:min(len(ratio_arr),idx+sz_window)]
est_peep_dense=peep_status_arr[idx:min(len(ratio_arr),idx+sz_window)]
est_peep_threshold=peep_threshold_arr[idx:min(len(ratio_arr),idx+sz_window)]
if np.sum((est_idx<=100) & ((est_vent==0.0) | (est_vent==1.0) & (est_peep_dense==0.0) | (est_vent==1.0) & (est_peep_dense==1.0) & (est_peep_threshold==1.0)) )>=2/3*len(est_idx):
event_status_arr[idx]="event_3"
elif np.sum((est_idx<=200) & ((est_vent==0.0) | (est_vent==1.0) & (est_peep_dense==0.0) | (est_vent==1.0) & (est_peep_dense==1.0) & (est_peep_threshold==1.0)) )>=2/3*len(est_idx):
event_status_arr[idx]="event_2"
elif | np.sum((est_idx<=300) & ((est_vent==0.0) | (est_vent==1.0) & (est_peep_dense==0.0) | (est_vent==1.0) & (est_peep_dense==1.0) & (est_peep_threshold==1.0)) )>=2/3*len(est_idx) | numpy.sum |
"""Non-negative matrix and tensor factorization core functions
"""
# Author: <NAME>
# License: MIT
# Jan 4, '20
import math
import numpy as np
#from sklearn.utils.extmath import randomized_svd
from tqdm import tqdm
from scipy.stats import hypergeom
from scipy.optimize import nnls
from .nmtf_utils import *
def NMFProjGrad(V, Vmis, W, Hinit, NMFAlgo, lambdax, tol, MaxIterations, NMFPriors):
"""Projected gradient
Code and notations adapted from Matlab code, Chih-Jen Lin
Input:
V: Input matrix
Vmis: Define missing values (0 = missing cell, 1 = real cell)
W: Left factoring vectors (fixed)
Hinit: Right factoring vectors (initial values)
NMFAlgo: =1,3: Divergence; =2,4: Least squares;
lambdax: Sparseness parameter
=-1: no penalty
< 0: Target percent zeroed rows in H
> 0: Current penalty
tol: Tolerance
MaxIterations: max number of iterations to achieve norm(projected gradient) < tol
NMFPriors: Elements in H that should be updated (others remain 0)
Output:
H: Estimated right factoring vectors
tol: Current level of the tolerance
lambdax: Current level of the penalty
Reference
---------
<NAME> (2007) Projected Gradient Methods for Non-negative Matrix Factorization
Neural Comput. 2007 Oct;19(10):2756-79.
"""
H = Hinit
try:
n_NMFPriors, nc = NMFPriors.shape
except:
n_NMFPriors = 0
n_Vmis = Vmis.shape[0]
n, p = np.shape(V)
n, nc = np.shape(W)
alpha = 1
if (NMFAlgo == 2) or (NMFAlgo == 4):
beta = .1
if n_Vmis > 0:
WtV = W.T @ (V * Vmis)
else:
WtV = W.T @ V
WtW = W.T @ W
else:
beta = .1
if n_Vmis > 0:
WtWH = W.T @ Vmis
else:
WtWH = W.T @ np.ones((n, p))
if (lambdax < 0) & (lambdax != -1):
H0 = H
restart = True
while restart:
for iIter in range(1, MaxIterations + 1):
addPenalty = 0
if lambdax != -1:
addPenalty = 1
if (NMFAlgo == 2) or (NMFAlgo == 4):
if n_Vmis > 0:
WtWH = W.T @ ((W @ H) * Vmis)
else:
WtWH = WtW @ H
else:
if n_Vmis > 0:
WtV = W.T @ ((V * Vmis) / (W @ H))
else:
WtV = W.T @ (V / (W @ H))
if lambdax > 0:
grad = WtWH - WtV + lambdax
else:
grad = WtWH - WtV
projgrad = np.linalg.norm(grad[(grad < 0) | (H > 0)])
if projgrad >= tol:
# search step size
for inner_iter in range(1, 21):
Hn = H - alpha * grad
Hn[np.where(Hn < 0)] = 0
if n_NMFPriors > 0:
Hn = Hn * NMFPriors
d = Hn - H
gradd = np.sum(grad * d)
if (NMFAlgo == 2) or (NMFAlgo == 4):
if n_Vmis > 0:
dQd = np.sum((W.T @ ((W @ d) * Vmis)) * d)
else:
dQd = np.sum((WtW @ d) * d)
else:
if n_Vmis > 0:
dQd = np.sum((W.T @ ((W @ d) * (Vmis / (W @ H)))) * d)
else:
dQd = np.sum((W.T @ ((W @ d) / (W @ H))) * d)
suff_decr = (0.99 * gradd + 0.5 * dQd < 0)
if inner_iter == 1:
decr_alpha = not suff_decr
Hp = H
if decr_alpha:
if suff_decr:
H = Hn
break
else:
alpha = alpha * beta
else:
if (suff_decr == False) | (np.where(Hp != Hn)[0].size == 0):
H = Hp
break
else:
alpha = alpha / beta
Hp = Hn
# End for (inner_iter
if (lambdax < 0) & addPenalty:
# Initialize penalty
lambdax = percentile_exc(H[np.where(H > 0)], -lambdax * 100)
H = H0
alpha = 1
else: # projgrad < tol
if (iIter == 1) & (projgrad > 0):
tol /= 10
else:
restart = False
break
# End if projgrad
if iIter == MaxIterations:
restart = False
# End For iIter
H = H.T
return [H, tol, lambdax]
def NMFProjGradKernel(Kernel, V, Vmis, W, Hinit, NMFAlgo, tol, MaxIterations, NMFPriors):
"""Projected gradient, kernel version
Code and notations adapted from Matlab code, <NAME>
Input:
Kernel: Kernel used
V: Input matrix
Vmis: Define missing values (0 = missing cell, 1 = real cell)
W: Left factoring vectors (fixed)
Hinit: Right factoring vectors (initial values)
NMFAlgo: =1,3: Divergence; =2,4: Least squares;
tol: Tolerance
MaxIterations: max number of iterations to achieve norm(projected gradient) < tol
NMFPriors: Elements in H that should be updated (others remain 0)
Output:
H: Estimated right factoring vectors
tol: Current level of the tolerance
Reference
---------
<NAME> (2007) Projected Gradient Methods for Non-negative Matrix Factorization
Neural Comput. 2007 Oct;19(10):2756-79.
"""
H = Hinit.T
try:
n_NMFPriors, nc = NMFPriors.shape
except:
n_NMFPriors = 0
n_Vmis = Vmis.shape[0]
n, p = np.shape(V)
p, nc = np.shape(W)
alpha = 1
VW = V @ W
if (NMFAlgo == 2) or (NMFAlgo == 4):
beta = .1
if n_Vmis > 0:
WtV = VW.T @ (V * Vmis)
else:
WtV = W.T @ Kernel
WtW = W.T @ Kernel @ W
else:
beta = .1
MaxIterations = round(MaxIterations/10)
if n_Vmis > 0:
WtWH = VW.T @ Vmis
else:
WtWH = VW.T @ np.ones((n, p))
restart = True
while restart:
for iIter in range(1, MaxIterations + 1):
if (NMFAlgo == 2) or (NMFAlgo == 4):
if n_Vmis > 0:
WtWH = VW.T @ ((VW @ H) * Vmis)
else:
WtWH = WtW @ H
else:
if n_Vmis > 0:
WtV = VW.T @ ((V * Vmis) / (VW @ H))
else:
WtV = VW.T @ (V / (VW @ H))
grad = WtWH - WtV
projgrad = np.linalg.norm(grad[(grad < 0) | (H > 0)])
if projgrad >= tol:
# search step size
for inner_iter in range(1, 21):
Hn = H - alpha * grad
Hn[np.where(Hn < 0)] = 0
if n_NMFPriors > 0:
Hn = Hn * NMFPriors
d = Hn - H
gradd = np.sum(grad * d)
if (NMFAlgo == 2) or (NMFAlgo == 4):
if n_Vmis > 0:
dQd = np.sum((VW.T @ ((VW @ d) * Vmis)) * d)
else:
dQd = np.sum((WtW @ d) * d)
else:
if n_Vmis > 0:
dQd = np.sum((VW.T @ ((VW @ d) * (Vmis / (VW @ H)))) * d)
else:
dQd = np.sum((VW.T @ ((VW @ d) / (VW @ H))) * d)
suff_decr = (0.99 * gradd + 0.5 * dQd < 0)
if inner_iter == 1:
decr_alpha = not suff_decr
Hp = H
if decr_alpha:
if suff_decr:
H = Hn
break
else:
alpha = alpha * beta
else:
if (suff_decr == False) | (np.where(Hp != Hn)[0].size == 0):
H = Hp
break
else:
alpha = alpha / beta
Hp = Hn
# End for (inner_iter
else: # projgrad < tol
if iIter == 1:
tol /= 10
else:
restart = False
break
# End if projgrad
if iIter == MaxIterations:
restart = False
# End For iIter
H = H.T
return [H, tol]
def NMFApplyKernel(M, NMFKernel, Mt, Mw):
"""Calculate kernel (used with convex NMF)
Input:
M: Input matrix
NMFKernel: Type of kernel
=-1: linear
= 2: quadratic
= 3: radiant
Mt: Left factoring matrix
Mw: Right factoring matrix
Output:
Kernel
"""
n, p = M.shape
try:
p, nc = Mw.shape
except:
nc = 0
if NMFKernel == 1:
Kernel = M.T @ M
elif NMFKernel == 2:
Kernel = (np.identity(p) + M.T @ M) ** 2
elif NMFKernel == 3:
Kernel = np.identity(p)
# Estimate Sigma2
Sigma2 = 0
for k1 in range(1, nc):
for k2 in range(0, k1):
Sigma2 = max(Sigma2, np.linalg.norm(Mt[:, k1] - Mt[:, k2]) ** 2)
Sigma2 /= nc
for j1 in range(1, p):
for j2 in range(0, j1):
Kernel[j1, j2] = math.exp(-np.linalg.norm(M[:, j1] - M[:, j2]) ** 2 / Sigma2)
Kernel[j2, j1] = Kernel[j1, j2]
return Kernel
def NMFReweigh(M, Mt, NMFPriors, AddMessage):
"""Overload skewed variables (used with deconvolution only)
Input:
M: Input matrix
Mt: Left hand matrix
NMFPriors: priors on right hand matrix
Output:
NMFPriors: updated priors
Note: This code is still experimental
"""
ErrMessage = ""
n, p = M.shape
n_NMFPriors, nc = NMFPriors.shape
NMFPriors[NMFPriors > 0] = 1
ID = np.where(np.sum(NMFPriors, axis=1) > 1)
n_ID = ID[0].shape[0]
if n_ID == p:
ErrMessage = 'Error! All priors are ambiguous.\nYou may uncheck the option in tab irMF+.'
return [NMFPriors, AddMessage, ErrMessage]
NMFPriors[ID, :] = 0
Mweight = np.zeros((p, nc))
for k in range(0, nc):
ID = np.where(NMFPriors[:, k] > 0)
pk = ID[0].shape[0]
if pk == 0:
ErrMessage = 'Error! Null column in NMF priors (' + str(k+1) + ', pre outlier filtering)'
return [NMFPriors, AddMessage, ErrMessage]
Mc = np.zeros((n, p))
# Exclude variables with outliers
NInterQuart = 1.5
for j in range(0, pk):
Quart75 = percentile_exc(M[:, ID[0][j]], 75)
Quart25 = percentile_exc(M[:, ID[0][j]], 25)
InterQuart = Quart75 - Quart25
MaxBound = Quart75 + NInterQuart * InterQuart
MinBound = Quart25 - NInterQuart * InterQuart
if np.where((M[:, ID[0][j]] < MinBound) | (M[:, ID[0][j]] > MaxBound))[0].shape[0] == 1:
NMFPriors[ID[0][j], k] = 0
ID = np.where(NMFPriors[:, k] > 0)
pk = ID[0].shape[0]
if pk == 0:
ErrMessage = 'Error! Null column in NMF priors (' + str(k+1) + ', post outlier filtering)'
return [NMFPriors, AddMessage, ErrMessage]
# Characterize clusters by skewness direction
Mtc = Mt[:, k] - np.mean(Mt[:, k])
std = math.sqrt(np.mean(Mtc ** 2))
skewness = np.mean((Mtc / std) ** 3) * math.sqrt(n * (n - 1)) / (n - 2)
# Scale columns and initialized weights
for j in range(0, pk):
M[:, ID[0][j]] /= np.sum(M[:, ID[0][j]])
Mc[:, ID[0][j]] = M[:, ID[0][j]] - np.mean(M[:, ID[0][j]])
std = math.sqrt(np.mean(Mc[:, ID[0][j]] ** 2))
Mweight[ID[0][j], k] = np.mean((Mc[:, ID[0][j]] / std) ** 3) * math.sqrt(n * (n - 1)) / (n - 2)
if skewness < 0:
# Negative skewness => Component identifiable through small proportions
Mweight[Mweight[:, k] > 0, k] = 0
Mweight = -Mweight
IDneg = np.where(Mweight[:, k] > 0)
Nneg = IDneg[0].shape[0]
if Nneg == 0:
ErrMessage = 'Error! No marker variable found in component ' + str(k+1)
return [NMFPriors, AddMessage, ErrMessage]
AddMessage.insert(len(AddMessage),
'Component ' + str(k+1) + ': compositions are negatively skewed (' + str(
Nneg) + ' active variables)')
else:
# Positive skewness => Component identifiable through large proportions
Mweight[Mweight[:, k] < 0, k] = 0
IDpos = np.where(Mweight[:, k] > 0)
Npos = IDpos[0].shape[0]
if Npos == 0:
ErrMessage = 'Error! No marker variable found in component ' + str(k+1)
return [NMFPriors, AddMessage, ErrMessage]
AddMessage.insert(len(AddMessage),
'Component ' + str(k+1) + ': compositions are positively skewed (' + str(
Npos) + ' active variables)')
# Logistic transform of non-zero weights
ID2 = np.where(Mweight[:, k] > 0)
n_ID2 = ID2[0].shape[0]
if n_ID2 > 1:
mu = np.mean(Mweight[ID2[0], k])
std = np.std(Mweight[ID2[0], k])
Mweight[ID2[0], k] = (Mweight[ID2[0], k] - mu) / std
Mweight[ID2[0], k] = np.ones(n_ID2) - np.ones(n_ID2) / (np.ones(n_ID2) + np.exp(
2 * (Mweight[ID2[0], k] - percentile_exc(Mweight[ID2[0], k], 90))))
else:
Mweight[ID2[0], k] = 1
# ReWeigh columns
M[:, ID[0]] = M[:, ID[0]] * Mweight[ID[0], k].T
# Update NMF priors (cancel columns with 0 weight & replace non zero values by 1)
NMFPriors[ID[0], k] = NMFPriors[ID[0], k] * Mweight[ID[0], k]
ID = np.where(NMFPriors[:, k] > 0)
if ID[0].shape[0] > 0:
NMFPriors[ID[0], k] = 1
# Scale parts
M[:, ID[0]] /= np.linalg.norm(M[:, ID[0]])
else:
ErrMessage = 'Error! Null column in NMF priors (' + str(k+1) + ', post cancelling 0-weight columns)'
return [NMFPriors, AddMessage, ErrMessage]
return [NMFPriors, AddMessage, ErrMessage]
def NMFSolve(M, Mmis, Mt0, Mw0, nc, tolerance, precision, LogIter, Status0, MaxIterations, NMFAlgo,
NMFFixUserLHE, NMFFixUserRHE, NMFMaxInterm, NMFMaxIterProj, NMFSparseLevel,
NMFFindParts, NMFFindCentroids, NMFKernel, NMFReweighColumns, NMFPriors, flagNonconvex, AddMessage,
myStatusBox):
"""
Estimate left and right hand matrices
Input:
M: Input matrix
Mmis: Define missing values (0 = missing cell, 1 = real cell)
Mt0: Initial left hand matrix
Mw0: Initial right hand matrix
nc: NMF rank
tolerance: Convergence threshold
precision: Replace 0-value in multiplication rules
LogIter: Log results through iterations
Status0: Initial displayed status to be updated during iterations
MaxIterations: Max iterations
NMFAlgo: =1,3: Divergence; =2,4: Least squares;
NMFFixUserLHE: = 1 => fixed left hand matrix columns
NMFFixUserRHE: = 1 => fixed right hand matrix columns
NMFMaxInterm: Max iterations for warmup multiplication rules
NMFMaxIterProj: Max iterations for projected gradient
NMFSparseLevel: Requested sparsity in terms of relative number of rows with 0 values in right hand matrix
NMFFindParts: Enforce convexity on left hand matrix
NMFFindCentroids: Enforce convexity on right hand matrix
NMFKernel: Type of kernel used; 1: linear; 2: quadratic; 3: radial
NMFReweighColumns: Reweigh columns in 2nd step of parts-based NMF
NMFPriors: Priors on right hand matrix
flagNonconvex: Non-convexity flag on left hand matrix
Output:
Mt: Left hand matrix
Mw: Right hand matrix
diff: objective cost
Mh: Convexity matrix
NMFPriors: Updated priors on right hand matrix
flagNonconvex: Updated non-convexity flag on left hand matrix
Reference
---------
<NAME> et al (2010) Convex and Semi-Nonnegative Matrix Factorizations
IEEE Transactions on Pattern Analysis and Machine Intelligence Vol: 32 Issue: 1
"""
ErrMessage = ''
cancel_pressed = 0
n, p = M.shape
n_Mmis = Mmis.shape[0]
try:
n_NMFPriors, nc = NMFPriors.shape
except:
n_NMFPriors = 0
nc = int(nc)
nxp = int(n * p)
Mh = np.array([])
Mt = np.copy(Mt0)
Mw = np.copy(Mw0)
diff = 1.e+99
# Add weights
if n_NMFPriors > 0:
if NMFReweighColumns > 0:
# A local copy of M will be updated
M = np.copy(M)
NMFPriors, AddMessage, ErrMessage = NMFReweigh(M, Mt, NMFPriors, AddMessage)
if ErrMessage != "":
return [Mt, Mw, diff, Mh, NMFPriors, flagNonconvex, AddMessage, ErrMessage, cancel_pressed]
else:
NMFPriors[NMFPriors > 0] = 1
if (NMFFindParts > 0) & (NMFFixUserLHE > 0):
NMFFindParts = 0
if (NMFFindCentroids > 0) & (NMFFixUserRHE > 0):
NMFFindCentroids = 0
NMFKernel = 1
if (NMFFindCentroids > 0) & (NMFKernel > 1):
if n_Mmis > 0:
NMFKernel = 1
AddMessage.insert(len(AddMessage), 'Warning: Non linear kernel canceled due to missing values.')
if (NMFAlgo == 1) or (NMFAlgo == 3) :
NMFKernel = 1
AddMessage.insert(len(AddMessage), 'Warning: Non linear kernel canceled due to divergence minimization.')
if n_NMFPriors > 0:
MwUser = NMFPriors
for k in range(0, nc):
if (NMFAlgo == 2) | (NMFAlgo == 4):
Mw[:, k] = MwUser[:, k] / np.linalg.norm(MwUser[:, k])
else:
Mw[:, k] = MwUser[:, k] / np.sum(MwUser[:, k])
MultOrPgrad = 1 # Start with Lee-Seung mult rules
MaxIterations += NMFMaxInterm # NMFMaxInterm Li-Seung iterations initialize projected gradient
StepIter = math.ceil(MaxIterations / 10)
pbar_step = 100 * StepIter / MaxIterations
iIter = 0
cont = 1
# Initialize penalty
# lambda = -1: no penalty
# lambda = -abs(NMFSparselevel) : initialisation by NMFSparselevel (in negative value)
if NMFSparseLevel > 0:
lambdaw = -NMFSparseLevel
lambdat = -1
elif NMFSparseLevel < 0:
lambdat = NMFSparseLevel
lambdaw = -1
else:
lambdaw = -1
lambdat = -1
PercentZeros = 0
iterSparse = 0
NMFConvex = 0
NLKernelApplied = 0
myStatusBox.init_bar(delay=1)
# Start loop
while (cont == 1) & (iIter < MaxIterations):
# Update RHE
if NMFFixUserRHE == 0:
if MultOrPgrad == 1:
if (NMFAlgo == 2) or (NMFAlgo == 4):
if n_Mmis > 0:
Mw = \
Mw * ((Mt.T @ (M * Mmis)) / (
Mt.T @ ((Mt @ Mw.T) * Mmis) + precision)).T
else:
Mw = \
Mw * ((Mt.T @ M) / (
(Mt.T @ Mt) @ Mw.T + precision)).T
else:
if n_Mmis > 0:
Mw = Mw * (((M * Mmis) / ((Mt @ Mw.T) * Mmis + precision)).T @ Mt)
else:
Mw = Mw * ((M / (Mt @ Mw.T + precision)).T @ Mt)
if n_NMFPriors > 0:
Mw = Mw * NMFPriors
else:
# Projected gradient
if (NMFConvex > 0) & (NMFFindParts > 0):
Mw, tolMw = NMFProjGradKernel(Kernel, M, Mmis, Mh, Mw, NMFAlgo, tolMw, NMFMaxIterProj, NMFPriors.T)
elif (NMFConvex > 0) & (NMFFindCentroids > 0):
Mh, tolMh, dummy = NMFProjGrad(In, np.array([]), Mt, Mh.T, NMFAlgo, -1, tolMh, NMFMaxIterProj, np.array([]))
else:
Mw, tolMw, lambdaw = NMFProjGrad(M, Mmis, Mt, Mw.T, NMFAlgo, lambdaw, tolMw, \
NMFMaxIterProj, NMFPriors.T)
if (NMFConvex > 0) & (NMFFindParts > 0):
for k in range(0, nc):
ScaleMw = np.linalg.norm(Mw[:, k])
Mw[:, k] = Mw[:, k] / ScaleMw
Mt[:, k] = Mt[:, k] * ScaleMw
# Update LHE
if NMFFixUserLHE == 0:
if MultOrPgrad == 1:
if (NMFAlgo == 2) | (NMFAlgo == 4):
if n_Mmis > 0:
Mt = \
Mt * ((M * Mmis) @ Mw / (
((Mt @ Mw.T) * Mmis) @ Mw + precision))
else:
Mt = \
Mt * (M @ Mw / (Mt @ (Mw.T @ Mw) + precision))
else:
if n_Mmis > 0:
Mt = Mt * (((M * Mmis).T / (Mw @ Mt.T + precision)).T @ Mw)
else:
Mt = Mt * ((M.T / (Mw @ Mt.T + precision)).T @ Mw)
else:
# Projected gradient
if (NMFConvex > 0) & (NMFFindParts > 0):
Mh, tolMh, dummy = NMFProjGrad(Ip, np.array([]), Mw, Mh.T, NMFAlgo, -1, tolMh, NMFMaxIterProj, np.array([]))
elif (NMFConvex > 0) & (NMFFindCentroids > 0):
Mt, tolMt = NMFProjGradKernel(Kernel, M.T, Mmis.T, Mh, Mt, NMFAlgo, tolMt, NMFMaxIterProj, np.array([]))
else:
Mt, tolMt, lambdat = NMFProjGrad(M.T, Mmis.T, Mw, Mt.T, NMFAlgo,
lambdat, tolMt, NMFMaxIterProj, np.array([]))
# Scaling
if ((NMFConvex == 0) | (NMFFindCentroids > 0)) & (NMFFixUserLHE == 0) & (NMFFixUserRHE == 0):
for k in range(0, nc):
if (NMFAlgo == 2) | (NMFAlgo == 4):
ScaleMt = np.linalg.norm(Mt[:, k])
else:
ScaleMt = np.sum(Mt[:, k])
if ScaleMt > 0:
Mt[:, k] = Mt[:, k] / ScaleMt
if MultOrPgrad == 2:
Mw[:, k] = Mw[:, k] * ScaleMt
# Switch to projected gradient
if iIter == NMFMaxInterm:
MultOrPgrad = 2
StepIter = 1
pbar_step = 100 / MaxIterations
gradMt = Mt @ (Mw.T @ Mw) - M @ Mw
gradMw = ((Mt.T @ Mt) @ Mw.T - Mt.T @ M).T
initgrad = np.linalg.norm(np.concatenate((gradMt, gradMw), axis=0))
tolMt = 1e-3 * initgrad
tolMw = tolMt
if iIter % StepIter == 0:
if (NMFConvex > 0) & (NMFFindParts > 0):
MhtKernel = Mh.T @ Kernel
diff = (TraceKernel + np.trace(-2 * Mw @ MhtKernel + Mw @ (MhtKernel @ Mh) @ Mw.T)) / nxp
elif (NMFConvex > 0) & (NMFFindCentroids > 0):
MhtKernel = Mh.T @ Kernel
diff = (TraceKernel + np.trace(-2 * Mt @ MhtKernel + Mt @ (MhtKernel @ Mh) @ Mt.T)) / nxp
else:
if (NMFAlgo == 2) | (NMFAlgo == 4):
if n_Mmis > 0:
Mdiff = (Mt @ Mw.T - M) * Mmis
else:
Mdiff = Mt @ Mw.T - M
else:
MF0 = Mt @ Mw.T
Mdiff = M * np.log(M / MF0 + precision) + MF0 - M
diff = (np.linalg.norm(Mdiff)) ** 2 / nxp
Status = Status0 + 'Iteration: %s' % int(iIter)
if NMFSparseLevel != 0:
if NMFSparseLevel > 0:
lambdax = lambdaw
else:
lambdax = lambdat
Status = Status + '; Achieved sparsity: ' + str(round(PercentZeros, 2)) + '; Penalty: ' + str(
round(lambdax, 2))
if LogIter == 1:
myStatusBox.myPrint(Status)
elif (NMFConvex > 0) & (NMFFindParts > 0):
Status = Status + ' - Find parts'
elif (NMFConvex > 0) & (NMFFindCentroids > 0) & (NLKernelApplied == 0):
Status = Status + ' - Find centroids'
elif NLKernelApplied == 1:
Status = Status + ' - Apply non linear kernel'
myStatusBox.update_status(delay=1, status=Status)
myStatusBox.update_bar(delay=1, step=pbar_step)
if myStatusBox.cancel_pressed:
cancel_pressed = 1
return [Mt, Mw, diff, Mh, NMFPriors, flagNonconvex, AddMessage, ErrMessage, cancel_pressed]
if LogIter == 1:
if (NMFAlgo == 2) | (NMFAlgo == 4):
myStatusBox.myPrint(Status0 + " Iter: " + str(iIter) + " MSR: " + str(diff))
else:
myStatusBox.myPrint(Status0 + " Iter: " + str(iIter) + " DIV: " + str(diff))
if iIter > NMFMaxInterm:
if (diff0 - diff) / diff0 < tolerance:
cont = 0
diff0 = diff
iIter += 1
if (cont == 0) | (iIter == MaxIterations):
if ((NMFFindParts > 0) | (NMFFindCentroids > 0)) & (NMFConvex == 0):
# Initialize convexity
NMFConvex = 1
diff0 = 1.e+99
iIter = NMFMaxInterm + 1
myStatusBox.init_bar(delay=1)
cont = 1
if NMFFindParts > 0:
Ip = np.identity(p)
if (NMFAlgo == 2) or (NMFAlgo == 4):
if n_Mmis > 0:
Kernel = NMFApplyKernel(Mmis * M, 1, np.array([]), np.array([]))
else:
Kernel = NMFApplyKernel(M, 1, np.array([]), np.array([]))
else:
if n_Mmis > 0:
Kernel = NMFApplyKernel(Mmis * (M / (Mt @ Mw.T)), 1, np.array([]), np.array([]))
else:
Kernel = NMFApplyKernel(M / (Mt @ Mw.T), 1, np.array([]), np.array([]))
TraceKernel = np.trace(Kernel)
try:
Mh = Mw @ np.linalg.inv(Mw.T @ Mw)
except:
Mh = Mw @ np.linalg.pinv(Mw.T @ Mw)
Mh[np.where(Mh < 0)] = 0
for k in range(0, nc):
ScaleMw = np.linalg.norm(Mw[:, k])
Mw[:, k] = Mw[:, k] / ScaleMw
Mh[:, k] = Mh[:, k] * ScaleMw
gradMh = Mh @ (Mw.T @ Mw) - Mw
gradMw = ((Mh.T @ Mh) @ Mw.T - Mh.T).T
initgrad = np.linalg.norm(np.concatenate((gradMh, gradMw), axis=0))
tolMh = 1.e-3 * initgrad
tolMw = tolMt
elif NMFFindCentroids > 0:
In = np.identity(n)
if (NMFAlgo == 2) or (NMFAlgo == 4):
if n_Mmis > 0:
Kernel = NMFApplyKernel(Mmis.T * M.T, 1, np.array([]), np.array([]))
else:
Kernel = NMFApplyKernel(M.T, 1, np.array([]), np.array([]))
else:
if n_Mmis > 0:
Kernel = NMFApplyKernel(Mmis.T * (M.T / (Mt @ Mw.T).T), 1, np.array([]), np.array([]))
else:
Kernel = NMFApplyKernel(M.T / (Mt @ Mw.T).T, 1, np.array([]), np.array([]))
TraceKernel = np.trace(Kernel)
try:
Mh = Mt @ np.linalg.inv(Mt.T @ Mt)
except:
Mh = Mt @ np.linalg.pinv(Mt.T @ Mt)
Mh[np.where(Mh < 0)] = 0
for k in range(0, nc):
ScaleMt = np.linalg.norm(Mt[:, k])
Mt[:, k] = Mt[:, k] / ScaleMt
Mh[:, k] = Mh[:, k] * ScaleMt
gradMt = Mt @ (Mh.T @ Mh) - Mh
gradMh = ((Mt.T @ Mt) @ Mh.T - Mt.T).T
initgrad = np.linalg.norm(np.concatenate((gradMt, gradMh), axis=0))
tolMh = 1.e-3 * initgrad
tolMt = tolMh
elif (NMFConvex > 0) & (NMFKernel > 1) & (NLKernelApplied == 0):
NLKernelApplied = 1
diff0 = 1.e+99
iIter = NMFMaxInterm + 1
myStatusBox.init_bar(delay=1)
cont = 1
# Calculate centroids
for k in range(0, nc):
Mh[:, k] = Mh[:, k] / np.sum(Mh[:, k])
Mw = (Mh.T @ M).T
if (NMFAlgo == 2) or (NMFAlgo == 4):
if n_Mmis > 0:
Kernel = NMFApplyKernel(Mmis.T * M.T, NMFKernel, Mw, Mt)
else:
Kernel = NMFApplyKernel(M.T, NMFKernel, Mw, Mt)
else:
if n_Mmis > 0:
Kernel = NMFApplyKernel(Mmis.T * (M.T / (Mt @ Mw.T).T), NMFKernel, Mw, Mt)
else:
Kernel = NMFApplyKernel(M.T / (Mt @ Mw.T).T, NMFKernel, Mw, Mt)
TraceKernel = np.trace(Kernel)
try:
Mh = Mt @ np.linalg.inv(Mt.T @ Mt)
except:
Mh = Mt @ np.linalg.pinv(Mt.T @ Mt)
Mh[np.where(Mh < 0)] = 0
for k in range(0, nc):
ScaleMt = np.linalg.norm(Mt[:, k])
Mt[:, k] = Mt[:, k] / ScaleMt
Mh[:, k] = Mh[:, k] * ScaleMt
gradMt = Mt @ (Mh.T @ Mh) - Mh
gradMh = ((Mt.T @ Mt) @ Mh.T - Mt.T).T
initgrad = np.linalg.norm(np.concatenate((gradMt, gradMh), axis=0))
tolMh = 1.e-3 * initgrad
tolMt = tolMh
if NMFSparseLevel > 0:
SparseTest = np.zeros((p, 1))
for k in range(0, nc):
SparseTest[np.where(Mw[:, k] > 0)] = 1
PercentZeros0 = PercentZeros
n_SparseTest = np.where(SparseTest == 0)[0].size
PercentZeros = max(n_SparseTest / p, .01)
if PercentZeros == PercentZeros0:
iterSparse += 1
else:
iterSparse = 0
if (PercentZeros < 0.99 * NMFSparseLevel) & (iterSparse < 50):
lambdaw *= min(1.01 * NMFSparseLevel / PercentZeros, 1.10)
iIter = NMFMaxInterm + 1
cont = 1
elif NMFSparseLevel < 0:
SparseTest = np.zeros((n, 1))
for k in range(0, nc):
SparseTest[np.where(Mt[:, k] > 0)] = 1
PercentZeros0 = PercentZeros
n_SparseTest = np.where(SparseTest == 0)[0].size
PercentZeros = max(n_SparseTest / n, .01)
if PercentZeros == PercentZeros0:
iterSparse += 1
else:
iterSparse = 0
if (PercentZeros < 0.99 * abs(NMFSparseLevel)) & (iterSparse < 50):
lambdat *= min(1.01 * abs(NMFSparseLevel) / PercentZeros, 1.10)
iIter = NMFMaxInterm + 1
cont = 1
if NMFFindParts > 0:
# Make Mt convex
Mt = M @ Mh
Mt, Mw, Mh, flagNonconvex, AddMessage, ErrMessage, cancel_pressed = NMFGetConvexScores(Mt, Mw, Mh, flagNonconvex,
AddMessage)
elif NMFFindCentroids > 0:
# Calculate row centroids
for k in range(0, nc):
ScaleMh = np.sum(Mh[:, k])
Mh[:, k] = Mh[:, k] / ScaleMh
Mt[:, k] = Mt[:, k] * ScaleMh
Mw = (Mh.T @ M).T
if (NMFKernel > 1) & (NLKernelApplied == 1):
diff /= TraceKernel / nxp
return [Mt, Mw, diff, Mh, NMFPriors, flagNonconvex, AddMessage, ErrMessage, cancel_pressed]
def NTFStack(M, Mmis, NBlocks):
"""Unfold tensor M
for future use with NMF
"""
n, p = M.shape
Mmis = Mmis.astype(np.int)
n_Mmis = Mmis.shape[0]
NBlocks = int(NBlocks)
Mstacked = np.zeros((int(n * p / NBlocks), NBlocks))
if n_Mmis > 0:
Mmis_stacked = np.zeros((int(n * p / NBlocks), NBlocks))
else:
Mmis_stacked = np.array([])
for iBlock in range(0, NBlocks):
for j in range(0, int(p / NBlocks)):
i1 = j * n
i2 = i1 + n
Mstacked[i1:i2, iBlock] = M[:, int(iBlock * p / NBlocks + j)]
if n_Mmis > 0:
Mmis_stacked[i1:i2, iBlock] = Mmis[:, int(iBlock * p / NBlocks + j)]
return [Mstacked, Mmis_stacked]
def NTFSolve(M, Mmis, Mt0, Mw0, Mb0, nc, tolerance, LogIter, Status0, MaxIterations, NMFFixUserLHE, NMFFixUserRHE, NMFFixUserBHE,
NMFSparseLevel, NTFUnimodal, NTFSmooth, NTFLeftComponents, NTFRightComponents, NTFBlockComponents, NBlocks, NTFNConv, NMFPriors, myStatusBox):
"""Interface to:
- NTFSolve_simple
- NTFSolve_conv
"""
try:
n_NMFPriors, nc = NMFPriors.shape
except:
n_NMFPriors = 0
if n_NMFPriors > 0:
NMFPriors[NMFPriors > 0] = 1
if NTFNConv > 0:
return NTFSolve_conv(M, Mmis, Mt0, Mw0, Mb0, nc, tolerance, LogIter, Status0, MaxIterations, NMFFixUserLHE, NMFFixUserRHE, NMFFixUserBHE,
NMFSparseLevel, NTFUnimodal, NTFSmooth, NTFLeftComponents, NTFRightComponents, NTFBlockComponents, NBlocks, NTFNConv, NMFPriors, myStatusBox)
else:
return NTFSolve_simple(M, Mmis, Mt0, Mw0, Mb0, nc, tolerance, LogIter, Status0, MaxIterations, NMFFixUserLHE, NMFFixUserRHE, NMFFixUserBHE,
NMFSparseLevel, NTFUnimodal, NTFSmooth, NTFLeftComponents, NTFRightComponents, NTFBlockComponents, NBlocks, NMFPriors, myStatusBox)
def NTFSolve_simple(M, Mmis, Mt0, Mw0, Mb0, nc, tolerance, LogIter, Status0, MaxIterations, NMFFixUserLHE, NMFFixUserRHE, NMFFixUserBHE,
NMFSparseLevel, NTFUnimodal, NTFSmooth, NTFLeftComponents, NTFRightComponents, NTFBlockComponents, NBlocks, NMFPriors, myStatusBox):
"""
Estimate NTF matrices (HALS)
Input:
M: Input matrix
Mmis: Define missing values (0 = missing cell, 1 = real cell)
Mt0: Initial left hand matrix
Mw0: Initial right hand matrix
Mb0: Initial block hand matrix
nc: NTF rank
tolerance: Convergence threshold
LogIter: Log results through iterations
Status0: Initial displayed status to be updated during iterations
MaxIterations: Max iterations
NMFFixUserLHE: = 1 => fixed left hand matrix columns
NMFFixUserRHE: = 1 => fixed right hand matrix columns
NMFFixUserBHE: = 1 => fixed block hand matrix columns
NMFSparseLevel : sparsity level (as defined by Hoyer); +/- = make RHE/LHe sparse
NTFUnimodal: Apply Unimodal constraint on factoring vectors
NTFSmooth: Apply Smooth constraint on factoring vectors
NTFLeftComponents: Apply Unimodal/Smooth constraint on left hand matrix
NTFRightComponents: Apply Unimodal/Smooth constraint on right hand matrix
NTFBlockComponents: Apply Unimodal/Smooth constraint on block hand matrix
NBlocks: Number of NTF blocks
NMFPriors: Elements in Mw that should be updated (others remain 0)
Output:
Mt: Left hand matrix
Mw: Right hand matrix
Mb: Block hand matrix
diff: objective cost
Reference
---------
<NAME>, <NAME>, Fast local algorithms for large scale nonnegative matrix and tensor factorizations,
IEICE Trans. Fundam. Electron. Commun. Comput. Sci. 92 (3) (2009) 708–721.
"""
cancel_pressed = 0
n, p0 = M.shape
n_Mmis = Mmis.shape[0]
nc = int(nc)
NBlocks = int(NBlocks)
p = int(p0 / NBlocks)
nxp = int(n * p)
nxp0 = int(n * p0)
Mt = np.copy(Mt0)
Mw = np.copy(Mw0)
Mb = np.copy(Mb0)
# StepIter = math.ceil(MaxIterations/10)
StepIter = 1
pbar_step = 100 * StepIter / MaxIterations
IDBlockp = np.arange(0, (NBlocks - 1) * p + 1, p)
A = np.zeros(n)
B = np.zeros(p)
C = np.zeros(NBlocks)
# Compute Residual tensor
Mfit = np.zeros((n, p0))
for k in range(0, nc):
if NBlocks > 1:
for iBlock in range(0, NBlocks):
Mfit[:, IDBlockp[iBlock]:IDBlockp[iBlock] + p] += Mb[iBlock, k] * np.reshape(Mt[:, k], (n, 1)) @ np.reshape(
Mw[:, k], (1, p))
else:
Mfit[:, IDBlockp[0]:IDBlockp[0] + p] += np.reshape(Mt[:, k], (n, 1)) @ np.reshape(Mw[:, k], (1, p))
denomt = np.zeros(n)
denomw = np.zeros(p)
denomBlock = np.zeros((NBlocks, nc))
Mt2 = np.zeros(n)
Mw2 = np.zeros(p)
MtMw = np.zeros(nxp)
denomCutoff = .1
if n_Mmis > 0:
Mres = (M - Mfit) * Mmis
else:
Mres = M - Mfit
myStatusBox.init_bar(delay=1)
# Loop
cont = 1
iIter = 0
diff0 = 1.e+99
Mpart = np.zeros((n, p0))
# alpha = NMFSparseLevel
alpha = NMFSparseLevel * .8
PercentZeros = 0
iterSparse = 0
while (cont > 0) & (iIter < MaxIterations):
for k in range(0, nc):
NBlocks, Mpart, IDBlockp, p, Mb, k, Mt, n, Mw, n_Mmis, Mmis, Mres, \
NMFFixUserLHE, denomt, Mw2, denomCutoff, alpha ,\
NTFUnimodal, NTFLeftComponents, NTFSmooth, A, NMFFixUserRHE, \
denomw, Mt2, NTFRightComponents, B, NMFFixUserBHE, MtMw, nxp, \
denomBlock, NTFBlockComponents, C, Mfit, NMFPriors = \
NTFUpdate(NBlocks, Mpart, IDBlockp, p, Mb, k, Mt, n, Mw, n_Mmis, Mmis, Mres, \
NMFFixUserLHE, denomt, Mw2, denomCutoff, alpha ,\
NTFUnimodal, NTFLeftComponents, NTFSmooth, A, NMFFixUserRHE, \
denomw, Mt2, NTFRightComponents, B, NMFFixUserBHE, MtMw, nxp, \
denomBlock, NTFBlockComponents, C, Mfit, NMFPriors)
if iIter % StepIter == 0:
# Check convergence
diff = np.linalg.norm(Mres) ** 2 / nxp0
if (diff0 - diff) / diff0 < tolerance:
cont = 0
else:
if diff > diff0:
myStatusBox.myPrint(Status0 + " Iter: " + str(iIter) + " MSR does not improve")
diff0 = diff
Status = Status0 + 'Iteration: %s' % int(iIter)
if NMFSparseLevel != 0:
Status = Status + '; Achieved sparsity: ' + str(round(PercentZeros, 2)) + '; alpha: ' + str(
round(alpha, 2))
if LogIter == 1:
myStatusBox.myPrint(Status)
myStatusBox.update_status(delay=1, status=Status)
myStatusBox.update_bar(delay=1, step=pbar_step)
if myStatusBox.cancel_pressed:
cancel_pressed = 1
return [np.array([]), Mt, Mw, Mb, Mres, cancel_pressed]
if LogIter == 1:
myStatusBox.myPrint(Status0 + " Iter: " + str(iIter) + " MSR: " + str(diff))
iIter += 1
if (cont == 0) | (iIter == MaxIterations):
# if NMFSparseLevel > 0:
# SparseTest = np.zeros((p, 1))
# for k in range(0, nc):
# SparseTest[np.where(Mw[:, k] > 0)] = 1
# PercentZeros0 = PercentZeros
# n_SparseTest = np.where(SparseTest == 0)[0].size
# PercentZeros = max(n_SparseTest / p, .01)
# if PercentZeros == PercentZeros0:
# iterSparse += 1
# else:
# iterSparse = 0
# if (PercentZeros < 0.99 * NMFSparseLevel) & (iterSparse < 50):
# alpha *= min(1.01 * NMFSparseLevel / PercentZeros, 1.01)
# if alpha < .99:
# iIter = 1
# cont = 1
# elif NMFSparseLevel < 0:
# SparseTest = np.zeros((n, 1))
# for k in range(0, nc):
# SparseTest[np.where(Mt[:, k] > 0)] = 1
# PercentZeros0 = PercentZeros
# n_SparseTest = np.where(SparseTest == 0)[0].size
# PercentZeros = max(n_SparseTest / n, .01)
# if PercentZeros == PercentZeros0:
# iterSparse += 1
# else:
# iterSparse = 0
# if (PercentZeros < 0.99 * abs(NMFSparseLevel)) & (iterSparse < 50):
# alpha *= min(1.01 * abs(NMFSparseLevel) / PercentZeros, 1.01)
# if abs(alpha) < .99:
# iIter = 1
# cont = 1
if NMFSparseLevel > 0:
SparseTest = np.zeros((nc, 1))
PercentZeros0 = PercentZeros
for k in range(0, nc):
SparseTest[k] = np.where(Mw[:, k] == 0)[0].size
PercentZeros = np.mean(SparseTest) / p
if PercentZeros < PercentZeros0:
iterSparse += 1
else:
iterSparse = 0
if (PercentZeros < 0.99 * NMFSparseLevel) & (iterSparse < 50):
alpha *= min(1.05 * NMFSparseLevel / PercentZeros, 1.1)
if alpha < 1:
iIter = 1
cont = 1
elif NMFSparseLevel < 0:
SparseTest = np.zeros((nc, 1))
PercentZeros0 = PercentZeros
for k in range(0, nc):
SparseTest[k] = np.where(Mw[:, k] == 0)[0].size
PercentZeros = np.mean(SparseTest) / n
if PercentZeros < PercentZeros0:
iterSparse += 1
else:
iterSparse = 0
if (PercentZeros < 0.99 * abs(NMFSparseLevel)) & (iterSparse < 50):
alpha *= min(1.05 * abs(NMFSparseLevel) / PercentZeros, 1.1)
if abs(alpha) < 1:
iIter = 1
cont = 1
if (n_Mmis > 0) & (NMFFixUserBHE == 0):
Mb *= denomBlock
return [np.array([]), Mt, Mw, Mb, diff, cancel_pressed]
def NTFSolve_conv(M, Mmis, Mt0, Mw0, Mb0, nc, tolerance, LogIter, Status0, MaxIterations, NMFFixUserLHE, NMFFixUserRHE, NMFFixUserBHE,
NMFSparseLevel, NTFUnimodal, NTFSmooth, NTFLeftComponents, NTFRightComponents, NTFBlockComponents, NBlocks, NTFNConv, NMFPriors, myStatusBox):
"""Estimate NTF matrices (HALS)
Input:
M: Input matrix
Mmis: Define missing values (0 = missing cell, 1 = real cell)
Mt0: Initial left hand matrix
Mw0: Initial right hand matrix
Mb0: Initial block hand matrix
nc: NTF rank
tolerance: Convergence threshold
LogIter: Log results through iterations
Status0: Initial displayed status to be updated during iterations
MaxIterations: Max iterations
NMFFixUserLHE: = 1 => fixed left hand matrix columns
NMFFixUserRHE: = 1 => fixed right hand matrix columns
NMFFixUserBHE: = 1 => fixed block hand matrix columns
NMFSparseLevel : sparsity level (as defined by Hoyer); +/- = make RHE/LHe sparse
NTFUnimodal: Apply Unimodal constraint on factoring vectors
NTFSmooth: Apply Smooth constraint on factoring vectors
NTFLeftComponents: Apply Unimodal/Smooth constraint on left hand matrix
NTFRightComponents: Apply Unimodal/Smooth constraint on right hand matrix
NTFBlockComponents: Apply Unimodal/Smooth constraint on block hand matrix
NBlocks: Number of NTF blocks
NTFNConv: Half-Size of the convolution window on 3rd-dimension of the tensor
NMFPriors: Elements in Mw that should be updated (others remain 0)
Output:
Mt : if NTFNConv > 0 only otherwise empty. Contains sub-components for each phase in convolution window
Mt_simple: Left hand matrix (sum of columns Mt_conv for each k)
Mw_simple: Right hand matrix
Mb_simple: Block hand matrix
diff: objective cost
Note:
This code extends HALS to allow for shifting on the 3rd dimension of the tensor. Suffix '_simple' is added to
the non-convolutional components. Convolutional components are named the usual way.
"""
cancel_pressed = 0
n, p0 = M.shape
n_Mmis = Mmis.shape[0]
nc = int(nc)
NBlocks = int(NBlocks)
NTFNConv = int(NTFNConv)
p = int(p0 / NBlocks)
nxp = int(n * p)
nxp0 = int(n * p0)
Mt_simple = np.copy(Mt0)
Mw_simple = np.copy(Mw0)
Mb_simple = np.copy(Mb0)
# StepIter = math.ceil(MaxIterations/10)
StepIter = 1
pbar_step = 100 * StepIter / MaxIterations
IDBlockp = np.arange(0, (NBlocks - 1) * p + 1, p)
A = np.zeros(n)
B = np.zeros(p)
C = np.zeros(NBlocks)
MtMw = np.zeros(nxp)
NTFNConv2 = 2*NTFNConv + 1
#Initialize Mt, Mw, Mb
Mt = np.repeat(Mt_simple, NTFNConv2, axis=1) / NTFNConv2
Mw = np.repeat(Mw_simple, NTFNConv2, axis=1)
Mb = np.repeat(Mb_simple, NTFNConv2, axis=1)
for k3 in range(0, nc):
n_shift = -NTFNConv - 1
for k2 in range(0, NTFNConv2):
n_shift += 1
k = k3*NTFNConv2+k2
Mb[:,k] = shift(Mb_simple[:, k3], n_shift)
# Initialize Residual tensor
Mfit = np.zeros((n, p0))
for k3 in range(0, nc):
for k2 in range(0, NTFNConv2):
k = k3*NTFNConv2+k2
for iBlock in range(0, NBlocks):
Mfit[:, IDBlockp[iBlock]:IDBlockp[iBlock] + p] += Mb[iBlock,k] * \
np.reshape(Mt[:, k], (n, 1)) @ np.reshape(Mw[:, k], (1, p))
denomt = np.zeros(n)
denomw = np.zeros(p)
denomBlock = np.zeros((NBlocks, nc))
Mt2 = np.zeros(n)
Mw2 = np.zeros(p)
denomCutoff = .1
if n_Mmis > 0:
Mres = (M - Mfit) * Mmis
else:
Mres = M - Mfit
myStatusBox.init_bar(delay=1)
# Loop
cont = 1
iIter = 0
diff0 = 1.e+99
Mpart = np.zeros((n, p0))
alpha = NMFSparseLevel
alpha_blocks = 0
PercentZeros = 0
iterSparse = 0
while (cont > 0) & (iIter < MaxIterations):
for k3 in range(0, nc):
for k2 in range(0, NTFNConv2):
k = k3*NTFNConv2+k2
NBlocks, Mpart, IDBlockp, p, Mb, k, Mt, n, Mw, n_Mmis, Mmis, Mres, \
NMFFixUserLHE, denomt, Mw2, denomCutoff, alpha ,\
NTFUnimodal, NTFLeftComponents, NTFSmooth, A, NMFFixUserRHE, \
denomw, Mt2, NTFRightComponents, B, NMFFixUserBHE, MtMw, nxp, \
denomBlock, NTFBlockComponents, C, Mfit, NMFPriors = \
NTFUpdate(NBlocks, Mpart, IDBlockp, p, Mb, k, Mt, n, Mw, n_Mmis, Mmis, Mres, \
NMFFixUserLHE, denomt, Mw2, denomCutoff, alpha, \
NTFUnimodal, NTFLeftComponents, NTFSmooth, A, NMFFixUserRHE, \
denomw, Mt2, NTFRightComponents, B, NMFFixUserBHE, MtMw, nxp, \
denomBlock, NTFBlockComponents, C, Mfit, NMFPriors)
#Update Mt_simple, Mw_simple & Mb_simple
k = k3*NTFNConv2+NTFNConv
Mt_simple[:, k3] = Mt[:, k]
Mw_simple[:, k3] = Mw[:, k]
Mb_simple[:, k3] = Mb[:, k]
# Update Mw & Mb
Mw[:,:] = np.repeat(Mw_simple, NTFNConv2, axis=1)
n_shift = -NTFNConv - 1
for k2 in range(0, NTFNConv2):
n_shift += 1
k = k3*NTFNConv2+k2
Mb[:,k] = shift(Mb_simple[:, k3], n_shift)
if iIter % StepIter == 0:
# Check convergence
diff = np.linalg.norm(Mres) ** 2 / nxp0
if (diff0 - diff) / diff0 < tolerance:
cont = 0
else:
diff0 = diff
Status = Status0 + 'Iteration: %s' % int(iIter)
if NMFSparseLevel != 0:
Status = Status + '; Achieved sparsity: ' + str(round(PercentZeros, 2)) + '; alpha: ' + str(
round(alpha, 2))
if LogIter == 1:
myStatusBox.myPrint(Status)
myStatusBox.update_status(delay=1, status=Status)
myStatusBox.update_bar(delay=1, step=pbar_step)
if myStatusBox.cancel_pressed:
cancel_pressed = 1
return [Mt, Mt_simple, Mw_simple, Mb_simple, cancel_pressed]
if LogIter == 1:
myStatusBox.myPrint(Status0 + " Iter: " + str(iIter) + " MSR: " + str(diff))
iIter += 1
if (cont == 0) | (iIter == MaxIterations):
if NMFSparseLevel > 0:
SparseTest = np.zeros((p, 1))
for k in range(0, nc):
SparseTest[ | np.where(Mw[:, k] > 0) | numpy.where |
import time
import wandb
import os
import numpy as np
from itertools import chain
import torch
from onpolicy.utils.util import update_linear_schedule
from onpolicy.runner.shared.base_runner import Runner
def _t2n(x):
return x.detach().cpu().numpy()
class HNSRunner(Runner):
def __init__(self, config):
super(HNSRunner, self).__init__(config)
def run(self):
self.warmup()
start = time.time()
episodes = int(self.num_env_steps) // self.episode_length // self.n_rollout_threads
for episode in range(episodes):
if self.use_linear_lr_decay:
self.trainer.policy.lr_decay(episode, episodes)
env_infos = {}
env_infos['max_box_move_prep'] = []
env_infos['max_box_move'] = []
env_infos['num_box_lock_prep'] = []
env_infos['num_box_lock'] = []
env_infos['max_ramp_move_prep'] = []
env_infos['max_ramp_move'] = []
env_infos['num_ramp_lock_prep'] = []
env_infos['num_ramp_lock'] = []
env_infos['food_eaten_prep'] = []
env_infos['food_eaten'] = []
env_infos['lock_rate'] = []
env_infos['activated_sites'] = []
discard_episode = 0
success = 0
trials = 0
for step in range(self.episode_length):
# Sample actions
values, actions, action_log_probs, rnn_states, rnn_states_critic = self.collect(step)
# Obser reward and next obs
obs, share_obs, rewards, dones, infos, _ = self.envs.step(actions)
for done, info in zip(dones, infos):
if done:
if "discard_episode" in info.keys() and info['discard_episode']:
discard_episode += 1
else:
trials += 1
if "success" in info.keys() and info['success']:
success += 1
for k in env_infos.keys():
if k in info.keys():
env_infos[k].append(info[k])
data = obs, share_obs, rewards, dones, infos, \
values, actions, action_log_probs, \
rnn_states, rnn_states_critic
# insert data into buffer
self.insert(data)
# compute return and update network
self.compute()
train_infos = self.train()
# post process
total_num_steps = (episode + 1) * self.episode_length * self.n_rollout_threads
# save model
if (episode % self.save_interval == 0 or episode == episodes - 1):
self.save()
# log information
if episode % self.log_interval == 0:
end = time.time()
print("\n Env {} Algo {} Exp {} updates {}/{} episodes, total num timesteps {}/{}, FPS {}.\n"
.format(self.env_name,
self.algorithm_name,
self.experiment_name,
episode,
episodes,
total_num_steps,
self.num_env_steps,
int(total_num_steps / (end - start))))
if self.env_name == "HideAndSeek" :
for hider_id in range(self.all_args.num_hiders):
agent_k = 'hider%i/average_step_rewards' % hider_id
train_infos[agent_k] = | np.mean(self.buffer.rewards[:, :, hider_id]) | numpy.mean |
"""
===========================
@Author : <NAME>
@Version: 1.0 12/07/2020
Vessel diameter estimation
===========================
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
import math
import vessel_select
# Find perpendicular direction
def perpendicluar(x, y, vx, vy, d):
mag = math.sqrt(vx * vx + vy * vy)
if (vy != 0):
vx = vx / mag
vy = vy / mag
temp = vx
vx = -1 * vy
vy = temp
Cx = (x + vx * d)
Cy = (y + vy * d)
Dx = (x - vx * d)
Dy = (y - vy * d)
else:
Cx = (x)
Cy = (y + d)
Dx = (x)
Dy = (y - d)
return (Cx,Cy,Dx,Dy)
# Bilinear interpolation to find values at non-integral positions
def interpolate(img, x, y):
y1 = int(y)
y2 = int(y)+1
x1 = int(x)
x2 = int(x)+1
if(x==x1 and y==y1):
return np.array([img[x1, y1]])[0]
if(x==x1 and y!=y1):
val = ((y2-y)/(y2-y1))*(img[x1, y1])+((y-y1)/(y2-y1))*(img[x1, y2])
return | np.array([val]) | numpy.array |
import os.path as osp
import numpy as np
import math
import torch
import json
import copy
import transforms3d
import scipy.sparse
import cv2
from pycocotools.coco import COCO
from core.config import cfg
from graph_utils import build_coarse_graphs
from noise_utils import synthesize_pose
from smpl import SMPL
from coord_utils import world2cam, cam2pixel, process_bbox, rigid_align, get_bbox
from aug_utils import affine_transform, j2d_processing, augm_params, j3d_processing, flip_2d_joint
from Human36M.noise_stats import error_distribution
from funcs_utils import save_obj, stop
from vis import vis_3d_pose, vis_2d_pose
class Human36M(torch.utils.data.Dataset):
def __init__(self, mode, args):
dataset_name = 'Human36M'
self.debug = args.debug
self.data_split = mode
self.img_dir = osp.join(cfg.data_dir, dataset_name, 'images')
self.annot_path = osp.join(cfg.data_dir, dataset_name, 'annotations')
self.subject_genders = {1: 'female', 5: 'female', 6: 'male', 7: 'female', 8: 'male', 9: 'male', 11: 'male'}
self.protocol = 2
self.action_name = ['Directions', 'Discussion', 'Eating', 'Greeting', 'Phoning', 'Posing', 'Purchases',
'Sitting', 'SittingDown', 'Smoking', 'Photo', 'Waiting', 'Walking', 'WalkDog',
'WalkTogether']
self.fitting_thr = 25 # milimeter
# SMPL joint set
self.mesh_model = SMPL()
self.smpl_root_joint_idx = self.mesh_model.root_joint_idx
self.smpl_face_kps_vertex = self.mesh_model.face_kps_vertex
self.smpl_vertex_num = 6890
self.smpl_joint_num = 24
self.smpl_flip_pairs = ((1, 2), (4, 5), (7, 8), (10, 11), (13, 14), (16, 17), (18, 19), (20, 21), (22, 23))
self.smpl_skeleton = (
(0, 1), (1, 4), (4, 7), (7, 10), (0, 2), (2, 5), (5, 8), (8, 11), (0, 3), (3, 6), (6, 9), (9, 14), (14, 17),
(17, 19), (19, 21), (21, 23), (9, 13), (13, 16), (16, 18), (18, 20), (20, 22), (9, 12), (12, 15))
self.joint_regressor_smpl = self.mesh_model.layer['neutral'].th_J_regressor
# H36M joint set
self.human36_joint_num = 17
self.human36_joints_name = (
'Pelvis', 'R_Hip', 'R_Knee', 'R_Ankle', 'L_Hip', 'L_Knee', 'L_Ankle', 'Torso', 'Neck', 'Nose', 'Head',
'L_Shoulder', 'L_Elbow', 'L_Wrist', 'R_Shoulder', 'R_Elbow', 'R_Wrist')
self.human36_flip_pairs = ((1, 4), (2, 5), (3, 6), (14, 11), (15, 12), (16, 13))
self.human36_skeleton = (
(0, 7), (7, 8), (8, 9), (9, 10), (8, 11), (11, 12), (12, 13), (8, 14), (14, 15), (15, 16), (0, 1), (1, 2),
(2, 3), (0, 4), (4, 5), (5, 6))
self.human36_root_joint_idx = self.human36_joints_name.index('Pelvis')
self.human36_error_distribution = self.get_stat()
self.human36_eval_joint = (1, 2, 3, 4, 5, 6, 8, 10, 11, 12, 13, 14, 15, 16)
self.joint_regressor_human36 = self.mesh_model.joint_regressor_h36m
# COCO joint set
self.coco_joint_num = 19 # 17 + 2, manually added pelvis and neck
self.coco_joints_name = (
'Nose', 'L_Eye', 'R_Eye', 'L_Ear', 'R_Ear', 'L_Shoulder', 'R_Shoulder', 'L_Elbow', 'R_Elbow', 'L_Wrist',
'R_Wrist', 'L_Hip', 'R_Hip', 'L_Knee', 'R_Knee', 'L_Ankle', 'R_Ankle', 'Pelvis', 'Neck')
self.coco_flip_pairs = ((1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12), (13, 14), (15, 16))
self.coco_skeleton = (
(1, 2), (0, 1), (0, 2), (2, 4), (1, 3), (6, 8), (8, 10), (5, 7), (7, 9), (12, 14), (14, 16), (11, 13),
(13, 15), #(5, 6), #(11, 12),
(17, 11), (17, 12), (17, 18), (18, 5), (18, 6), (18, 0))
self.joint_regressor_coco = self.mesh_model.joint_regressor_coco
self.input_joint_name = cfg.DATASET.input_joint_set # 'coco'
self.joint_num, self.skeleton, self.flip_pairs = self.get_joint_setting(self.input_joint_name)
self.datalist, skip_idx, skip_img_path = self.load_data()
if self.data_split == 'test':
det_2d_data_path = osp.join(cfg.data_dir, dataset_name, 'absnet_output_on_testset.json')
self.datalist_pose2d_det = self.load_pose2d_det(det_2d_data_path, skip_img_path)
print("Check lengths of annotation and detection output: ", len(self.datalist), len(self.datalist_pose2d_det))
self.graph_Adj, self.graph_L, self.graph_perm, self.graph_perm_reverse = \
build_coarse_graphs(self.mesh_model.face, self.joint_num, self.skeleton, self.flip_pairs, levels=9)
def load_pose2d_det(self, data_path, skip_list):
pose_list = []
with open(data_path) as f:
data = json.load(f)
for img_path, pose2d in data.items():
pose2d = np.array(pose2d, dtype=np.float32)
if img_path in skip_list:
continue
pose_list.append({'img_name': img_path, 'pose2d': pose2d})
pose_list = sorted(pose_list, key=lambda x: x['img_name'])
return pose_list
def get_joint_setting(self, joint_category='human36'):
joint_num = eval(f'self.{joint_category}_joint_num')
skeleton = eval(f'self.{joint_category}_skeleton')
flip_pairs = eval(f'self.{joint_category}_flip_pairs')
return joint_num, skeleton, flip_pairs
def get_subsampling_ratio(self):
if self.data_split == 'train':
return 5 # 50
elif self.data_split == 'test':
return 50 #
else:
assert 0, print('Unknown subset')
def get_subject(self):
if self.data_split == 'train':
if self.protocol == 1:
subject = [1, 5, 6, 7, 8, 9]
elif self.protocol == 2:
subject = [1, 5, 6, 7, 8]
elif self.data_split == 'test':
if self.protocol == 1:
subject = [11]
elif self.protocol == 2:
subject = [9, 11]
else:
assert 0, print("Unknown subset")
if self.debug:
subject = subject[0:1]
return subject
def get_stat(self):
ordered_stats = []
for joint in self.human36_joints_name:
item = list(filter(lambda stat: stat['Joint'] == joint, error_distribution))[0]
ordered_stats.append(item)
return ordered_stats
def generate_syn_error(self):
noise = np.zeros((self.human36_joint_num, 2), dtype=np.float32)
weight = np.zeros(self.human36_joint_num, dtype=np.float32)
for i, ed in enumerate(self.human36_error_distribution):
noise[i, 0] = np.random.normal(loc=ed['mean'][0], scale=ed['std'][0])
noise[i, 1] = np.random.normal(loc=ed['mean'][1], scale=ed['std'][1])
weight[i] = ed['weight']
prob = np.random.uniform(low=0.0, high=1.0, size=self.human36_joint_num)
weight = (weight > prob)
noise = noise * weight[:, None]
return noise
def load_data(self):
print('Load annotations of Human36M Protocol ' + str(self.protocol))
subject_list = self.get_subject()
sampling_ratio = self.get_subsampling_ratio()
# aggregate annotations from each subject
db = COCO()
cameras = {}
joints = {}
smpl_params = {}
for subject in subject_list:
# data load
with open(osp.join(self.annot_path, 'Human36M_subject' + str(subject) + '_data.json'), 'r') as f:
annot = json.load(f)
if len(db.dataset) == 0:
for k, v in annot.items():
db.dataset[k] = v
else:
for k, v in annot.items():
db.dataset[k] += v
# camera load
with open(osp.join(self.annot_path, 'Human36M_subject' + str(subject) + '_camera.json'), 'r') as f:
cameras[str(subject)] = json.load(f)
# joint coordinate load
with open(osp.join(self.annot_path, 'Human36M_subject' + str(subject) + '_joint_3d.json'), 'r') as f:
joints[str(subject)] = json.load(f)
# smpl parameter load
with open(osp.join(self.annot_path, 'Human36M_subject' + str(subject) + '_smpl_param.json'), 'r') as f:
smpl_params[str(subject)] = json.load(f)
db.createIndex()
skip_idx = []
datalist = []
skip_img_idx = []
for aid in db.anns.keys():
ann = db.anns[aid]
image_id = ann['image_id']
img = db.loadImgs(image_id)[0]
img_path = osp.join(self.img_dir, img['file_name'])
img_name = img_path.split('/')[-1]
# check subject and frame_idx
frame_idx = img['frame_idx'];
if frame_idx % sampling_ratio != 0:
continue
# check smpl parameter exist
subject = img['subject'];
action_idx = img['action_idx'];
subaction_idx = img['subaction_idx'];
frame_idx = img['frame_idx'];
try:
smpl_param = smpl_params[str(subject)][str(action_idx)][str(subaction_idx)][str(frame_idx)]
except KeyError:
skip_idx.append(image_id)
skip_img_idx.append(img_path.split('/')[-1])
continue
smpl_param['gender'] = 'neutral' # self.subject_genders[subject] # set corresponding gender
# camera parameter
cam_idx = img['cam_idx']
cam_param = cameras[str(subject)][str(cam_idx)]
R, t, f, c = np.array(cam_param['R'], dtype=np.float32), np.array(cam_param['t'],
dtype=np.float32), np.array(
cam_param['f'], dtype=np.float32), np.array(cam_param['c'], dtype=np.float32)
cam_param = {'R': R, 't': t, 'focal': f, 'princpt': c}
# project world coordinate to cam, image coordinate space
joint_world = np.array(joints[str(subject)][str(action_idx)][str(subaction_idx)][str(frame_idx)],
dtype=np.float32)
joint_cam = world2cam(joint_world, R, t)
joint_img = cam2pixel(joint_cam, f, c)
joint_vis = np.ones((self.human36_joint_num, 1))
bbox = process_bbox(np.array(ann['bbox']))
if bbox is None: continue
datalist.append({
'img_path': img_path,
'img_name': img_name,
'img_id': image_id,
'bbox': bbox,
'img_hw': (img['height'], img['width']),
'joint_img': joint_img, # [x_img, y_img, z_cam]
'joint_cam': joint_cam, # [X, Y, Z] in camera coordinate
'joint_vis': joint_vis,
'smpl_param': smpl_param,
'cam_param': cam_param})
datalist = sorted(datalist, key=lambda x: x['img_name'])
return datalist, skip_idx, skip_img_idx
def get_smpl_coord(self, smpl_param, cam_param):
pose, shape, trans, gender = smpl_param['pose'], smpl_param['shape'], smpl_param['trans'], smpl_param['gender']
# smpl parameters (pose: 72 dimension, shape: 10 dimension)
smpl_pose = torch.FloatTensor(pose).view(-1, 3)
smpl_shape = torch.FloatTensor(shape).view(1, -1)
# translation vector from smpl coordinate to h36m world coordinate
trans = np.array(trans, dtype=np.float32).reshape(3)
# camera rotation and translation
R, t = np.array(cam_param['R'],dtype=np.float32).reshape(3, 3), np.array(cam_param['t'],dtype=np.float32).reshape(3)
# change to mean shape if beta is too far from it
smpl_shape[(smpl_shape.abs() > 3).any(dim=1)] = 0.
# transform world coordinate to camera coordinate
root_pose = smpl_pose[self.smpl_root_joint_idx, :].numpy()
angle = np.linalg.norm(root_pose)
root_pose = transforms3d.axangles.axangle2mat(root_pose / angle, angle)
root_pose = np.dot(R, root_pose)
axis, angle = transforms3d.axangles.mat2axangle(root_pose)
root_pose = axis * angle
smpl_pose[self.smpl_root_joint_idx] = torch.from_numpy(root_pose)
smpl_pose = smpl_pose.view(1, -1)
# get mesh and joint coordinates
smpl_mesh_coord, smpl_joint_coord = self.mesh_model.layer[gender](smpl_pose, smpl_shape)
# incorporate face keypoints
smpl_mesh_coord = smpl_mesh_coord.numpy().astype(np.float32).reshape(-1, 3);
smpl_joint_coord = smpl_joint_coord.numpy().astype(np.float32).reshape(-1, 3)
# smpl_face_kps_coord = smpl_mesh_coord[self.face_kps_vertex, :].reshape(-1, 3)
# smpl_joint_coord = np.concatenate((smpl_joint_coord, smpl_face_kps_coord))
# compenstate rotation (translation from origin to root joint was not cancled)
smpl_trans = np.array(trans, dtype=np.float32).reshape(
3) # translation vector from smpl coordinate to h36m world coordinate
smpl_trans = np.dot(R, smpl_trans[:, None]).reshape(1, 3) + t.reshape(1, 3) / 1000
root_joint_coord = smpl_joint_coord[self.smpl_root_joint_idx].reshape(1, 3)
smpl_trans = smpl_trans - root_joint_coord + np.dot(R, root_joint_coord.transpose(1, 0)).transpose(1, 0)
# translation
smpl_mesh_coord += smpl_trans; smpl_joint_coord += smpl_trans
# meter -> milimeter
smpl_mesh_coord *= 1000; smpl_joint_coord *= 1000;
return smpl_mesh_coord, smpl_joint_coord
def get_fitting_error(self, h36m_joint, smpl_mesh):
h36m_joint = h36m_joint - h36m_joint[self.human36_root_joint_idx,None,:] # root-relative
h36m_from_smpl = np.dot(self.joint_regressor_human36, smpl_mesh)
# translation alignment
h36m_from_smpl = h36m_from_smpl - np.mean(h36m_from_smpl,0)[None,:] + np.mean(h36m_joint,0)[None,:]
error = np.sqrt(np.sum((h36m_joint - h36m_from_smpl)**2,1)).mean()
return error
def get_coco_from_mesh(self, mesh_coord_cam, cam_param):
# regress coco joints
joint_coord_cam = np.dot(self.joint_regressor_coco, mesh_coord_cam)
joint_coord_cam = self.add_pelvis_and_neck(joint_coord_cam)
# projection
f, c = cam_param['focal'], cam_param['princpt']
joint_coord_img = cam2pixel(joint_coord_cam, f, c)
joint_coord_img[:, 2] = 1
return joint_coord_cam, joint_coord_img
def add_pelvis_and_neck(self, joint_coord):
lhip_idx = self.coco_joints_name.index('L_Hip')
rhip_idx = self.coco_joints_name.index('R_Hip')
pelvis = (joint_coord[lhip_idx, :] + joint_coord[rhip_idx, :]) * 0.5
pelvis = pelvis.reshape((1, -1))
lshoulder_idx = self.coco_joints_name.index('L_Shoulder')
rshoulder_idx = self.coco_joints_name.index('R_Shoulder')
neck = (joint_coord[lshoulder_idx, :] + joint_coord[rshoulder_idx, :]) * 0.5
neck = neck.reshape((1,-1))
joint_coord = | np.concatenate((joint_coord, pelvis, neck)) | numpy.concatenate |
import numpy as np
import matplotlib.pyplot as plt
from utilities_plotting import adapt_figure_size_from_axes,set_figure_params,hide_spines, cm2inches,set_frame_properties
def cost_per_episode_scenario(cost_array,safety_failures,shapes, count_safe_only = True, safe_avg = False, norm = 1):
""" compute average cost per episode and scenario from cost_array
"""
n_scen, n_ep, n_steps = shapes
#safety_failures = np.zeros((n_scen,n_ep))
print(safety_failures)
res_sum = np.zeros((n_scen,n_ep)) - 1e5 #initialize with -10000
for i in range(n_scen):
for j in range(n_ep):
if not safety_failures[i,j]:
res_sum[i,j] = np.sum(cost_array[i,j])/norm
if np.isnan(res_sum[i,j]):
print("Something went wrong:")
print(cost_array[i,j])
if safe_avg:
res_avg_mean = np.empty((n_ep,))
res_avg_std = np.empty((n_ep,))
failure_mask = np.array(safety_failures,dtype = bool)
for j in range(n_ep):
safe_indices = np.where(np.invert(failure_mask[:,j]))
if len(safe_indices) == 0:
warnings.warn("No successful rollout in episode {}".format(j))
res_avg_mean[j] = np.mean(res_sum[safe_indices,j])
res_avg_std[j] = np.std(res_sum[safe_indices,j])
return res_avg_mean,res_avg_std
return res_sum
def _get_failure_ratio(failures,per_episode = False):
""" Return the failure ratio of all rollouts
Returns the ratio of failed rollout among all rollouts
and all episodes
Parameters
----------
failures: np.ndarray[boolean]
List of shape (n_ep,n_scenarios) with entries failure_list[i,j] = True if rollout i in scenario j failed
per_episode: boolean, optional
Set to True for failure ratio per episode
Returns
-------
failure_ratio: float
The ratio of failed rollouts and total rollouts
"""
n_ep, n_scen = np.shape(failures)
zero_one_failures = np.array(failures,dtype=np.float32)
if per_episode:
return np.mean(zero_one_failures,axis = 1)
return np.mean(zero_one_failures)
plot_trainset = False
set_figure_params()
h_fig_rl_episodes_cm = 3.6
h_fig_bar_cm = 3.6
w_figure_cm = 8.63477
w_full_figure_cm = 17.77747
x_lim_samples = [-1,1]
y_lim_samples = [-1.5,1.5]
rgb_frame = tuple((80/256,80/256,80/256))
h_fig_samples = 4.5
num_fig_samples = 3
h_fig_colorbar = h_fig_samples
w_fig_colorbar = 1.5
w_fig_samples = (w_full_figure_cm - w_fig_colorbar) / num_fig_samples
results_path = "/home/kollert/git_repos/safe-exploration/experiments/results_journal" #"thesis_results_dynamic_exploration" #
sub_folder_path = "results_rl"#"res_dynamic_exploration"#
colorbar_label = "Iterations" #"Time step"
n_ep = 8
n_steps = 50
n_scen = 6
savedir_safempc = lambda n_safe,n_perf,r,beta_safety: "safempc_CartPole_nsafe={}_nperf={}_r={}_beta_safety={}".format(n_safe,n_perf,r,beta_safety)
"""
"""
a_safe_1_perf_10 = np.load("{}/{}/{}/results_episode.npy".format(results_path,sub_folder_path,savedir_safempc("1","15","1","2_0"))).item()
a_safe_2_perf_10 = np.load("{}/{}/{}/results_episode.npy".format(results_path,sub_folder_path,savedir_safempc("2","15","1","2_0"))).item()
a_safe_3_perf_10 = np.load("{}/{}/{}/results_episode.npy".format(results_path,sub_folder_path,savedir_safempc("3","15","1","2_0"))).item()
a_safe_4_perf_10 = np.load("{}/{}/{}/results_episode.npy".format(results_path,sub_folder_path,savedir_safempc("4","15","1","2_0"))).item()
#a_safe_5_perf_10 = np.load("{}/{}/{}/results_episode.npy".format(results_path,sub_folder_path,savedir_safempc("5","10","1","2_0"))).item()
safe_perf_10_list = [a_safe_1_perf_10, a_safe_2_perf_10,a_safe_3_perf_10,a_safe_4_perf_10]
#safe_perf_10_list = [a_safe_1_perf_10,a_safe_2_perf_10,a_safe_3_perf_10,a_safe_4_perf_10]#,a_safe_5_perf_10]
#for k,v in a_safe_1_perf_0.items():
# print(k)
#print(np.array(a_safe_1_perf_10["cc_all"])[0,0])
#print(np.array(a_safe_1_perf_10["safety_failure_all"]))
#print(np.array(a_safe_1_perf_10["X_all"])[1,4])
#print(np.array(a_safe_1_perf_10["X_all"])[0,2][:,2])
# Compute average cost per episode for each n_safe with n_perf=0 and n_perf=10 (two plots)
n_settings_safe = 4
#_, n_ep,_ = np.array(a_safe_1_perf_0["cc_all"]).shape
normalizer = 100
print(a_safe_3_perf_10["safety_failure_all"])
"""
"""
avg_cost_10_perf = np.zeros((n_settings_safe,n_ep))
std_cost_10_perf= np.zeros((n_settings_safe,n_ep))
for i in range(len(safe_perf_10_list)):
print(safe_perf_10_list[i]["safety_failure_all"])
avg_cost_10_perf[i],std_cost_10_perf[i] = cost_per_episode_scenario(np.array(safe_perf_10_list[i]["cc_all"]),np.array(safe_perf_10_list[i]["safety_failure_all"]),(n_scen,n_ep,n_steps),safe_avg = True, norm = normalizer)
n_it = n_ep
Ts = np.arange(4)+1
set_figure_params()
fig = plt.figure()
ax = fig.add_subplot(111)
#ax_T_1 = plt.subplot2grid((1, 7), (0, 0), colspan=2)
#ax_T_4 = plt.subplot2grid((1, 7), (0, 2), colspan=2)
#ax_T_5 = plt.subplot2grid((1, 7), (0, 4), colspan=2)
#ax_cb = plt.subplot2grid((1, 7), (0, 6))
y_lim = [100,450]
ax.set_xlabel('Episode')
ax.set_ylabel('Episode cost ($C_{ep}$)')
#ax.set_yscale('log')
ax.plot( | np.arange(1,n_it+1) | numpy.arange |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-04-17 15:58
# @Author : erwin
import numpy as np
from common.util_function import *
np.set_printoptions(precision=3)
arr = np.linspace(0, 100, 10).reshape((2, 5))
print_line("原始数据")
print_br(arr)
print_line("单个array操作")
print_br(np.add(arr, 2))
print_br( | np.subtract(arr, 2) | numpy.subtract |
import networkx as nx
import numpy as np
import pandas as pd
import config as cfg
# NetworkX Graph Utility Functions
def adjacency_matrix_to_graph(adjacency, labels, label_name, prune=False):
G = nx.DiGraph()
G = nx.from_numpy_array(adjacency, create_using=G)
node_idx = | np.arange(adjacency.shape[0]) | numpy.arange |
# Copyright 2018 The Cirq Developers
#
# 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.
import random
import numpy as np
import pytest
from cirq import linalg
from cirq import testing
from cirq.linalg import combinators
X = np.array([[0, 1], [1, 0]])
Y = np.array([[0, -1j], [1j, 0]])
Z = np.array([[1, 0], [0, -1]])
H = np.array([[1, 1], [1, -1]]) * np.sqrt(0.5)
SQRT_X = np.array([[1, 1j], [1j, 1]])
c = np.exp(1j * np.pi / 4)
SQRT_SQRT_X = np.array([[1 + c, 1 - c], [1 - c, 1 + c]]) / 2
SWAP = np.array([[1, 0, 0, 0],
[0, 0, 1, 0],
[0, 1, 0, 0],
[0, 0, 0, 1]])
CNOT = np.array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0]])
CZ = np.diag([1, 1, 1, -1])
@pytest.mark.parametrize('matrix', [
X,
linalg.kron(X, X),
linalg.kron(X, Y),
linalg.kron(X, np.eye(2))
])
def test_map_eigenvalues_identity(matrix):
identity_mapped = linalg.map_eigenvalues(matrix, lambda e: e)
assert np.allclose(matrix, identity_mapped)
@pytest.mark.parametrize('matrix,exponent,desired', [
[X, 2, np.eye(2)],
[X, 3, X],
[Z, 2, np.eye(2)],
[H, 2, np.eye(2)],
[Z, 0.5, np.diag([1, 1j])],
[X, 0.5, np.array([[1j, 1], [1, 1j]]) * (1 - 1j) / 2],
])
def test_map_eigenvalues_raise(matrix, exponent, desired):
exp_mapped = linalg.map_eigenvalues(matrix, lambda e: complex(e)**exponent)
assert np.allclose(desired, exp_mapped)
@pytest.mark.parametrize('f1,f2', [
(H, X),
(H * 1j, X),
(H, SQRT_X),
(H, SQRT_SQRT_X),
(H, H),
(SQRT_SQRT_X, H),
(X, np.eye(2)),
(1j * X, np.eye(2)),
(X, 1j * np.eye(2)),
(-X, 1j * np.eye(2)),
(X, X),
] + [
(testing.random_unitary(2), testing.random_unitary(2))
for _ in range(10)
])
def test_kron_factor(f1, f2):
p = linalg.kron(f1, f2)
g, g1, g2 = linalg.kron_factor_4x4_to_2x2s(p)
assert abs(np.linalg.det(g1) - 1) < 0.00001
assert abs(np.linalg.det(g2) - 1) < 0.00001
assert np.allclose(g * linalg.kron(g1, g2), p)
@pytest.mark.parametrize('f1,f2', [
(testing.random_special_unitary(2), testing.random_special_unitary(2))
for _ in range(10)
])
def test_kron_factor_special_unitaries(f1, f2):
p = linalg.kron(f1, f2)
g, g1, g2 = linalg.kron_factor_4x4_to_2x2s(p)
assert np.allclose(linalg.kron(g1, g2), p)
assert abs(g - 1) < 0.000001
assert linalg.is_special_unitary(g1)
assert linalg.is_special_unitary(g2)
def test_kron_factor_fail():
with pytest.raises(ValueError):
_ = linalg.kron_factor_4x4_to_2x2s(
linalg.kron_with_controls(linalg.CONTROL_TAG, X))
with pytest.raises(ValueError):
_ = linalg.kron_factor_4x4_to_2x2s(np.diag([1, 1, 1, 1j]))
def recompose_so4(a: np.ndarray, b: np.ndarray) -> np.ndarray:
assert a.shape == (2, 2)
assert b.shape == (2, 2)
assert linalg.is_special_unitary(a)
assert linalg.is_special_unitary(b)
magic = np.array([[1, 0, 0, 1j],
[0, 1j, 1, 0],
[0, 1j, -1, 0],
[1, 0, 0, -1j]]) * np.sqrt(0.5)
result = np.real(combinators.dot(np.conj(magic.T),
linalg.kron(a, b),
magic))
assert linalg.is_orthogonal(result)
return result
@pytest.mark.parametrize('m', [
testing.random_special_orthogonal(4)
for _ in range(10)
])
def test_so4_to_magic_su2s(m):
a, b = linalg.so4_to_magic_su2s(m)
m2 = recompose_so4(a, b)
assert | np.allclose(m, m2) | numpy.allclose |
import numpy as np
def norm(im):
im = im.astype(np.float32)
min_v = | np.min(im) | numpy.min |
import numpy as np
import paddle
from .abc_interpreter import Interpreter
from ..data_processor.readers import preprocess_inputs, preprocess_save_path
from ..data_processor.visualizer import explanation_to_vis, show_vis_explanation, save_image
class GradCAMInterpreter(Interpreter):
"""
Gradient CAM Interpreter.
More details regarding the GradCAM method can be found in the original paper:
https://arxiv.org/abs/1610.02391
"""
def __init__(self,
paddle_model,
use_cuda=True,
device='gpu:0',
model_input_shape=[3, 224, 224]) -> None:
"""
Args:
paddle_model (callable): A model with ``forward`` and possibly ``backward`` functions.
device (str): The device used for running `paddle_model`, options: ``cpu``, ``gpu:0``, ``gpu:1`` etc.
use_cuda (bool): Would be deprecated soon. Use ``device`` directly.
model_input_shape (list, optional): The input shape of the model. Default: [3, 224, 224]
"""
Interpreter.__init__(self, paddle_model, device, use_cuda)
self.model_input_shape = model_input_shape
self.paddle_prepared = False
# init for usages during the interpretation.
self._target_layer_name = None
self._feature_maps = {}
def interpret(self,
inputs,
target_layer_name,
label=None,
visual=True,
save_path=None):
"""
Main function of the interpreter.
Args:
inputs (str or list of strs or numpy.ndarray): The input image filepath or a list of filepaths or numpy array of read images.
target_layer_name (str): The target layer to calculate gradients.
labels (list or tuple or numpy.ndarray, optional): The target labels to analyze. The number of labels should be equal to the number of images. If None, the most likely label for each image will be used. Default: None
visual (bool, optional): Whether or not to visualize the processed image. Default: True
save_path (str or list of strs or None, optional): The filepath(s) to save the processed image(s). If None, the image will not be saved. Default: None
Returns:
[numpy.ndarray]: interpretations/heatmap for images
"""
imgs, data = preprocess_inputs(inputs, self.model_input_shape)
bsz = len(data) # batch size
save_path = preprocess_save_path(save_path, bsz)
assert target_layer_name in [n for n, v in self.paddle_model.named_sublayers()], \
f"target_layer_name {target_layer_name} does not exist in the given model, " \
f"please check all valid layer names by [n for n, v in paddle_model.named_sublayers()]"
if self._target_layer_name != target_layer_name:
self._target_layer_name = target_layer_name
self.paddle_prepared = False
if not self.paddle_prepared:
self._paddle_prepare()
feature_map, gradients, preds = self.predict_fn(data, label)
if label is None:
label = preds
label = | np.array(label) | numpy.array |
from __future__ import print_function
from __future__ import absolute_import
import numpy as nm
import sys
from six.moves import range
sys.path.append('.')
from sfepy.base.base import output, assert_
from sfepy.base.ioutils import ensure_path
from sfepy.linalg import cycle
from sfepy.discrete.fem.mesh import Mesh
from sfepy.mesh.mesh_tools import elems_q2t
def get_tensor_product_conn(shape):
"""
Generate vertex connectivity for cells of a tensor-product mesh of the
given shape.
Parameters
----------
shape : array of 2 or 3 ints
Shape (counts of nodes in x, y, z) of the mesh.
Returns
-------
conn : array
The vertex connectivity array.
desc : str
The cell kind.
"""
shape = nm.asarray(shape)
dim = len(shape)
assert_(1 <= dim <= 3)
n_nod = nm.prod(shape)
n_el = nm.prod(shape - 1)
grid = nm.arange(n_nod, dtype=nm.int32)
grid.shape = shape
if dim == 1:
conn = nm.zeros((n_el, 2), dtype=nm.int32)
conn[:, 0] = grid[:-1]
conn[:, 1] = grid[1:]
desc = '1_2'
elif dim == 2:
conn = nm.zeros((n_el, 4), dtype=nm.int32)
conn[:, 0] = grid[:-1, :-1].flat
conn[:, 1] = grid[1:, :-1].flat
conn[:, 2] = grid[1:, 1:].flat
conn[:, 3] = grid[:-1, 1:].flat
desc = '2_4'
else:
conn = nm.zeros((n_el, 8), dtype=nm.int32)
conn[:, 0] = grid[:-1, :-1, :-1].flat
conn[:, 1] = grid[1:, :-1, :-1].flat
conn[:, 2] = grid[1:, 1:, :-1].flat
conn[:, 3] = grid[:-1, 1:, :-1].flat
conn[:, 4] = grid[:-1, :-1, 1:].flat
conn[:, 5] = grid[1:, :-1, 1:].flat
conn[:, 6] = grid[1:, 1:, 1:].flat
conn[:, 7] = grid[:-1, 1:, 1:].flat
desc = '3_8'
return conn, desc
def gen_block_mesh(dims, shape, centre, mat_id=0, name='block',
coors=None, verbose=True):
"""
Generate a 2D or 3D block mesh. The dimension is determined by the
lenght of the shape argument.
Parameters
----------
dims : array of 2 or 3 floats
Dimensions of the block.
shape : array of 2 or 3 ints
Shape (counts of nodes in x, y, z) of the block mesh.
centre : array of 2 or 3 floats
Centre of the block.
mat_id : int, optional
The material id of all elements.
name : string
Mesh name.
verbose : bool
If True, show progress of the mesh generation.
Returns
-------
mesh : Mesh instance
"""
dims = nm.asarray(dims, dtype=nm.float64)
shape = nm.asarray(shape, dtype=nm.int32)
centre = nm.asarray(centre, dtype=nm.float64)
dim = shape.shape[0]
centre = centre[:dim]
dims = dims[:dim]
n_nod = nm.prod(shape)
output('generating %d vertices...' % n_nod, verbose=verbose)
x0 = centre - 0.5 * dims
dd = dims / (shape - 1)
ngrid = nm.mgrid[[slice(ii) for ii in shape]]
ngrid.shape = (dim, n_nod)
coors = x0 + ngrid.T * dd
output('...done', verbose=verbose)
n_el = nm.prod(shape - 1)
output('generating %d cells...' % n_el, verbose=verbose)
mat_ids = nm.empty((n_el,), dtype=nm.int32)
mat_ids.fill(mat_id)
conn, desc = get_tensor_product_conn(shape)
output('...done', verbose=verbose)
mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc])
return mesh
def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False,
is_open=False, open_angle=0.0, non_uniform=False,
name='cylinder', verbose=True):
"""
Generate a cylindrical mesh along an axis. Its cross-section can be
ellipsoidal.
Parameters
----------
dims : array of 5 floats
Dimensions of the cylinder: inner surface semi-axes a1, b1, outer
surface semi-axes a2, b2, length.
shape : array of 3 ints
Shape (counts of nodes in radial, circumferential and longitudinal
directions) of the cylinder mesh.
centre : array of 3 floats
Centre of the cylinder.
axis: one of 'x', 'y', 'z'
The axis of the cylinder.
force_hollow : boolean
Force hollow mesh even if inner radii a1 = b1 = 0.
is_open : boolean
Generate an open cylinder segment.
open_angle : float
Opening angle in radians.
non_uniform : boolean
If True, space the mesh nodes in radial direction so that the element
volumes are (approximately) the same, making thus the elements towards
the outer surface thinner.
name : string
Mesh name.
verbose : bool
If True, show progress of the mesh generation.
Returns
-------
mesh : Mesh instance
"""
dims = nm.asarray(dims, dtype=nm.float64)
shape = nm.asarray(shape, dtype=nm.int32)
centre = | nm.asarray(centre, dtype=nm.float64) | numpy.asarray |
#!/usr/bin/env python
#
# THE KITTI VISION BENCHMARK SUITE: ROAD BENCHMARK
#
# Copyright (C) 2013
# Honda Research Institute Europe GmbH
# Carl-Legien-Str. 30
# 63073 Offenbach/Main
# Germany
#
# UNPUBLISHED PROPRIETARY MATERIAL.
# ALL RIGHTS RESERVED.
#
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
import numpy as np
# import pylab
import matplotlib.cm as cm
import os
# import cv2
def make_overlay(image, gt_prob):
mycm = cm.get_cmap('bwr')
overimage = mycm(gt_prob, bytes=True)
output = 0.4*overimage[:,:,0:3] + 0.6*image
return output
def overlayImageWithConfidence(in_image, conf, vis_channel = 1, threshold = 0.5):
'''
:param in_image:
:param conf:
:param vis_channel:
:param threshold:
'''
if in_image.dtype == 'uint8':
visImage = in_image.copy().astype('f4')/255
else:
visImage = in_image.copy()
channelPart = visImage[:, :, vis_channel] * (conf > threshold) - conf
channelPart[channelPart < 0] = 0
visImage[:, :, vis_channel] = 0.5*visImage[:, :, vis_channel] + 255*conf
return visImage
def evalExp(gtBin, cur_prob, thres, validMap = None, validArea=None):
'''
Does the basic pixel based evaluation!
:param gtBin:
:param cur_prob:
:param thres:
:param validMap:
'''
assert len(cur_prob.shape) == 2, 'Wrong size of input prob map'
assert len(gtBin.shape) == 2, 'Wrong size of input prob map'
thresInf = np.concatenate(([-np.Inf], thres, [np.Inf]))
#Merge validMap with validArea
if validMap is not None:
if validArea is not None:
validMap = (validMap == True) & (validArea == True)
elif validArea is not None:
validMap=validArea
# histogram of false negatives
if validMap is not None:
fnArray = cur_prob[(gtBin == True) & (validMap == True)]
else:
fnArray = cur_prob[(gtBin == True)]
fnHist = np.histogram(fnArray,bins=thresInf)[0]
fnCum = | np.cumsum(fnHist) | numpy.cumsum |
import numpy as np
import scipy.sparse as sparse
from typing import *
import html
import logging
def normalize_attr_strings(a: np.ndarray) -> np.ndarray:
"""
Take an np.ndarray of all kinds of string-like elements, and return an array of ascii (np.string_) objects
"""
if np.issubdtype(a.dtype, np.object_):
# if np.all([type(x) is str for x in a]) or np.all([type(x) is np.str_ for x in a]) or np.all([type(x) is np.unicode_ for x in a]):
if np.all([(type(x) is str or type(x) is np.str_ or type(x) is np.unicode_) for x in a]):
return np.array([x.encode('ascii', 'xmlcharrefreplace') for x in a])
elif np.all([type(x) is np.string_ for x in a]) or np.all([type(x) is np.bytes_ for x in a]):
return a.astype("string_")
else:
logging.debug(f"Attribute contains mixed object types ({np.unique([str(type(x)) for x in a])}); casting all to string")
return np.array([str(x) for x in a], dtype="string_")
elif np.issubdtype(a.dtype, np.string_) or | np.issubdtype(a.dtype, np.object_) | numpy.issubdtype |
# pylint: disable=no-member,E1130,E1137
import cortex
from datetime import datetime
from linescanning import (
planning,
plotting,
dataset,
pycortex,
transform,
utils
)
import matplotlib.pyplot as plt
import nibabel as nb
import numpy as np
import os
import pandas as pd
import random
import warnings
warnings.filterwarnings('ignore')
opj = os.path.join
def set_threshold(name=None, borders=None, set_default=None):
"""set_threshold
This function is utilized in call_pycortex2 to fetch the thresholds for multiple properties including pRF-parameters (eccentricity, r2, and polar angle), and structural (surface) properties such as cortical thickness and sulcal depth. To make verbosity nicer, you can specify a 'name' to print to the terminal what kind of property is being processed. Then, you can specify a range where the user input should fall in (default is None to not force a specific range). You can also set a default value if you do not wish to set a certain threshold (usually this is the minimum/maximum of your array depending on what kind of thresholding you're about to do, e.g., 'greater/smaller than <value>').
Parameters
----------
name: str, optional
For verbosity reasons, a string of the property's name that needs thresholding
borders: tuple, optional
Specific range the user input needs to fall in. Default is None to not enforce a range
set_default: int, float, optional
Minimum/maximum of array (depending on the kind of thresholding to be applied) if
you do not wish to enforce a threshold
Returns
----------
float
thresholds given `borders`
Example
----------
>>> ecc_val = set_threshold(name="eccentricity", range=(0,15), set_default=min(ecc_array))
"""
if not name:
name = "property"
# set threshold for 'name'
while True:
try:
val = float(input(f" {name} [def = {int(set_default)}]: \t") or set_default)
except ValueError:
print(" Please enter a number")
continue
else:
pass
if borders and len(borders) == 2:
if borders[0] <= float(val) <= borders[1]:
return float(val)
else:
print(f" WARNING: specified range is ({borders[0]},{borders[1]}), your value is {val}. Try again..")
continue
else:
return float(val)
def target_vertex(subject,
deriv=None,
prf_dir=None,
cx_dir=None,
fs_dir=None,
task="2R_model-gauss_stage-iter",
webshow=True,
out=None,
roi="V1_exvivo.thresh",
use_prf=True,
vert=None):
"""target_vertex
Full procedure to extract a target vertex given a set of criteria (as per :func:`linescanning.optimal.set_threshold`) from structural (:class:`linescanning.optimal.SurfaceCalc`) and functional (:class:`linescanning.optimal.pRFCalc`) by combining everything in :class:`linescanning.optimal.CalcBestVert`. The workflow looks as follows:
* Set thresholds for pRF/structural properties
* Combine functional/structural properties into :class:`linescanning.optimal.CalcBestVert`
* Pick out vertex/normal/surface coordinate
* Verify coordinate using `FreeView`
* Store pRF/vertex information in `<subject>_desc-prf_params_best_vertices.csv` & `line_pycortex.csv`
Parameters
----------
subject: str
Subject ID as used in `SUBJECTS_DIR`
deriv: str, optional
Path to derivatives folder of the project. Generally should be the path specified with `DIR_DATA_DERIV` in the bash environment. This option overwrite the individual specification of `prf_dir`, `cx_dir`, and `fs_dir`, and will look up defaults.
cx_dir: str, optional
Path to `pycortex`-directory (should be `filestore`, as specified in the pycortex config file)
fs_dir: str, optional
`FreeSurfer` directory (default = SUBJECTS_DIR)
prf_dir: str, optional
`prf` directory in derivatives folder
task: str, optional
This tag is used to fetch the `prf_params` file created with `spinoza_fitprfs`. Because we write out both the `gridfit` and the `iterative fit`, we have a slightly more complex tag by default. Can be any set of pRF-parameters that you want, as long as it has the same dimensions as the surfaces created with `FreeSurfer`/`Pycortex`
webshow: bool
Start `FreeView` for visual verification. During debugging this is rather cumbersome, so you can turn it off by specifying `webshow=False`
roi: str, optional
ROI-name to extract the vertex from as per ROIs created with `FreeSurfer`. Default is V1_exvivo.thresh
use_prf: bool
In case you want to base the selection of the target_vertex on both structural and functional properties, set `use_prf=True`. If you only want to include anatomical information such as curvature, set `use_prf=False`. This is relevant for non-visual experiments
verts: list, optional
List of manually selected vertices rather than selecting the vertices based on structural/functional properties
Returns
---------
str
Creates vertex-information files `<subject>_desc-prf_params_best_vertices.csv` & `line_pycortex.csv` as well as figures showing the timecourses/pRF-location of selected vertices. Doesn't
class
:class:`linescanning.CalcBestVertex`
Example
----------
>>> # use Gaussian iterative parameters to find target vertex for sub-001 in V1_exvivo.thresh by using the default derivatives folders
>>> optimal.target_vertex("sub-001", task="2R_model-gauss_stage-iter", use_prf=True, out="line_pycortex.csv", roi="V1_exvivo.thresh", webshow=True)
"""
if deriv:
# This is mainly for displaying purposes
dirs = {'prf': opj(deriv, 'prf'),
'fs': opj(deriv, 'freesurfer'),
'ctx': opj(deriv, 'pycortex')}
prf_dir, fs_dir, cx_dir = dirs['prf'], dirs['fs'], dirs['ctx']
else:
# This is mainly for displaying purposes
dirs = {'prf': prf_dir,
'fs': fs_dir,
'ctx': cx_dir}
for element in list(dirs.keys()):
if element != "prf":
if dirs[element] == None:
raise ValueError(f"Need the {element}-directory")
else:
if use_prf:
if dirs[element] == None:
raise ValueError(f"Need the {element}-directory")
print("Using following directories:")
[print(f" {i}:\t{dirs[i]}") for i in dirs]
if not out:
out = opj(cx_dir, subject, 'line_pycortex.csv')
#----------------------------------------------------------------------------------------------------------------
# Read in surface and pRF-data
if os.path.isfile(out):
print(f"Loading in {out}")
return utils.VertexInfo(out, subject=subject, hemi="both")
else:
if use_prf == True:
print(f"Selecting pRF-parameters from: {task}")
prf_params = utils.get_file_from_substring(f"task-{task}_desc-prf_params.npy", prf_dir)
if "gauss" in prf_params:
model = "gauss"
elif "norm" in prf_params:
model = "norm"
else:
prf_params = None
model = "none"
print(f"prf file = {prf_params}")
print(f"roi = {roi}")
# This thing mainly does everything. See the linescanning/optimal.py file for more information
print("Combining surface and pRF-estimates in one object")
GetBestVertex = CalcBestVertex(subject=subject, fs_dir=fs_dir, prffile=prf_params, fs_label=roi)
#----------------------------------------------------------------------------------------------------------------
# Set the cutoff criteria based on which you'd like to select a vertex
check = False
while check == False:
if not isinstance(vert, np.ndarray):
print("Set thresholds (leave empty and press [ENTER] to not use a particular property):")
# get user input with set_threshold > included the possibility to have only pRF or structure only!
if hasattr(GetBestVertex, 'prf'):
size_val = set_threshold(name="pRF size (beta)", borders=(0,5), set_default=round(min(GetBestVertex.prf.size)))
r2_val = set_threshold(name="r2 (variance)", borders=(0,1), set_default=round(min(GetBestVertex.prf.r2)))
ecc_val = set_threshold(name="eccentricity", borders=(0,15), set_default=round(min(GetBestVertex.prf.ecc)))
pol_val_lh = set_threshold(name="polar angle lh", borders=(0,np.pi), set_default=round(np.pi))
pol_val_rh = set_threshold(name="polar angle rh", borders=(-np.pi,0), set_default=round(-np.pi))
pol_val = [pol_val_lh,pol_val_rh]
else:
size_val = 0
ecc_val = 0
r2_val = 0
pol_val = 0
if hasattr(GetBestVertex, 'surface'):
thick_val = set_threshold(name="thickness (mm)", borders=(0,5), set_default=max(GetBestVertex.surface.thickness.data))
depth_val = set_threshold(name="sulcal depth", set_default=round(min(GetBestVertex.surface.depth.data)))
else:
thick_val = 0
depth_val = 0
# print out to confirm
print("Using these parameters to find vertex with minimal curvature:")
print(f" pRF size: {round(size_val,2)}")
print(f" eccentricity: {round(ecc_val,4)}")
print(f" r2: {round(r2_val,4)}")
print(f" polar angle: {pol_val}")
print(f" thickness: {thick_val}")
print(f" depth: {round(depth_val,4)}")
# Create mask using selected criteria
GetBestVertex.apply_thresholds(ecc_thresh=ecc_val,
size_thresh=size_val,
r2_thresh=r2_val,
polar_thresh=pol_val,
depth_thresh=depth_val,
thick_thresh=thick_val)
# # Look for minimal curvature within that mask
# GetBestVertex.mask_curv_with_prf()
# Pick out best vertex
GetBestVertex.best_vertex()
# check = True
else:
for i,r in enumerate(['lh', 'rh']):
setattr(GetBestVertex, f"{r}_best_vertex", vert[i])
setattr(GetBestVertex, f"{r}_best_vertex_coord", getattr(GetBestVertex.surface, f'{r}_surf_data')[0][vert[i]])
setattr(GetBestVertex, f"{r}_best_vert_mask", (getattr(GetBestVertex.surface, f'{r}_surf_data')[1] == [vert[i]]).sum(0))
# Calculate normal using the standard method. Other options are "cross" and "Newell"
GetBestVertex.fetch_normal()
# Print some stuff to show what's going on
print("Found following vertex in left hemisphere:")
print(" coord = {coord}".format(coord=GetBestVertex.lh_best_vertex_coord))
print(" normal = {norm}".format(norm=GetBestVertex.surface.lh_surf_normals[GetBestVertex.lh_best_vertex]))
print(" vertex = {vert}".format(vert=GetBestVertex.lh_best_vertex))
if use_prf == True:
os.system(f"call_prfinfo -s {subject} -v {GetBestVertex.lh_best_vertex}")
print("Found following vertex in right hemisphere:")
print(" coord = {coord}".format(coord=GetBestVertex.rh_best_vertex_coord))
print(" normal = {norm}".format(norm=GetBestVertex.surface.lh_surf_normals[GetBestVertex.rh_best_vertex]))
print(" vertex = {vert}".format(vert=GetBestVertex.rh_best_vertex))
if use_prf == True:
os.system(f"call_prfinfo -s {subject} -v {GetBestVertex.rh_best_vertex} -h rh")
# # Smooth vertex maps
# print("Smooth vertex maps for visual verification")
# GetBestVertex.vertex_to_map()
# GetBestVertex.smooth_vertexmap()
# visually check if parameters should be adjusted
# print(f" Webshow is set to {webshow}")
port = random.randint(1024, 65536)
# place = get_base_dir()[1]
if isinstance(vert,np.ndarray):
webshow = False
if webshow:
orig = opj(fs_dir, subject, 'mri', 'orig.mgz')
tkr = transform.ctx2tkr(subject, coord=[GetBestVertex.lh_best_vertex_coord,GetBestVertex.rh_best_vertex_coord])
tkr_coords = {'lh': tkr[0], 'rh': tkr[1]}
os.system("freeview -v {orig} -f {lh_fid}:edgecolor=green {rh_fid}:edgecolor=green --ras {x} {y} {z} tkreg 2>/dev/null".format(orig=orig,
lh_fid=opj(fs_dir, subject, 'surf', "lh.fiducial"),
rh_fid=opj(fs_dir, subject, 'surf', "rh.fiducial"),
x=round(tkr_coords['lh'][0],2),
y=round(tkr_coords['lh'][1],2),
z=round(tkr_coords['lh'][2],2)))
else:
print("Verification with FreeView disabled")
#----------------------------------------------------------------------------------------------------------------
# Write out files if all is OK
happy = input("Happy with the position? (y/n): ")
if happy.lower() == 'y' or happy == 'yes':
print(" Alrighty, continuing with these parameters")
if not isinstance(vert, np.ndarray):
textList = ["# Created on {date}\n".format(date=datetime.now().strftime("%d/%m/%Y %H:%M:%S")),
f"size: {size_val}\n",
f"ecc: {ecc_val}\n",
f"r2: {r2_val}\n",
f"polar: {pol_val}\n",
f"thickness: {thick_val}\n",
f"depth: {depth_val}\n",
]
else:
textList = ["# Created on {date}\n".format(date=datetime.now().strftime("%d/%m/%Y %H:%M:%S")),
"Manually selected following vertices:\n",
f"lh: {vert[0]}\n",
f"rh: {vert[1]}\n"]
outF = open(opj(cx_dir, subject, "cutoffs.o{ext}".format(ext=os.getpid())), "w")
outF.writelines(textList)
outF.close()
check = True
GetBestVertex.write_line_pycortex(save_as=out)
print(" writing {file}".format(file=out))
#----------------------------------------------------------------------------------------------------------------
# Get pRF-parameters from best vertices
if prf_params and os.path.exists(prf_params):
prf_data = np.load(prf_params)
prf_bestvertex = opj(cx_dir, subject, f'{subject}_model-{model}_desc-best_vertices.csv')
prf_right = prf_data[GetBestVertex.surface.lh_surf_data[0].shape[0]:][GetBestVertex.rh_best_vertex]
prf_left = prf_data[0:GetBestVertex.surface.lh_surf_data[0].shape[0]][GetBestVertex.lh_best_vertex]
# print(prf_right)
# print(prf_left)
best_vertex = pd.DataFrame({"hemi": ["L", "R"],
"x": [prf_left[0], prf_right[0]],
"y": [prf_left[1], prf_right[1]],
"size": [prf_left[2], prf_right[2]],
"beta": [prf_left[3], prf_right[3]],
"baseline": [prf_left[4], prf_right[4]],
"r2": [prf_left[5], prf_right[5]],
"ecc": [GetBestVertex.prf.ecc[GetBestVertex.lh_best_vertex], GetBestVertex.prf.ecc[GetBestVertex.surface.lh_surf_data[0].shape[0]:][GetBestVertex.rh_best_vertex]],
"polar": [GetBestVertex.prf.polar[GetBestVertex.lh_best_vertex], GetBestVertex.prf.polar[GetBestVertex.surface.lh_surf_data[0].shape[0]:][GetBestVertex.rh_best_vertex]],
"index": [GetBestVertex.lh_best_vertex, GetBestVertex.rh_best_vertex],
"position": [GetBestVertex.lh_best_vertex_coord, GetBestVertex.rh_best_vertex_coord],
"normal": [GetBestVertex.lh_normal, GetBestVertex.rh_normal]})
best_vertex.to_csv(prf_bestvertex)
print(" writing {file}".format(file=prf_bestvertex))
# load pRF-experiment details
for hemi in ["lh", "rh"]:
if hemi == "lh":
hemi_tag = "hemi-L"
elif hemi == "rh":
hemi_tag = "hemi-R"
# fetch subject's pRF-stuff
subject_info = utils.CollectSubject(subject, cx_dir=opj(cx_dir, subject), prf_dir=prf_dir, settings='recent', hemi=hemi, verbose=False)
# initiate figure
fig = plt.figure(constrained_layout=True, figsize=(20,5))
gs00 = fig.add_gridspec(1,2, width_ratios=[10,20])
# add pRF-plot
ax1 = fig.add_subplot(gs00[0])
plotting.LazyPRF(subject_info.prf_array, subject_info.settings['vf_extent'], ax=ax1)
# create timecourse plot
ax2 = fig.add_subplot(gs00[1])
bold = np.load(utils.get_file_from_substring(f"avg_bold_{hemi_tag}.npy", os.path.dirname(prf_params)))
vert = getattr(GetBestVertex, f"{hemi}_best_vertex")
plotting.LazyPlot(bold[:,vert],
x_label="volumes",
y_label="amplitude (z-score)",
font_size=14,
line_width=2,
color="#53107B",
add_hline='default',
axs=ax2)
fig.savefig(opj(cx_dir, subject, f'{subject}_{hemi_tag}_desc-prf_info.pdf'))
print("Done")
return GetBestVertex
class SurfaceCalc(object):
"""SurfaceCalc
This object does all the surface initialization given a subject and a freesurfer directory. For instance, it reads in the curvature, thickness, and sulcal depth maps from freesurfer, smooths the curvature map, reads by default the V1_exvivo_thresh label in, and creates a boolean mask of this label. So with this one class you will have everything you need from the surface calculations.
Parameters
----------
subject: str
subject ID as used in `SUBJECTS_DIR`
fs_dir: str, optional
`FreeSurfer` directory (default = SUBJECTS_DIR)
fs_label: str, optional
ROI-name to extract the vertex from as per ROIs created with `FreeSurfer`. Default is V1_exvivo.thresh
Example
----------
>>> surf_calcs = SurfaceCalc(subj="sub-001")
Notes
----------
Embedded in :class:`linescanning.optimal.CalcBestVertex`, so if you can also just call that class and you won't have to run the command in "usage"
"""
def __init__(self, subject=None, fs_dir=None, fs_label="V1_exvivo.thresh"):
"""Initialize object"""
# print(" Perform surface operations")
self.subject = subject
self.ctx_path = opj(cortex.database.default_filestore, self.subject)
if fs_dir == None:
self.fs_dir = os.environ['SUBJECTS_DIR']
else:
self.fs_dir = fs_dir
if not os.path.exists(self.ctx_path):
# import subject from freesurfer (will have the same names)
cortex.freesurfer.import_subj(fs_subject=self.subject,
cx_subject=self.subject,
freesurfer_subject_dir=self.fs_dir,
whitematter_surf='smoothwm')
self.curvature = cortex.db.get_surfinfo(self.subject, type="curvature")
self.thickness = cortex.db.get_surfinfo(self.subject, type="thickness")
self.depth = cortex.db.get_surfinfo(self.subject, type="sulcaldepth")
self.lh_surf_data, self.rh_surf_data = cortex.db.get_surf(self.subject, 'fiducial')
self.lh_surf,self.rh_surf = cortex.polyutils.Surface(self.lh_surf_data[0], self.lh_surf_data[1]), cortex.polyutils.Surface(self.rh_surf_data[0], self.rh_surf_data[1])
# Normal vector for each vertex (average of normals for neighboring faces)
self.lh_surf_normals = self.lh_surf.vertex_normals
self.rh_surf_normals = self.rh_surf.vertex_normals
self.smooth_surfs(kernel=3,nr_iter=3)
# try:
setattr(self, 'roi_label', fs_label.replace('.', '_'))
if not fs_label.endswith('.gii'):
make_mask = True
tmp = self.read_fs_label(subject=self.subject, fs_dir=self.fs_dir, fs_label=fs_label, hemi="both")
else:
make_mask = False
tmp = {}
for ii in ['lh', 'rh']:
gifti = dataset.ParseGiftiFile(opj(fs_dir, subject, 'label', f"{ii}.{fs_label}"), set_tr=1)
if gifti.data.ndim > 1:
tmp[ii] = np.squeeze(gifti.data, axis=0)
else:
tmp[ii] = gifti.data.copy()
setattr(self, f'lh_{self.roi_label}', tmp['lh'])
setattr(self, f'rh_{self.roi_label}', tmp['rh'])
# this way we can also use read_fs_label for more custom purposes
if make_mask:
pp = self.label_to_mask(subject=self.subject, lh_arr=getattr(self, f'lh_{self.roi_label}'), rh_arr=getattr(self, f'rh_{self.roi_label}'), hemi="both")
self.lh_roi_mask = pp['lh_mask']
self.rh_roi_mask = pp['rh_mask']
self.whole_roi = pp['whole_roi']
self.whole_roi_v = pp['whole_roi_v']
else:
self.lh_roi_mask = getattr(self, f'lh_{self.roi_label}')
self.rh_roi_mask = getattr(self, f'rh_{self.roi_label}')
self.whole_roi = np.concatenate((self.lh_roi_mask, self.rh_roi_mask))
self.whole_roi_v = cortex.Vertex(self.whole_roi, subject=subject, vmin=-0.5, vmax=1)
def smooth_surfs(self, kernel=10, nr_iter=1):
"""smooth_surfs
smooth surfaces with a given kernel size. The kernel size does not refer to mm, but to a factor. Therefore it has to be an integer value
Parameters
-----------
kernel: int
size of kernel to use for smoothing
nr_iter: int
number of iterations
Returns
----------
sets the attributes `self.?h_surf_sm`
"""
if not isinstance(kernel,int):
print(f" Rounding smoothing factor '{kernel}' to '{int(kernel)}'")
kernel = int(kernel)
setattr(self, 'lh_surf_sm', self.lh_surf.smooth(self.curvature.data[:self.lh_surf_data[0].shape[0]], factor=kernel, iterations=nr_iter))
setattr(self, 'rh_surf_sm', self.rh_surf.smooth(self.curvature.data[self.lh_surf_data[0].shape[0]:], factor=kernel, iterations=nr_iter))
@staticmethod
def read_fs_label(subject, fs_dir=None, fs_label=None, hemi="both"):
"""read_fs_label
read a freesurfer label file (name must match with file in freesurfer directory)
Parameters
-----------
subject: str
subject ID as used in `SUBJECTS_DIR`
fs_dir: str, optional
`FreeSurfer` directory (default = SUBJECTS_DIR)
fs_label: str, optional
ROI-name to extract the vertex from as per ROIs created with `FreeSurfer`. Default is V1_exvivo.thresh
hemi: str, optional
For which hemisphere to perform the process, `lh`=left hemisphere, `rh`=right hemisphere, `both`=both hemispheres (default = `both`)
Returns
----------
dict
Dictionary collecting outputs under the following keys
* lh: output from `nibabel.freesurfer.io.read_label`
* rh: output from `nibabel.freesurfer.io.read_label`
"""
# # dots are annoying in attributes, to replace them with underscores; won't fail if there aren't any present
# setattr(self, 'roi_label', fs_label.replace('.', '_'))
# print("reading {}".format(opj(self.fs_dir, self.subject, 'label', f'{fs_label}.label')))
if hemi == "both":
return {'lh': nb.freesurfer.io.read_label(opj(fs_dir, subject, 'label', f'lh.{fs_label}.label'), read_scalars=False),
'rh': nb.freesurfer.io.read_label(opj(fs_dir, subject, 'label', f'rh.{fs_label}.label'), read_scalars=False)}
# [setattr(self, f'{i}_{self.roi_label}', nb.freesurfer.io.read_label(opj(self.fs_dir, self.subject, 'label', f'{i}.{fs_label}.label'), read_scalars=False)) for i in ['lh','rh']]
else:
if hemi.lower() != "lh" and hemi.lower() != "rh":
raise ValueError(f"Hemisphere should be one of 'both', 'lh', or 'rh'; not {hemi}")
else:
label_file = opj(fs_dir, subject, 'label', f'{hemi}.{fs_label}.label')
# setattr(self, f'{hemi}_{self.roi_label}', nb.freesurfer.io.read_label(label_file, read_scalars=False))
return {hemi: nb.freesurfer.io.read_label(label_file, read_scalars=False)}
def label_to_mask(self, subject=None, lh_arr=None, rh_arr=None, hemi="both"):
"""label_to_mask
Convert freesurfer label or set of vertices to boolean vector
Parameters
-----------
subject: str
subject ID as used in `SUBJECTS_DIR`
lh_arr: numpy.ndarray, optional
array containing the mask in the left hemisphere (can be read from :class:`linescanning.optimal.SurfaceCalc` itself)
rh_arr: numpy.ndarray, optional
array containing the mask in the right hemisphere (can be read from :class:`linescanning.optimal.SurfaceCalc` itself)
hemi: str, optional
For which hemisphere to perform the process, `lh`=left hemisphere, `rh`=right hemisphere, `both`=both hemispheres (default = `both`)
Returns
----------
dict
Dictionary collecting outputs under the following keys
* lh_mask: boolean numpy.ndarray in the left hemisphere
* rh_mask: boolean numpy.ndarray in the left hemisphere
* whole_roi: mask of both hemispheres combined
* whole_roi_v: cortex.Vertex object of `whole_roi`
"""
if hemi == "both":
lh_mask = np.zeros(self.lh_surf_data[0].shape[0], dtype=bool)
lh_mask[lh_arr] = True
rh_mask = np.zeros(self.rh_surf_data[0].shape[0], dtype=bool)
rh_mask[rh_arr] = True
elif hemi == "lh":
lh_mask = np.zeros(getattr(self, f"lh_surf_data")[0].shape[0], dtype=bool)
lh_mask[lh_arr] = True
rh_mask = np.zeros(getattr(self, f"rh_surf_data")[0].shape[0], dtype=bool)
elif hemi == "rh":
lh_mask = np.zeros(getattr(self, f"lh_surf_data")[0].shape[0], dtype=bool)
rh_mask = np.zeros(getattr(self, f"rh_surf_data")[0].shape[0], dtype=bool)
rh_mask[rh_arr] = True
else:
raise ValueError(f"Invalid option '{hemi}' for hemi. Must be one of 'both', 'lh', or 'rh'")
whole_roi = np.concatenate((lh_mask, rh_mask))
whole_roi_v = cortex.Vertex(whole_roi, subject=subject, vmin=-0.5, vmax=1)
return {'lh_mask': lh_mask,
'rh_mask': rh_mask,
'whole_roi': whole_roi,
'whole_roi_v': whole_roi_v}
class pRFCalc(object):
"""pRFCalc
This short class deals with the population receptive field modeling output from spinoza_fitprfs and/or call_prfpy. Ideally, the output of these scripts is a numpy array containing the 6 pRF-parameters for each voxel. If you have one of those files, specify it in the `prffile` argument. If, for some reason, you do not have this file, but separate files for each pRF variable (e.g., a file for R2, a file for eccentricitry, and a file for polar angle), make sure they are all in 1 directory and specify that directory in the `prf_dir` parameter. The only function of this class is to collect path names and the data arrays containing information about the pRF parameters. It will actually be used in :class:`linescanning.optimal.CalcBestVertex`.
Parameters
----------
subject: str
subject ID as used in `SUBJECTS_DIR`
prf_dir: str, optional
Path to pRF-output directory possible containing maps for *variance explained* (desc-R2.npy), *eccentricity* (desc-eccentricity_map.npy), and *polar angle* (desc-polarangle_map.npy) as created with `call_fitprfs` and `spinoza_fitprfs`
prffile: str, optional
Path to a desc-prf_params.npy file containing a 6xn dataframe representing the 6 variables from the pRF-analysis times the amount of TRs (time points). You can either specify this file directly or specify the pRF-directory containing separate files for R2, eccentricity, and polar angle if you do not happen to have the prf parameter file
Returns
----------
:class:
Several attributes will be set upon calling the class. These attributes will be necessary to complete :class:`linescanning.optimal.CalcBestVertex`
Example
----------
>>> prf = pRFCalc(subject="sub-001", prffile="sub-001_desc-prf_params.npy")
"""
# Get stuff from SurfaceCalc
def __init__(self, subject=None, prffile=None, prf_dir=None, ses_nr=1, task="2R"):
self.subject = subject
self.session = ses_nr
self.task_id = task
self.fname = f"{self.subject}_ses-{self.session}_task-{self.task_id}"
if prf_dir == None:
self.prf_dir = os.environ['PRF']
else:
self.prf_dir = prf_dir
if not prffile or not os.path.exists(prffile):
if self.prf_dir != None:
try:
# print(" Load in pRF-estimates")
self.r2_file = utils.get_file_from_substring("R2", opj(self.prf_dir, self.subject))
self.ecc_file = utils.get_file_from_substring("eccentricity", opj(self.prf_dir, self.subject))
self.polar_file = utils.get_file_from_substring("polar", opj(self.prf_dir, self.subject))
except:
# print(" Set pRF-estimates to none")
self.r2 = None
self.ecc = None
self.polar = None
else:
raise NameError("Could not find pRF-parameter file and also not loose r2, ecc, polar angle files..")
else:
if os.path.exists(prffile):
# print(" Extracting pRF-parameters from file")
self.prffile = prffile
self.prf_params = | np.load(self.prffile) | numpy.load |
# Copyright 2019-2020 QuantumBlack Visual Analytics Limited
#
# The methods found in this file are derived from a repository under Apache 2.0:
# DAGs with NO TEARS.
# @inproceedings{zheng2018dags,
# author = {<NAME> and <NAME> and <NAME> <NAME>.},
# booktitle = {Advances in Neural Information Processing Systems},
# title = {{DAGs with NO TEARS: Continuous Optimization for Structure Learning}},
# year = {2018},
# codebase = {https://github.com/xunzheng/notears}
# }
#
# 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
#
# 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 WILL THE LICENSOR OR OTHER CONTRIBUTORS
# 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.
#
# The QuantumBlack Visual Analytics Limited ("QuantumBlack") name and logo
# (either separately or in combination, "QuantumBlack Trademarks") are
# trademarks of QuantumBlack. The License does not grant you any right or
# license to the QuantumBlack Trademarks. You may not use the QuantumBlack
# Trademarks or any confusingly similar mark as a trademark for your product,
# or use the QuantumBlack Trademarks in any other manner that might cause
# confusion in the marketplace, including but not limited to in advertising,
# on websites, or on software.
#
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Tools to learn a ``StructureModel`` which describes the conditional dependencies between variables in a dataset.
"""
import logging
import warnings
from copy import deepcopy
from typing import List, Tuple
import numpy as np
import pandas as pd
import scipy.linalg as slin
import scipy.optimize as sopt
from causalnex.structure.structuremodel import StructureModel
__all__ = ["from_numpy", "from_pandas", "from_numpy_lasso", "from_pandas_lasso"]
def from_numpy(
X: np.ndarray,
max_iter: int = 100,
h_tol: float = 1e-8,
w_threshold: float = 0.0,
tabu_edges: List[Tuple[int, int]] = None,
tabu_parent_nodes: List[int] = None,
tabu_child_nodes: List[int] = None,
) -> StructureModel:
"""
Learn the `StructureModel`, the graph structure describing conditional dependencies between variables
in data presented as a numpy array.
The optimisation is to minimise a score function :math:`F(W)` over the graph's
weighted adjacency matrix, :math:`W`, subject to the a constraint function :math:`h(W)`,
where :math:`h(W) == 0` characterises an acyclic graph.
:math:`h(W) > 0` is a continuous, differentiable function that encapsulated how acyclic the graph is
(less == more acyclic).
Full details of this approach to structure learning are provided in the publication:
Based on DAGs with NO TEARS.
@inproceedings{zheng2018dags,
author = {<NAME> <NAME> <NAME> <NAME>.},
booktitle = {Advances in Neural Information Processing Systems},
title = {{DAGs with NO TEARS: Continuous Optimization for Structure Learning}},
year = {2018},
codebase = {https://github.com/xunzheng/notears}
}
Args:
X: 2d input data, axis=0 is data rows, axis=1 is data columns. Data must be row oriented.
max_iter: max number of dual ascent steps during optimisation.
h_tol: exit if h(W) < h_tol (as opposed to strict definition of 0).
w_threshold: fixed threshold for absolute edge weights.
tabu_edges: list of edges(from, to) not to be included in the graph.
tabu_parent_nodes: list of nodes banned from being a parent of any other nodes.
tabu_child_nodes: list of nodes banned from being a child of any other nodes.
Returns:
StructureModel: a graph of conditional dependencies between data variables.
Raises:
ValueError: If X does not contain data.
"""
# n examples, d properties
_, d = X.shape
_assert_all_finite(X)
bnds = [
(0, 0)
if i == j
else (0, 0)
if tabu_edges is not None and (i, j) in tabu_edges
else (0, 0)
if tabu_parent_nodes is not None and i in tabu_parent_nodes
else (0, 0)
if tabu_child_nodes is not None and j in tabu_child_nodes
else (None, None)
for i in range(d)
for j in range(d)
]
return _learn_structure(X, bnds, max_iter, h_tol, w_threshold)
def from_numpy_lasso(
X: np.ndarray,
beta: float,
max_iter: int = 100,
h_tol: float = 1e-8,
w_threshold: float = 0.0,
tabu_edges: List[Tuple[int, int]] = None,
tabu_parent_nodes: List[int] = None,
tabu_child_nodes: List[int] = None,
) -> StructureModel:
"""
Learn the `StructureModel`, the graph structure with lasso regularisation
describing conditional dependencies between variables in data presented as a numpy array.
Based on DAGs with NO TEARS.
@inproceedings{zheng2018dags,
author = {<NAME> <NAME> <NAME> <NAME>.},
booktitle = {Advances in Neural Information Processing Systems},
title = {{DAGs with NO TEARS: Continuous Optimization for Structure Learning}},
year = {2018},
codebase = {https://github.com/xunzheng/notears}
}
Args:
X: 2d input data, axis=0 is data rows, axis=1 is data columns. Data must be row oriented.
beta: Constant that multiplies the lasso term.
max_iter: max number of dual ascent steps during optimisation.
h_tol: exit if h(W) < h_tol (as opposed to strict definition of 0).
w_threshold: fixed threshold for absolute edge weights.
tabu_edges: list of edges(from, to) not to be included in the graph.
tabu_parent_nodes: list of nodes banned from being a parent of any other nodes.
tabu_child_nodes: list of nodes banned from being a child of any other nodes.
Returns:
StructureModel: a graph of conditional dependencies between data variables.
Raises:
ValueError: If X does not contain data.
"""
# n examples, d properties
_, d = X.shape
_assert_all_finite(X)
bnds = [
(0, 0)
if i == j
else (0, 0)
if tabu_edges is not None and (i, j) in tabu_edges
else (0, 0)
if tabu_parent_nodes is not None and i in tabu_parent_nodes
else (0, 0)
if tabu_child_nodes is not None and j in tabu_child_nodes
else (0, None)
for i in range(d)
for j in range(d)
] * 2
return _learn_structure_lasso(X, beta, bnds, max_iter, h_tol, w_threshold)
def from_pandas(
X: pd.DataFrame,
max_iter: int = 100,
h_tol: float = 1e-8,
w_threshold: float = 0.0,
tabu_edges: List[Tuple[str, str]] = None,
tabu_parent_nodes: List[str] = None,
tabu_child_nodes: List[str] = None,
) -> StructureModel:
"""
Learn the `StructureModel`, the graph structure describing conditional dependencies between variables
in data presented as a pandas dataframe.
The optimisation is to minimise a score function :math:`F(W)` over the graph's
weighted adjacency matrix, :math:`W`, subject to the a constraint function :math:`h(W)`,
where :math:`h(W) == 0` characterises an acyclic graph.
:math:`h(W) > 0` is a continuous, differentiable function that encapsulated how acyclic the graph is
(less == more acyclic).
Full details of this approach to structure learning are provided in the publication:
Based on DAGs with NO TEARS.
@inproceedings{zheng2018dags,
author = {<NAME> <NAME> <NAME> <NAME>.},
booktitle = {Advances in Neural Information Processing Systems},
title = {{DAGs with NO TEARS: Continuous Optimization for Structure Learning}},
year = {2018},
codebase = {https://github.com/xunzheng/notears}
}
Args:
X: input data.
max_iter: max number of dual ascent steps during optimisation.
h_tol: exit if h(W) < h_tol (as opposed to strict definition of 0).
w_threshold: fixed threshold for absolute edge weights.
tabu_edges: list of edges(from, to) not to be included in the graph.
tabu_parent_nodes: list of nodes banned from being a parent of any other nodes.
tabu_child_nodes: list of nodes banned from being a child of any other nodes.
Returns:
StructureModel: graph of conditional dependencies between data variables.
Raises:
ValueError: If X does not contain data.
"""
data = deepcopy(X)
non_numeric_cols = data.select_dtypes(exclude="number").columns
if len(non_numeric_cols) > 0:
raise ValueError(
"All columns must have numeric data. "
"Consider mapping the following columns to int {non_numeric_cols}".format(
non_numeric_cols=non_numeric_cols
)
)
col_idx = {c: i for i, c in enumerate(data.columns)}
idx_col = {i: c for c, i in col_idx.items()}
if tabu_edges:
tabu_edges = [(col_idx[u], col_idx[v]) for u, v in tabu_edges]
if tabu_parent_nodes:
tabu_parent_nodes = [col_idx[n] for n in tabu_parent_nodes]
if tabu_child_nodes:
tabu_child_nodes = [col_idx[n] for n in tabu_child_nodes]
g = from_numpy(
data.values,
max_iter,
h_tol,
w_threshold,
tabu_edges,
tabu_parent_nodes,
tabu_child_nodes,
)
sm = StructureModel()
sm.add_nodes_from(data.columns)
sm.add_weighted_edges_from(
[(idx_col[u], idx_col[v], w) for u, v, w in g.edges.data("weight")],
origin="learned",
)
return sm
def from_pandas_lasso(
X: pd.DataFrame,
beta: float,
max_iter: int = 100,
h_tol: float = 1e-8,
w_threshold: float = 0.0,
tabu_edges: List[Tuple[str, str]] = None,
tabu_parent_nodes: List[str] = None,
tabu_child_nodes: List[str] = None,
) -> StructureModel:
"""
Learn the `StructureModel`, the graph structure with lasso regularisation
describing conditional dependencies between variables in data presented as a pandas dataframe.
Based on DAGs with NO TEARS.
@inproceedings{zheng2018dags,
author = {<NAME> <NAME> <NAME> <NAME>.},
booktitle = {Advances in Neural Information Processing Systems},
title = {{DAGs with NO TEARS: Continuous Optimization for Structure Learning}},
year = {2018},
codebase = {https://github.com/xunzheng/notears}
}
Args:
X: input data.
beta: Constant that multiplies the lasso term.
max_iter: max number of dual ascent steps during optimisation.
h_tol: exit if h(W) < h_tol (as opposed to strict definition of 0).
w_threshold: fixed threshold for absolute edge weights.
tabu_edges: list of edges(from, to) not to be included in the graph.
tabu_parent_nodes: list of nodes banned from being a parent of any other nodes.
tabu_child_nodes: list of nodes banned from being a child of any other nodes.
Returns:
StructureModel: graph of conditional dependencies between data variables.
Raises:
ValueError: If X does not contain data.
"""
data = deepcopy(X)
non_numeric_cols = data.select_dtypes(exclude="number").columns
if not non_numeric_cols.empty:
raise ValueError(
"All columns must have numeric data. "
"Consider mapping the following columns to int {non_numeric_cols}".format(
non_numeric_cols=non_numeric_cols
)
)
col_idx = {c: i for i, c in enumerate(data.columns)}
idx_col = {i: c for c, i in col_idx.items()}
if tabu_edges:
tabu_edges = [(col_idx[u], col_idx[v]) for u, v in tabu_edges]
if tabu_parent_nodes:
tabu_parent_nodes = [col_idx[n] for n in tabu_parent_nodes]
if tabu_child_nodes:
tabu_child_nodes = [col_idx[n] for n in tabu_child_nodes]
g = from_numpy_lasso(
data.values,
beta,
max_iter,
h_tol,
w_threshold,
tabu_edges,
tabu_parent_nodes,
tabu_child_nodes,
)
sm = StructureModel()
sm.add_nodes_from(data.columns)
sm.add_weighted_edges_from(
[(idx_col[u], idx_col[v], w) for u, v, w in g.edges.data("weight")],
origin="learned",
)
return sm
def _learn_structure(
X: np.ndarray,
bnds,
max_iter: int = 100,
h_tol: float = 1e-8,
w_threshold: float = 0.0,
) -> StructureModel:
"""
Based on initial implementation at https://github.com/xunzheng/notears
"""
def _h(w: np.ndarray) -> float:
"""
Constraint function of the NOTEARS algorithm.
Args:
w: current adjacency matrix.
Returns:
float: DAGness of the adjacency matrix (0 == DAG, >0 == cyclic).
"""
W = w.reshape([d, d])
return np.trace(slin.expm(W * W)) - d
def _func(w: np.ndarray) -> float:
"""
Objective function that the NOTEARS algorithm tries to minimise.
Args:
w: current adjacency matrix.
Returns:
float: objective.
"""
W = w.reshape([d, d])
loss = 0.5 / n * np.square(np.linalg.norm(X.dot(np.eye(d, d) - W), "fro"))
h = _h(W)
return loss + 0.5 * rho * h * h + alpha * h
def _grad(w: np.ndarray) -> np.ndarray:
"""
Gradient function used to compute next step in NOTEARS algorithm.
Args:
w: the current adjacency matrix.
Returns:
np.ndarray: gradient vector.
"""
W = w.reshape([d, d])
loss_grad = -1.0 / n * X.T.dot(X).dot(np.eye(d, d) - W)
E = slin.expm(W * W)
obj_grad = loss_grad + (rho * (np.trace(E) - d) + alpha) * E.T * W * 2
return obj_grad.flatten()
if X.size == 0:
raise ValueError("Input data X is empty, cannot learn any structure")
logging.info("Learning structure using 'NOTEARS' optimisation.")
# n examples, d properties
n, d = X.shape
# initialise matrix to zeros
w_est, w_new = np.zeros(d * d), np.zeros(d * d)
# initialise weights and constraints
rho, alpha, h, h_new = 1.0, 0.0, np.inf, np.inf
# start optimisation
for n_iter in range(max_iter):
while (rho < 1e20) and (h_new > 0.25 * h or h_new == np.inf):
sol = sopt.minimize(_func, w_est, method="L-BFGS-B", jac=_grad, bounds=bnds)
w_new = sol.x
h_new = _h(w_new)
if h_new > 0.25 * h:
rho *= 10
w_est, h = w_new, h_new
alpha += rho * h
if h <= h_tol:
break
if h > h_tol and n_iter == max_iter - 1:
warnings.warn("Failed to converge. Consider increasing max_iter.")
w_est[np.abs(w_est) <= w_threshold] = 0
return StructureModel(w_est.reshape([d, d]))
def _learn_structure_lasso(
X: np.ndarray,
beta: float,
bnds,
max_iter: int = 100,
h_tol: float = 1e-8,
w_threshold: float = 0.0,
) -> StructureModel:
"""
Based on initial implementation at https://github.com/xunzheng/notears
"""
def _h(w_vec: np.ndarray) -> float:
"""
Constraint function of the NOTEARS algorithm with lasso regularisation.
Args:
w_vec: weight vector (wpos and wneg).
Returns:
float: DAGness of the adjacency matrix (0 == DAG, >0 == cyclic).
"""
W = w_vec.reshape([d, d])
return np.trace(slin.expm(W * W)) - d
def _func(w_vec: np.ndarray) -> float:
"""
Objective function that the NOTEARS algorithm with lasso regularisation tries to minimise.
Args:
w_vec: weight vector (wpos and wneg).
Returns:
float: objective.
"""
w_pos = w_vec[: d ** 2]
w_neg = w_vec[d ** 2 :]
wmat_pos = w_pos.reshape([d, d])
wmat_neg = w_neg.reshape([d, d])
wmat = wmat_pos - wmat_neg
loss = 0.5 / n * np.square(np.linalg.norm(X.dot( | np.eye(d, d) | numpy.eye |
"""
DISCRIMINATOR FOR BINARY CROSS ENTROPY (LABELED IMAGES)
"""
# Libraries
# Standard library
import json
import random
import time
import numpy as np
import matplotlib.pyplot as plt
from typing import Dict, List, Tuple
def load(filename):
"""Load a neural network from the file ``filename``. Returns an
instance of Network.
"""
f = open(filename, "r")
data = json.load(f)
f.close()
# cost = getattr(sys.modules[__name__], data["cost"])
net = DiscriminatorBCE(data["sizes"])
net.weights = [np.array(w) for w in data["weights"]]
net.biases = [np.array(b) for b in data["biases"]]
return net
class DiscriminatorBCE:
def __init__(self, sizes: List[int]) -> None:
"""The list ``sizes`` contains the number of neuronfs in the
respective layers of the network. For example, iff the list
was [2, 3, 1] then it would be a three-layer netwfork, with the
first layer containing 2 neurons, the second layffer 3 neurons,
and the third layer 1 neuron."""
self.num_layers = len(sizes)
self.sizes = sizes
self._ret: Dict[str, any] = {"loss": [],
"label real": [],
"label fake": [],
"label fake time": [],
"label real time": []}
self.biases = [np.random.randn(y, ) for y in sizes[1:]]
self.weights = [np.random.randn(y, x)
for x, y in zip(sizes[:-1], sizes[1:])]
def feedforward(self, a):
"""Return the output of the network if ``a`` is input."""
for b, w in zip(self.biases, self.weights):
a = sigmoid(np.dot(w, a) + b)
return a
def predict(self, x):
# feedforward
activation = x
activations = [x] # list to store all the activations, layer by layer
zs = [] # list to store all the z vectors, layer by layer
for b, w in zip(self.biases, self.weights):
z = np.dot(w, activation) + b
zs.append(z)
activation = sigmoid(z)
activations.append(activation)
return activation
def evaluate(self, test_data):
"""Return the number of test inputs for which the neural
network outputs the correct result. Note that the neural
network's output is assumed to be the index of whichever
neuron in the final layer has the highest activation."""
test_results = [(np.argmax(self.feedforward(x)), y)
for (x, y) in test_data]
return sum(int(x == y) for (x, y) in test_results)
def save(self, filename):
"""Save the neural network to the file ``filename``."""
data = {"sizes": self.sizes,
"weights": [w.tolist() for w in self.weights],
"biases": [b.tolist() for b in self.biases] # ,
# "cost": str(self..__name__)
}
f = open(filename, "w")
json.dump(data, f)
f.close()
def MSE_derivative(self, prediction, y):
"""Return the vector of partial derivatives \partial{C_x,a}
for the output activations."""
return 2 * (y - prediction)
def MSE(self, prediction, y):
return (y - prediction)**2
def BCE_derivative(self, prediction, target):
return -target / prediction + (1 - target) / (1 - prediction)
def BCE(self, predictions: np.ndarray, targets: np.ndarray) -> float:
return targets * np.log10(predictions) + (1 - targets) * np.log10(1 - predictions).mean()
def minimax_derivative(self, real_prediction, fake_prediction):
real_prediction = np.array(real_prediction)
fake_prediction = np.array(fake_prediction)
return 1 / (real_prediction * np.log10(10)) + 1 / ((fake_prediction - 1) * np.log10(10))
@property
def ret(self):
return self._ret
def backprop(self, x, y) -> Tuple:
"""Return a tuple ``(nabla_b, nabla_w)`` representing the
gradient for the cost function C_x. ``nabla_b`` and
``nabla_w`` are layer-by-layer lists of numpy arrays, similar
to ``self.biases`` and ``self.weights``."""
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
nabla_w_prev = nabla_w
# feedforward
activation = x
activations = [x] # list to store all the activations, layer by layer
zs = [] # list to store all the z vectors, layer by layer
for b, w in zip(self.biases, self.weights):
z = np.dot(w, activation) + b
zs.append(z)
activation = sigmoid(z)
activations.append(activation)
self.data_for_loss = (activation, y)
# backward pass
delta = self.BCE_derivative(activations[-1], y) * sigmoid_prime(zs[-1])
nabla_b[-1] = delta
nabla_w[-1] = np.dot(delta, activations[-2].reshape(1, activations[-2].shape[0]))
for l in range(2, self.num_layers):
z = zs[-l]
delta = np.dot(self.weights[-l + 1].transpose(), delta) * sigmoid_prime(z)
nabla_b[-l] = delta
nabla_w[-l] = np.dot(delta.reshape(delta.shape[0], 1),
activations[-l - 1].reshape(1, activations[-l - 1].shape[0]))
return (nabla_b, nabla_w)
def train_mini_batch(self, mini_batch, learning_rate):
"""Update the network's weights and biases by applying
gradient descent using backpropagation to a single mini batch.
The ``mini_batch`` is a list of tuples ``(x, y)``"""
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [ | np.zeros(w.shape) | numpy.zeros |
# Copyright 2016 Princeton University
#
# 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.
"""Event segmentation using a Hidden Markov Model
Given an ROI timeseries, this class uses an annealed fitting procedure to
segment the timeseries into events with stable activity patterns. After
learning the signature activity pattern of each event, the model can then be
applied to other datasets to identify a corresponding sequence of events.
Full details are available in the bioRxiv preprint:
<NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, <NAME>
Discovering event structure in continuous narrative perception and memory
Neuron, Volume 95, Issue 3, 709 - 721.e5
http://www.cell.com/neuron/abstract/S0896-6273(17)30593-7
"""
# Authors: <NAME> and <NAME> (Princeton University)
import numpy as np
from scipy import stats
import logging
import copy
from sklearn.base import BaseEstimator
from sklearn.utils.validation import check_is_fitted, check_array
from sklearn.exceptions import NotFittedError
from . import _utils as utils # type: ignore
logger = logging.getLogger(__name__)
__all__ = [
"EventSegment",
]
class EventSegment(BaseEstimator):
"""Class for event segmentation of continuous fMRI data
Parameters
----------
n_events: int
Number of segments to learn
step_var: Callable[[int], float] : default 4 * (0.98 ** (step - 1))
The Gaussian variance to use during fitting, as a function of the
number of steps. Should decrease slowly over time.
n_iter: int : default 500
Maximum number of steps to run during fitting
Attributes
----------
p_start, p_end: length n_events+1 ndarray
initial and final prior distributions over events
P: n_events+1 by n_events+1 ndarray
HMM transition matrix
ll_ : ndarray with length = number of training datasets
Log-likelihood for training datasets over the course of training
segments_: list of (time by event) ndarrays
Learned (soft) segmentation for training datasets
event_var_ : float
Gaussian variance at the end of learning
event_pat_ : voxel by event ndarray
Learned mean patterns for each event
"""
def _default_var_schedule(step):
return 4 * (0.98 ** (step - 1))
def __init__(self, n_events=2,
step_var=_default_var_schedule,
n_iter=500):
self.n_events = n_events
self.step_var = step_var
self.n_iter = n_iter
def fit(self, X, y=None):
"""Learn a segmentation on training data
Fits event patterns and a segmentation to training data. After
running this function, the learned event patterns can be used to
segment other datasets using find_events
Parameters
----------
X: time by voxel ndarray, or a list of such ndarrays
fMRI data to be segmented. If a list is given, then all datasets
are segmented simultaneously with the same event patterns
y: not used (added to comply with BaseEstimator definition)
Returns
-------
self: the EventSegment object
"""
X = copy.deepcopy(X)
if type(X) is not list:
X = check_array(X)
X = [X]
n_train = len(X)
for i in range(n_train):
X[i] = X[i].T
self.classes_ = np.arange(self.n_events)
n_dim = X[0].shape[0]
for i in range(n_train):
assert (X[i].shape[0] == n_dim)
# Double-check that data is z-scored in time
for i in range(n_train):
X[i] = stats.zscore(X[i], axis=1, ddof=1)
# Initialize variables for fitting
log_gamma = []
for i in range(n_train):
log_gamma.append(np.zeros((X[i].shape[1],
self.n_events)))
step = 1
best_ll = float("-inf")
self.ll_ = np.empty((0, n_train))
while step <= self.n_iter:
iteration_var = self.step_var(step)
# Based on the current segmentation, compute the mean pattern
# for each event
seg_prob = [np.exp(lg) / np.sum(np.exp(lg), axis=0)
for lg in log_gamma]
mean_pat = np.empty((n_train, n_dim, self.n_events))
for i in range(n_train):
mean_pat[i, :, :] = X[i].dot(seg_prob[i])
mean_pat = np.mean(mean_pat, axis=0)
# Based on the current mean patterns, compute the event
# segmentation
self.ll_ = np.append(self.ll_, np.empty((1, n_train)), axis=0)
for i in range(n_train):
logprob = self._logprob_obs(X[i],
mean_pat, iteration_var)
log_gamma[i], self.ll_[-1, i] = self._forward_backward(logprob)
# If log-likelihood has started decreasing, undo last step and stop
if np.mean(self.ll_[-1, :]) < best_ll:
self.ll_ = self.ll_[:-1, :]
break
self.segments_ = [np.exp(lg) for lg in log_gamma]
self.event_var_ = iteration_var
self.event_pat_ = mean_pat
best_ll = np.mean(self.ll_[-1, :])
logger.debug("Fitting step %d, LL=%f", step, best_ll)
step += 1
return self
def _logprob_obs(self, data, mean_pat, var):
"""Log probability of observing each timepoint under each event model
Computes the log probability of each observed timepoint being
generated by the Gaussian distribution for each event pattern
Parameters
----------
data: voxel by time ndarray
fMRI data on which to compute log probabilities
mean_pat: voxel by event ndarray
Centers of the Gaussians for each event
var: float or 1D array of length equal to the number of events
Variance of the event Gaussians. If scalar, all events are
assumed to have the same variance
Returns
-------
logprob : time by event ndarray
Log probability of each timepoint under each event Gaussian
"""
n_vox = data.shape[0]
t = data.shape[1]
# z-score both data and mean patterns in space, so that Gaussians
# are measuring Pearson correlations and are insensitive to overall
# activity changes
data_z = stats.zscore(data, axis=0, ddof=1)
mean_pat_z = stats.zscore(mean_pat, axis=0, ddof=1)
logprob = np.empty((t, self.n_events))
if type(var) is not np.ndarray:
var = var * np.ones(self.n_events)
for k in range(self.n_events):
logprob[:, k] = -0.5 * n_vox * np.log(
2 * np.pi * var[k]) - 0.5 * np.sum(
(data_z.T - mean_pat_z[:, k]).T ** 2, axis=0) / var[k]
logprob /= n_vox
return logprob
def _forward_backward(self, logprob):
"""Runs forward-backward algorithm on observation log probs
Given the log probability of each timepoint being generated by
each event, run the HMM forward-backward algorithm to find the
probability that each timepoint belongs to each event (based on the
transition priors in p_start, p_end, and P)
See https://en.wikipedia.org/wiki/Forward-backward_algorithm for
mathematical details
Parameters
----------
logprob : time by event ndarray
Log probability of each timepoint under each event Gaussian
Returns
-------
log_gamma : time by event ndarray
Log probability of each timepoint belonging to each event
ll : float
Log-likelihood of fit
"""
logprob = copy.copy(logprob)
t = logprob.shape[0]
logprob = np.hstack((logprob, float("-inf") * np.ones((t, 1))))
# Initialize variables
log_scale = np.zeros(t)
log_alpha = np.zeros((t, self.n_events + 1))
log_beta = np.zeros((t, self.n_events + 1))
# Set up transition matrix, with final sink state
# For transition matrix of this form, the transition probability has
# no impact on the final solution, since all valid paths must take
# the same number of transitions
p_start = np.zeros((1, self.n_events + 1))
p_start[0, 0] = 1
p_trans = (self.n_events-1)/t
P = np.vstack((np.hstack((
(1 - p_trans) * np.diag(np.ones(self.n_events))
+ p_trans * np.diag(np.ones(self.n_events - 1), 1),
np.append(np.zeros((self.n_events - 1, 1)), [[p_trans]], axis=0))),
np.append(np.zeros((1, self.n_events)), [[1]],
axis=1)))
p_end = np.zeros((1, self.n_events + 1))
p_end[0, -2] = 1
# Forward pass
for i in range(t):
if i == 0:
log_alpha[0, :] = self._log(p_start) + logprob[0, :]
else:
log_alpha[i, :] = self._log(np.exp(log_alpha[i - 1, :])
.dot(P)) + logprob[i, :]
log_scale[i] = np.logaddexp.reduce(log_alpha[i, :])
log_alpha[i] -= log_scale[i]
# Backward pass
log_beta[-1, :] = self._log(p_end) - log_scale[-1]
for i in reversed(range(t - 1)):
obs_weighted = log_beta[i + 1, :] + logprob[i + 1, :]
offset = np.max(obs_weighted)
log_beta[i, :] = offset + self._log(
np.exp(obs_weighted - offset).dot(P.T)) - log_scale[i]
# Combine and normalize
log_gamma = log_alpha + log_beta
log_gamma -= np.logaddexp.reduce(log_gamma, axis=1, keepdims=True)
ll = np.sum(log_scale[:(t - 1)]) + np.logaddexp.reduce(
log_alpha[-1, :] + log_scale[-1] + self._log(p_end), axis=1)
log_gamma = log_gamma[:, :-1]
return log_gamma, ll
def _log(self, x):
"""Modified version of np.log that manually sets values <=0 to -inf
Parameters
----------
x: ndarray of floats
Input to the log function
Returns
-------
log_ma: ndarray of floats
log of x, with x<=0 values replaced with -inf
"""
xshape = x.shape
_x = x.flatten()
y = utils.masked_log(_x)
return y.reshape(xshape)
def set_event_patterns(self, event_pat):
"""Set HMM event patterns manually
Rather than fitting the event patterns automatically using fit(), this
function allows them to be set explicitly. They can then be used to
find corresponding events in a new dataset, using find_events().
Parameters
----------
event_pat: voxel by event ndarray
"""
if event_pat.shape[1] != self.n_events:
raise ValueError(("Number of columns of event_pat must match "
"number of events"))
self.event_pat_ = event_pat.copy()
def find_events(self, testing_data, var=None, scramble=False):
"""Applies learned event segmentation to new testing dataset
After fitting an event segmentation using fit() or setting event
patterns directly using set_event_patterns(), this function finds the
same sequence of event patterns in a new testing dataset.
Parameters
----------
testing_data: timepoint by voxel ndarray
fMRI data to segment based on previously-learned event patterns
var: float or 1D ndarray of length equal to the number of events
default: uses variance that maximized training log-likelihood
Variance of the event Gaussians. If scalar, all events are
assumed to have the same variance. If fit() has not previously
been run, this must be specifed (cannot be None).
scramble: bool : default False
If true, the order of the learned events are shuffled before
fitting, to give a null distribution
Returns
-------
segments : time by event ndarray
The resulting soft segmentation. segments[t,e] = probability
that timepoint t is in event e
test_ll : float
Log-likelihood of model fit
"""
if var is None:
if not hasattr(self, 'event_var_'):
raise NotFittedError(("The event patterns must first be set "
"by fit() or set_event_patterns()"))
else:
var = self.event_var_
if scramble:
mean_pat = self.event_pat_[:, np.random.permutation(self.n_events)]
else:
mean_pat = self.event_pat_
logprob = self._logprob_obs(testing_data.T, mean_pat, var)
lg, test_ll = self._forward_backward(logprob)
segments = np.exp(lg)
return segments, test_ll
def predict(self, X):
"""Applies learned event segmentation to new testing dataset
Alternative function for segmenting a new dataset after using
fit() to learn a sequence of events, to comply with the sklearn
Classifier interface
Parameters
----------
X: timepoint by voxel ndarray
fMRI data to segment based on previously-learned event patterns
Returns
-------
Event label for each timepoint
"""
check_is_fitted(self, ["event_pat_", "event_var_"])
X = check_array(X)
segments, test_ll = self.find_events(X)
return np.argmax(segments, axis=1)
def calc_weighted_event_var(self, D, weights, event_pat):
"""Computes normalized weighted variance around event pattern
Utility function for computing variance in a training set of weighted
event examples. For each event, the sum of squared differences for all
timepoints from the event pattern is computed, and then the weights
specify how much each of these differences contributes to the
variance (normalized by the number of voxels).
Parameters
----------
D : timepoint by voxel ndarray
fMRI data for which to compute event variances
weights : timepoint by event ndarray
specifies relative weights of timepoints for each event
event_pat : voxel by event ndarray
mean event patterns to compute variance around
Returns
-------
ev_var : ndarray of variances for each event
"""
Dz = stats.zscore(D, axis=1, ddof=1)
ev_var = np.empty(event_pat.shape[1])
for e in range(event_pat.shape[1]):
# Only compute variances for weights > 0.1% of max weight
nz = weights[:, e] > np.max(weights[:, e])/1000
sumsq = np.dot(weights[nz, e],
np.sum(np.square(Dz[nz, :] -
event_pat[:, e]), axis=1))
ev_var[e] = sumsq/( | np.sum(weights[nz, e]) | numpy.sum |
from __future__ import absolute_import
import unittest
from sklearn.datasets import load_iris as load_data
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.cluster import KMeans
import numpy as np
import matplotlib.pyplot as plt
from scikitplot.metrics import plot_confusion_matrix
from scikitplot.metrics import plot_roc_curve
from scikitplot.metrics import plot_roc
from scikitplot.metrics import plot_ks_statistic
from scikitplot.metrics import plot_precision_recall_curve
from scikitplot.metrics import plot_precision_recall
from scikitplot.metrics import plot_silhouette
from scikitplot.metrics import plot_calibration_curve
from scikitplot.metrics import plot_cumulative_gain
from scikitplot.metrics import plot_lift_curve
def convert_labels_into_string(y_true):
return ["A" if x == 0 else x for x in y_true]
class TestPlotConfusionMatrix(unittest.TestCase):
def setUp(self):
np.random.seed(0)
self.X, self.y = load_data(return_X_y=True)
p = np.random.permutation(len(self.X))
self.X, self.y = self.X[p], self.y[p]
def tearDown(self):
plt.close("all")
def test_string_classes(self):
np.random.seed(0)
clf = LogisticRegression()
clf.fit(self.X, convert_labels_into_string(self.y))
preds = clf.predict(self.X)
plot_confusion_matrix(convert_labels_into_string(self.y), preds)
def test_normalize(self):
np.random.seed(0)
clf = LogisticRegression()
clf.fit(self.X, self.y)
preds = clf.predict(self.X)
plot_confusion_matrix(self.y, preds, normalize=True)
plot_confusion_matrix(self.y, preds, normalize=False)
def test_labels(self):
np.random.seed(0)
clf = LogisticRegression()
clf.fit(self.X, self.y)
preds = clf.predict(self.X)
plot_confusion_matrix(self.y, preds, labels=[0, 1, 2])
def test_hide_counts(self):
np.random.seed(0)
clf = LogisticRegression()
clf.fit(self.X, self.y)
preds = clf.predict(self.X)
plot_confusion_matrix(self.y, preds, hide_counts=True)
def test_true_pred_labels(self):
np.random.seed(0)
clf = LogisticRegression()
clf.fit(self.X, self.y)
preds = clf.predict(self.X)
true_labels = [0, 1]
pred_labels = [0, 2]
plot_confusion_matrix(self.y, preds,
true_labels=true_labels,
pred_labels=pred_labels)
def test_cmap(self):
np.random.seed(0)
clf = LogisticRegression()
clf.fit(self.X, self.y)
preds = clf.predict(self.X)
plot_confusion_matrix(self.y, preds, cmap='nipy_spectral')
plot_confusion_matrix(self.y, preds, cmap=plt.cm.nipy_spectral)
def test_ax(self):
np.random.seed(0)
clf = LogisticRegression()
clf.fit(self.X, self.y)
preds = clf.predict(self.X)
fig, ax = plt.subplots(1, 1)
out_ax = plot_confusion_matrix(self.y, preds)
assert ax is not out_ax
out_ax = plot_confusion_matrix(self.y, preds, ax=ax)
assert ax is out_ax
def test_array_like(self):
plot_confusion_matrix([0, 'a'], ['a', 0])
plot_confusion_matrix([0, 1], [1, 0])
plot_confusion_matrix(['b', 'a'], ['a', 'b'])
class TestPlotROCCurve(unittest.TestCase):
def setUp(self):
| np.random.seed(0) | numpy.random.seed |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 29 14:18:59 2021
@author: <NAME> - Hatlab
"""
from plottr.apps.autoplot import main
from plottr.data.datadict_storage import all_datadicts_from_hdf5
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
datapath = r'C:/Users/Hatlab-RRK/Downloads/2021-07-12_0001_Amp_0__Phase_0.0_rad_.ddh5'
name = '2021-07-12_0001_Amp_0__Phase_0.0_rad_.ddh5'
def histogram(fig, ax, start_pt, stop_pt, sI, sQ, Ioffset = 0, Qoffset = 0, scale = 1, num_bins = 100, boxcar = True, I_weights = None, Q_weights = None):
I_bground = Ioffset
Q_bground = Qoffset
if boxcar:
weights = np.zeros(np.shape(sI)[1])
weights[start_pt:stop_pt] = 1
I_weights = weights.copy()
Q_weights = weights.copy()
# print(I_bground, Q_bground)
I_pts = []
Q_pts = []
for I_row, Q_row in zip(sI, sQ):
I_pts.append(np.average(I_row-I_bground, weights = I_weights))
Q_pts.append(np.average(Q_row-Q_bground, weights = Q_weights))
# plt.imshow(np.histogram2d(np.array(I_pts), np.array(Q_pts))[0])
divider = make_axes_locatable(ax)
ax.set_aspect(1)
bins = np.linspace(-1,1, num_bins)*scale
(h, xedges, yedges, im) = ax.hist2d(I_pts, Q_pts, bins = [bins, bins])
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(im, cax = cax, orientation = 'vertical')
ax.hexbin(I_pts, Q_pts, extent = np.array([-1,1,-1,1])*scale)
ax.set_xticks(np.array([-100,-75,-50,-25,0,25,50,75,100])*scale/100)
ax.set_yticks(np.array([-100,-75,-50,-25,0,25,50,75,100])*scale/100)
ax.grid()
def generate_weight_function(IorQ1_avg, IorQ2_avg, start, stop):
wf = np.zeros(np.size(IorQ1_avg)) #or Q_c_avg, they should be the same
wf[start:stop] = np.sqrt((IorQ1_avg-IorQ2_avg)**2)[start:stop]
return wf
#autoplot, easiest way to see data if you dont need access to values
# main(datapath, 'data')
#extracting individual arrays
dd = all_datadicts_from_hdf5(datapath)['data']
time_unit = dd['time']['unit']
time_vals = dd['time']['values']
rec_unit = dd['record_num']['unit']
rec_num = dd['record_num']['values']
I_plus = dd['I_plus']['values']
I_minus = dd['I_minus']['values']
Q_plus = dd['Q_plus']['values']
Q_minus = dd['Q_minus']['values']
#plotting averages
I_plus_avg = np.average(np.reshape(I_plus, (3840, 205)), axis = 0)
I_minus_avg = np.average( | np.reshape(I_minus, (3840, 205)) | numpy.reshape |
#
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
import sys
import ctypes
import numpy as np
from onnx.backend.test.case.node import _extract_value_info
import onnx
from onnx import TensorProto, helper, mapping, numpy_helper
import pycuda.driver as cuda
import tensorrt as trt
import tensorflow as tf
sys.path.append("..")
from python import *
os.chdir("../python/")
I_GPU = 0
os.environ["CUDA_VISIBLE_DEVICES"] = str(I_GPU)
tf.set_random_seed(1234)
np.random.seed(0)
ITERATIONS = 10
CONFIG = tf.ConfigProto()
CONFIG.gpu_options.allow_growth = True
INPUT_MODEL_FILE = "model/test_op_plugin.onnx"
OUTPUT_MODEL_FILE = "model/test_op_trt.onnx"
TRT_LOGGER = trt.Logger(trt.Logger.WARNING)
# TRT_LOGGER = trt.Logger(trt.Logger.VERBOSE)
BATCH_SIZE = 1
# Simple helper data class that's a little nicer to use than a 2-tuple.
class HostDeviceMem(object):
def __init__(self, host_mem, device_mem):
self.host = host_mem
self.device = device_mem
def __str__(self):
return "Host:\n" + str(self.host) + "\nDevice:\n" + str(self.device)
def __repr__(self):
return self.__str__()
# Allocates all buffers required for an engine, i.e. host/device inputs/outputs.
def allocate_buffers(engine):
inputs = []
outputs = []
bindings = []
stream = cuda.Stream()
for binding in engine:
# size = trt.volume(engine.get_binding_shape(binding)) * engine.max_batch_size
size = trt.volume(engine.get_binding_shape(binding))
dtype = trt.nptype(engine.get_binding_dtype(binding))
# Allocate host and device buffers
host_mem = cuda.pagelocked_empty(size, dtype)
device_mem = cuda.mem_alloc(host_mem.nbytes)
# Append the device buffer to device bindings.
bindings.append(int(device_mem))
# Append to the appropriate list.
if engine.binding_is_input(binding):
inputs.append(HostDeviceMem(host_mem, device_mem))
else:
outputs.append(HostDeviceMem(host_mem, device_mem))
return inputs, outputs, bindings, stream
# This function is generalized for multiple inputs/outputs.
# inputs and outputs are expected to be lists of HostDeviceMem objects.
def do_inference(context, bindings, inputs, outputs, stream, batch_size=1):
# Transfer input data to the GPU.
[cuda.memcpy_htod_async(inp.device, inp.host, stream) for inp in inputs]
# Run inference.
context.execute_async(
batch_size=batch_size, bindings=bindings, stream_handle=stream.handle
)
# Transfer predictions back from the GPU.
[cuda.memcpy_dtoh_async(out.host, out.device, stream) for out in outputs]
# Synchronize the stream
stream.synchronize()
# Return only the host outputs.
return [out.host for out in outputs]
def convert_to_list(x):
if not isinstance(x, list):
x = [x]
return x
def run_tf_graph(sess, input_data, input_node, output_node):
"""Generic function to execute tensorflow"""
input_data = convert_to_list(input_data)
input_node = convert_to_list(input_node)
output_node = convert_to_list(output_node)
tensor = [sess.graph.get_tensor_by_name(output_name) for output_name in output_node]
input_dict = {e: input_data[i] for i, e in enumerate(input_node)}
# if len(input_node) == 1 and input_node[0] == "":
# output_data = sess.run(tensor)
# else:
output_data = sess.run(tensor, input_dict)
return output_data
def verify_tf_with_trt_result(in_data, in_name, out_name, op_name):
def name_without_num(name):
return name.split(":")[0] if ":" in name else name
out_name = convert_to_list(out_name)
out_node = [name_without_num(name) for name in out_name]
in_data = convert_to_list(in_data)
in_name = convert_to_list(in_name)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
tf_result = run_tf_graph(sess, in_data, in_name, out_name)
frozen_graph = tf.graph_util.convert_variables_to_constants(
sess, sess.graph_def, out_node
)
with open("model/test_op_{}.pb".format(op_name), "wb") as ofile:
ofile.write(frozen_graph.SerializeToString())
os.system(
"python3 -m tf2onnx.convert --input model/test_op_{}.pb --inputs {} --outputs {} --output {} --opset 11".format(
op_name, str(",").join(in_name), str(",").join(out_name), INPUT_MODEL_FILE
)
)
ops_name = [op_name]
trt_plugin_name = onnx2plugin(
INPUT_MODEL_FILE, OUTPUT_MODEL_FILE, node_names=ops_name
)
for plugin_name in trt_plugin_name:
ctypes.cdll.LoadLibrary("./trt_plugin/lib/{}.so".format(plugin_name))
cuda.Device(0).make_context()
with trt.Builder(TRT_LOGGER) as builder, builder.create_network(
1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
) as network, trt.OnnxParser(network, TRT_LOGGER) as parser:
builder.max_batch_size = batch_size
builder_config = builder.create_builder_config()
builder_config.max_workspace_size = 1 << 30
with open(OUTPUT_MODEL_FILE, "rb") as model:
# parse onnx model
parser.parse(model.read())
for i in range(parser.num_errors):
print(parser.get_error(i))
engine = builder.build_engine(network, builder_config)
if engine is None:
print("[ERROR] engine is None")
exit(-1)
inputs, outputs, bindings, stream = allocate_buffers(engine)
with engine.create_execution_context() as context:
for i in range(len(inputs)):
input_data = in_data[i].ravel()
np.copyto(inputs[i].host, input_data)
trt_result = do_inference(
context,
bindings=bindings,
inputs=inputs,
outputs=outputs,
stream=stream,
batch_size=batch_size,
)
cuda.Context.pop()
ret = True
if len(trt_result) == 1:
ret = compare_tf_trt_result(tf_result, trt_result)
else:
for i in range(len(trt_result)):
ret &= compare_tf_trt_result(tf_result[i], trt_result[i])
assert ret, "result check False"
return ret
def compare_tf_trt_result(tf_result, trt_result):
print(tf_result)
print("================")
print(trt_result)
tf_reshape = np.array(tf_result).reshape(-1)
trt_reshape = np.array(trt_result).reshape(-1)
if (
isinstance(tf_result, list)
and isinstance(trt_result, list)
and len(tf_result) > 0
and len(trt_result) > 0
and np.isnan(tf_result[0]).any()
and np.isnan(trt_result[0]).any()
):
return True
elif (
isinstance(tf_result, list)
and isinstance(trt_result, list)
and len(tf_result) > 0
and len(trt_result) > 0
and np.isinf(tf_result[0]).any()
and np.isinf(trt_result[0]).any()
):
return True
print(
"trt cross_check output ",
str(np.allclose(tf_reshape.flatten(), trt_reshape.flatten(), atol=1e-5)),
flush=True,
)
return bool(np.allclose(tf_reshape.flatten(), trt_reshape.flatten(), atol=1e-5))
def get_onnxruntime_output(model, inputs):
import onnxruntime.backend
rep = onnxruntime.backend.prepare(model, "CPU")
if isinstance(inputs, list) and len(inputs) == 1:
inp = inputs[0]
else:
inp = inputs
output = rep.run(inp)
# Unpack output if there's only a single value.
if len(output) == 1:
output = output[0]
return output
def verify_with_ort_with_trt(
model,
inputs,
op_name,
opset=None,
dtype="float32",
opt_level=1,
np_result=None,
use_vm=False,
):
if opset is not None:
model.opset_import[0].version = opset
onnx.save(model, INPUT_MODEL_FILE)
if np_result is None:
ort_result = get_onnxruntime_output(model, inputs)
else:
ort_result = np_result
in_data = convert_to_list(inputs)
ops_name = [op_name]
trt_plugin_name = onnx2plugin(
INPUT_MODEL_FILE, OUTPUT_MODEL_FILE, node_names=ops_name
)
for plugin_name in trt_plugin_name:
ctypes.cdll.LoadLibrary("./trt_plugin/lib/{}.so".format(plugin_name))
cuda.Device(0).make_context()
with trt.Builder(TRT_LOGGER) as builder, builder.create_network(
1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
) as network, trt.OnnxParser(network, TRT_LOGGER) as parser:
builder.max_batch_size = BATCH_SIZE
builder_config = builder.create_builder_config()
builder_config.max_workspace_size = 1 << 30
with open(OUTPUT_MODEL_FILE, "rb") as model:
# parse onnx model
parser.parse(model.read())
for i in range(parser.num_errors):
print(parser.get_error(i))
engine = builder.build_engine(network, builder_config)
if engine is None:
print("[ERROR] engine is None")
exit(-1)
inputs, outputs, bindings, stream = allocate_buffers(engine)
with engine.create_execution_context() as context:
for i in range(len(inputs)):
input_data = in_data[i].ravel()
np.copyto(inputs[i].host, input_data)
trt_result = do_inference(
context,
bindings=bindings,
inputs=inputs,
outputs=outputs,
stream=stream,
batch_size=BATCH_SIZE,
)
cuda.Context.pop()
ret = True
if len(trt_result) == 1:
ret = compare_tf_trt_result(ort_result, trt_result)
else:
for i in range(len(trt_result)):
ret &= compare_tf_trt_result(ort_result[i], trt_result[i])
assert ret, "result check False"
return ret
def make_constant_node(name, data_type, dims, vals):
return helper.make_node(
"Constant",
inputs=[],
outputs=[name],
value=helper.make_tensor(name=name, data_type=data_type, dims=dims, vals=vals),
)
def make_onnx_model(node, inputs, outputs, name, **kwargs):
present_inputs = [x for x in node.input if (x != "")]
present_outputs = [x for x in node.output if (x != "")]
input_type_protos = [None] * len(inputs)
if "input_type_protos" in kwargs:
input_type_protos = kwargs[str("input_type_protos")]
del kwargs[str("input_type_protos")]
output_type_protos = [None] * len(outputs)
if "output_type_protos" in kwargs:
output_type_protos = kwargs[str("output_type_protos")]
del kwargs[str("output_type_protos")]
inputs_vi = [
_extract_value_info(arr, arr_name, input_type)
for arr, arr_name, input_type in zip(inputs, present_inputs, input_type_protos)
]
outputs_vi = [
_extract_value_info(arr, arr_name, output_type)
for arr, arr_name, output_type in zip(
outputs, present_outputs, output_type_protos
)
]
graph = helper.make_graph(
nodes=[node], name=name, inputs=inputs_vi, outputs=outputs_vi
)
kwargs[str("producer_name")] = "TRTPluginAutoGen-test"
model = onnx.helper.make_model(graph, **kwargs)
return model
def op_expect(node, inputs, outputs, op_type, op_name, np_result=None):
model = make_onnx_model(
node, inputs=inputs, outputs=outputs, name="test_{}".format(op_type)
)
verify_with_ort_with_trt(model, inputs, op_name, np_result=np_result)
# ====================================================================================
# ---UnitTest
# ====================================================================================
def test_abs():
op_name = "abs_0"
op_type = "Abs"
x = np.random.randn(3, 4, 5).astype(np.float32)
y = abs(x)
node = helper.make_node(op_type, inputs=["x"], outputs=["y"], name=op_name)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_acos():
op_name = "acos_0"
op_type = "Acos"
node = onnx.helper.make_node("Acos", inputs=["x"], outputs=["y"], name=op_name)
x = np.array([-0.5, 0, 0.5]).astype(np.float32)
y = np.arccos(x)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "acos_1"
op_type = "Acos"
node = onnx.helper.make_node("Acos", inputs=["x"], outputs=["y"], name=op_name)
x = np.random.rand(3, 4, 5).astype(np.float32)
y = np.arccos(x)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_and():
op_name = "and_0"
op_type = "And"
node = onnx.helper.make_node(
"And", inputs=["x", "y"], outputs=["and"], name=op_name
)
# 2d
x = (np.random.randn(3, 4) > 0).astype(bool)
y = (np.random.randn(3, 4) > 0).astype(bool)
z = np.logical_and(x, y)
op_expect(node, inputs=[x, y], outputs=[z], op_type=op_type, op_name=op_name)
op_name = "and_1"
op_type = "And"
node = onnx.helper.make_node(
"And", inputs=["x", "y"], outputs=["and"], name=op_name
)
x = (np.random.randn(3, 4, 5) > 0).astype(bool)
y = (np.random.randn(3, 4, 5) > 0).astype(bool)
z = np.logical_and(x, y)
op_expect(node, inputs=[x, y], outputs=[z], op_type=op_type, op_name=op_name)
op_name = "and_2"
op_type = "And"
node = onnx.helper.make_node(
"And", inputs=["x", "y"], outputs=["and"], name=op_name
)
x = (np.random.randn(3, 4, 5, 6) > 0).astype(bool)
y = (np.random.randn(3, 4, 5, 6) > 0).astype(bool)
z = np.logical_and(x, y)
op_expect(node, inputs=[x, y], outputs=[z], op_type=op_type, op_name=op_name)
def test_add():
op_name = "add_0"
op_type = "Add"
node = onnx.helper.make_node(
"Add", inputs=["x", "y"], outputs=["sum"], name=op_name
)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.random.randn(3, 4, 5).astype(np.float32)
op_expect(node, inputs=[x, y], outputs=[x + y], op_type=op_type, op_name=op_name)
op_name = "add_1"
op_type = "Add"
node = onnx.helper.make_node(
"Add", inputs=["x", "y"], outputs=["sum"], name=op_name
)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.random.randn(5).astype(np.float32)
op_expect(node, inputs=[x, y], outputs=[x + y], op_type=op_type, op_name=op_name)
def test_argmax():
op_type = "ArgMax"
op_name = "argmax_0"
data = np.array([[2, 1, 3, 10], [3, 4, 5, 6]], dtype=np.float32)
keepdims = 1
axis = -1
node = onnx.helper.make_node(
"ArgMax",
inputs=["data"],
outputs=["result"],
keepdims=keepdims,
axis=axis,
name=op_name,
)
# result: [[1], [1]]
from onnx.backend.test.case.node.argmax import argmax_use_numpy
result = argmax_use_numpy(data, keepdims=keepdims, axis=axis)
op_expect(node, inputs=[data], outputs=[result], op_type=op_type, op_name=op_name)
op_name = "argmax_1"
node = onnx.helper.make_node(
"ArgMax",
inputs=["data"],
outputs=["result"],
keepdims=keepdims,
axis=axis,
name=op_name,
)
data = np.random.uniform(-10, 10, [2, 3, 4]).astype(np.float32)
# result's shape: [1, 3, 4]
result = argmax_use_numpy(data, keepdims=keepdims, axis=axis)
op_expect(node, inputs=[data], outputs=[result], op_type=op_type, op_name=op_name)
def test_argmin():
op_type = "ArgMin"
op_name = "argmin_0"
data = np.array([[2, 1], [3, 10]], dtype=np.float32)
keepdims = 1
axis = 1
node = onnx.helper.make_node(
"ArgMin",
inputs=["data"],
outputs=["result"],
keepdims=keepdims,
axis=axis,
name=op_name,
)
# result: [[1], [1]]
from onnx.backend.test.case.node.argmin import argmin_use_numpy
result = argmin_use_numpy(data, keepdims=keepdims, axis=axis)
op_expect(node, inputs=[data], outputs=[result], op_type=op_type, op_name=op_name)
def test_asin():
op_name = "asin_0"
op_type = "Asin"
node = onnx.helper.make_node("Asin", inputs=["x"], outputs=["y"], name=op_name)
x = np.array([-0.5, 0, 0.5]).astype(np.float32)
y = np.arcsin(x)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "asin_1"
op_type = "Asin"
node = onnx.helper.make_node("Asin", inputs=["x"], outputs=["y"], name=op_name)
x = np.random.rand(3, 4, 5).astype(np.float32)
y = np.arcsin(x)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_asinh():
op_name = "asinh_0"
op_type = "Asinh"
node = onnx.helper.make_node("Asinh", inputs=["x"], outputs=["y"], name=op_name)
x = np.array([-1, 0, 1]).astype(np.float32)
y = np.arcsinh(x) # expected output [-0.88137358, 0., 0.88137358]
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "asinh_1"
op_type = "Asinh"
node = onnx.helper.make_node("Asinh", inputs=["x"], outputs=["y"], name=op_name)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.arcsinh(x)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_atan():
op_type = "Atan"
op_name = "atan_0"
node = onnx.helper.make_node("Atan", inputs=["x"], outputs=["y"], name=op_name)
x = np.array([-1, 0, 1]).astype(np.float32)
y = np.arctan(x)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_type = "Atan"
op_name = "atan_1"
node = onnx.helper.make_node("Atan", inputs=["x"], outputs=["y"], name=op_name)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.arctan(x)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_atanh():
op_name = "atanh_0"
op_type = "Atanh"
node = onnx.helper.make_node("Atanh", inputs=["x"], outputs=["y"], name=op_name)
x = np.array([-0.5, 0, 0.5]).astype(np.float32)
y = np.arctanh(x) # expected output [-0.54930615, 0., 0.54930615]
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "atanh_1"
op_type = "Atanh"
node = onnx.helper.make_node("Atanh", inputs=["x"], outputs=["y"], name=op_name)
x = np.random.uniform(0.0, 1.0, (3, 4, 5)).astype(np.float32)
y = np.arctanh(x)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_averagepool():
op_name = "averagepool_1d_default"
op_type = "AveragePool"
"""
input_shape: [1, 3, 32]
output_shape: [1, 3, 31]
"""
node = onnx.helper.make_node(
"AveragePool", inputs=["x"], outputs=["y"], kernel_shape=[2], name=op_name
)
x = np.random.randn(1, 3, 32).astype(np.float32)
x_shape = np.shape(x)
kernel_shape = [2]
strides = [1]
from onnx.backend.test.case.node.pool_op_common import get_output_shape, pool
out_shape = get_output_shape("VALID", x_shape[2:], kernel_shape, strides)
padded = x
y = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], "AVG")
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "averagepool_2d_ceil"
op_type = "AveragePool"
node = onnx.helper.make_node(
"AveragePool",
inputs=["x"],
outputs=["y"],
kernel_shape=[3, 3],
strides=[2, 2],
ceil_mode=True,
name=op_name,
)
x = np.array(
[
[
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16],
]
]
]
).astype(np.float32)
y = np.array([[[[6, 7.5], [12, 13.5]]]]).astype(np.float32)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_batchnormalization():
op_name = "batchnormalization_0"
op_type = "BatchNormalization"
# input size: (2, 3, 4, 5)
x = np.random.randn(2, 3, 4, 5).astype(np.float32)
s = np.random.randn(3).astype(np.float32)
bias = np.random.randn(3).astype(np.float32)
mean = np.random.randn(3).astype(np.float32)
var = np.random.rand(3).astype(np.float32)
from onnx.backend.test.case.node.batchnorm import _batchnorm_test_mode
y = _batchnorm_test_mode(x, s, bias, mean, var).astype(np.float32)
node = onnx.helper.make_node(
"BatchNormalization",
inputs=["x", "s", "bias", "mean", "var"],
outputs=["y"],
name=op_name,
)
# output size: (2, 3, 4, 5)
op_expect(
node,
inputs=[x, s, bias, mean, var],
outputs=[y],
op_type=op_type,
op_name=op_name,
)
def test_ceil():
op_name = "ceil_0"
op_type = "Ceil"
node = onnx.helper.make_node("Ceil", inputs=["x"], outputs=["y"], name=op_name)
x = np.array([-1.5, 1.2]).astype(np.float32)
y = np.ceil(x) # expected output [-1., 2.]
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "ceil_1"
op_type = "Ceil"
node = onnx.helper.make_node("Ceil", inputs=["x"], outputs=["y"], name=op_name)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.ceil(x)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_celu():
op_name = "celu_0"
op_type = "Celu"
alpha = 2.0
node = onnx.helper.make_node(
"Celu", inputs=["X"], outputs=["Y"], alpha=alpha, name=op_name
)
input_data = np.array(
[
[
[[0.8439683], [0.5665144], [0.05836735]],
[[0.02916367], [0.12964272], [0.5060197]],
[[0.79538304], [0.9411346], [0.9546573]],
],
[
[[0.17730942], [0.46192095], [0.26480448]],
[[0.6746842], [0.01665257], [0.62473077]],
[[0.9240844], [0.9722341], [0.11965699]],
],
[
[[0.41356155], [0.9129373], [0.59330076]],
[[0.81929934], [0.7862604], [0.11799799]],
[[0.69248444], [0.54119414], [0.07513223]],
],
],
dtype=np.float32,
)
# Calculate expected output data
positive_input = np.maximum(0, input_data)
negative_input = np.minimum(0, alpha * (np.exp(input_data / alpha) - 1))
expected_output = positive_input + negative_input
op_expect(
node,
inputs=[input_data],
outputs=[expected_output],
op_type=op_type,
op_name=op_name,
)
def test_clip():
op_name = "Clip_0"
op_type = "Clip"
node = onnx.helper.make_node(
"Clip", inputs=["x", "min", "max"], outputs=["y"], name=op_name
)
x = np.array([-2, 0, 2]).astype(np.float32)
min_val = np.array([-1.0]).astype(np.float32) # .float32(-1.0)
max_val = np.array([1.0]).astype(np.float32) # .float32(1.0)
y = np.clip(x, min_val, max_val) # expected output [-1., 0., 1.]
op_expect(
node,
inputs=[x, min_val, max_val],
outputs=[y],
op_type=op_type,
op_name=op_name,
)
op_name = "Clip_1"
op_type = "Clip"
node = onnx.helper.make_node(
"Clip", inputs=["x", "min", "max"], outputs=["y"], name=op_name
)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.clip(x, min_val, max_val)
op_expect(
node,
inputs=[x, min_val, max_val],
outputs=[y],
op_type=op_type,
op_name=op_name,
)
op_name = "Clip_2"
op_type = "Clip"
node = onnx.helper.make_node(
"Clip", inputs=["x", "min", "max"], outputs=["y"], name=op_name
)
min_val = np.array([-5.0]).astype(np.float32) # .float32(-1.0)
max_val = np.array([5.0]).astype(np.float32) # .float32(1.0)
op_name = "Clip_3"
op_type = "Clip"
node = onnx.helper.make_node(
"Clip", inputs=["x", "min", "max"], outputs=["y"], name=op_name
)
x = np.array([-1, 0, 1]).astype(np.float32)
y = np.array([-1, 0, 1]).astype(np.float32)
op_expect(
node,
inputs=[x, min_val, max_val],
outputs=[y],
op_type=op_type,
op_name=op_name,
)
op_name = "Clip_4"
op_type = "Clip"
node = onnx.helper.make_node(
"Clip", inputs=["x", "min", "max"], outputs=["y"], name=op_name
)
x = np.array([-6, 0, 6]).astype(np.float32)
y = np.array([-5, 0, 5]).astype(np.float32)
op_expect(
node,
inputs=[x, min_val, max_val],
outputs=[y],
op_type=op_type,
op_name=op_name,
)
op_name = "Clip_5"
op_type = "Clip"
node = onnx.helper.make_node(
"Clip", inputs=["x", "min", "max"], outputs=["y"], name=op_name
)
x = np.array([-1, 0, 6]).astype(np.float32)
y = np.array([-1, 0, 5]).astype(np.float32)
op_expect(
node,
inputs=[x, min_val, max_val],
outputs=[y],
op_type=op_type,
op_name=op_name,
)
def test_concat():
test_cases = {
"1d": ([1, 2], [3, 4]),
"2d": ([[1, 2], [3, 4]], [[5, 6], [7, 8]]),
"3d": (
[[[1, 2], [3, 4]], [[5, 6], [7, 8]]],
[[[9, 10], [11, 12]], [[13, 14], [15, 16]]],
),
} # type: Dict[Text, Sequence[Any]]
for test_case, values_ in test_cases.items():
values = [np.asarray(v, dtype=np.float32) for v in values_]
for i in range(len(values[0].shape)):
op_name = "concat_{}_{}".format(test_case, i)
op_type = "Concat"
in_args = ["value" + str(k) for k in range(len(values))]
node = onnx.helper.make_node(
"Concat",
inputs=[s for s in in_args],
outputs=["output"],
axis=i,
name=op_name,
)
output = np.concatenate(values, i)
op_expect(
node,
inputs=[v for v in values],
outputs=[output],
op_type=op_type,
op_name=op_name,
)
for i in range(-len(values[0].shape), 0):
op_name = "concat_{}_1_{}".format(test_case, abs(i))
op_type = "Concat"
in_args = ["value" + str(k) for k in range(len(values))]
node = onnx.helper.make_node(
"Concat",
inputs=[s for s in in_args],
outputs=["output"],
axis=i,
name=op_name,
)
output = np.concatenate(values, i)
op_expect(
node,
inputs=[v for v in values],
outputs=[output],
op_type=op_type,
op_name=op_name,
)
def test_conv():
# ------Conv
op_name, op_type = "test_basic_conv_with_padding", "Conv"
x = np.array(
[
[
[
[0.0, 1.0, 2.0, 3.0, 4.0], # (1, 1, 5, 5) input tensor
[5.0, 6.0, 7.0, 8.0, 9.0],
[10.0, 11.0, 12.0, 13.0, 14.0],
[15.0, 16.0, 17.0, 18.0, 19.0],
[20.0, 21.0, 22.0, 23.0, 24.0],
]
]
]
).astype(np.float32)
#NOCC:invalid-name(其他:onnx example)
W = np.array(
[
[
[
[1.0, 1.0, 1.0], # (1, 1, 3, 3) tensor for convolution weights
[1.0, 1.0, 1.0],
[1.0, 1.0, 1.0],
]
]
]
).astype(np.float32)
# Convolution with padding
node_with_padding = onnx.helper.make_node(
"Conv",
inputs=["x", "W"],
outputs=["y"],
kernel_shape=[3, 3],
# Default values for other attributes: strides=[1, 1], dilations=[1, 1], groups=1
pads=[1, 1, 1, 1],
name=op_name,
)
y_with_padding = np.array(
[
[
[
[12.0, 21.0, 27.0, 33.0, 24.0], # (1, 1, 5, 5) output tensor
[33.0, 54.0, 63.0, 72.0, 51.0],
[63.0, 99.0, 108.0, 117.0, 81.0],
[93.0, 144.0, 153.0, 162.0, 111.0],
[72.0, 111.0, 117.0, 123.0, 84.0],
]
]
]
).astype(np.float32)
op_expect(
node_with_padding,
inputs=[x, W],
outputs=[y_with_padding],
op_type=op_type,
op_name=op_name,
)
op_name, op_type = "test_basic_conv_without_padding", "Conv"
# Convolution without padding
node_without_padding = onnx.helper.make_node(
"Conv",
inputs=["x", "W"],
outputs=["y"],
kernel_shape=[3, 3],
# Default values for other attributes: strides=[1, 1], dilations=[1, 1], groups=1
pads=[0, 0, 0, 0],
name=op_name,
)
y_without_padding = np.array(
[
[
[
[54.0, 63.0, 72.0], # (1, 1, 3, 3) output tensor
[99.0, 108.0, 117.0],
[144.0, 153.0, 162.0],
]
]
]
).astype(np.float32)
op_expect(
node_without_padding,
inputs=[x, W],
outputs=[y_without_padding],
op_type=op_type,
op_name=op_name,
)
# conv_with_autopad_same
op_name, op_type = "test_conv_with_autopad_same", "Conv"
x = np.array(
[
[
[
[0.0, 1.0, 2.0, 3.0, 4.0], # (1, 1, 5, 5) input tensor
[5.0, 6.0, 7.0, 8.0, 9.0],
[10.0, 11.0, 12.0, 13.0, 14.0],
[15.0, 16.0, 17.0, 18.0, 19.0],
[20.0, 21.0, 22.0, 23.0, 24.0],
]
]
]
).astype(np.float32)
#NOCC:invalid-name(其他:onnx example)
W = np.array(
[
[
[
[1.0, 1.0, 1.0], # (1, 1, 3, 3) tensor for convolution weights
[1.0, 1.0, 1.0],
[1.0, 1.0, 1.0],
]
]
]
).astype(np.float32)
# Convolution with auto_pad='SAME_LOWER' and strides=2
node = onnx.helper.make_node(
"Conv",
inputs=["x", "W"],
outputs=["y"],
auto_pad="SAME_LOWER",
kernel_shape=[3, 3],
strides=[2, 2],
name=op_name,
)
y = np.array(
[[[[12.0, 27.0, 24.0], [63.0, 108.0, 81.0], [72.0, 117.0, 84.0]]]]
).astype(np.float32)
op_expect(node, inputs=[x, W], outputs=[y], op_type=op_type, op_name=op_name)
# conv_with_strides
op_name, op_type = "test_conv_with_strides_padding", "Conv"
x = np.array(
[
[
[
[0.0, 1.0, 2.0, 3.0, 4.0], # (1, 1, 7, 5) input tensor
[5.0, 6.0, 7.0, 8.0, 9.0],
[10.0, 11.0, 12.0, 13.0, 14.0],
[15.0, 16.0, 17.0, 18.0, 19.0],
[20.0, 21.0, 22.0, 23.0, 24.0],
[25.0, 26.0, 27.0, 28.0, 29.0],
[30.0, 31.0, 32.0, 33.0, 34.0],
]
]
]
).astype(np.float32)
#NOCC:invalid-name(其他:onnx example)
W = np.array(
[
[
[
[1.0, 1.0, 1.0], # (1, 1, 3, 3) tensor for convolution weights
[1.0, 1.0, 1.0],
[1.0, 1.0, 1.0],
]
]
]
).astype(np.float32)
# Convolution with strides=2 and padding
node_with_padding = onnx.helper.make_node(
"Conv",
inputs=["x", "W"],
outputs=["y"],
kernel_shape=[3, 3],
pads=[1, 1, 1, 1],
strides=[
2,
2,
], # Default values for other attributes: dilations=[1, 1], groups=1
name=op_name,
)
y_with_padding = np.array(
[
[
[
[12.0, 27.0, 24.0], # (1, 1, 4, 3) output tensor
[63.0, 108.0, 81.0],
[123.0, 198.0, 141.0],
[112.0, 177.0, 124.0],
]
]
]
).astype(np.float32)
op_expect(
node_with_padding,
inputs=[x, W],
outputs=[y_with_padding],
op_type=op_type,
op_name=op_name,
)
op_name = "test_conv_with_strides_no_padding"
# Convolution with strides=2 and no padding
node_without_padding = onnx.helper.make_node(
"Conv",
inputs=["x", "W"],
outputs=["y"],
kernel_shape=[3, 3],
pads=[0, 0, 0, 0],
strides=[
2,
2,
], # Default values for other attributes: dilations=[1, 1], groups=1
name=op_name,
)
y_without_padding = np.array(
[[[[54.0, 72.0], [144.0, 162.0], [234.0, 252.0]]]] # (1, 1, 3, 2) output tensor
).astype(np.float32)
op_expect(
node_without_padding,
inputs=[x, W],
outputs=[y_without_padding],
op_type=op_type,
op_name=op_name,
)
op_name = "test_conv_with_strides_and_asymmetric_padding"
# Convolution with strides=2 and padding only along one dimension (the H dimension in NxCxHxW tensor)
node_with_asymmetric_padding = onnx.helper.make_node(
"Conv",
inputs=["x", "W"],
outputs=["y"],
kernel_shape=[3, 3],
pads=[1, 0, 1, 0],
strides=[
2,
2,
], # Default values for other attributes: dilations=[1, 1], groups=1
name=op_name,
)
y_with_asymmetric_padding = np.array(
[
[
[
[21.0, 33.0], # (1, 1, 4, 2) output tensor
[99.0, 117.0],
[189.0, 207.0],
[171.0, 183.0],
]
]
]
).astype(np.float32)
op_expect(
node_with_asymmetric_padding,
inputs=[x, W],
outputs=[y_with_asymmetric_padding],
op_type=op_type,
op_name=op_name,
)
def test_convtranspose():
op_name, op_type = "test_convtranspose", "ConvTranspose"
x = np.array(
[[[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]]] # (1, 1, 3, 3)
).astype(np.float32)
#NOCC:invalid-name(其他:onnx example)
W = np.array(
[
[
[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]], # (1, 2, 3, 3)
[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],
]
]
).astype(np.float32)
node = onnx.helper.make_node("ConvTranspose", ["X", "W"], ["Y"], name=op_name)
y = np.array(
[
[
[
[0.0, 1.0, 3.0, 3.0, 2.0], # (1, 2, 5, 5)
[3.0, 8.0, 15.0, 12.0, 7.0],
[9.0, 21.0, 36.0, 27.0, 15.0],
[9.0, 20.0, 33.0, 24.0, 13.0],
[6.0, 13.0, 21.0, 15.0, 8.0],
],
[
[0.0, 1.0, 3.0, 3.0, 2.0],
[3.0, 8.0, 15.0, 12.0, 7.0],
[9.0, 21.0, 36.0, 27.0, 15.0],
[9.0, 20.0, 33.0, 24.0, 13.0],
[6.0, 13.0, 21.0, 15.0, 8.0],
],
]
]
).astype(np.float32)
op_expect(node, inputs=[x, W], outputs=[y], op_type=op_type, op_name=op_name)
op_name, op_type = "test_convtranspose_1d", "ConvTranspose"
x = np.array([[[0.0, 1.0, 2.0]]]).astype(np.float32) # (1, 1, 3)
#NOCC:invalid-name(其他:onnx example)
W = np.array([[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]]).astype(np.float32) # (1, 2, 3)
node = onnx.helper.make_node("ConvTranspose", ["X", "W"], ["Y"], name=op_name)
y = np.array(
[[[0.0, 1.0, 3.0, 3.0, 2.0], [0.0, 1.0, 3.0, 3.0, 2.0]]] # (1, 2, 5)
).astype(np.float32)
op_expect(node, inputs=[x, W], outputs=[y], op_type=op_type, op_name=op_name)
op_name, op_type = "test_convtranspose_3d", "ConvTranspose"
x = np.array(
[
[
[
[
[0.0, 1.0, 2.0, 3.0, 4.0], # (1, 1, 3, 4, 5)
[5.0, 6.0, 7.0, 8.0, 9.0],
[10.0, 11.0, 12.0, 13.0, 14.0],
[15.0, 16.0, 17.0, 18.0, 19.0],
],
[
[20.0, 21.0, 22.0, 23.0, 24.0],
[25.0, 26.0, 27.0, 28.0, 29.0],
[30.0, 31.0, 32.0, 33.0, 34.0],
[35.0, 36.0, 37.0, 38.0, 39.0],
],
[
[40.0, 41.0, 42.0, 43.0, 44.0],
[45.0, 46.0, 47.0, 48.0, 49.0],
[50.0, 51.0, 52.0, 53.0, 54.0],
[55.0, 56.0, 57.0, 58.0, 59.0],
],
]
]
]
).astype(np.float32)
#NOCC:invalid-name(其他:onnx example)
W = np.array(
[
[
[
[
[1.0, 1.0, 1.0], # (1, 2, 3, 3, 3)
[1.0, 1.0, 1.0],
[1.0, 1.0, 1.0],
],
[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],
[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],
],
[
[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],
[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],
[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],
],
]
]
).astype(np.float32)
node = onnx.helper.make_node("ConvTranspose", ["X", "W"], ["Y"], name=op_name)
y = np.array(
[
[
[
[
[0.0, 1.0, 3.0, 6.0, 9.0, 7.0, 4.0], # (1, 2, 5, 6, 7)
[5.0, 12.0, 21.0, 27.0, 33.0, 24.0, 13.0],
[15.0, 33.0, 54.0, 63.0, 72.0, 51.0, 27.0],
[30.0, 63.0, 99.0, 108.0, 117.0, 81.0, 42.0],
[25.0, 52.0, 81.0, 87.0, 93.0, 64.0, 33.0],
[15.0, 31.0, 48.0, 51.0, 54.0, 37.0, 19.0],
],
[
[20.0, 42.0, 66.0, 72.0, 78.0, 54.0, 28.0],
[50.0, 104.0, 162.0, 174.0, 186.0, 128.0, 66.0],
[90.0, 186.0, 288.0, 306.0, 324.0, 222.0, 114.0],
[120.0, 246.0, 378.0, 396.0, 414.0, 282.0, 144.0],
[90.0, 184.0, 282.0, 294.0, 306.0, 208.0, 106.0],
[50.0, 102.0, 156.0, 162.0, 168.0, 114.0, 58.0],
],
[
[60.0, 123.0, 189.0, 198.0, 207.0, 141.0, 72.0],
[135.0, 276.0, 423.0, 441.0, 459.0, 312.0, 159.0],
[225.0, 459.0, 702.0, 729.0, 756.0, 513.0, 261.0],
[270.0, 549.0, 837.0, 864.0, 891.0, 603.0, 306.0],
[195.0, 396.0, 603.0, 621.0, 639.0, 432.0, 219.0],
[105.0, 213.0, 324.0, 333.0, 342.0, 231.0, 117.0],
],
[
[60.0, 122.0, 186.0, 192.0, 198.0, 134.0, 68.0],
[130.0, 264.0, 402.0, 414.0, 426.0, 288.0, 146.0],
[210.0, 426.0, 648.0, 666.0, 684.0, 462.0, 234.0],
[240.0, 486.0, 738.0, 756.0, 774.0, 522.0, 264.0],
[170.0, 344.0, 522.0, 534.0, 546.0, 368.0, 186.0],
[90.0, 182.0, 276.0, 282.0, 288.0, 194.0, 98.0],
],
[
[40.0, 81.0, 123.0, 126.0, 129.0, 87.0, 44.0],
[85.0, 172.0, 261.0, 267.0, 273.0, 184.0, 93.0],
[135.0, 273.0, 414.0, 423.0, 432.0, 291.0, 147.0],
[150.0, 303.0, 459.0, 468.0, 477.0, 321.0, 162.0],
[105.0, 212.0, 321.0, 327.0, 333.0, 224.0, 113.0],
[55.0, 111.0, 168.0, 171.0, 174.0, 117.0, 59.0],
],
],
[
[
[0.0, 1.0, 3.0, 6.0, 9.0, 7.0, 4.0],
[5.0, 12.0, 21.0, 27.0, 33.0, 24.0, 13.0],
[15.0, 33.0, 54.0, 63.0, 72.0, 51.0, 27.0],
[30.0, 63.0, 99.0, 108.0, 117.0, 81.0, 42.0],
[25.0, 52.0, 81.0, 87.0, 93.0, 64.0, 33.0],
[15.0, 31.0, 48.0, 51.0, 54.0, 37.0, 19.0],
],
[
[20.0, 42.0, 66.0, 72.0, 78.0, 54.0, 28.0],
[50.0, 104.0, 162.0, 174.0, 186.0, 128.0, 66.0],
[90.0, 186.0, 288.0, 306.0, 324.0, 222.0, 114.0],
[120.0, 246.0, 378.0, 396.0, 414.0, 282.0, 144.0],
[90.0, 184.0, 282.0, 294.0, 306.0, 208.0, 106.0],
[50.0, 102.0, 156.0, 162.0, 168.0, 114.0, 58.0],
],
[
[60.0, 123.0, 189.0, 198.0, 207.0, 141.0, 72.0],
[135.0, 276.0, 423.0, 441.0, 459.0, 312.0, 159.0],
[225.0, 459.0, 702.0, 729.0, 756.0, 513.0, 261.0],
[270.0, 549.0, 837.0, 864.0, 891.0, 603.0, 306.0],
[195.0, 396.0, 603.0, 621.0, 639.0, 432.0, 219.0],
[105.0, 213.0, 324.0, 333.0, 342.0, 231.0, 117.0],
],
[
[60.0, 122.0, 186.0, 192.0, 198.0, 134.0, 68.0],
[130.0, 264.0, 402.0, 414.0, 426.0, 288.0, 146.0],
[210.0, 426.0, 648.0, 666.0, 684.0, 462.0, 234.0],
[240.0, 486.0, 738.0, 756.0, 774.0, 522.0, 264.0],
[170.0, 344.0, 522.0, 534.0, 546.0, 368.0, 186.0],
[90.0, 182.0, 276.0, 282.0, 288.0, 194.0, 98.0],
],
[
[40.0, 81.0, 123.0, 126.0, 129.0, 87.0, 44.0],
[85.0, 172.0, 261.0, 267.0, 273.0, 184.0, 93.0],
[135.0, 273.0, 414.0, 423.0, 432.0, 291.0, 147.0],
[150.0, 303.0, 459.0, 468.0, 477.0, 321.0, 162.0],
[105.0, 212.0, 321.0, 327.0, 333.0, 224.0, 113.0],
[55.0, 111.0, 168.0, 171.0, 174.0, 117.0, 59.0],
],
],
]
]
).astype(np.float32)
op_expect(node, inputs=[x, W], outputs=[y], op_type=op_type, op_name=op_name)
op_name, op_type = "test_convtranspose_pads", "ConvTranspose"
x = np.array(
[[[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]]] # (1, 1, 3, 3)
).astype(np.float32)
#NOCC:invalid-name(其他:onnx example)
W = np.array(
[
[
[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]], # (1, 2, 3, 3)
[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],
]
]
).astype(np.float32)
node = onnx.helper.make_node(
"ConvTranspose",
["X", "W"],
["Y"],
strides=[3, 2],
pads=[1, 2, 1, 2],
name=op_name,
)
y = np.array(
[
[
[
[1.0, 1.0, 3.0], # (1, 2, 7, 3)
[1.0, 1.0, 3.0],
[7.0, 4.0, 9.0],
[7.0, 4.0, 9.0],
[7.0, 4.0, 9.0],
[13.0, 7.0, 15.0],
[13.0, 7.0, 15.0],
],
[
[1.0, 1.0, 3.0],
[1.0, 1.0, 3.0],
[7.0, 4.0, 9.0],
[7.0, 4.0, 9.0],
[7.0, 4.0, 9.0],
[13.0, 7.0, 15.0],
[13.0, 7.0, 15.0],
],
]
]
).astype(np.float32)
op_expect(node, inputs=[x, W], outputs=[y], op_type=op_type, op_name=op_name)
def test_cos():
op_name, op_type = "test_cos_example", "Cos"
node = onnx.helper.make_node("Cos", inputs=["x"], outputs=["y"], name=op_name)
x = np.array([-1, 0, 1]).astype(np.float32)
y = np.cos(x)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name, op_type = "test_cos", "Cos"
node = onnx.helper.make_node("Cos", inputs=["x"], outputs=["y"], name=op_name)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.cos(x)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_cosh():
op_name, op_type = "test_cosh_example", "Cosh"
node = onnx.helper.make_node("Cosh", inputs=["x"], outputs=["y"], name=op_name)
x = np.array([-1, 0, 1]).astype(np.float32)
y = np.cosh(x) # expected output [1.54308069, 1., 1.54308069]
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name, op_type = "test_cosh", "Cosh"
node = onnx.helper.make_node("Cosh", inputs=["x"], outputs=["y"], name=op_name)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.cosh(x)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_depthtospace():
op_name, op_type = "test_depthtospace_crd_mode_example", "DepthToSpace"
node = onnx.helper.make_node(
"DepthToSpace",
inputs=["x"],
outputs=["y"],
blocksize=2,
mode="CRD",
name=op_name,
)
# (1, 8, 2, 3) input tensor
x = np.array(
[
[
[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]],
[[9.0, 10.0, 11.0], [12.0, 13.0, 14.0]],
[[18.0, 19.0, 20.0], [21.0, 22.0, 23.0]],
[[27.0, 28.0, 29.0], [30.0, 31.0, 32.0]],
[[36.0, 37.0, 38.0], [39.0, 40.0, 41.0]],
[[45.0, 46.0, 47.0], [48.0, 49.0, 50.0]],
[[54.0, 55.0, 56.0], [57.0, 58.0, 59.0]],
[[63.0, 64.0, 65.0], [66.0, 67.0, 68.0]],
]
]
).astype(np.float32)
# (1, 2, 4, 6) output tensor
y = np.array(
[
[
[
[0.0, 9.0, 1.0, 10.0, 2.0, 11.0],
[18.0, 27.0, 19.0, 28.0, 20.0, 29.0],
[3.0, 12.0, 4.0, 13.0, 5.0, 14.0],
[21.0, 30.0, 22.0, 31.0, 23.0, 32.0],
],
[
[36.0, 45.0, 37.0, 46.0, 38.0, 47.0],
[54.0, 63.0, 55.0, 64.0, 56.0, 65.0],
[39.0, 48.0, 40.0, 49.0, 41.0, 50.0],
[57.0, 66.0, 58.0, 67.0, 59.0, 68.0],
],
]
]
).astype(np.float32)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "test_depthtospace_example"
node = onnx.helper.make_node(
"DepthToSpace",
inputs=["x"],
outputs=["y"],
blocksize=2,
mode="DCR",
name=op_name,
)
# (1, 8, 2, 3) input tensor
x = np.array(
[
[
[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]],
[[9.0, 10.0, 11.0], [12.0, 13.0, 14.0]],
[[18.0, 19.0, 20.0], [21.0, 22.0, 23.0]],
[[27.0, 28.0, 29.0], [30.0, 31.0, 32.0]],
[[36.0, 37.0, 38.0], [39.0, 40.0, 41.0]],
[[45.0, 46.0, 47.0], [48.0, 49.0, 50.0]],
[[54.0, 55.0, 56.0], [57.0, 58.0, 59.0]],
[[63.0, 64.0, 65.0], [66.0, 67.0, 68.0]],
]
]
).astype(np.float32)
# (1, 2, 4, 6) output tensor
y = np.array(
[
[
[
[0.0, 18.0, 1.0, 19.0, 2.0, 20.0],
[36.0, 54.0, 37.0, 55.0, 38.0, 56.0],
[3.0, 21.0, 4.0, 22.0, 5.0, 23.0],
[39.0, 57.0, 40.0, 58.0, 41.0, 59.0],
],
[
[9.0, 27.0, 10.0, 28.0, 11.0, 29.0],
[45.0, 63.0, 46.0, 64.0, 47.0, 65.0],
[12.0, 30.0, 13.0, 31.0, 14.0, 32.0],
[48.0, 66.0, 49.0, 67.0, 50.0, 68.0],
],
]
]
).astype(np.float32)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_div():
op_name, op_type = "test_div_example", "Div"
node = onnx.helper.make_node("Div", inputs=["x", "y"], outputs=["z"], name=op_name)
x = np.array([3, 4]).astype(np.float32)
y = np.array([1, 2]).astype(np.float32)
z = x / y # expected output [3., 2.]
op_expect(node, inputs=[x, y], outputs=[z], op_type=op_type, op_name=op_name)
op_name, op_type = "test_div", "Div"
node = onnx.helper.make_node("Div", inputs=["x", "y"], outputs=["z"], name=op_name)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.random.rand(3, 4, 5).astype(np.float32) + 1.0
z = x / y
op_expect(node, inputs=[x, y], outputs=[z], op_type=op_type, op_name=op_name)
op_name, op_type = "test_div_bcast", "Div"
node = onnx.helper.make_node("Div", inputs=["x", "y"], outputs=["z"], name=op_name)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.random.rand(5).astype(np.float32) + 1.0
z = x / y
op_expect(node, inputs=[x, y], outputs=[z], op_type=op_type, op_name=op_name)
def test_einsum():
op_name, op_type = "test_einsum_batch_diagonal", "Einsum"
eqn = "...ii ->...i"
node = onnx.helper.make_node(
"Einsum", inputs=["x"], outputs=["y"], equation=eqn, name=op_name
)
#NOCC:invalid-name(其他:onnx example)
X = np.random.randn(3, 5, 5).astype(np.float32)
from onnx.backend.test.case.node.einsum import einsum_reference_implementation
#NOCC:invalid-name(其他:onnx example)
Z = einsum_reference_implementation(eqn, (X,))
op_expect(node, inputs=[X], outputs=[Z], op_type=op_type, op_name=op_name)
def test_elu():
op_name, op_type = "test_elu_example", "Elu"
node = onnx.helper.make_node(
"Elu", inputs=["x"], outputs=["y"], alpha=2.0, name=op_name
)
x = np.array([-1, 0, 1]).astype(np.float32)
# expected output [-1.2642411, 0., 1.]
y = np.clip(x, 0, np.inf) + (np.exp(np.clip(x, -np.inf, 0)) - 1) * 2.0
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name, op_type = "test_elu", "Elu"
node = onnx.helper.make_node(
"Elu", inputs=["x"], outputs=["y"], alpha=2.0, name=op_name
)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.clip(x, 0, np.inf) + (np.exp(np.clip(x, -np.inf, 0)) - 1) * 2.0
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name, op_type = "test_elu_default", "Elu"
default_alpha = 1.0
node = onnx.helper.make_node("Elu", inputs=["x"], outputs=["y"], name=op_name)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.clip(x, 0, np.inf) + (np.exp(np.clip(x, -np.inf, 0)) - 1) * default_alpha
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_erf():
op_name, op_type = "test_erf", "Erf"
node = onnx.helper.make_node("Erf", inputs=["x"], outputs=["y"], name=op_name)
x = np.random.randn(1, 3, 32, 32).astype(np.float32)
import math
y = np.vectorize(math.erf)(x).astype(np.float32)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_exp():
op_name, op_type = "test_exp_example", "Exp"
node = onnx.helper.make_node("Exp", inputs=["x"], outputs=["y"], name=op_name)
x = np.array([-1, 0, 1]).astype(np.float32)
y = np.exp(x) # expected output [0.36787945, 1., 2.71828175]
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name, op_type = "test_exp", "Exp"
node = onnx.helper.make_node("Exp", inputs=["x"], outputs=["y"], name=op_name)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.exp(x)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_eyelike():
op_name, op_type = "test_eyelike_populate_off_main_diagonal", "EyeLike"
shape = (4, 5)
off_diagonal_offset = 1
node = onnx.helper.make_node(
"EyeLike",
inputs=["x"],
outputs=["y"],
k=off_diagonal_offset,
dtype=onnx.TensorProto.FLOAT,
name=op_name,
)
x = np.random.randint(0, 100, size=shape, dtype=np.int32)
y = np.eye(shape[0], shape[1], k=off_diagonal_offset, dtype=np.float32)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "test_eyelike_with_dtype"
shape = (3, 4)
node = onnx.helper.make_node(
"EyeLike",
inputs=["x"],
outputs=["y"],
dtype=onnx.TensorProto.FLOAT,
name=op_name,
)
x = np.random.randint(0, 100, size=shape, dtype=np.int32)
y = np.eye(shape[0], shape[1], dtype=np.float32)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "test_eyelike_without_dtype"
shape = (4, 4)
node = onnx.helper.make_node("EyeLike", inputs=["x"], outputs=["y"], name=op_name)
x = np.random.randint(0, 100, size=shape, dtype=np.int32)
y = np.eye(shape[0], shape[1], dtype=np.int32)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_floor():
op_name, op_type = "test_floor_example", "Floor"
node = onnx.helper.make_node("Floor", inputs=["x"], outputs=["y"], name=op_name)
x = np.array([-1.5, 1.2, 2]).astype(np.float32)
y = np.floor(x) # expected output [-2., 1., 2.]
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name, op_type = "test_floor", "Floor"
node = onnx.helper.make_node("Floor", inputs=["x"], outputs=["y"], name=op_name)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.floor(x)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def verify_rnn(
seq_length,
batch_size,
input_size,
hidden_size,
rnn_type="LSTM",
use_bias=False,
activations=None,
alphas=None,
betas=None,
use_initial_state=False,
use_peep=False,
linear_before_reset=False,
op_name=None,
):
if rnn_type == "LSTM":
multiplier = 4
elif rnn_type == "GRU":
multiplier = 3
else:
raise NotImplementedError("%s RNNs not yet supported." % rnn_type)
x_np = np.random.uniform(size=(seq_length, batch_size, input_size)).astype(
"float32"
)
w_np = np.random.uniform(size=(1, multiplier * hidden_size, input_size)).astype(
"float32"
)
r_np = np.random.uniform(size=(1, multiplier * hidden_size, hidden_size)).astype(
"float32"
)
input_names = ["X", "W", "R"]
input_tensors = [
helper.make_tensor_value_info("X", TensorProto.FLOAT, list(x_np.shape)),
helper.make_tensor_value_info("W", TensorProto.FLOAT, list(w_np.shape)),
helper.make_tensor_value_info("R", TensorProto.FLOAT, list(r_np.shape)),
]
input_values = [x_np, w_np, r_np]
if use_bias:
b_np = np.random.uniform(size=(1, multiplier * 2 * hidden_size)).astype(
"float32"
)
input_names.append("B")
input_tensors.append(
helper.make_tensor_value_info(
"B", TensorProto.FLOAT, [1, multiplier * 2 * hidden_size]
)
)
input_values.append(b_np)
if use_initial_state:
assert use_bias is True, "Initial states must have bias specified."
sequence_np = np.repeat(seq_length, batch_size).astype("int32")
input_names.append("sequence_lens")
input_tensors.append(
helper.make_tensor_value_info(
"sequence_lens", TensorProto.INT32, [batch_size]
)
)
input_values.append(sequence_np)
initial_h_np = np.random.uniform(size=(1, batch_size, hidden_size)).astype(
"float32"
)
input_names.append("initial_h")
input_tensors.append(
helper.make_tensor_value_info(
"initial_h", TensorProto.FLOAT, [1, batch_size, hidden_size]
)
)
input_values.append(initial_h_np)
if rnn_type == "LSTM":
initial_c_np = np.random.uniform(size=(1, batch_size, hidden_size)).astype(
"float32"
)
input_names.append("initial_c")
input_tensors.append(
helper.make_tensor_value_info(
"initial_c", TensorProto.FLOAT, [1, batch_size, hidden_size]
)
)
input_values.append(initial_c_np)
if use_peep and rnn_type == "LSTM":
assert (
use_initial_state is True
), "Peepholes require initial state to be specified."
p_np = np.random.uniform(size=(1, 3 * hidden_size)).astype("float32")
input_names.append("P")
input_tensors.append(
helper.make_tensor_value_info("P", TensorProto.FLOAT, [1, 3 * hidden_size])
)
input_values.append(p_np)
#NOCC:invalid-name(其他:onnx example)
Y_shape = [seq_length, 1, batch_size, hidden_size]
#NOCC:invalid-name(其他:onnx example)
Y_h_shape = [1, batch_size, hidden_size]
outputs = ["Y", "Y_h"]
graph_outputs = [
helper.make_tensor_value_info("Y", TensorProto.FLOAT, list(Y_shape)),
helper.make_tensor_value_info("Y_h", TensorProto.FLOAT, list(Y_h_shape)),
]
output_shapes = [Y_shape, Y_h_shape]
if rnn_type == "LSTM":
#NOCC:invalid-name(其他:onnx example)
Y_c_shape = [1, batch_size, hidden_size]
outputs.append("Y_c")
graph_outputs.append(
helper.make_tensor_value_info("Y_c", TensorProto.FLOAT, list(Y_c_shape))
)
output_shapes.append(Y_c_shape)
rnn_node = helper.make_node(
rnn_type,
inputs=input_names,
outputs=outputs,
hidden_size=hidden_size,
name=op_name,
)
if activations is not None:
activations_attr = helper.make_attribute("activations", activations)
rnn_node.attribute.append(activations_attr)
if alphas is not None:
alphas_attr = helper.make_attribute("activation_alpha", alphas)
rnn_node.attribute.append(alphas_attr)
if betas is not None:
betas_attr = helper.make_attribute("activation_beta", betas)
rnn_node.attribute.append(betas_attr)
if linear_before_reset and rnn_type == "GRU":
lbr_attr = helper.make_attribute("linear_before_reset", 1)
rnn_node.attribute.append(lbr_attr)
graph = helper.make_graph(
[rnn_node], "rnn_test", inputs=input_tensors, outputs=graph_outputs
)
model = helper.make_model(graph, producer_name="rnn_test")
verify_with_ort_with_trt(model, input_values, op_name)
def test_gather():
op_name, op_type = "test_gather_0", "Gather"
node = onnx.helper.make_node(
"Gather", inputs=["data", "indices"], outputs=["y"], axis=0, name=op_name
)
data = np.random.randn(5, 4, 3, 2).astype(np.float32)
indices = np.array([0, 1, 3])
y = np.take(data, indices, axis=0)
op_expect(
node,
inputs=[data, indices.astype(np.int64)],
outputs=[y],
op_type=op_type,
op_name=op_name,
)
op_name = "test_gather_1"
node = onnx.helper.make_node(
"Gather", inputs=["data", "indices"], outputs=["y"], axis=1, name=op_name
)
data = np.random.randn(5, 4, 3, 2).astype(np.float32)
indices = np.array([0, 1, 3])
y = np.take(data, indices, axis=1)
op_expect(
node,
inputs=[data, indices.astype(np.int64)],
outputs=[y],
op_type=op_type,
op_name=op_name,
)
op_name = "test_gather_2d_indices"
node = onnx.helper.make_node(
"Gather", inputs=["data", "indices"], outputs=["y"], axis=1, name=op_name
)
data = np.random.randn(3, 3).astype(np.float32)
indices = np.array([[0, 2]])
y = np.take(data, indices, axis=1)
op_expect(
node,
inputs=[data, indices.astype(np.int64)],
outputs=[y],
op_type=op_type,
op_name=op_name,
)
op_name = "test_gather_negative_indices"
node = onnx.helper.make_node(
"Gather", inputs=["data", "indices"], outputs=["y"], axis=0, name=op_name
)
data = np.arange(10).astype(np.float32)
indices = np.array([0, -9, -10])
y = np.take(data, indices, axis=0)
# print(y)
# [0. 1. 0.]
op_expect(
node,
inputs=[data, indices.astype(np.int64)],
outputs=[y],
op_type=op_type,
op_name=op_name,
)
def test_gatherelement():
op_name, op_type = "test_gather_elements_0", "GatherElements"
axis = 1
node = onnx.helper.make_node(
"GatherElements",
inputs=["data", "indices"],
outputs=["y"],
axis=axis,
name=op_name,
)
data = np.array([[1, 2], [3, 4]], dtype=np.float32)
indices = np.array([[0, 0], [1, 0]], dtype=np.int32)
from onnx.backend.test.case.node.gatherelements import gather_elements
y = gather_elements(data, indices, axis)
# print(y) produces
# [[1, 1],
# [4, 3]]
op_expect(
node,
inputs=[data, indices.astype(np.int64)],
outputs=[y],
op_type=op_type,
op_name=op_name,
)
op_name = "test_gather_elements_1"
axis = 0
node = onnx.helper.make_node(
"GatherElements",
inputs=["data", "indices"],
outputs=["y"],
axis=axis,
name=op_name,
)
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32)
indices = np.array([[1, 2, 0], [2, 0, 0]], dtype=np.int32)
y = gather_elements(data, indices, axis)
# print(y) produces
# [[4, 8, 3],
# [7, 2, 3]]
op_expect(
node,
inputs=[data, indices.astype(np.int64)],
outputs=[y],
op_type=op_type,
op_name=op_name,
)
op_name = "test_gather_elements_negative_indices"
axis = 0
node = onnx.helper.make_node(
"GatherElements",
inputs=["data", "indices"],
outputs=["y"],
axis=axis,
name=op_name,
)
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32)
indices = np.array([[-1, -2, 0], [-2, 0, 0]], dtype=np.int32)
y = gather_elements(data, indices, axis)
# print(y) produces
# [[7, 5, 3],
# [4, 2, 3]]
op_expect(
node,
inputs=[data, indices.astype(np.int64)],
outputs=[y],
op_type=op_type,
op_name=op_name,
)
def test_gathernd():
op_name, op_type = "test_gathernd_example_float32", "GatherND"
node = onnx.helper.make_node(
"GatherND", inputs=["data", "indices"], outputs=["output"], name=op_name
)
data = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], dtype=np.float32)
indices = np.array([[[0, 1]], [[1, 0]]], dtype=np.int64)
from onnx.backend.test.case.node.gathernd import gather_nd_impl
output = gather_nd_impl(data, indices, 0)
expected_output = np.array([[[2, 3]], [[4, 5]]], dtype=np.float32)
assert np.array_equal(output, expected_output)
op_expect(
node, inputs=[data, indices], outputs=[output], op_type=op_type, op_name=op_name
)
op_name = "test_gathernd_example_int32"
node = onnx.helper.make_node(
"GatherND", inputs=["data", "indices"], outputs=["output"], name=op_name
)
data = np.array([[0, 1], [2, 3]], dtype=np.int32)
indices = np.array([[0, 0], [1, 1]], dtype=np.int64)
output = gather_nd_impl(data, indices, 0)
expected_output = np.array([0, 3], dtype=np.int32)
assert np.array_equal(output, expected_output)
op_expect(
node, inputs=[data, indices], outputs=[output], op_type=op_type, op_name=op_name
)
op_name = "test_gathernd_example_int32_batch_dim1"
node = onnx.helper.make_node(
"GatherND",
inputs=["data", "indices"],
outputs=["output"],
batch_dims=1,
name=op_name,
)
data = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], dtype=np.int32)
indices = np.array([[1], [0]], dtype=np.int64)
output = gather_nd_impl(data, indices, 1)
expected_output = np.array([[2, 3], [4, 5]], dtype=np.int32)
assert np.array_equal(output, expected_output)
op_expect(
node, inputs=[data, indices], outputs=[output], op_type=op_type, op_name=op_name
)
def test_gemm():
op_name, op_type = "test_gemm_all_attributes", "Gemm"
node = onnx.helper.make_node(
"Gemm",
inputs=["a", "b", "c"],
outputs=["y"],
alpha=0.25,
beta=0.35,
transA=1,
transB=1,
name=op_name,
)
a = np.random.ranf([4, 3]).astype(np.float32)
b = np.random.ranf([5, 4]).astype(np.float32)
c = np.random.ranf([1, 5]).astype(np.float32)
from onnx.backend.test.case.node.gemm import gemm_reference_implementation
y = gemm_reference_implementation(
a, b, c, transA=1, transB=1, alpha=0.25, beta=0.35
)
op_expect(node, inputs=[a, b, c], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "test_gemm_alpha"
node = onnx.helper.make_node(
"Gemm", inputs=["a", "b", "c"], outputs=["y"], alpha=0.5, name=op_name
)
a = np.random.ranf([3, 5]).astype(np.float32)
b = np.random.ranf([5, 4]).astype(np.float32)
c = np.zeros([1, 4]).astype(np.float32)
y = gemm_reference_implementation(a, b, c, alpha=0.5)
op_expect(node, inputs=[a, b, c], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "test_gemm_beta"
node = onnx.helper.make_node(
"Gemm", inputs=["a", "b", "c"], outputs=["y"], beta=0.5, name=op_name
)
a = np.random.ranf([2, 7]).astype(np.float32)
b = np.random.ranf([7, 4]).astype(np.float32)
c = np.random.ranf([1, 4]).astype(np.float32)
y = gemm_reference_implementation(a, b, c, beta=0.5)
op_expect(node, inputs=[a, b, c], outputs=[y], op_type=op_type, op_name=op_name)
def test_globalaveragepool():
op_name, op_type = "test_globalaveragepool", "GlobalAveragePool"
node = onnx.helper.make_node(
"GlobalAveragePool", inputs=["x"], outputs=["y"], name=op_name
)
x = np.random.randn(1, 3, 5, 5).astype(np.float32)
y = np.mean(x, axis=tuple(range(2, np.ndim(x))), keepdims=True)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "test_globalaveragepool_precomputed"
node = onnx.helper.make_node(
"GlobalAveragePool", inputs=["x"], outputs=["y"], name=op_name
)
x = np.array(
[
[
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
]
]
).astype(np.float32)
y = np.array([[[[5]]]]).astype(np.float32)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_globalmaxpool():
op_name = "test_globalmaxpool"
op_type = "GlobalMaxPool"
node = onnx.helper.make_node(
"GlobalMaxPool", inputs=["x"], outputs=["y"], name=op_name
)
x = np.random.randn(1, 3, 5, 5).astype(np.float32)
y = np.max(x, axis=tuple(range(2, np.ndim(x))), keepdims=True)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "test_globalmaxpool_precomputed"
node = onnx.helper.make_node(
"GlobalMaxPool", inputs=["x"], outputs=["y"], name=op_name
)
x = np.array(
[
[
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
]
]
).astype(np.float32)
y = np.array([[[[9]]]]).astype(np.float32)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_hardsigmoid():
op_name, op_type = "test_hardsigmoid_example", "HardSigmoid"
node = onnx.helper.make_node(
"HardSigmoid", inputs=["x"], outputs=["y"], alpha=0.5, beta=0.6, name=op_name
)
x = np.array([-1, 0, 1]).astype(np.float32)
y = np.clip(x * 0.5 + 0.6, 0, 1) # expected output [0.1, 0.6, 1.]
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "test_hardsigmoid"
node = onnx.helper.make_node(
"HardSigmoid", inputs=["x"], outputs=["y"], alpha=0.5, beta=0.6, name=op_name
)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.clip(x * 0.5 + 0.6, 0, 1)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "test_hardsigmoid_default"
default_alpha = 0.2
default_beta = 0.5
node = onnx.helper.make_node(
"HardSigmoid", inputs=["x"], outputs=["y"], name=op_name
)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.clip(x * default_alpha + default_beta, 0, 1)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_hardswish():
op_name, op_type = "test_hardswish", "HardSwish"
node = onnx.helper.make_node("HardSwish", inputs=["x"], outputs=["y"], name=op_name)
x = np.random.randn(3, 4, 5).astype(np.float32)
from onnx.backend.test.case.node.hardswish import hardswish
y = hardswish(x)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_hardmax():
op_name, op_type = "test_hardmax_example", "Hardmax"
node = onnx.helper.make_node("Hardmax", inputs=["x"], outputs=["y"], name=op_name)
x = np.array([[3, 0, 1, 2], [2, 5, 1, 0], [0, 1, 3, 2], [0, 1, 2, 3]]).astype(
np.float32
)
# expect result:
# [[1. 0. 0. 0.]
# [0. 1. 0. 0.]
# [0. 0. 1. 0.]
# [0. 0. 0. 1.]]
from onnx.backend.test.case.node.hardmax import hardmax
y = hardmax(x)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_identity():
op_name, op_type = "test_identity", "Identity"
node = onnx.helper.make_node("Identity", inputs=["x"], outputs=["y"], name=op_name)
data = np.array(
[
[
[
[1, 2],
[3, 4],
]
]
],
dtype=np.float32,
)
op_expect(node, inputs=[data], outputs=[data], op_type=op_type, op_name=op_name)
def test_instancenormalization():
op_name, op_type = "test_instancenorm_example", "InstanceNormalization"
def _instancenorm_test_mode(x, s, bias, epsilon=1e-5): # type: ignore
dims_x = len(x.shape)
axis = tuple(range(2, dims_x))
mean = np.mean(x, axis=axis, keepdims=True)
var = np.var(x, axis=axis, keepdims=True)
dim_ones = (1,) * (dims_x - 2)
s = s.reshape(-1, *dim_ones)
bias = bias.reshape(-1, *dim_ones)
return s * (x - mean) / np.sqrt(var + epsilon) + bias
# input size: (1, 2, 1, 3)
x = np.array([[[[-1, 0, 1]], [[2, 3, 4]]]]).astype(np.float32)
s = np.array([1.0, 1.5]).astype(np.float32)
bias = np.array([0, 1]).astype(np.float32)
y = _instancenorm_test_mode(x, s, bias).astype(np.float32)
node = onnx.helper.make_node(
"InstanceNormalization", inputs=["x", "s", "bias"], outputs=["y"], name=op_name
)
# output size: (1, 2, 1, 3)
op_expect(node, inputs=[x, s, bias], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "test_instancenorm_epsilon"
# input size: (2, 3, 4, 5)
x = np.random.randn(2, 3, 4, 5).astype(np.float32)
s = np.random.randn(3).astype(np.float32)
bias = np.random.randn(3).astype(np.float32)
epsilon = 1e-2
y = _instancenorm_test_mode(x, s, bias, epsilon).astype(np.float32)
node = onnx.helper.make_node(
"InstanceNormalization",
inputs=["x", "s", "bias"],
outputs=["y"],
epsilon=epsilon,
name=op_name,
)
# output size: (2, 3, 4, 5)
op_expect(node, inputs=[x, s, bias], outputs=[y], op_type=op_type, op_name=op_name)
def test_leakyrelu():
op_name, op_type = "test_leakyrelu_example", "LeakyRelu"
node = onnx.helper.make_node(
"LeakyRelu", inputs=["x"], outputs=["y"], alpha=0.1, name=op_name
)
x = np.array([-1, 0, 1]).astype(np.float32)
# expected output [-0.1, 0., 1.]
y = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * 0.1
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "test_leakyrelu"
node = onnx.helper.make_node(
"LeakyRelu", inputs=["x"], outputs=["y"], alpha=0.1, name=op_name
)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * 0.1
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "test_leakyrelu_default"
default_alpha = 0.01
node = onnx.helper.make_node("LeakyRelu", inputs=["x"], outputs=["y"], name=op_name)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * default_alpha
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_log():
op_name = "test_log_example"
op_type = "Log"
node = onnx.helper.make_node("Log", inputs=["x"], outputs=["y"], name=op_name)
x = np.array([1, 10]).astype(np.float32)
y = np.log(x) # expected output [0., 2.30258512]
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "test_log"
node = onnx.helper.make_node("Log", inputs=["x"], outputs=["y"], name=op_name)
x = np.exp(np.random.randn(3, 4, 5).astype(np.float32))
y = np.log(x)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_logsoftmax():
op_name, op_type = "test_logsoftmax_example_1", "LogSoftmax"
node = onnx.helper.make_node(
"LogSoftmax", inputs=["x"], outputs=["y"], name=op_name
)
x = np.array([[-1, 0, 1]]).astype(np.float32)
# expected output
# [[-2.4076061 -1.407606 -0.407606 ]]
from onnx.backend.test.case.node.logsoftmax import logsoftmax
y = logsoftmax(x)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
x = np.array([[0, 1, 2, 3], [10000, 10001, 10002, 10003]]).astype(np.float32)
axis_order = [0, 1, -1]
for axis in axis_order:
op_name = "test_logsoftmax_axis_{}".format(str(axis + 1))
node = onnx.helper.make_node(
"LogSoftmax", inputs=["x"], outputs=["y"], axis=axis, name=op_name
)
y = logsoftmax(x, axis=axis)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_matmul():
op_name, op_type = "test_matmul_2d", "MatMul"
node = onnx.helper.make_node(
"MatMul", inputs=["a", "b"], outputs=["c"], name=op_name
)
# 2d
a = np.random.randn(3, 4).astype(np.float32)
b = np.random.randn(4, 3).astype(np.float32)
c = np.matmul(a, b)
op_expect(node, inputs=[a, b], outputs=[c], op_type=op_type, op_name=op_name)
def test_max():
op_name = "test_max_example"
op_type = "Max"
data_0 = np.array([3, 2, 1]).astype(np.float32)
data_1 = np.array([1, 4, 4]).astype(np.float32)
data_2 = np.array([2, 5, 3]).astype(np.float32)
result = np.array([3, 5, 4]).astype(np.float32)
node = onnx.helper.make_node(
"Max", inputs=["data_0", "data_1", "data_2"], outputs=["result"], name=op_name
)
op_expect(
node,
inputs=[data_0, data_1, data_2],
outputs=[result],
op_type=op_type,
op_name=op_name,
)
op_name = "test_max_two_inputs"
result = np.maximum(data_0, data_1)
node = onnx.helper.make_node(
"Max", inputs=["data_0", "data_1"], outputs=["result"], name=op_name
)
op_expect(
node,
inputs=[data_0, data_1],
outputs=[result],
op_type=op_type,
op_name=op_name,
)
def _test_maxpool_2d_ceil():
op_name, op_type = "test_maxpool_2d_ceil", "MaxPool"
node = onnx.helper.make_node(
"MaxPool",
inputs=["x"],
outputs=["y"],
kernel_shape=[3, 3],
strides=[2, 2],
ceil_mode=True,
name=op_name,
)
x = np.array(
[
[
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16],
]
]
]
).astype(np.float32)
y = np.array([[[[11, 12], [15, 16]]]]).astype(np.float32)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def _test_maxpool_1d_default():
op_name, op_type = "test_maxpool_1d_default", "MaxPool"
node = onnx.helper.make_node(
"MaxPool", inputs=["x"], outputs=["y"], kernel_shape=[2], name=op_name
)
x = np.random.randn(1, 3, 32).astype(np.float32)
x_shape = np.shape(x)
kernel_shape = [2]
strides = [1]
from onnx.backend.test.case.node.pool_op_common import get_output_shape, pool
out_shape = get_output_shape("VALID", x_shape[2:], kernel_shape, strides)
padded = x
y = pool(padded, x_shape, kernel_shape, strides, out_shape, [0], "MAX")
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_maxpool():
_test_maxpool_2d_ceil()
_test_maxpool_1d_default()
def test_mean():
op_name, op_type = "test_mean_example", "Mean"
data_0 = np.array([3, 0, 2]).astype(np.float32)
data_1 = np.array([1, 3, 4]).astype(np.float32)
data_2 = np.array([2, 6, 6]).astype(np.float32)
result = np.array([2, 3, 4]).astype(np.float32)
node = onnx.helper.make_node(
"Mean", inputs=["data_0", "data_1", "data_2"], outputs=["result"], name=op_name
)
op_expect(
node,
inputs=[data_0, data_1, data_2],
outputs=[result],
op_type=op_type,
op_name=op_name,
)
op_name = "test_mean_two_inputs"
result = np.divide(np.add(data_0, data_1), 2.0)
node = onnx.helper.make_node(
"Mean", inputs=["data_0", "data_1"], outputs=["result"], name=op_name
)
op_expect(
node,
inputs=[data_0, data_1],
outputs=[result],
op_type=op_type,
op_name=op_name,
)
def test_min():
op_name, op_type = "test_min_example", "Min"
data_0 = np.array([3, 2, 1]).astype(np.float32)
data_1 = np.array([1, 4, 4]).astype(np.float32)
data_2 = np.array([2, 5, 0]).astype(np.float32)
result = np.array([1, 2, 0]).astype(np.float32)
node = onnx.helper.make_node(
"Min", inputs=["data_0", "data_1", "data_2"], outputs=["result"], name=op_name
)
op_expect(
node,
inputs=[data_0, data_1, data_2],
outputs=[result],
op_type=op_type,
op_name=op_name,
)
op_name = "test_min_two_inputs"
result = np.minimum(data_0, data_1)
node = onnx.helper.make_node(
"Min", inputs=["data_0", "data_1"], outputs=["result"], name=op_name
)
op_expect(
node,
inputs=[data_0, data_1],
outputs=[result],
op_type=op_type,
op_name=op_name,
)
def test_mul():
op_name, op_type = "test_mul_example", "Mul"
node = onnx.helper.make_node("Mul", inputs=["x", "y"], outputs=["z"], name=op_name)
x = np.array([1, 2, 3]).astype(np.float32)
y = np.array([4, 5, 6]).astype(np.float32)
z = x * y # expected output [4., 10., 18.]
op_expect(node, inputs=[x, y], outputs=[z], op_type=op_type, op_name=op_name)
op_name = "test_mul"
node = onnx.helper.make_node("Mul", inputs=["x", "y"], outputs=["z"], name=op_name)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.random.randn(3, 4, 5).astype(np.float32)
z = x * y
op_expect(node, inputs=[x, y], outputs=[z], op_type=op_type, op_name=op_name)
op_name = "test_mul_bcast"
node = onnx.helper.make_node("Mul", inputs=["x", "y"], outputs=["z"], name=op_name)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.random.randn(5).astype(np.float32)
z = x * y
op_expect(node, inputs=[x, y], outputs=[z], op_type=op_type, op_name=op_name)
def test_neg():
op_name, op_type = "test_neg_example", "Neg"
node = onnx.helper.make_node("Neg", inputs=["x"], outputs=["y"], name=op_name)
x = np.array([-4, 2]).astype(np.float32)
y = np.negative(x) # expected output [4., -2.],
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "test_neg"
node = onnx.helper.make_node("Neg", inputs=["x"], outputs=["y"], name=op_name)
x = np.random.randn(3, 4, 5).astype(np.float32)
y = np.negative(x)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_negativeloglikelihoodloss():
op_name, op_type = "test_nllloss_NC", "NegativeLogLikelihoodLoss"
reduction = "none"
node = onnx.helper.make_node(
"NegativeLogLikelihoodLoss",
inputs=["input", "target"],
outputs=["loss"],
reduction=reduction,
name=op_name,
)
#NOCC:invalid-name(其他:onnx example)
N, C = 3, 5
np.random.seed(0)
input = np.random.rand(N, C).astype(np.float32)
target = np.random.randint(0, high=C, size=(N,)).astype(np.int64)
from onnx.backend.test.case.node.negativeloglikelihoodloss import (
compute_negative_log_likelihood_loss,
)
negative_log_likelihood_loss = compute_negative_log_likelihood_loss(
input, target, weight=None, reduction=reduction
)
op_expect(
node,
inputs=[input, target],
outputs=[negative_log_likelihood_loss],
op_type=op_type,
op_name=op_name,
)
def test_prelu():
op_name, op_type = "test_prelu_example", "PRelu"
node = onnx.helper.make_node(
"PRelu", inputs=["x", "slope"], outputs=["y"], name=op_name
)
x = np.random.randn(3, 4, 5).astype(np.float32)
slope = np.random.randn(3, 4, 5).astype(np.float32)
y = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * slope
op_expect(node, inputs=[x, slope], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "test_prelu_broadcast"
node = onnx.helper.make_node(
"PRelu", inputs=["x", "slope"], outputs=["y"], name=op_name
)
x = np.random.randn(3, 4, 5).astype(np.float32)
slope = np.random.randn(5).astype(np.float32)
y = np.clip(x, 0, np.inf) + np.clip(x, -np.inf, 0) * slope
op_expect(node, inputs=[x, slope], outputs=[y], op_type=op_type, op_name=op_name)
def test_pow():
op_name, op_type = "test_pow_example", "Pow"
node = onnx.helper.make_node("Pow", inputs=["x", "y"], outputs=["z"], name=op_name)
x = np.array([1, 2, 3]).astype(np.float32)
y = np.array([4, 5, 6]).astype(np.float32)
z = pow(x, y) # expected output [1., 32., 729.]
op_expect(node, inputs=[x, y], outputs=[z], op_type=op_type, op_name=op_name)
op_name = "test_pow"
node = onnx.helper.make_node("Pow", inputs=["x", "y"], outputs=["z"], name=op_name)
x = np.arange(60).reshape(3, 4, 5).astype(np.float32)
y = np.random.randn(3, 4, 5).astype(np.float32)
z = pow(x, y)
op_expect(node, inputs=[x, y], outputs=[z], op_type=op_type, op_name=op_name)
op_name = "test_pow_bcast_scalar"
node = onnx.helper.make_node("Pow", inputs=["x", "y"], outputs=["z"], name=op_name)
x = np.array([1, 2, 3]).astype(np.float32)
y = np.array([2]).astype(np.float32)
z = pow(x, y) # expected output [1., 4., 9.]
op_expect(node, inputs=[x, y], outputs=[z], op_type=op_type, op_name=op_name)
op_name = "test_pow_bcast_array"
node = onnx.helper.make_node("Pow", inputs=["x", "y"], outputs=["z"], name=op_name)
x = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32)
y = np.array([[1, 2, 3]]).astype(np.float32)
# expected output [[1, 4, 27], [4, 25, 216]]
z = pow(x, y)
op_expect(node, inputs=[x, y], outputs=[z], op_type=op_type, op_name=op_name)
def test_reciprocal():
op_name, op_type = "test_reciprocal_example", "Reciprocal"
node = onnx.helper.make_node(
"Reciprocal", inputs=["x"], outputs=["y"], name=op_name
)
x = np.array([-4, 2]).astype(np.float32)
y = np.reciprocal(x) # expected output [-0.25, 0.5],
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
op_name = "test_reciprocal"
node = onnx.helper.make_node(
"Reciprocal", inputs=["x"], outputs=["y"], name=op_name
)
x = np.random.rand(3, 4, 5).astype(np.float32) + 0.5
y = np.reciprocal(x)
op_expect(node, inputs=[x], outputs=[y], op_type=op_type, op_name=op_name)
def test_reducel1():
op_name, op_type = "test_reduce_l1_default_axes_keepdims_example", "ReduceL1"
shape = [3, 2, 2]
axes = None
keepdims = 1
node = onnx.helper.make_node(
"ReduceL1",
inputs=["data"],
outputs=["reduced"],
keepdims=keepdims,
name=op_name,
)
data = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)
# print(data)
# [[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]
reduced = np.sum(a=np.abs(data), axis=axes, keepdims=keepdims == 1)
# print(reduced)
# [[[78.]]]
op_expect(node, inputs=[data], outputs=[reduced], op_type=op_type, op_name=op_name)
np.random.seed(0)
data = np.random.uniform(-10, 10, shape).astype(np.float32)
reduced = np.sum(a=np.abs(data), axis=axes, keepdims=keepdims == 1)
op_name = "test_reduce_l1_default_axes_keepdims_random"
node = onnx.helper.make_node(
"ReduceL1",
inputs=["data"],
outputs=["reduced"],
keepdims=keepdims,
name=op_name,
)
op_expect(node, inputs=[data], outputs=[reduced], op_type=op_type, op_name=op_name)
def test_reducel2():
op_name, op_type = "test_reduce_l2_default_axes_keepdims_example", "ReduceL2"
shape = [3, 2, 2]
axes = None
keepdims = 1
node = onnx.helper.make_node(
"ReduceL2",
inputs=["data"],
outputs=["reduced"],
keepdims=keepdims,
name=op_name,
)
data = np.reshape(np.arange(1, np.prod(shape) + 1, dtype=np.float32), shape)
# print(data)
# [[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]], [[9., 10.], [11., 12.]]]
reduced = np.sqrt(np.sum(a=np.square(data), axis=axes, keepdims=keepdims == 1))
# print(reduced)
# [[[25.49509757]]]
op_expect(node, inputs=[data], outputs=[reduced], op_type=op_type, op_name=op_name)
op_name = "test_reduce_l2_default_axes_keepdims_random"
np.random.seed(0)
data = np.random.uniform(-10, 10, shape).astype(np.float32)
reduced = np.sqrt(np.sum(a=np.square(data), axis=axes, keepdims=keepdims == 1))
node = onnx.helper.make_node(
"ReduceL2",
inputs=["data"],
outputs=["reduced"],
keepdims=keepdims,
name=op_name,
)
op_expect(node, inputs=[data], outputs=[reduced], op_type=op_type, op_name=op_name)
def test_reducelogsum():
op_name, op_type = "test_reduce_log_sum_default", "ReduceLogSum"
node = onnx.helper.make_node(
"ReduceLogSum", inputs=["data"], outputs=["reduced"], name=op_name
)
data = np.random.ranf([3, 4, 5]).astype(np.float32)
reduced = np.log(np.sum(data, keepdims=True))
op_expect(node, inputs=[data], outputs=[reduced], op_type=op_type, op_name=op_name)
op_name = "test_reduce_log_sum_negative_axes"
node = onnx.helper.make_node(
"ReduceLogSum", inputs=["data"], outputs=["reduced"], axes=[-2], name=op_name
)
data = np.random.ranf([3, 4, 5]).astype(np.float32)
reduced = np.log(np.sum(data, axis=(-2), keepdims=True))
# print(reduced)
op_expect(node, inputs=[data], outputs=[reduced], op_type=op_type, op_name=op_name)
op_name = "test_reduce_log_sum_desc_axes"
node = onnx.helper.make_node(
"ReduceLogSum",
inputs=["data"],
outputs=["reduced"],
axes=[2, 1],
keepdims=0,
name=op_name,
)
data = np.random.ranf([3, 4, 5]).astype(np.float32)
reduced = np.log(np.sum(data, axis=(2, 1), keepdims=False))
op_expect(node, inputs=[data], outputs=[reduced], op_type=op_type, op_name=op_name)
op_name = "test_reduce_log_sum_asc_axes"
node = onnx.helper.make_node(
"ReduceLogSum",
inputs=["data"],
outputs=["reduced"],
axes=[0, 1],
keepdims=0,
name=op_name,
)
data = np.random.ranf([3, 4, 5]).astype(np.float32)
reduced = np.log(np.sum(data, axis=(0, 1), keepdims=False))
op_expect(node, inputs=[data], outputs=[reduced], op_type=op_type, op_name=op_name)
def test_reducelogsumexp():
op_name, op_type = (
"test_reduce_log_sum_exp_default_axes_keepdims_example",
"ReduceLogSumExp",
)
shape = [3, 2, 2]
axes = None
keepdims = 1
node = onnx.helper.make_node(
"ReduceLogSumExp",
inputs=["data"],
outputs=["reduced"],
keepdims=keepdims,
name=op_name,
)
data = np.array(
[[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32
)
reduced = np.log(np.sum(np.exp(data), axis=axes, keepdims=keepdims == 1))
# print(reduced)
# [[[60.00671387]]]
op_expect(node, inputs=[data], outputs=[reduced], op_type=op_type, op_name=op_name)
op_name = "test_reduce_log_sum_exp_default_axes_keepdims_random"
node = onnx.helper.make_node(
"ReduceLogSumExp",
inputs=["data"],
outputs=["reduced"],
keepdims=keepdims,
name=op_name,
)
np.random.seed(0)
data = np.random.uniform(-10, 10, shape).astype(np.float32)
reduced = np.log(np.sum(np.exp(data), axis=axes, keepdims=keepdims == 1))
op_expect(node, inputs=[data], outputs=[reduced], op_type=op_type, op_name=op_name)
def test_reducemax():
op_name, op_type = "test_reduce_max_default_axes_keepdim_example", "ReduceMax"
shape = [3, 2, 2]
axes = None
keepdims = 1
node = onnx.helper.make_node(
"ReduceMax",
inputs=["data"],
outputs=["reduced"],
keepdims=keepdims,
name=op_name,
)
data = np.array(
[[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32
)
reduced = np.maximum.reduce(data, axis=axes, keepdims=keepdims == 1)
# print(reduced)
# [[[60.]]]
op_expect(node, inputs=[data], outputs=[reduced], op_type=op_type, op_name=op_name)
op_name = "test_reduce_max_default_axes_keepdims_random"
node = onnx.helper.make_node(
"ReduceMax",
inputs=["data"],
outputs=["reduced"],
keepdims=keepdims,
name=op_name,
)
np.random.seed(0)
data = np.random.uniform(-10, 10, shape).astype(np.float32)
reduced = np.maximum.reduce(data, axis=axes, keepdims=keepdims == 1)
op_expect(node, inputs=[data], outputs=[reduced], op_type=op_type, op_name=op_name)
def test_reducemean():
op_name, op_type = "test_reduce_mean_default_axes_keepdims_example", "ReduceMean"
shape = [3, 2, 2]
axes = None
keepdims = 1
node = onnx.helper.make_node(
"ReduceMean",
inputs=["data"],
outputs=["reduced"],
keepdims=keepdims,
name=op_name,
)
data = np.array(
[[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32
)
reduced = np.mean(data, axis=axes, keepdims=keepdims == 1)
# print(reduced)
# [[[18.25]]]
op_expect(node, inputs=[data], outputs=[reduced], op_type=op_type, op_name=op_name)
op_name = "test_reduce_mean_default_axes_keepdims_random"
node = onnx.helper.make_node(
"ReduceMean",
inputs=["data"],
outputs=["reduced"],
keepdims=keepdims,
name=op_name,
)
np.random.seed(0)
data = np.random.uniform(-10, 10, shape).astype(np.float32)
reduced = np.mean(data, axis=axes, keepdims=keepdims == 1)
op_expect(node, inputs=[data], outputs=[reduced], op_type=op_type, op_name=op_name)
def test_reducesum():
batch_size = 32
op_name = "reduce_sum_1"
with tf.Graph().as_default():
input_ph = tf.placeholder(
dtype=tf.float32, shape=[batch_size, 256], name="input"
) # [batchsize, 10]
input_data = np.random.rand(batch_size, 256).astype(np.float32)
x = tf.math.reduce_sum(input_ph, axis=1, name=op_name)
_ = tf.identity(x, name="output")
verify_tf_with_trt_result(
[input_data], ["input:0"], ["output:0"], op_name=op_name
)
def test_maxunpool():
def verify_maxunpool(
data, indices, kernel_shape, strides, output_shape=None, pads=None, op_name=None
):
input_names = ["xT", "xI"]
input_info = [
helper.make_tensor_value_info("xT", TensorProto.FLOAT, list(data.shape)),
helper.make_tensor_value_info("xI", TensorProto.INT64, list(indices.shape)),
]
input_values = [data, indices]
# input_values = [data ]
if output_shape is not None:
input_names.append("output_shape")
input_info.append(
helper.make_tensor_value_info(
"output_shape", TensorProto.INT64, list(output_shape.shape)
)
)
input_values.append(output_shape)
else:
# Compute expected output shape
output_shape = np.asarray(([1, 1] + list(strides))) * np.asarray(
list(data.shape)
)
output_shape += np.asarray(([0, 0] + list(kernel_shape))) - np.asarray(
([0, 0] + list(strides))
)
if pads is not None:
output_shape -= np.asarray(
[0, 0] + list(np.sum(np.reshape(list(pads), [-1, 2]), axis=-1))
)
output_shape = [int(i) for i in output_shape]
node = helper.make_node(
"MaxUnpool",
inputs=input_names,
outputs=["y"],
kernel_shape=kernel_shape,
name=op_name,
)
if pads is not None:
pad_attr = helper.make_attribute("pads", pads)
node.attribute.append(pad_attr)
if strides is not None:
strides_attr = helper.make_attribute("strides", strides)
node.attribute.append(strides_attr)
graph = helper.make_graph(
[node],
"maxunpool_test",
inputs=input_info,
outputs=[
helper.make_tensor_value_info("y", TensorProto.FLOAT, output_shape)
],
)
model = helper.make_model(graph, producer_name="size_test")
verify_with_ort_with_trt(model, input_values, op_name=op_name, opset=11)
#NOCC:invalid-name(其他:onnx example)
xT = np.array([[[[5, 6], [7, 8]]]], dtype=np.float32)
#NOCC:invalid-name(其他:onnx example)
xI = np.array([[[[0, 7], [13, 15]]]], dtype=np.int64)
verify_maxunpool(xT, xI, [2, 2], strides=[2, 2], op_name="max_unpool_1")
def _test_forward_one_hot(
indices_shape, depth, on_value, off_value, axis, out_dtype, op_name
):
inp_array1 = np.random.randint(0, 5, size=indices_shape)
with tf.Graph().as_default():
in1 = tf.placeholder(
shape=inp_array1.shape, dtype=inp_array1.dtype, name="input"
)
out = tf.one_hot(
in1, depth, on_value, off_value, axis, dtype=out_dtype, name=op_name
)
out = tf.identity(out, "output")
verify_tf_with_trt_result([inp_array1], ["input:0"], ["output:0"], op_name)
# compare_tf_with_tvm(inp_array1, in1.name, out.name)
def test_forward_one_hot():
_test_forward_one_hot((3,), 3, 1.0, 0.0, -1, "float32", "onehot_2")
def test_where():
op_name, op_type = "test_where", "Where"
node = onnx.helper.make_node(
"Where", inputs=["condition", "x", "y"], outputs=["z"], name=op_name
)
condition = np.array([[1, 0], [1, 1]], dtype=bool)
x = np.array([[1, 2], [3, 4]], dtype=np.float32)
y = np.array([[9, 8], [7, 6]], dtype=np.float32)
z = np.where(condition, x, y) # expected output [[1, 8], [3, 4]]
op_expect(
node, inputs=[condition, x, y], outputs=[z], op_type=op_type, op_name=op_name
)
def _test_slice_iteration_v1(indata, outdata, starts, ends, axes=None):
op_name = "slice_0"
if axes:
y = helper.make_node(
"Slice", ["in"], ["out"], axes=axes, starts=starts, ends=ends, name=op_name
)
else:
y = helper.make_node(
"Slice", ["in"], ["out"], starts=starts, ends=ends, name=op_name
)
graph = helper.make_graph(
[y],
"slice_test",
inputs=[
helper.make_tensor_value_info("in", TensorProto.FLOAT, list(indata.shape))
],
outputs=[
helper.make_tensor_value_info("out", TensorProto.FLOAT, list(outdata.shape))
],
)
model = helper.make_model(graph, producer_name="slice_test")
# verify_with_ort_with_trt(model, [indata], [outdata.shape], op_name=op_name, opset=1)
verify_with_ort_with_trt(model, [indata], op_name=op_name, opset=1)
def test_slice():
x = np.random.randn(20, 10, 5).astype(np.float32)
_test_slice_iteration_v1(x, x[0:3, 0:10], starts=(0, 0), ends=(3, 10), axes=(0, 1))
def verify_pad_v11(indata, pads, mode="constant", value=0.0):
op_name = "pad_001"
indata = np.array(indata).astype(np.float32)
# numpy expect result
len_dim = len(pads) // 2
np_pads = [(pads[i], pads[i + len_dim]) for i in range(len_dim)]
pads = np.array(pads)
# onnx graph
if mode in ["edge", "reflect"]:
inputs = [indata]
outdata = np.pad(indata, pad_width=np_pads, mode=mode)
node = helper.make_node(
"Pad", inputs=["input", "pads"], outputs=["output"], mode=mode, name=op_name
)
graph = helper.make_graph(
[node],
"pad_test",
inputs=[
helper.make_tensor_value_info(
"input", TensorProto.FLOAT, list(indata.shape)
),
helper.make_tensor_value_info("pads", TensorProto.INT64, (len(pads),)),
],
initializer=[
helper.make_tensor("pads", TensorProto.INT64, (len(pads),), pads)
],
outputs=[
helper.make_tensor_value_info(
"output", TensorProto.FLOAT, list(outdata.shape)
)
],
)
else:
inputs = [indata]
outdata = np.pad(
indata, pad_width=np_pads, mode="constant", constant_values=value
)
node = helper.make_node(
"Pad",
inputs=["input", "pads", "constant_value"],
outputs=["output"],
mode="constant",
name=op_name,
)
graph = helper.make_graph(
[node],
"pad_test",
inputs=[
helper.make_tensor_value_info(
"input", TensorProto.FLOAT, list(indata.shape)
),
helper.make_tensor_value_info("pads", TensorProto.INT64, (len(pads),)),
helper.make_tensor_value_info(
"constant_value", TensorProto.FLOAT, (1,)
),
],
initializer=[
helper.make_tensor("pads", TensorProto.INT64, (len(pads),), pads),
helper.make_tensor("constant_value", TensorProto.FLOAT, (1,), [value]),
],
outputs=[
helper.make_tensor_value_info(
"output", TensorProto.FLOAT, list(outdata.shape)
)
],
)
model = helper.make_model(graph, producer_name="pad_test")
verify_with_ort_with_trt(model, inputs, op_name, opset=11)
def test_pad():
verify_pad_v11(
np.random.randn(2, 2).astype(np.float32), [0, 1, 0, 0], "constant", 0.0
)
def test_batch_norm():
def verify_batch_norm(in_shape):
op_name = "batchNorm_{}".format(sum(in_shape))
batchnorm = onnx.helper.make_node(
"BatchNormalization",
inputs=["x", "scale", "B", "mean", "var"],
outputs=["Y"],
name=op_name,
)
graph = helper.make_graph(
[batchnorm],
"batchnorm_test",
inputs=[
helper.make_tensor_value_info("x", TensorProto.FLOAT, list(in_shape)),
helper.make_tensor_value_info(
"scale", TensorProto.FLOAT, [in_shape[1]]
),
helper.make_tensor_value_info("B", TensorProto.FLOAT, [in_shape[1]]),
helper.make_tensor_value_info("mean", TensorProto.FLOAT, [in_shape[1]]),
helper.make_tensor_value_info("var", TensorProto.FLOAT, [in_shape[1]]),
],
outputs=[
helper.make_tensor_value_info("Y", TensorProto.FLOAT, list(in_shape))
],
)
model = helper.make_model(graph, producer_name="batchnorm_test")
# X, scale, b, mean, var
inshapes = [in_shape, in_shape[1], in_shape[1], in_shape[1], in_shape[1]]
inputs = [
np.random.uniform(size=ishape).astype("float32") for ishape in inshapes
]
verify_with_ort_with_trt(model, inputs, op_name=op_name)
# verify_batch_norm([1, 3, 224, 224])
verify_batch_norm([1, 3, 24, 24])
# verify_batch_norm([16, 3, 24, 24])
# verify_batch_norm([16, 16, 24, 24])
# verify_batch_norm([16, 16, 10, 10])
def verify_softmax(inshape, axis, op_name):
indata = np.random.uniform(size=inshape).astype(np.float32)
outshape = inshape
y = helper.make_node("Softmax", ["in"], ["out"], name=op_name)
if axis is not None:
axis_attr = helper.make_attribute("axis", axis)
y.attribute.append(axis_attr)
graph = helper.make_graph(
[y],
"Softmax_test",
inputs=[
helper.make_tensor_value_info("in", TensorProto.FLOAT, list(indata.shape))
],
outputs=[
helper.make_tensor_value_info("out", TensorProto.FLOAT, list(outshape))
],
)
model = helper.make_model(graph, producer_name="Softmax_test")
verify_with_ort_with_trt(model, [indata], op_name=op_name)
def test_softmax():
verify_softmax((1, 10), None, op_name="softmax_0")
# verify_softmax((1, 10), 1, op_name='softmax_1')
def verify_mod(x_shape, y_shape, fmod, out_shape, dtype="float32", op_name=""):
x_np = np.random.uniform(-100.0, 100.0, x_shape).astype(dtype)
y_np = np.random.uniform(-100.0, 100.0, y_shape).astype(dtype)
y_np = np.where(y_np == 0, 1, y_np) # remove 0's to avoid division by zero error
mod_node = helper.make_node(
"Mod", inputs=["x", "y"], outputs=["z"], fmod=fmod, name=op_name
)
onnx_dtype = TensorProto.FLOAT if dtype == "float32" else TensorProto.INT32
graph = helper.make_graph(
[mod_node],
"mod_test",
inputs=[
helper.make_tensor_value_info("x", onnx_dtype, list(x_shape)),
helper.make_tensor_value_info("y", onnx_dtype, list(y_shape)),
],
outputs=[helper.make_tensor_value_info("z", onnx_dtype, list(out_shape))],
)
model = helper.make_model(graph, producer_name="mod_test")
# verify_with_ort_with_trt(model, [x_np, y_np], [out_shape], op_name=op_name)
verify_with_ort_with_trt(model, [x_np, y_np], op_name=op_name)
def test_mod():
# Mod
verify_mod(
x_shape=[1, 32, 32],
y_shape=[1, 1, 32],
fmod=0,
out_shape=(1, 32, 32),
dtype="int32",
op_name="tvm_mod",
)
def verify_mean(input_dim, op_name):
dtype = "float32"
a_np1 = np.random.uniform(size=input_dim).astype(dtype)
a_np2 = np.random.uniform(size=input_dim).astype(dtype)
a_np3 = np.random.uniform(size=input_dim).astype(dtype)
mean_node = helper.make_node(
"Mean", ["a_np1", "a_np2", "a_np3"], ["out"], name=op_name
)
graph = helper.make_graph(
[mean_node],
"Mean_test",
inputs=[
helper.make_tensor_value_info("a_np1", TensorProto.FLOAT, list(input_dim)),
helper.make_tensor_value_info("a_np2", TensorProto.FLOAT, list(input_dim)),
helper.make_tensor_value_info("a_np3", TensorProto.FLOAT, list(input_dim)),
],
outputs=[
helper.make_tensor_value_info("out", TensorProto.FLOAT, list(input_dim))
],
)
model = helper.make_model(graph, producer_name="Mean_test")
verify_with_ort_with_trt(model, [a_np1, a_np2, a_np3], op_name=op_name)
def test_forward_mean():
verify_mean((1, 3, 20, 20), op_name="mean_111")
verify_mean((20, 20), op_name="mean_222")
def verify_instance_norm(shape, axis=1, op_name="default"):
x = np.random.randn(*shape).astype(np.float32)
gamma = np.random.randn(shape[1]).astype(np.float32)
beta = np.random.randn(shape[1]).astype(np.float32)
epsilon = 1e-5
node = onnx.helper.make_node(
"InstanceNormalization",
inputs=["x", "gamma", "beta"],
outputs=["y"],
epsilon=epsilon,
name=op_name,
)
graph = helper.make_graph(
[node],
"instance_norm_test",
inputs=[
helper.make_tensor_value_info("x", TensorProto.FLOAT, list(shape)),
helper.make_tensor_value_info("gamma", TensorProto.FLOAT, (shape[1],)),
helper.make_tensor_value_info("beta", TensorProto.FLOAT, (shape[1],)),
],
outputs=[helper.make_tensor_value_info("y", TensorProto.FLOAT, list(shape))],
)
model = helper.make_model(graph, producer_name="instance_norm_test")
verify_with_ort_with_trt(model, [x, gamma, beta], op_name=op_name)
def test_instance_norm():
verify_instance_norm((2, 3, 4, 5), op_name="instance_norm")
# verify_instance_norm((32, 64, 80, 64))
# verify_instance_norm((8, 6, 5))
# verify_instance_norm((8, 7, 6, 5, 4))
def verify_lrn(shape, nsize, dtype, alpha=None, beta=None, bias=None, op_name=None):
in_array = np.random.uniform(size=shape).astype(dtype)
if alpha is None and beta is None and bias is None:
alpha = 0.0001
beta = 0.75
bias = 1.0
node = onnx.helper.make_node(
"LRN", inputs=["in"], outputs=["out"], size=nsize, name=op_name
)
else:
node = onnx.helper.make_node(
"LRN",
inputs=["in"],
outputs=["out"],
alpha=alpha,
beta=beta,
bias=bias,
size=nsize,
name=op_name,
)
graph = helper.make_graph(
[node],
"lrn_test",
inputs=[helper.make_tensor_value_info("in", TensorProto.FLOAT, list(shape))],
outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(shape))],
)
model = helper.make_model(graph, producer_name="lrn_test")
verify_with_ort_with_trt(model, [in_array], op_name=op_name)
def test_lrn():
verify_lrn((5, 5, 5, 5), 3, "float32", op_name="test_lrn_1")
verify_lrn(
(5, 5, 5, 5),
3,
"float32",
alpha=0.0002,
beta=0.5,
bias=2.0,
op_name="test_lrn_2",
)
def test_lstm():
# # Different activation testing.
# # Default value hardsigmoid.
verify_rnn(
seq_length=2,
batch_size=1,
input_size=16,
hidden_size=32,
use_bias=False,
activations=["HardSigmoid", "Tanh", "Tanh"],
rnn_type="LSTM",
op_name="test_lstm_without_bias",
)
# # Multiple parameterized activations.
# verify_rnn(
# seq_length=2,
# batch_size=1,
# input_size=16,
# hidden_size=32,
# use_bias=False,
# activations=["HardSigmoid", "LeakyRelu", "Tanh"],
# alphas=[2.0, 0.5],
# betas=[0.3],
# rnn_type="LSTM",
# )
# # All parameterized with new Affine activation.
# verify_rnn(
# seq_length=2,
# batch_size=1,
# input_size=16,
# hidden_size=32,
# use_bias=False,
# activations=["HardSigmoid", "LeakyRelu", "Affine"],
# alphas=[2.0, 0.5, 0.8],
# betas=[0.3, 0.1],
# rnn_type="LSTM",
# )
# # Testing with initial state and peepholes
# verify_rnn(
# seq_length=2,
# batch_size=1,
# input_size=16,
# hidden_size=32,
# use_bias=True,
# use_initial_state=True,
# rnn_type="LSTM",
# )
# verify_rnn(
# seq_length=2,
# batch_size=1,
# input_size=16,
# hidden_size=32,
# use_bias=True,
# use_initial_state=True,
# use_peep=True,
# rnn_type="LSTM",
# )
def test_binary_ops():
in_shape = (1, 2, 3, 3)
dtype = "float32"
out_shape = in_shape
def verify_binary_ops(op, x, y, out_type="float32", op_name=None):
z = helper.make_node(op, ["in1", "in2"], ["out"], name=op_name)
graph = helper.make_graph(
[z],
"_test",
inputs=[
helper.make_tensor_value_info("in1", TensorProto.FLOAT, x.shape),
helper.make_tensor_value_info("in2", TensorProto.FLOAT, y.shape),
],
outputs=[
helper.make_tensor_value_info(
"out",
mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(out_type)],
list(out_shape),
)
],
)
model = helper.make_model(graph, producer_name="_test")
verify_with_ort_with_trt(model, [x, y], op_name=op_name)
x = np.random.uniform(size=in_shape).astype(dtype)
y = np.random.uniform(size=in_shape).astype(dtype)
z = np.random.uniform(size=(3,)).astype(dtype)
verify_binary_ops("Sub", x, y, op_name="sub_1")
verify_binary_ops("Sub", x, z, op_name="sub_2")
def test_gru():
# No bias.
verify_rnn(
seq_length=2,
batch_size=1,
input_size=16,
hidden_size=32,
use_bias=False,
rnn_type="GRU",
op_name="test_gru_without_bias",
)
def verify_reduce_func(func, data, axis, keepdims, op_name=None):
inshape = data.shape
outshape = np.sum(data, axis=axis, keepdims=keepdims == 1).shape
if axis:
node = onnx.helper.make_node(
func,
inputs=["x"],
outputs=["y"],
axes=axis,
keepdims=keepdims,
name=op_name,
)
else:
node = onnx.helper.make_node(
func, inputs=["x"], outputs=["y"], keepdims=keepdims, name=op_name
)
graph = helper.make_graph(
[node],
"reduce_test",
inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(inshape))],
outputs=[helper.make_tensor_value_info("y", TensorProto.FLOAT, list(outshape))],
)
model = helper.make_model(graph, producer_name="reduce_test")
verify_with_ort_with_trt(model, [data], opset=11, op_name=op_name)
def test_all_reduce_funcs():
funcs = [
# "ReduceMax",
# "ReduceMean",
# "ReduceMin",
# "ReduceProd",
# "ReduceSum",
"ReduceSumSquare",
"ReduceLogSum",
"ReduceLogSumExp",
"ReduceL1",
"ReduceL2",
]
for func in funcs:
for keepdims in [True, False]:
verify_reduce_func(
func,
np.random.randn(3, 2, 2).astype(np.float32),
axis=None,
keepdims=keepdims,
op_name=func + str(int(keepdims)) + "1",
)
verify_reduce_func(
func,
np.random.randn(3, 2, 3).astype(np.float32),
axis=None,
keepdims=keepdims,
op_name=func + str(int(keepdims)) + "2",
)
verify_reduce_func(
func,
np.random.randn(3, 3, 3).astype(np.float32),
axis=(1,),
keepdims=keepdims,
op_name=func + str(int(keepdims)) + "3",
)
verify_reduce_func(
func,
np.random.randn(3, 3, 3, 1).astype(np.float32),
axis=(1, 2),
keepdims=keepdims,
op_name=func + str(int(keepdims)) + "4",
)
verify_reduce_func(
func,
np.random.randn(3, 3, 3, 1).astype(np.float32),
axis=(1,),
keepdims=keepdims,
op_name=func + str(int(keepdims)) + "5",
)
verify_reduce_func(
func,
np.random.randn(1, 3, 4, 1).astype(np.float32),
axis=(1,),
keepdims=keepdims,
op_name=func + str(int(keepdims)) + "6",
)
def test_roi_align():
def verify_roi_align(
input_dims,
num_roi,
output_height,
output_width,
sampling_ratio=0,
spatial_scale=1.0,
mode="avg",
op_name=None,
):
output_dims = [num_roi, input_dims[1], output_height, output_width]
node = helper.make_node(
"RoiAlign",
inputs=["X", "rois", "batch_indicies"],
outputs=["Y"],
mode=mode,
output_height=output_height,
output_width=output_width,
sampling_ratio=sampling_ratio,
spatial_scale=spatial_scale,
name=op_name,
)
graph = helper.make_graph(
[node],
"roialign_test",
inputs=[
helper.make_tensor_value_info("X", TensorProto.FLOAT, list(input_dims)),
helper.make_tensor_value_info("rois", TensorProto.FLOAT, [num_roi, 4]),
helper.make_tensor_value_info(
"batch_indicies",
TensorProto.INT64,
[
num_roi,
],
),
],
outputs=[
helper.make_tensor_value_info("Y", TensorProto.FLOAT, output_dims)
],
)
model = helper.make_model(graph, producer_name="roialign_test")
np_data = np.random.uniform(size=input_dims).astype("float32")
np_rois = np.random.uniform(size=[num_roi, 4]).astype("float32") * input_dims[2]
np_batch_indicies = np.random.randint(low=0, high=input_dims[0], size=num_roi)
verify_with_ort_with_trt(
model, [np_data, np_rois, np_batch_indicies], op_name=op_name
)
verify_roi_align(
(1, 4, 16, 16), 32, 7, 7, sampling_ratio=0, spatial_scale=1.0, op_name="roi1"
)
verify_roi_align(
(4, 4, 16, 32), 32, 7, 7, sampling_ratio=0, spatial_scale=1.0, op_name="roi2"
)
verify_roi_align(
(1, 8, 16, 16), 32, 7, 7, sampling_ratio=0, spatial_scale=1.0, op_name="roi3"
)
verify_roi_align(
(1, 4, 8, 8), 32, 7, 7, sampling_ratio=0, spatial_scale=1.0, op_name="roi4"
)
verify_roi_align(
(1, 4, 16, 16), 16, 5, 7, sampling_ratio=0, spatial_scale=1.0, op_name="roi5"
)
verify_roi_align(
(1, 4, 16, 12), 8, 7, 3, sampling_ratio=0, spatial_scale=1.0, op_name="roi6"
)
verify_roi_align(
(1, 4, 16, 16), 32, 7, 7, sampling_ratio=0, spatial_scale=0.5, op_name="roi7"
)
verify_roi_align(
(3, 4, 12, 16), 32, 7, 7, sampling_ratio=0, spatial_scale=1.5, op_name="roi8"
)
verify_roi_align(
(5, 4, 16, 14), 32, 7, 7, sampling_ratio=1, spatial_scale=1.0, op_name="roi9"
)
verify_roi_align(
(1, 4, 16, 16), 32, 7, 7, sampling_ratio=2, spatial_scale=1.0, op_name="roi10"
)
# ONNX implementation of roi_align with max mode is incorrect, so we don't compare outputs here.
def verify_split(
indata, outdatas, split, axis=0, pass_split=True, opset=11, op_name=None
):
indata = np.array(indata).astype(np.float32)
outdatas = [np.array(o).astype(np.float32) for o in outdatas]
inputs = [
helper.make_tensor_value_info("input", TensorProto.FLOAT, list(indata.shape))
]
input_names = ["input"]
initializer = []
if split:
split_index = range(len(split))
else:
split_index = range(len(outdatas))
if pass_split:
if opset >= 13:
input_names.append("split")
np_split = np.array(split).astype(np.int64)
inputs.append(
helper.make_tensor_value_info(
"split", TensorProto.INT64, list(np_split.shape)
)
)
indata = [indata, np_split]
initializer.append(
helper.make_tensor(
"split", TensorProto.INT64, list(np_split.shape), np_split
)
)
node = helper.make_node(
"Split",
inputs=input_names,
outputs=["output_{}".format(i) for i in range(len(split_index))],
axis=axis,
name=op_name,
)
if pass_split and opset < 13:
split_attr = helper.make_attribute("split", split)
node.attribute.append(split_attr)
graph = helper.make_graph(
[node],
"split_test",
inputs=inputs,
initializer=initializer,
outputs=[
helper.make_tensor_value_info(
"output_{}".format(i), TensorProto.FLOAT, list(outdatas[i].shape)
)
for i in range(len(split_index))
],
)
model = helper.make_model(graph, producer_name="split_test")
verify_with_ort_with_trt(model, indata, opset=opset, op_name=op_name)
def test_split():
# 1D
verify_split(
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],
[2, 2, 2],
0,
op_name="split_1",
)
verify_split(
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],
[2, 2, 2],
0,
False,
op_name="split_2",
)
# 2D
verify_split(
[[1.0, 2.0, 3.0, 4.0], [7.0, 8.0, 9.0, 10.0]],
[[[1.0, 2.0], [7.0, 8.0]], [[3.0, 4.0], [9.0, 10.0]]],
[2, 2],
1,
op_name="split_4",
)
# Split evenly (unstack)
verify_split([1, 2, 3], [[1], [2], [3]], False, 0, False, op_name="split_5")
# Split a single value to a single value
verify_split([1], [[1]], [1], pass_split=True, op_name="split_6")
def verify_xor(x_shape, y_shape, op_name=None):
x_np = np.random.choice(a=[False, True], size=x_shape).astype("bool")
y_np = np.random.choice(a=[False, True], size=y_shape).astype("bool")
np_out = np.logical_xor(x_np, y_np)
out_shape = np_out.shape
xor_node = helper.make_node("Xor", inputs=["x", "y"], outputs=["z"], name=op_name)
onnx_dtype = TensorProto.BOOL
graph = helper.make_graph(
[xor_node],
"xor_test",
inputs=[
helper.make_tensor_value_info("x", onnx_dtype, list(x_shape)),
helper.make_tensor_value_info("y", onnx_dtype, list(y_shape)),
],
outputs=[helper.make_tensor_value_info("z", onnx_dtype, list(out_shape))],
)
model = helper.make_model(graph, producer_name="xor_test")
verify_with_ort_with_trt(model, [x_np, y_np], op_name=op_name)
def test_xor():
# XOR
verify_xor(x_shape=[1, 32, 32], y_shape=[1, 32, 32], op_name="test_xor_1")
# Xor broadcast
verify_xor(x_shape=[1, 32, 32], y_shape=[1, 1, 32], op_name="test_xor_2")
def verify_if(cond_array, op_name):
# Given a bool scalar input cond.
# return constant tensor x if cond is True, otherwise return constant tensor y.
then_out = onnx.helper.make_tensor_value_info(
"then_out", onnx.TensorProto.FLOAT, [5]
)
else_out = onnx.helper.make_tensor_value_info(
"else_out", onnx.TensorProto.FLOAT, [5]
)
x = np.array([1, 2, 3, 4, 5]).astype(np.float32)
y = np.array([5, 4, 3, 2, 1]).astype(np.float32)
then_const_node = onnx.helper.make_node(
"Constant", inputs=[], outputs=["then_out"], value=numpy_helper.from_array(x)
)
else_const_node = onnx.helper.make_node(
"Constant", inputs=[], outputs=["else_out"], value=numpy_helper.from_array(y)
)
then_body = onnx.helper.make_graph([then_const_node], "then_body", [], [then_out])
else_body = onnx.helper.make_graph([else_const_node], "else_body", [], [else_out])
if_node = onnx.helper.make_node(
"If",
inputs=["cond"],
outputs=["res"],
then_branch=then_body,
else_branch=else_body,
name=op_name,
)
if_graph = onnx.helper.make_graph(
[if_node],
"if_outer",
inputs=[
onnx.helper.make_tensor_value_info("cond", onnx.TensorProto.BOOL, []),
],
outputs=[
onnx.helper.make_tensor_value_info("res", onnx.TensorProto.FLOAT, [5]),
],
)
if_model = onnx.helper.make_model(if_graph)
if cond_array:
cond = np.array([1]).astype("bool")
else:
cond = np.array(1).astype("bool")
verify_with_ort_with_trt(if_model, [cond], op_name=op_name)
def test_if():
# Confirm that if works with cond as an array or scalar.
verify_if(cond_array=False, op_name="if_test_1")
verify_if(cond_array=True, op_name="if_test_2")
def test_softmax_cross_entropyloss():
op_name = "test_SoftmaxCrossEntropyLoss"
reduction = "mean"
ignore_index = np.int64(-1)
node = onnx.helper.make_node(
"SoftmaxCrossEntropyLoss",
inputs=["x", "y", "w"],
outputs=["z"],
reduction=reduction,
ignore_index=ignore_index,
name=op_name,
)
#NOCC:invalid-name(其他:onnx example)
N, C, dim1 = 3, 5, 6
| np.random.seed(0) | numpy.random.seed |
import os
import sys
import glob
import numpy as np
import matplotlib.pyplot as plt
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
from . import stabilization
class SelectPoles:
def __init__(self, Model):
"""
Plot the measured Frequency Response Functions and computed poles.
Picking the poles is done with pressing the SHIFT key + left mouse button.
To unselect last pole: SHIFT + right mouse button.
To unselect closest pole: SHIFT + middle mouse button.
For more information check the HELP menu tab in the chart window.
param model: object of pyEMA.Model
"""
self.Model = Model
self.shift_is_held = False
self.chart_type = 0 # 0 - stability chart, 1 - cluster diagram
self.show_legend = 0
self.frf_plot_type = 'abs'
self.Model.nat_freq = []
self.Model.nat_xi = []
self.Model.pole_ind = []
self.root = tk.Tk()
self.root.title('Stability Chart')
self.fig = Figure(figsize=(20, 8))
# Create axes
self.ax2 = self.fig.add_subplot(111)
self.ax1 = self.ax2.twinx()
self.ax1.grid(True)
# Tkinter menu
menubar = tk.Menu(self.root)
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label='Save figure', command=self.save_this_figure)
menubar.add_cascade(label='File', menu=filemenu)
chartmenu = tk.Menu(menubar, tearoff=0)
chartmenu.add_command(label='Stability chart', command=lambda: self.toggle_chart_type(0))
chartmenu.add_command(label='Cluster diagram', command=lambda: self.toggle_chart_type(1))
menubar.add_cascade(label="Chart type", menu=chartmenu)
mifmenu = tk.Menu(menubar, tearoff=0)
mifmenu.add_command(label='Plot mean abs', command=lambda: self.toggle_mif_frf('abs'))
mifmenu.add_command(label='Plot all FRFs', command=lambda: self.toggle_mif_frf('all'))
menubar.add_cascade(label="FRF plot type", menu=mifmenu)
legendmenu = tk.Menu(menubar, tearoff=0)
legendmenu.add_command(label='Show legend', command=lambda: self.toggle_legend(1))
legendmenu.add_command(label='Hide legend', command=lambda: self.toggle_legend(0))
menubar.add_cascade(label="Legend", menu=legendmenu)
helpmenu = tk.Menu(menubar, tearoff=0)
helpmenu.add_command(label='Help', command=self.show_help)
menubar.add_cascade(label='Help', menu=helpmenu)
self.root.config(menu=menubar)
# Program execution
self.plot_frf(initial=True)
self.get_stability()
self.plot_stability()
# Integrate matplotib figure
canvas = FigureCanvasTkAgg(self.fig, self.root)
canvas.get_tk_widget().pack(side='top', fill='both', expand=1)
NavigationToolbar2Tk(canvas, self.root)
# Connecting functions to event manager
self.fig.canvas.mpl_connect('key_press_event', lambda x: self.on_key_press(x))
self.fig.canvas.mpl_connect('key_release_event', lambda x: self.on_key_release(x))
self.fig.canvas.mpl_connect('button_press_event', lambda x: self.on_click(x))
self.root.protocol("WM_DELETE_WINDOW", lambda: self.on_closing())
tk.Button(self.root, text="Quit", command=self.__quit).pack()
self.root.mainloop()
def plot_frf(self, initial=False):
"""Reconstruct and plot the Frequency Response Function.
This is done on the fly.
:param initial: if True, the frf is not computed, only the measured
FRFs are shown.
"""
self.ax2.clear()
if self.frf_plot_type == 'abs':
self.ax2.semilogy(self.Model.freq, np.average(
np.abs(self.Model.frf), axis=0), alpha=0.7, color='k')
elif self.frf_plot_type == 'all':
self.ax2.semilogy(self.Model.freq, np.abs(self.Model.frf.T), alpha=0.3, color='k')
if not initial and len(self.Model.nat_freq) > 0:
self.H, self.A = self.Model.get_constants(whose_poles='own', FRF_ind='all', least_squares_type='new')
if self.frf_plot_type == 'abs':
self.ax2.semilogy(self.Model.freq, np.average(
np.abs(self.H), axis=0), color='r', lw=2)
elif self.frf_plot_type == 'all':
self.ax2.semilogy(self.Model.freq, np.abs(self.H.T), color='r', lw=1)
else:
x_position = (self.Model.lower + self.Model.upper) / 2
y_position = np.max(np.abs(self.Model.frf))
message = [
'Select a pole: SHIFT + LEFT mouse button',
'Deselect a pole: SHIFT + RIGHT mouse button'
]
self.ax2.text(x_position, y_position, '\n'.join(message),
fontsize=12, verticalalignment='top', horizontalalignment='center',
bbox=dict(facecolor='lightgreen', edgecolor='lightgreen'))
self.ax1.set_xlim([self.Model.lower, self.Model.upper])
self.fig.canvas.draw()
def get_stability(self, fn_temp=0.001, xi_temp=0.05):
"""Get the stability matrix.
:param fn_temp: Natural frequency stability crieterion.
:param xi_temp: Damping stability criterion.
"""
Nmax = self.Model.pol_order_high
self.fn_temp, self.xi_temp, self.test_fn, self.test_xi = stabilization._stabilization(
self.Model.all_poles, Nmax, err_fn=fn_temp, err_xi=xi_temp)
def plot_stability(self, update_ticks=False):
if not update_ticks:
self.ax1.clear()
self.ax1.grid(True)
# stable eigenfrequencues, unstable damping ratios
a = np.argwhere((self.test_fn > 0) & ((self.test_xi == 0) | (self.xi_temp <= 0)))
# stable eigenfrequencies, stable damping ratios
b = np.argwhere((self.test_fn > 0) & ((self.test_xi > 0) & (self.xi_temp > 0)))
# unstable eigenfrequencues, unstable damping ratios
c = np.argwhere((self.test_fn == 0) & ((self.test_xi == 0) | (self.xi_temp <= 0)))
# unstable eigenfrequencues, stable damping ratios
d = np.argwhere((self.test_fn == 0) & ((self.test_xi > 0) & (self.xi_temp > 0)))
p1 = self.ax1.plot(self.fn_temp[a[:, 0], a[:, 1]], 1+a[:, 1], 'bx',
markersize=4, label="stable frequency, unstable damping")
p2 = self.ax1.plot(self.fn_temp[b[:, 0], b[:, 1]], 1+b[:, 1], 'gx',
markersize=7, label="stable frequency, stable damping")
p3 = self.ax1.plot(self.fn_temp[c[:, 0], c[:, 1]], 1+c[:, 1], 'r.',
markersize=4, label="unstable frequency, unstable damping")
p4 = self.ax1.plot(self.fn_temp[d[:, 0], d[:, 1]], 1+d[:, 1], 'r*',
markersize=4, label="unstable frequency, stable damping")
self.line, = self.ax1.plot(self.Model.nat_freq, np.repeat(
self.Model.pol_order_high, len(self.Model.nat_freq)), 'kv', markersize=8)
self.selected, = self.ax1.plot([self.Model.pole_freq[p[0]][p[1]] for p in self.Model.pole_ind],
[p[0] for p in self.Model.pole_ind], 'ko')
if self.show_legend:
self.pole_legend = self.ax1.legend(loc='upper center', ncol=2, frameon=True)
self.ax1.set_title('Stability chart')
self.ax1.set_ylabel('Polynomial order')
plt.tight_layout()
else:
self.line.set_xdata(np.asarray(self.Model.nat_freq)) # update data
self.line.set_ydata(np.repeat(self.Model.pol_order_high*1.04, len(self.Model.nat_freq)))
self.selected.set_xdata([self.Model.pole_freq[p[0]][p[1]]
for p in self.Model.pole_ind]) # update data
self.selected.set_ydata([p[0] for p in self.Model.pole_ind])
plt.tight_layout()
self.ax1.set_ylim([0, self.Model.pol_order_high+5])
self.fig.canvas.draw()
def plot_cluster(self, update_ticks=False):
"""Plot clusters - damping with respect to frequency.
:param update_ticks: if True, only ticks are updated, not the whole plot.
"""
b1 = np.argwhere(((self.test_fn > 0) & ((self.test_xi > 0) & (self.xi_temp > 0))) & ((self.fn_temp > self.Model.lower) & (self.fn_temp < self.Model.upper)))
if not update_ticks:
self.ax1.clear()
self.ax1.grid(True)
# stable eigenfrequencues, unstable damping ratios
a = np.argwhere((self.test_fn > 0) & ((self.test_xi == 0) | (self.xi_temp <= 0)))
# stable eigenfrequencies, stable damping ratios
b = np.argwhere((self.test_fn > 0) & ((self.test_xi > 0) & (self.xi_temp > 0)))
# unstable eigenfrequencues, unstable damping ratios
c = np.argwhere((self.test_fn == 0) & ((self.test_xi == 0) | (self.xi_temp <= 0)))
# unstable eigenfrequencues, stable damping ratios
d = np.argwhere((self.test_fn == 0) & ((self.test_xi > 0) & (self.xi_temp > 0)))
p1 = self.ax1.plot(self.fn_temp[a[:, 0], a[:, 1]], self.xi_temp[a[:, 0], a[:, 1]], 'bx',
markersize=4, label="stable frequency, unstable damping")
p2 = self.ax1.plot(self.fn_temp[b[:, 0], b[:, 1]], self.xi_temp[b[:, 0], b[:, 1]], 'gx',
markersize=7, label="stable frequency, stable damping")
p3 = self.ax1.plot(self.fn_temp[c[:, 0], c[:, 1]], self.xi_temp[c[:, 0], c[:, 1]], 'r.',
markersize=4, label="unstable frequency, unstable damping")
p4 = self.ax1.plot(self.fn_temp[d[:, 0], d[:, 1]], self.xi_temp[d[:, 0], d[:, 1]], 'r*',
markersize=4, label="unstable frequency, stable damping")
self.line, = self.ax1.plot(self.Model.nat_freq, np.repeat(
1.05*np.max(self.xi_temp[b1[:, 0], b1[:, 1]]), len(self.Model.nat_freq)), 'kv', markersize=8)
self.selected, = self.ax1.plot([self.Model.pole_freq[p[0]][p[1]] for p in self.Model.pole_ind],
[self.Model.pole_xi[p[0]][p[1]] for p in self.Model.pole_ind], 'ko')
if self.show_legend:
self.pole_legend = self.ax1.legend(loc='upper center', ncol=2, frameon=True)
self.ax1.set_title('Cluster diagram')
self.ax1.set_ylabel('Damping ratio')
plt.tight_layout()
else:
self.line.set_xdata(np.asarray(self.Model.nat_freq)) # update data
self.line.set_ydata(np.repeat(1.05*np.max(self.xi_temp[b1[:, 0], b1[:, 1]]), len(self.Model.nat_freq)))
self.selected.set_xdata([self.Model.pole_freq[p[0]][p[1]] for p in self.Model.pole_ind]) # update data
self.selected.set_ydata([self.Model.pole_xi[p[0]][p[1]] for p in self.Model.pole_ind])
to_lim = self.xi_temp[b1[:, 0], b1[:, 1]]
up_lim = min(np.max(to_lim), | np.mean(to_lim) | numpy.mean |
#================================================================
#
# File name : RL-Bitcoin-trading-bot_1.py
# Author : PyLessons
# Created date: 2020-12-02
# Website : https://pylessons.com/
# GitHub : https://github.com/pythonlessons/RL-Bitcoin-trading-bot
# Description : Introduction to trading Crypto with Reinforcement Learning
#
#================================================================
import pandas as pd
import numpy as np
import random
from collections import deque
class CustomEnv:
# A custom Bitcoin trading environment
def __init__(self, df, initial_balance=1000, lookback_window_size=50):
# Define action space and state size and other custom parameters
self.df = df.dropna().reset_index()
self.df_total_steps = len(self.df)-1
self.initial_balance = initial_balance
self.lookback_window_size = lookback_window_size
# Action space from 0 to 3, 0 is hold, 1 is buy, 2 is sell
self.action_space = np.array([0, 1, 2])
# Orders history contains the balance, net_worth, crypto_bought, crypto_sold, crypto_held values for the last lookback_window_size steps
self.orders_history = deque(maxlen=self.lookback_window_size)
# Market history contains the OHCL values for the last lookback_window_size prices
self.market_history = deque(maxlen=self.lookback_window_size)
# State size contains Market+Orders history for the last lookback_window_size steps
self.state_size = (self.lookback_window_size, 10)
# Reset the state of the environment to an initial state
def reset(self, env_steps_size = 0):
self.balance = self.initial_balance
self.net_worth = self.initial_balance
self.prev_net_worth = self.initial_balance
self.crypto_held = 0
self.crypto_sold = 0
self.crypto_bought = 0
if env_steps_size > 0: # used for training dataset
self.start_step = random.randint(self.lookback_window_size, self.df_total_steps - env_steps_size)
self.end_step = self.start_step + env_steps_size
else: # used for testing dataset
self.start_step = self.lookback_window_size
self.end_step = self.df_total_steps
self.current_step = self.start_step
for i in reversed(range(self.lookback_window_size)):
current_step = self.current_step - i
self.orders_history.append([self.balance, self.net_worth, self.crypto_bought, self.crypto_sold, self.crypto_held])
self.market_history.append([self.df.loc[current_step, 'Open'],
self.df.loc[current_step, 'High'],
self.df.loc[current_step, 'Low'],
self.df.loc[current_step, 'Close'],
self.df.loc[current_step, 'Volume']
])
state = np.concatenate((self.market_history, self.orders_history), axis=1)
return state
# Get the data points for the given current_step
def _next_observation(self):
self.market_history.append([self.df.loc[self.current_step, 'Open'],
self.df.loc[self.current_step, 'High'],
self.df.loc[self.current_step, 'Low'],
self.df.loc[self.current_step, 'Close'],
self.df.loc[self.current_step, 'Volume']
])
obs = | np.concatenate((self.market_history, self.orders_history), axis=1) | numpy.concatenate |
# Python 2-to-3 compatibility code
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from collections import namedtuple
try:
import qutip as qu
except ImportError:
qu = None
import numpy as np
import scipy.constants as cnst
import scipy.sparse as scisp
import scipy.sparse.linalg as scisp_lin
from pyschro.grid import Grid
from pyschro.basis import BasisSet, MNumerovBasis
QEvol = namedtuple('QEvol', ['params', 't', 'E', 'density'])
class QSolution(object):
def __init__(self, bounds, size, V, m,
basis=MNumerovBasis,
basis_pars={},
n_states=None):
self.grid = Grid(bounds, size)
# Check that the basis type matches
if not issubclass(basis, BasisSet):
raise ValueError("Invalid basis set!")
self.basis = basis(self.grid, V, m, **basis_pars)
if n_states is None or n_states >= len(self.grid.grid_lin):
if hasattr(self.basis.H, 'toarray'):
H = self.basis.H.toarray()
else:
H = self.basis.H
try:
assert(np.isclose(H-H.conjugate().T, 0).all())
except AssertionError:
raise RuntimeError("Hamiltonian is not Hermitian, "
"something has gone terribly wrong!")
self.evals, self.evecs = np.linalg.eigh(H)
else:
H = self.basis.H
try:
HHcheck = (H-H.conjugate().T)
if hasattr(HHcheck, 'todense'):
HHcheck = HHcheck.todense()
assert( | np.isclose(HHcheck, 0) | numpy.isclose |
import numpy as np
class LazyFrames:
def __init__(self, frames):
"""This object ensures that common frames between the observations are only stored once."""
self._frames = frames
self._out = None
def _force(self):
if self._out is None:
self._out = | np.array(self._frames) | numpy.array |
from __future__ import print_function, division
import sys
import os
from os.path import expanduser
home = expanduser("~")
path_to_cosmodc2 = os.path.join(home, 'cosmology/cosmodc2')
if 'mira-home' in home:
sys.path.insert(0, '/gpfs/mira-home/ekovacs/.local/lib/python2.7/site-packages')
sys.path.insert(0, path_to_cosmodc2)
sys.path.insert(0, os.path.join(home, 'cosmology/halotools/build/lib.linux-x86_64-2.7'))
#sys.path.insert(0, '/homes/dkorytov/.local/lib/python2.7/site-packages/halotools-0.7.dev4939-py2.7-linux-x86_64.egg')
import os
import numpy as np
import scipy as sp
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.colors as clr
import pdb
import dtk
import h5py
import time
import sys
import datetime
import subprocess
from astropy.table import Table
from scipy.spatial import cKDTree
from pecZ import pecZ
from astropy.cosmology import WMAP7 as cosmo
from scipy.integrate import cumtrapz
from scipy.interpolate import interp1d
from cosmodc2.black_hole_modeling import monte_carlo_bh_acc_rate, bh_mass_from_bulge_mass, monte_carlo_black_hole_mass
from cosmodc2.size_modeling import mc_size_vs_luminosity_late_type, mc_size_vs_luminosity_early_type
from cosmodc2.sdss_colors import assign_restframe_sdss_gri
from cosmodc2.mock_diagnostics import mean_des_red_sequence_gr_color_vs_redshift, mean_des_red_sequence_ri_color_vs_redshift, mean_des_red_sequence_iz_color_vs_redshift
from ellipticity_model import monte_carlo_ellipticity_bulge_disk
from halotools.utils import fuzzy_digitize
import galmatcher
def construct_gal_prop(fname, verbose=False, mask = None, mag_r_cut =
False):
t1 = time.time()
gal_prop = {}
hfile = h5py.File(fname,'r')
hgp = hfile['galaxyProperties']
m_star = np.log10(hgp['totalMassStellar'].value)
mag_g = hgp['SDSS_filters/magnitude:SDSS_g:rest:dustAtlas'].value
mag_r = hgp['SDSS_filters/magnitude:SDSS_r:rest:dustAtlas'].value
mag_i = hgp['SDSS_filters/magnitude:SDSS_i:rest:dustAtlas'].value
if mask is None:
mask = np.ones(mag_r.size,dtype=bool)
if mag_r_cut:
mask = (mag_r < -10) & mask
gal_prop['m_star'] = m_star[mask]
gal_prop['Mag_r'] = mag_r[mask]
gal_prop['clr_gr'] = mag_g[mask]-mag_r[mask]
gal_prop['clr_ri'] = mag_r[mask]-mag_i[mask]
if verbose:
print('done loading gal prop. {}'.format(time.time()-t1))
return gal_prop,mask
def cat_dics(dics, keys = None):
new_dic = {}
if keys is None:
keys = dics[0].keys()
for key in keys:
new_dic[key] = []
for dic in dics:
new_dic[key].append(dic[key])
new_dic[key] = np.concatenate(new_dic[key])
return new_dic
def select_dic(dic, slct):
new_dic = {}
for key in dic.keys():
new_dic[key]=dic[key][slct]
return new_dic
def clean_up_gal_prop(gal_prop):
"""For each galaxy, if any property is not finite, set all other
properties to some value (4) that will not be selected by the
kdtree query.
"""
print("Cleaning up gal prop: ",end="")
slct_nfnt = ~np.isfinite(gal_prop['m_star'])
for key in gal_prop.keys():
slct_nfnt = slct_nfnt | ~np.isfinite(gal_prop[key])
print("bad vals: ", np.sum(slct_nfnt))
for key in gal_prop.keys():
gal_prop[key][slct_nfnt] = -4
return gal_prop
def construct_gal_prop_redshift_dust_raw(fname, index, step1, step2,
step1_a, step2_a, target_a,
mask1, mask2,
dust_factor=1.0,
match_obs_color_red_seq = False,
cut_small_galaxies_mass = None,
snapshot = False):
"""Constructs gal_prop using the interpolation scheme from the galacticus
snapshots and index matching galaxies in step2 to galaxies in step1.
"""
h_in_gp1 = h5py.File(fname.replace("${step}", str(step1)), 'r')['galaxyProperties']
h_in_gp2 = h5py.File(fname.replace("${step}", str(step2)), 'r')['galaxyProperties']
##======DEBUG========
# stepz = dtk.StepZ(sim_name="AlphaQ")
# step1_ab = stepz.get_a(step1)
# step2_ab = stepz.get_a(step2)
# print("\t\t step1/2: {} - {}".format(step1, step2))
# print("\t\t step1/2_a: {:.4f} -> {:.4f}".format(step1_a, step2_a))
# print("\t\t step1/2_ab: {:.4f} -> {:.4f}".format(step1_ab, step2_ab))
# print("\t\t step1/2_z: {:.4f} -> {:.4f}".format(1.0/step1_a-1.0, 1.0/step2_a-1.0))
# print("\t\t step1/2_z2:{:.4f} -> {:.4f}".format(stepz.get_z(step1), stepz.get_z(step2)))
# print("\t\t target a: {:.4f}".format(target_a))
# print("\t\t target z: {:.3f}".format(1.0/target_a -1.0))
# step1_a = stepz.get_a(step1)
# step2_a = stepz.get_a(step2)
##=========DEBUG========
lum_g_d = get_column_interpolation_dust_raw(
'SDSS_filters/diskLuminositiesStellar:SDSS_g:rest:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_r_d = get_column_interpolation_dust_raw(
'SDSS_filters/diskLuminositiesStellar:SDSS_r:rest:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_i_d = get_column_interpolation_dust_raw(
'SDSS_filters/diskLuminositiesStellar:SDSS_i:rest:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_g_b = get_column_interpolation_dust_raw(
'SDSS_filters/spheroidLuminositiesStellar:SDSS_g:rest:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_r_b = get_column_interpolation_dust_raw(
'SDSS_filters/spheroidLuminositiesStellar:SDSS_r:rest:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_i_b = get_column_interpolation_dust_raw(
'SDSS_filters/spheroidLuminositiesStellar:SDSS_i:rest:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_g = lum_g_d + lum_g_b
lum_i = lum_i_d + lum_i_b
lum_r = lum_r_d + lum_r_b
##=======DEBUG======
# print("=============")
# print("lum_r non-finite: ", np.sum(~np.isfinite(lum_r)), np.sum(lum_r<0), lum_r.size)
# print("lum_r_d non-finite: ", np.sum(~np.isfinite(lum_r_d)), np.sum(lum_r_d<0), lum_r_d.size)
# print("lum_r_b non-finite: ", np.sum(~np.isfinite(lum_r_b)), np.sum(lum_r_b<0), lum_r_b.size)
# slct_neg = lum_r<0
# print(lum_r[slct_neg])
# print(lum_r_d[slct_neg])
# print(lum_r_b[slct_neg])
# print("=============")
##=======DEBUG======
m_star = get_column_interpolation_dust_raw(
'totalMassStellar',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
node_index = get_column_interpolation_dust_raw('infallIndex', h_in_gp1,
h_in_gp2, index, mask1, mask2, step1_a, step2_a, target_a,
dust_factor, snapshot=snapshot)
mag_g = -2.5*np.log10(lum_g)
mag_r = -2.5*np.log10(lum_r)
mag_i = -2.5*np.log10(lum_i)
size = m_star.size
gal_prop = {}
gal_prop['m_star'] = np.log10(m_star)
gal_prop['Mag_r'] = mag_r
gal_prop['clr_gr'] = mag_g - mag_r
gal_prop['clr_ri'] = mag_r - mag_i
gal_prop['dust_factor'] = np.ones(size, dtype='f4')*dust_factor
gal_prop['index'] = np.arange(size, dtype='i8')
gal_prop['node_index'] = node_index
if match_obs_color_red_seq:
lum_g_obs_d = get_column_interpolation_dust_raw(
'SDSS_filters/diskLuminositiesStellar:SDSS_g:observed:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_r_obs_d = get_column_interpolation_dust_raw(
'SDSS_filters/diskLuminositiesStellar:SDSS_r:observed:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_i_obs_d = get_column_interpolation_dust_raw(
'SDSS_filters/diskLuminositiesStellar:SDSS_i:observed:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_z_obs_d = get_column_interpolation_dust_raw(
'SDSS_filters/diskLuminositiesStellar:SDSS_z:observed:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_g_obs_s = get_column_interpolation_dust_raw(
'SDSS_filters/spheroidLuminositiesStellar:SDSS_g:observed:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_r_obs_s = get_column_interpolation_dust_raw(
'SDSS_filters/spheroidLuminositiesStellar:SDSS_r:observed:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_i_obs_s = get_column_interpolation_dust_raw(
'SDSS_filters/spheroidLuminositiesStellar:SDSS_i:observed:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_z_obs_s = get_column_interpolation_dust_raw(
'SDSS_filters/spheroidLuminositiesStellar:SDSS_z:observed:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_g_obs = lum_g_obs_d + lum_g_obs_s
lum_r_obs = lum_r_obs_d + lum_r_obs_s
lum_i_obs = lum_i_obs_d + lum_i_obs_s
lum_z_obs = lum_z_obs_d + lum_z_obs_s
# Luminosity distance factors cancle when we compute galaxy color,
# so I'm not including them the magnitude calculation
mag_g_obs = -2.5*np.log10(lum_g_obs)
mag_r_obs = -2.5*np.log10(lum_r_obs)
mag_i_obs = -2.5*np.log10(lum_i_obs)
mag_z_obs = -2.5*np.log10(lum_z_obs)
gal_prop['clr_gr_obs'] = mag_g_obs - mag_r_obs
gal_prop['clr_ri_obs'] = mag_r_obs - mag_i_obs
gal_prop['clr_iz_obs'] = mag_i_obs - mag_z_obs
# Record LSST g-r color
lum_g_obs_d_lsst = get_column_interpolation_dust_raw(
'LSST_filters/diskLuminositiesStellar:LSST_g:observed:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
lum_r_obs_d_lsst = get_column_interpolation_dust_raw(
'LSST_filters/diskLuminositiesStellar:LSST_r:observed:dustAtlas',
h_in_gp1, h_in_gp2, index, mask1, mask2, step1_a, step2_a,
target_a, dust_factor, snapshot=snapshot)
gal_prop['clr_gr_obs_lsst'] = -2.5*np.log10(lum_g_obs_d_lsst) + 2.5*np.log10( lum_r_obs_d_lsst)
if not (cut_small_galaxies_mass is None):
print("cutting out small galaxies in gltcs")
slct_gal = gal_prop['m_star']>cut_small_galaxies_mass
gal_prop = dic_select(gal_prop, slct_gal)
# print("nan test")
# print(np.sum(np.isnan(gal_prop['m_star'])))
# print("not finite test")
# print(np.sum(~np.isfinite(gal_prop['m_star'])))
# print(gal_prop['m_star'][np.isnan(gal_prop['m_star'])])
return gal_prop
def construct_lc_data(fname, match_obs_color_red_seq = False, verbose
= False, recolor=False, internal_step=None,
cut_small_galaxies_mass = None,
red_sequence_transition_mass_start=13.0,
red_sequence_transition_mass_end=13.5,
snapshot = False):
t1 = time.time()
lc_data = {}
if snapshot: # Snapshot baseDC2 format
hfile_snap = h5py.File(fname,'r')
hfile = hfile_snap['galaxyProperties']
snapshot_redshift = hfile_snap['metaData/redshift'].value
elif internal_step is None: # flat-file baseDC2 format
hfile = h5py.File(fname,'r')
else: # healpix basedDC2 format
hfile = h5py.File(fname,'r')[str(internal_step)]
non_empty_step = "obs_sm" in hfile
print("Reading {} (size={})".format(os.path.basename(fname), len(hfile)))
if non_empty_step:
lc_data['m_star'] = np.log10(hfile['obs_sm'].value)
lc_data['Mag_r'] = hfile['restframe_extincted_sdss_abs_magr'].value
lc_data['clr_gr'] = hfile['restframe_extincted_sdss_gr'].value
lc_data['clr_ri'] = hfile['restframe_extincted_sdss_ri'].value
if not snapshot:
lc_data['redshift'] = hfile['redshift'].value
else:
lc_data['redshift'] = np.ones(lc_data['m_star'].size)*snapshot_redshift
lc_data['sfr_percentile'] = hfile['sfr_percentile'].value
else:
lc_data['m_star'] = np.zeros(0, dtype=np.float)
lc_data['Mag_r'] = np.zeros(0, dtype=np.float)
lc_data['clr_gr'] = np.zeros(0, dtype=np.float)
lc_data['clr_ri'] = np.zeros(0, dtype=np.float)
if not snapshot:
lc_data['redshift'] = np.zeros(0, dtype=np.float)
else:
lc_data['redshift'] = np.ones(lc_data['m_star'].size)*snapshot_redshift
lc_data['sfr_percentile'] = np.zeros(0, dtype=np.float)
if recolor:
upid_mock = hfile['upid'].value
mstar_mock = hfile['obs_sm'].value
sfr_percentile_mock = hfile['sfr_percentile'].value
host_halo_mvir_mock = hfile['host_halo_mvir'].value
redshift_mock = lc_data['redshift']
a,b,c = assign_restframe_sdss_gri(upid_mock, mstar_mock, sfr_percentile_mock,
host_halo_mvir_mock, redshift_mock)
# plt.figure()
# h,xbins,ybins = np.histogram2d(lc_data['Mag_r'], a, bins=250)
# plt.pcolor(xbins,ybins, h.T, cmap='PuBu', norm =clr.LogNorm())
# plt.grid()
# plt.figure()
# h,xbins,ybins = np.histogram2d(lc_data['clr_gr'], b, bins=250)
# plt.pcolor(xbins,ybins, h.T, cmap='PuBu', norm =clr.LogNorm())
# plt.grid()
# plt.figure()
# h,xbins,ybins = np.histogram2d(lc_data['clr_ri'], c, bins=250)
# plt.pcolor(xbins,ybins, h.T, cmap='PuBu', norm =clr.LogNorm())
# plt.grid()
# plt.show()
lc_data['Mag_r'] = a
lc_data['clr_gr'] = b
lc_data['clr_ri'] = c
#lc_data['Mag_r'], lc_data['clr_gr'], lc_data['clr_ri'] = [a,b,c]
if match_obs_color_red_seq and non_empty_step:
# print("match obs color red seq")
host_halo_mvir_mock = hfile['host_halo_mvir'].value
is_on_red_seq_gr = hfile['is_on_red_sequence_gr'].value
is_on_red_seq_ri = hfile['is_on_red_sequence_ri'].value
mass_rs = soft_transition(np.log10(host_halo_mvir_mock), red_sequence_transition_mass_start, red_sequence_transition_mass_end)
lc_data['is_cluster_red_sequence'] = mass_rs & is_on_red_seq_gr & is_on_red_seq_ri
#lc_data['is_cluster_red_sequence'] = is_on_red_seq_gr & is_on_red_seq_ri
lc_data['clr_gr_obs'] = mean_des_red_sequence_gr_color_vs_redshift(lc_data['redshift'])
lc_data['clr_ri_obs'] = mean_des_red_sequence_ri_color_vs_redshift(lc_data['redshift'])
lc_data['clr_iz_obs'] = mean_des_red_sequence_iz_color_vs_redshift(lc_data['redshift'])
elif match_obs_color_red_seq:
lc_data['is_cluster_red_sequence'] = np.zeros(0,dtype=bool)
lc_data['clr_gr_obs'] = np.zeros(0,dtype=bool)
lc_data['clr_ri_obs'] = np.zeros(0,dtype=bool)
lc_data['clr_iz_obs'] = np.zeros(0,dtype=bool)
if not (cut_small_galaxies_mass is None):
print("cutting out small galaxies!")
# Cutting out low mass galaxies so it runs fasters
slct_gals = lc_data['m_star']>cut_small_galaxies_mass
lc_data = dic_select(lc_data, slct_gals)
#TODO remove once bug is fixed
lc_data['Mag_r'][~np.isfinite(lc_data['Mag_r'])] = -14.0
if verbose:
print('done loading lc data. {}'.format(time.time()-t1))
return lc_data
def construct_lc_data_healpix(fname, match_obs_color_red_seq = False,
verbose = False, recolor=False,
internal_step=None,
cut_small_galaxies_mass = None,
healpix_pixels=None,
red_sequence_transition_mass_start=13.0,
red_sequence_transition_mass_end=13.5,
snapshot=False):
print("Constructing light cone data.")
print("Input lightcone file pattern: ", fname)
print("Healpix files: ",healpix_pixels)
if healpix_pixels is None:
print("No healpix used")
lc_data = construct_lc_data(fname, match_obs_color_red_seq = match_obs_color_red_seq,
verbose = verbose, recolor=recolor, internal_step = internal_step,
cut_small_galaxies_mass = cut_small_galaxies_mass,
red_sequence_transition_mass_start = red_sequence_transition_mass_start,
red_sequence_transition_mass_end = red_sequence_transition_mass_end,
snapshot=snapshot)
else:
lc_data_hps = []
for healpix_pixel in healpix_pixels:
fname_healpix = fname.replace('${healpix}', str(healpix_pixel))
lc_data_hp = construct_lc_data(fname_healpix,
match_obs_color_red_seq = match_obs_color_red_seq,
recolor=recolor,
internal_step = internal_step,
cut_small_galaxies_mass = cut_small_galaxies_mass,
red_sequence_transition_mass_start = red_sequence_transition_mass_start,
red_sequence_transition_mass_end = red_sequence_transition_mass_end, verbose=False,
snapshot=snapshot)
lc_data_hp['healpix_pixel'] = np.ones(lc_data_hp['m_star'].size, dtype='i4')*healpix_pixel
lc_data_hps.append(lc_data_hp)
lc_data = cat_dics(lc_data_hps)
for key in lc_data.keys():
num = np.sum(~np.isfinite(lc_data[key]))
assert num == 0
return lc_data
def dic_select(dic, slct):
new_dic = {}
for key in dic.keys():
new_dic[key] = dic[key][slct]
return new_dic
def select_by_index(data,index):
new_data = {}
for key in data.keys():
new_data[key] = data[key][index]
return new_data
def squash_magnitudes(mag_dic, lim, a):
# I'm using a tanh function for the soft threshold. No magnitude will excessed
# 'lim'. Mags below lim-a aren't affect.
# plt.figure()
# plt.hist2d(mag_dic[:,0],mag_dic[:,1],bins=250,cmap='Blues',norm=clr.LogNorm())
# plt.axvline(x=lim+a,c='k',ls=':')
# plt.axvline(x=lim,c='k',ls='--')
# xlims = plt.xlim()
# plt.title("before magnitude squash")
# plt.xlabel('Mag_r')
# plt.ylabel('g-r rest')
if(a == 0.0):
slct = mag_dic[:,0]<lim
mag_dic[slct,0]= lim
else:
slct = mag_dic[:,0]<lim+a
mag_dic[slct,0]=a*np.tanh((mag_dic[slct,0]-lim-a)/a) + lim + a
# plt.figure()
# plt.hist2d(mag_dic[:,0],mag_dic[:,1],bins=250,cmap='Blues',norm=clr.LogNorm())
# plt.axvline(x=lim+a,c='k',ls=':')
# plt.axvline(x=lim,c='k',ls='--')
# plt.xlim(xlims)
# plt.title("after magntiude squash")
# plt.xlabel('Mag_r')
# plt.ylabel('g-r rest')
# plt.show()
return mag_dic
def resample_index(lc_data, gal_prop, ignore_mstar = False, nnk = 10,
verbose = False, select_match='ran', ignore_bright_luminosity=False,
ignore_bright_luminosity_threshold=None,
ignore_bright_luminosity_softness=0.0, ):
if verbose:
t1 = time.time()
print("Starting kdtree resampling")
print("\nNum LC Galaxies: {:.2e} Num Gltcs Galaxies: {:.2e}".format(lc_data['m_star'].size, gal_prop['m_star'].size))
m_star = lc_data['m_star']
mag_r = lc_data['Mag_r']
clr_gr = lc_data['clr_gr']
clr_ri = lc_data['clr_ri']
if ignore_mstar:
print("\tIgnoring Mstar!")
lc_mat = np.stack((mag_r,clr_gr,clr_ri),axis=1)
gal_mat = np.stack((gal_prop['Mag_r'],
gal_prop['clr_gr'],
gal_prop['clr_ri']),axis=1)
else:
lc_mat = np.stack((mag_r,clr_gr,clr_ri,m_star),axis=1)
gal_mat = np.stack((gal_prop['Mag_r'],
gal_prop['clr_gr'],
gal_prop['clr_ri'],
gal_prop['m_star']),axis=1)
if ignore_bright_luminosity:
lc_mat = squash_magnitudes(lc_mat, ignore_bright_luminosity_threshold, ignore_bright_luminosity_softness)
gal_mat = squash_magnitudes(gal_mat, ignore_bright_luminosity_threshold, ignore_bright_luminosity_softness)
# slct_lc_mat = lc_mat[:,0]<ignore_bright_luminosity_threshold
# lc_mat[slct_lc_mat,0] = ignore_bright_luminosity_threshold
# slct_gal_mat = gal_mat[:,0]< ignore_bright_luminosity_threshold
# gal_mat[slct_gal_mat,0] = ignore_bright_luminosity_threshold
if verbose:
t2 = time.time()
print('\tdone formating data. {}'.format(t2-t1))
print("data size: {:.2e}".format(m_star.size))
# if the search size is large enough, it's saves total time to construct a
# faster to search tree. Otherwise build a quick tree.
if m_star.size > 3e7:
if verbose:
print("long balanced tree")
ckdtree = cKDTree(gal_mat, balanced_tree = True, compact_nodes = True)
elif m_star.size > 3e6:
if verbose:
print("long tree")
ckdtree = cKDTree(gal_mat, balanced_tree = False, compact_nodes = True)
else:
if verbose:
print("quick tree")
ckdtree = cKDTree(gal_mat, balanced_tree = False, compact_nodes = False)
if verbose:
t3 = time.time()
print('\tdone making tree. {}'.format(t3-t2))
dist_raw, index_raw = ckdtree.query(lc_mat, nnk, n_jobs=10)
if verbose:
t4= time.time()
print('\tdone querying. {}'.format(t4-t3))
print("\tusing {}/{} match".format(select_match, nnk))
if nnk > 1:
if 'best' in select_match:
rand = np.zeros(index_raw.shape[0]).astype(int)
elif 'worst' in select_match:
rand = np.array([nnk-1]*index_raw.shape[0]) #indices run from 0 to nnk-1
else:
rand = np.random.randint(nnk,size=index_raw.shape[0])
aa = np.arange(index_raw.shape[0])
#dist = dist[aa,rand]
index = index_raw[aa,rand]
else:
index = index_raw
##======DEBUG===========
# print("lc_data size:")
# for k in lc_data:
# print(k,np.sum(~np.isfinite(lc_data[k])),'/',lc_data[k].size)
# print("\n\ngal_prop size:")
# for k in gal_prop:
# print(k,np.sum(~np.isfinite(gal_prop[k])),'/',gal_prop[k].size)
# print("index min/max: ", np.min(index), np.max(index))
# print("ckdtree size: ",gal_mat[:,0].size, gal_mat[0,:].size)
# plt.figure()
# h,xbins = np.histogram(index, bins=1000)
# plt.plot(dtk.bins_avg(xbins), h)
# plt.grid()
# plt.xlabel('index num')
# plt.ylabel('count')
##======DEBUG===========
return index
def resample_index_cluster_red_squence(lc_data, gal_prop, ignore_mstar
= False, nnk = 10, verbose =
False, select_match='ran',
ignore_bright_luminosity=False,
ignore_bright_luminosity_threshold=False,
ignore_bright_luminosity_softness=0.0,
rs_scatter_dict = {}):
if verbose:
t1 = time.time()
print("Starting kdtree resampling with obs colors")
lc_data_list = []
gal_prop_list = []
# We modify the lightcone/baseDC2/query data with rs scatter, if listed
lc_data_list += (lc_data['Mag_r'],
lc_data['clr_gr'],
lc_data['clr_ri'],
modify_array_with_rs_scatter(lc_data, "query", "gr", rs_scatter_dict), #clr_gr_obs
modify_array_with_rs_scatter(lc_data, "query", "ri", rs_scatter_dict), #clr_ri_obs
modify_array_with_rs_scatter(lc_data, "query", "iz", rs_scatter_dict), #clr_iz_obs
)
# We modify the galaxy properties/galactics/tree data with rs scatter, if listed
gal_prop_list += (gal_prop['Mag_r'],
gal_prop['clr_gr'],
gal_prop['clr_ri'],
modify_array_with_rs_scatter(gal_prop, "tree", "gr", rs_scatter_dict), #clr_gr_obs
modify_array_with_rs_scatter(gal_prop, "tree", "ri", rs_scatter_dict), #clr_ri_obs
modify_array_with_rs_scatter(gal_prop, "tree", "iz", rs_scatter_dict), #clr_iz_obs
)
if ignore_mstar:
pass
else:
lc_data_list.append(lc_data['m_star'])
gal_prop_list.append(gal_prop['m_star'])
lc_mat = np.transpose(lc_data_list)
gal_mat = np.transpose(gal_prop_list)
if ignore_bright_luminosity:
if(ignore_bright_luminosity_softness == 0.0):
slct_lc_mat = lc_mat[:,0]<ignore_bright_luminosity_threshold
lc_mat[slct_lc_mat,0] = ignore_bright_luminosity_threshold
slct_gal_mat = gal_mat[:,0]< ignore_bright_luminosity_threshold
gal_mat[slct_gal_mat,0] = ignore_bright_luminosity_threshold
else:
lim = ignore_bright_luminosity_threshold
a = ignore_bright_luminosity_softness
slct_lc_mat = lc_mat[:,0]<lim+a
lc_mat[slct_lc_mat,0]=a*np.tanh((lc_mat[slct_lc_mat,0]-lim-a)/a) + lim +a
slct_gal_mat = gal_mat[:,0]<lim+a
gal_mat[slct_gal_mat,0]=a*np.tanh((gal_mat[slct_gal_mat,0]-lim-a)/a) + lim +a
if verbose:
t2 = time.time()
print("\tdone formatting data. {}".format(t2-t1))
if lc_data['m_star'].size > 3e6:
if verbose:
print("long tree")
ckdtree = cKDTree(gal_mat, balanced_tree = False, compact_nodes = True)
else:
if verbose:
print("quick tree")
ckdtree = cKDTree(gal_mat, balanced_tree = False, compact_nodes = False)
if verbose:
t3 = time.time()
print("\tdone making kdtree. {}".format(t3-t2))
dist, index = ckdtree.query(lc_mat, nnk, n_jobs=10)
if verbose:
t4 = time.time()
print("\tdone querying. {}".format(t4-t3))
print("\tusing {}/{} match".format(select_match, nnk))
if nnk > 1:
if 'best' in select_match:
rand = np.zeros(dist.shape[0]).astype(int)
elif 'worst' in select_match:
rand = np.array([nnk-1]*dist.shape[0]) #indices run from 0 to nnk-1
else:
rand = np.random.randint(nnk,size=dist.shape[0])
aa = np.arange(dist.shape[0])
#dist = dist[aa,rand]
index = index[aa,rand]
# return orignal_index[slct_valid][index]
return index
def get_keys(hgroup):
keys = []
def _collect_keys(name, obj):
if isinstance(obj, h5py.Dataset):
keys.append(name)
hgroup.visititems(_collect_keys)
return keys
def soft_transition(vals, trans_start, trans_end):
if(vals.size ==0):
return np.ones(vals.size,dytpe='bool')
slct_between = (vals>trans_start) & (vals<trans_end)
if(trans_start == trans_end or np.sum(slct_between) == 0):
return vals>trans_start
elif(trans_start > trans_end):
raise ValueError('Trans_start value is greater than trans_end')
else:
# print(trans_start, trans_end)
# print(vals.size)
# print(np.sum(slct_between))
# print(vals[slct_between])
bins = fuzzy_digitize(vals[slct_between],[trans_start,trans_end], min_counts=0)
result = np.ones(vals.size, dtype='bool')
result[vals<=trans_start] = False
result[slct_between] = bins==1
return result
def get_rs_scatter_dict_from_param(param):
"""This function takes in a dtk.Param object and returns a dictionary
containing the scatter"""
print("seaching param file for red squence scatter information")
rs_scatter_dict = {}
colors = ['gr', 'ri', 'iz']
scatter_locations = ['query', 'tree']
for scatter_loc in scatter_locations:
for color in colors:
key = "red_sequence_scatter_{}_{}".format(scatter_loc, color)
if key in param:
val = param.get_float(key)
print("found {} = {:f} in param file".format(key, val))
rs_scatter_dict[key] = val
return rs_scatter_dict
def modify_data_with_rs_scatter(data_dict, data_type, rs_scatter_dict):
data_dict = data_dict.copydeep()
assert data_type == "query" or data_type == "tree", "Data type must be either \"query\" or \"tree\". Given data_type is {}".format(data_type)
colors = ['gr', 'ri', 'iz']
for color in colors:
rs_scatter_key = 'rs_scatter_{}_{}'.format(data_type, color)
if rs_scatter_key in rs_scatter_dict:
data = query_dict["clr_{}_obs".format(color)]
scatter = np.random.normal(scale=rs_scatter_dict[key],
size =data.size)
query_dict["clr_{}_obs".format(color)] = data + scatter
return data_dict
def modify_array_with_rs_scatter(data_dict, data_type, color,
rs_scatter_dict):
assert data_type == "query" or data_type == "tree", "Data type must be either \"query\" or \"tree\". Given data_type is {}".format(data_type)
data = data_dict['clr_{}_obs'.format(color)]
rs_scatter_key = "red_sequence_scatter_{}_{}".format(data_type, color)
if rs_scatter_key in rs_scatter_dict:
print("modifying {} data: color {} ".format(data_type, color))
scatter = np.random.normal(scale=rs_scatter_dict[rs_scatter_key],
size =data.size)
return data+scatter
else:
return data
copy_avoids = ('x','y','z','vx','vy','vz', 'peculiarVelocity','galaxyID','redshift',
'redshiftHubble','placementType','isCentral','hostIndex',
'blackHoleAccretionRate','blackHoleMass', 'step','infallHaloMass','infallHaloTag')
#TODO re-allow nitrogen contamination
copy_avoids_ptrn = ('hostHalo','magnitude','ageStatistics','Radius','Axis','Ellipticity','positionAngle','total', 'ContinuumLuminosity', 'contam_nitrogenII6584', 'Sersic', 'morphology', 'contam_nitrogen')
no_slope_var = ('x','y','z','vx','vy','vz', 'peculiarVelocity','galaxyID','redshift','redshiftHubble','inclination','positionAngle')
no_slope_ptrn =('morphology','hostHalo','infall')
def to_copy(key, short, supershort):
if short:
if "SED" in key or "other" in key or "Lines" in key:
print("\tnot copied: short var cut")
return False
if supershort:
if "SDSS" not in key and "total" not in key and ":rest" not in key and "MassStellar" not in key and "infallIndex" != key and "inclination" not in key:
print("\tnot copied: supershort var cut")
return False
if any([ ca == key for ca in copy_avoids]) or any([ cap in key for cap in copy_avoids_ptrn ]):
print("\tnot copied: by explicit listing")
return False
return True
# Keys that have their luminosity adjusted
luminosity_factors_keys = ['Luminosities', 'Luminosity']
_cached_column = {}
def get_column_interpolation_dust_raw(key, h_in_gp1, h_in_gp2, index,
mask1, mask2, step1_a, step2_a,
target_a, dust_factors,
kdtree_index=None,
luminosity_factors = None, cache
= False, snapshot = False):
"""This function returns the interpolated quantity between two
timesteps, from step1 to step2. Some galaxies are masked out: Any
galaxy that doesn't pass the mask in step1 (mask1), any galaxy
that doesn't a decendent in step2, or any galaxy that whose
descendent doesn't pass the step2 mask (mask2).
"""
print("\tLoading key: {}".format(key))
# if luminosity_factors is None:
# print("\t\tluminosity factors is none")
#print("dust_factors: ", dust_factors)
t1 = time.time()
step_del_a = step2_a - step1_a
target_del_a = target_a - step1_a
##=========DEBUG==========
# print("step del_a {:.3f} - {:.3f} = {:.3f}".format(step2_a, step1_a, step_del_a))
# print("target_del_a {:.3f} - {:.3f} = {:.3f}".format(target_a, step1_a, target_del_a))
##=========DEBUG==========
# The masking all galaxies that fail galmatcher's requirements at
# step1, galaxies that don't have a descndent, or if the
# descendent galaxy at step2 doesn't pass galmatcher requirements.
# If index is set None, we aren't doing interpolation at all. We
# are just using
if not snapshot:
mask_tot = mask1 & (index != -1) & mask2[index]
if (key in no_slope_var) or any(ptrn in key for ptrn in no_slope_ptrn):
#print('\t\tno interpolation')
data = h_in_gp1[key].value[mask_tot]
if kdtree_index is None:
val_out = data
else:
val_out = data[kdtree_index]
elif ":dustAtlas" in key:
#print('\t\tinterpolation with dust')
key_no_dust = key.replace(":dustAtlas","")
val1_no_dust = h_in_gp1[key_no_dust].value[mask_tot]
val1_dust = h_in_gp1[key].value[mask_tot]
if index is not None:
val2_no_dust = h_in_gp2[key].value[index][mask_tot]
else:
val2_no_dust = val1_no_dust
# val1_no_dust_lg = np.log(val1_no_dust)
# val1_dust_lg = np.log(val1_dust)
# val2_no_dust_lg = np.log(val2_no_dust)
dust_effect = val1_dust/val1_no_dust
dust_effect[val1_no_dust == 0] = 1
slope = (val2_no_dust - val1_no_dust)/step_del_a
slope[step_del_a ==0] =0
# slope_mag = (val2_no_dust_lg - val1_no_dust_lg)/step_del_a
# slope_mag[step_del_a == 0] = 0
##=======DEBUG=======
# def print_vals(label, data):
# print("\t\t{} below/zero/size: {}/{}/{}".format(label, np.sum(data<0), np.sum(data==0), data.size))
# print_vals("val1_no_dust", val1_no_dust)
# print_vals("val2_no_dust", val2_no_dust)
# print_vals("val1_dust", val1_dust)
##=======DEBUG=======
if kdtree_index is None:
tot_dust_effect = dust_effect**dust_factors
slct = dust_effect > 1.0
tot_dust_effect[slct] = dust_effect[slct]
val_out = (val1_no_dust + slope*target_del_a)*tot_dust_effect
#val_out = np.exp((val1_no_dust_lg + slope_mag*target_del_a)*tot_dust_effect)
else:
tot_dust_effect = (dust_effect[kdtree_index]**dust_factors)
slct = dust_effect[kdtree_index] > 1.0
tot_dust_effect[slct] = dust_effect[kdtree_index][slct]
val_out = (val1_no_dust[kdtree_index] + slope[kdtree_index]*target_del_a)*tot_dust_effect
#val_out = np.exp((val1_no_dust_lg[kdtree_index] + slope_mag[kdtree_index]*target_del_a)*tot_dust_effect)
else:
#print('\t\tinerpolation without dust')
val1_data = h_in_gp1[key].value[mask_tot]
val2_data = h_in_gp2[key].value[index][mask_tot]
# val1_data_lg = np.log(val1_data)
# val2_data_lg = np.log(val2_data)
slope = (val2_data - val1_data)/step_del_a
slope[step_del_a==0]=0
# slope_mag = (val1_data_lg-val2_data_lg)/step_del_a
# slope_mag[step_del_a==0]=0
if kdtree_index is None:
val_out = val1_data + slope*target_del_a
#val_out = np.log(val1_data_lg + slope_mag*target_del_a)
else:
val_out = val1_data[kdtree_index] + slope[kdtree_index]*target_del_a
#val_out = np.log(val1_data_lg[kdtree_index] + slope_mag[kdtree_index]*target_del_a)
#print('\t\t',val_out.dtype)
# If running on snapshot, we don't need to interpolate
else:
mask_tot = mask1
val1_data = h_in_gp1[key].value[mask_tot]
# reorder the data if it's a post-matchup index
if kdtree_index is None:
val_out = val1_data
else:
val_out = val1_data[kdtree_index]
if not(luminosity_factors is None):
if(any(l in key for l in luminosity_factors_keys)):
#print("\t\tluminosity adjusted")
val_out = val_out*luminosity_factors
elif('Luminosities' in key or 'Luminosity' in key):
#print("\t\tluminosity adjusted 2")
val_out = val_out*luminosity_factors
else:
pass
#print("\t\tluminosity untouched")
if np.sum(~np.isfinite(val_out))!=0:
print(key, "has a non-fininte value")
print("{:.2e} {:.2e}".format(np.sum(~np.isfinite(val_out)), val_out.size))
if ":dustAtlas" in key:
print(np.sum(~np.isfinite(val1_no_dust)))
print(np.sum(~np.isfinite(dust_effect)))
slct = ~np.isfinite(dust_effect)
print(val1_no_dust[slct])
print(val1_dust[slct])
print(np.sum(~np.isfinite(slope_mag)))
print(np.sum(~np.isfinite(target_del_a)))
if "emissionLines" in key:
print("overwriting non-finite values with 0")
val_out[~np.isfinite(val_out)]=0.0
else:
raise
#print("\t\toutput size: {:.2e}".format(val_out.size))
print("\t\t mask size:{:.1e}/{:.1e} data size:{:.1e} read + format time: {}".format(np.sum(mask_tot), mask_tot.size, val_out.size, time.time()-t1))
##=======DEBUG======
# print("\t\t non-finite: {}/{}/{}".format(np.sum(~np.isfinite(val_out)), np.sum(val_out<0), val_out.size))
# print("\t\t below/zero/size: {}/{}/{}".format(np.sum(val_out<0), np.sum(val_out==0), val_out.size))
##=======DEBUG======
return val_out
def copy_columns_interpolation_dust_raw(input_fname, output_fname,
kdtree_index, step1, step2,
step1_a, step2_a, mask1, mask2,
index_2to1, lc_a,
verbose = False,
short = False, supershort = False,
step = -1, dust_factors = 1.0,
luminosity_factors = None,
library_index = None,
node_index = None,
snapshot = False):
print("===================================")
print("copy columns interpolation dust raw")
# lc_a = 1.0/(1.0+lc_redshift)
# input_a = 1.0/(1.0 + input_redshift)
del_a = lc_a-step1_a
dtk.ensure_dir(output_fname)
h_out = h5py.File(output_fname,'w')
h_out_gp = h_out.create_group('galaxyProperties')
h_out_gp['matchUp/dustFactor'] = dust_factors
if luminosity_factors is not None:
h_out_gp['matchUp/luminosityFactor'] = luminosity_factors
if library_index is not None:
h_out_gp['matchUp/libraryIndex'] = library_index
if node_index is not None:
h_out_gp['matchUp/GalacticusNodeIndex'] = node_index
h_in_gp1 = h5py.File(input_fname.replace("${step}",str(step1)),'r')['galaxyProperties']
h_in_gp2 = h5py.File(input_fname.replace("${step}",str(step2)),'r')['galaxyProperties']
keys = get_keys(h_in_gp1)
max_float = np.finfo(np.float32).max #The max float size
for i in range(0,len(keys)):
t1 = time.time()
key = keys[i]
if verbose:
print('{}/{} [{}] {}'.format(i,len(keys),step, key))
if not to_copy(key, short, supershort):
continue
new_data = get_column_interpolation_dust_raw(
key, h_in_gp1, h_in_gp2, index_2to1, mask1, mask2, step1_a, step2_a, lc_a, dust_factors,
kdtree_index = kdtree_index, luminosity_factors = luminosity_factors, snapshot=snapshot)
slct_finite = np.isfinite(new_data)
#If the data is a double, record it as a float to save on disk space
if(new_data.dtype == np.float64 and np.sum(new_data[slct_finite]>max_float) == 0):
h_out_gp[key]= new_data.astype(np.float32)
else:
h_out_gp[key] = new_data
print("\t\tDone writing. read+format+write: {}".format(time.time()-t1))
return
def copy_columns_interpolation_dust_raw_healpix(input_fname, output_fname,
kdtree_index, step1, step2,
step1_a, step2_a, mask1, mask2,
index_2to1, lc_a,
healpix_pixels, lc_healpix,
verbose = False,
short = False, supershort = False,
step = -1, dust_factors = 1.0,
luminosity_factors = None,
library_index = None,
node_index = None,
snapshot= False):
print("===================================")
print("copy columns interpolation dust raw")
# lc_a = 1.0/(1.0+lc_redshift)
# input_a = 1.0/(1.0 + input_redshift)
del_a = lc_a-step1_a
#print("del_a: ", del_a)
h_out_gps = {}
h_out_gps_slct = {}
for healpix_pixel in healpix_pixels:
hp_fname = output_fname.replace("${healpix}", str(healpix_pixel))
dtk.ensure_dir(hp_fname)
h_out = h5py.File(hp_fname,'w')
h_out_gps[healpix_pixel] = h_out.create_group('galaxyProperties')
slct = lc_healpix == healpix_pixel
h_out_gps[healpix_pixel]['matchUp/dustFactor'] = dust_factors[slct]
h_out_gps[healpix_pixel]['matchUp/luminosityFactor'] = luminosity_factors[slct]
h_out_gps[healpix_pixel]['matchUp/libraryIndex'] = library_index[slct]
h_out_gps[healpix_pixel]['matchUp/GalacticusNodeIndex'] = node_index[slct]
h_out_gps_slct[healpix_pixel] = slct
h_in_gp1 = h5py.File(input_fname.replace("${step}",str(step1)),'r')['galaxyProperties']
h_in_gp2 = h5py.File(input_fname.replace("${step}",str(step2)),'r')['galaxyProperties']
keys = get_keys(h_in_gp1)
max_float = np.finfo(np.float32).max #The max float size
for i in range(0,len(keys)):
t1 = time.time()
key = keys[i]
if verbose:
print('{}/{} [{}] {}'.format(i,len(keys),step, key))
if not to_copy(key, short, supershort):
continue
new_data = get_column_interpolation_dust_raw(
key, h_in_gp1, h_in_gp2, index_2to1, mask1, mask2, step1_a, step2_a, lc_a, dust_factors,
kdtree_index = kdtree_index, luminosity_factors = luminosity_factors, snapshot = snapshot)
slct_finite = np.isfinite(new_data)
#If the data is a double, record it as a float to save on disk space
if(new_data.dtype == np.float64 and np.sum(new_data[slct_finite]>max_float) == 0):
new_data= new_data.astype(np.float32)
if 'LineLuminosity' in key:
key = key.replace(':rest', '')
for healpix_pixel in healpix_pixels:
h_out_gps[healpix_pixel][key] = new_data[h_out_gps_slct[healpix_pixel]]
print("\t\tDone writing. read+format+write: {}".format(time.time()-t1))
return
def overwrite_columns(input_fname, output_fname, ignore_mstar = False,
verbose=False, cut_small_galaxies_mass = None,
internal_step=None, fake_lensing=False,
healpix=False, step = None, healpix_shear_file =
None, no_shear_steps=None,
snapshot = False,
snapshot_redshift = None):
t1 = time.time()
if verbose:
print("\nOverwriting columns for file {}".format(os.path.basename(output_fname)))
#sdss = Table.read(input_fname,path='data')
if snapshot:
assert snapshot_redshift is not None, "Snapshot redshift must be specified in snapshot mode"
h_out = h5py.File(output_fname, 'a')
h_out_gp = h_out['galaxyProperties']
if snapshot:
h_in = h5py.File(input_fname,'r')['galaxyProperties']
elif internal_step is None:
h_in = h5py.File(input_fname,'r')
else:
h_in = h5py.File(input_fname,'r')[str(internal_step)]
# if the input file has no galaxies, it doesn't have any columns
step_has_data = "obs_sm" in h_in
if step_has_data:
sm = h_in['obs_sm'].value
else:
sm = np.zeros(0, dtype=float)
if cut_small_galaxies_mass is None:
mask = np.ones(sm.size, dtype=bool)
else:
mask = np.log10(sm) > cut_small_galaxies_mass
#redshift = np.ones(sdss['x'].quantity.size)*0.1
t2 = time.time()
if verbose:
print("\t done reading in data", t2-t1)
#xyz,v(xyz)
if step_has_data:
x = h_in['x'].value[mask]
y = h_in['y'].value[mask]
z = h_in['z'].value[mask]
vx = h_in['vx'].value[mask]
vy = h_in['vy'].value[mask]
vz = h_in['vz'].value[mask]
if snapshot:
redshift = np.ones(x.size)*snapshot_redshift
else:
redshift =h_in['redshift'].value[mask]
size = h_in['x'].size
if not snapshot:
h_out_gp['lightcone_rotation'] = h_in['lightcone_rotation'].value[mask]
h_out_gp['lightcone_replication'] = h_in['lightcone_replication'].value[mask]
else:
x = np.zeros(0, dtype=float)
y = np.zeros(0, dtype=float)
z = np.zeros(0, dtype=float)
vx = np.zeros(0, dtype=float)
vy = np.zeros(0, dtype=float)
vz = np.zeros(0, dtype=float)
size = 0
redshift =np.zeros(0, dtype=float)
if not snapshot:
h_out_gp['lightcone_rotation'] = np.zeros(0, dtype=int)
h_out_gp['lightcone_replication'] = np.zeros(0, dtype=int)
print('step: ', step)
assert step is not None, "Step is not specified"
if not snapshot:
h_out_gp['step']=np.ones(size,dtype='i4')*step
h_out_gp['x']=x
h_out_gp['y']=y
h_out_gp['z']=z
h_out_gp['vx']=vx
h_out_gp['vy']=vy
h_out_gp['vz']=vz
keys = get_keys(h_out_gp)
for key in keys:
if "spheroid" in key:
spheroid_key = key
disk_key = key.replace('spheroid','disk')
total_key = key.replace('spheroid','total')
h_out_gp[total_key] = np.array(h_out_gp[disk_key].value + h_out_gp[spheroid_key].value, dtype='f4')
if ignore_mstar:
if step_has_data:
print("Ignoring M* in stellar mass assignment!")
# m*_delta = M*_new/M*_old
mstar_delta = h_in['obs_sm'].value[mask]/h_out_gp['totalMassStellar'].value
h_out_gp['totalMassStellar'][:] = h_out_gp['totalMassStellar'].value*mstar_delta
h_out_gp['diskMassStellar'][:] = h_out_gp['diskMassStellar'].value*mstar_delta
h_out_gp['spheroidMassStellar'][:] = h_out_gp['spheroidMassStellar'].value*mstar_delta
else:
# No need to modify data on disk if the data sets are empty
pass
t3 = time.time()
#peculiar velocity
if not snapshot:
_,z_obs,v_pec,_,_,_,_ = pecZ(x,y,z,vx,vy,vz,redshift)
h_out_gp['peculiarVelocity'] = np.array(v_pec, dtype='f4')
#obs mag
#Calculate the oringal redshift
stepz = dtk.StepZ(200,0,500)
# Precompute redshfit to luminosity distance relationship
zs = np.linspace(0,3.5,1000)
z_to_dl = interp1d(zs,cosmo.luminosity_distance(zs))
dl = z_to_dl(redshift)
adjust_mag = -2.5*np.log10(1.0+redshift)+5*np.log10(dl)+25.0
t4 = time.time()
keys = get_keys(h_out_gp)
for key in keys:
# Calculating new observer frame magnitudes
if("totalLuminositiesStellar" in key and ":observed" in key and ("SDSS" in key or "LSST" in key)):
new_key = key.replace("totalLuminositiesStellar",'magnitude',1)
#print("making: "+new_key+" from "+key)
h_out_gp[new_key]=np.array(adjust_mag -2.5*np.log10(h_out_gp[key].value), dtype='f4')
# Calculating new rest frame magnitudes
if("totalLuminositiesStellar" in key and ":rest" in key and ("SDSS" in key or "LSST" in key)):
new_key = key.replace("totalLuminositiesStellar","magnitude",1)
#print("making: "+new_key+" from "+key)
h_out_gp[new_key]=np.array(-2.5*np.log10(h_out_gp[key].value), dtype='f4')
t5 = time.time()
if verbose:
print("\t done rewriting mags",t5-t4)
#redshift
if snapshot:
h_out_gp['redshift'] = redshift
else:
h_out_gp['redshift'] = z_obs
h_out_gp['redshiftHubble'] = redshift
if not snapshot:
if step_has_data:
h_out_gp['ra_true'] = h_in['ra'].value[mask]
h_out_gp['dec_true'] = h_in['dec'].value[mask]
else:
h_out_gp['ra_true'] = np.zeros(0, dtype=np.float)
h_out_gp['dec_true'] = np.zeros(0, dtype=np.float)
# Skip shears for this step if it's in the list
if no_shear_steps is not None:
fake_lensing_step = (step in no_shear_steps)
if (step in no_shear_steps):
print("==== no shear step ====", step)
pritn("\t step {} is list as in no_shear_steps".format(step), no_shear_steps)
if fake_lensing or fake_lensing_step:
print("\tfake shears")
if step_has_data:
size = h_in['x'].size
else:
size = 0
if not snapshot:
if step_has_data:
h_out_gp['ra'] = h_in['ra'].value[mask]
h_out_gp['dec'] = h_in['dec'].value[mask]
else:
h_out_gp['ra'] = np.zeros(0,dtype=float)
h_out_gp['dec'] =np.zeros(0,dtype=float)
h_out_gp['shear1'] = np.zeros(size, dtype='f4')
h_out_gp['shear2'] = np.zeros(size, dtype='f4')
h_out_gp['magnification'] = np.ones(size, dtype='f4')
h_out_gp['convergence'] = np.zeros(size, dtype='f4')
elif healpix:
print("\thealpix shears")
h_shear = h5py.File(healpix_shear_file, 'r')[str(step)]
if step_has_data:
shear_id = h_shear['galaxy_id'].value
print("\t\tassigning shears ")
base_id = h_in['galaxy_id'].value[mask]
srt = np.argsort(shear_id)
shear_indx = dtk.search_sorted(shear_id, base_id, sorter=srt)
assert np.sum(shear_indx==-1) == 0, "a baseDC2 galaxy wasn't found in shear catalog?"
h_out_gp['ra'] = h_shear['ra_lensed'].value[shear_indx]
h_out_gp['dec'] = h_shear['dec_lensed'].value[shear_indx]
s1 = h_shear['shear_1'].value[shear_indx]
s2 = h_shear['shear_2'].value[shear_indx]
k = h_shear['conv'].value[shear_indx]
u = 1.0/((1.0-k)**2 - s1**2 -s2**2)
h_out_gp['shear1'] = s1
h_out_gp['shear2'] = s2
h_out_gp['magnification'] = u
h_out_gp['convergence'] = k
# h_out_gp['ra'] = h_shear['ra_lensed'].value[mask]
# h_out_gp['dec'] = h_shear['dec_lensed'].value[mask]
# s1 = h_shear['shear_1'].value[mask]
# s2 = h_shear['shear_2'].value[mask]
# k = h_shear['conv'].value[mask]
else:
print("\t\tno data in this step, setting it all to zeros")
h_out_gp['shear1'] = np.zeros(0, dtype=np.float)
h_out_gp['shear2'] = np.zeros(0, dtype=np.float)
h_out_gp['magnification'] = np.zeros(0, dtype=np.float)
h_out_gp['convergence'] = np.zeros(0, dtype=np.float)
else:
print('\tprotoDC2 shear style')
#No protection against empty step. This is only a feature of CosmoDC2
h_out_gp['ra'] = h_in['ra_lensed'].value[mask]
h_out_gp['dec'] = h_in['dec_lensed'].value[mask]
h_out_gp['shear1'] = h_in['shear1'].value[mask]
h_out_gp['shear2'] = h_in['shear2'].value[mask]
h_out_gp['magnification'] = h_in['magnification'].value[mask]
h_out_gp['convergence'] = h_in['convergence'].value[mask]
if healpix:
if step_has_data:
h_out_gp['galaxyID'] = h_in['galaxy_id'].value[mask]
else:
h_out_gp['galaxyID'] = np.zeros(0, dtype=np.int64)
if step_has_data:
central = h_in['upid'].value[mask] == -1
h_out_gp['isCentral'] = central
if snapshot:
pass
h_out_gp['hostHaloTag'] = h_in['target_halo_id'].value[mask]
else:
h_out_gp['hostHaloTag'] = h_in['target_halo_fof_halo_id'].value[mask]
h_out_gp['uniqueHaloID'] = h_in['target_halo_id'].value[mask]
h_out_gp['hostHaloMass'] = h_in['target_halo_mass'].value[mask]
unq, indx, cnt = np.unique(h_out_gp['infallIndex'].value, return_inverse=True, return_counts = True)
h_out_gp['matchUp/NumberSelected'] = cnt[indx]
central_2 = (h_in['host_centric_x'].value[mask] ==0) & (h_in['host_centric_y'].value[mask] ==0) & (h_in['host_centric_z'].value[mask] == 0)
assert np.sum(central_2 != central) == 0, "double centrals? centrals by upid {}, centrals by halo centric position {}".format(np.sum(central), np.sum(central_2))
else:
h_out_gp['isCentral'] = np.zeros(0, dtype=bool)
h_out_gp['hostHaloTag'] = np.zeros(0, dtype=np.int64)
h_out_gp['uniqueHaloID'] = np.zeros(0, dtype=np.int64)
h_out_gp['hostHaloMass'] = np.zeros(0, dtype=np.float)
h_out_gp['matchUp/NumberSelected'] = np.zeros(0,dtype=np.int)
tf = time.time()
if verbose:
print("\tDone overwrite columns", tf-t1)
def swap(slct, x1, x2):
xa = x1[slct]
x1[slct] = x2[slct]
x2[slct]=xa
def rotate_host_halo(rot, x,y,z):
""""
From the documentation:
// 0 = no rotation
// 1 = swap(x, y) rotation applied
// 2 = swap(y, z) rotation applied
// 3 = swap(x, y) then swap(y, z) rotations applied
// 4 = swap(z, x) rotation applied
// 5 = swap(x, y) then swap(z, x) rotations applied
// There are also two other possibilities:
// 6 = swap(y, z) then swap(z, x) rotations applied
// 7 = swap(x, y), then swap(y, z), then swap(z, x) rotations applied
// which are equivalent to rotations 3 and 2 above, respectively
"""
slct1 = rot == 1
swap(slct1, x, y)
slct2 = (rot == 2) | (rot == 7)
swap(slct2, y, z)
slct3 = (rot == 3) | (rot == 6)
swap(slct3, x, y )
swap(slct3, y, z)
slct4 = rot == 4
swap(slct4, z, x)
slct5 = rot == 5
swap(slct5, x, y)
swap(slct5, z, x)
return
def overwrite_host_halo(output_fname, sod_loc, halo_shape_loc,
halo_shape_red_step_loc, verbose=False, snapshot = False):
hgroup = h5py.File(output_fname,'r+')['galaxyProperties']
halo_tag = hgroup['hostHaloTag'].value
size = halo_tag.size
if not snapshot:
halo_rot = hgroup['lightcone_rotation'].value
# fof_tag = dtk.read_gio(fof_loc,'fof_halo_tag')
# fof_mass = dtk.read_gio(fof_loc,'fof_mass')
# fof_srt = np.argsort(fof_tag)
sod_mass = -1*np.ones(halo_tag.size)
if os.path.isfile(sod_loc):
sod_cat_tag = dtk.gio_read(sod_loc,'fof_halo_tag')
sod_cat_mass = dtk.gio_read(sod_loc,'sod_halo_mass')
sod_cat_srt = np.argsort(sod_cat_tag)
indx = dtk.search_sorted(sod_cat_mass,halo_tag,sorter=sod_cat_srt)
slct = indx != -1
sod_mass[slct] = sod_cat_mass[indx[slct]]
hgroup['hostHaloSODMass']=sod_mass
print("Filling host halo information: Num of galaxies: ", halo_tag.size)
eg_cat_eg1 = np.zeros(size,dtype='f4')
eg_cat_eg2 = np.zeros(size,dtype='f4')
eg_cat_eg3 = np.zeros(size,dtype='f4')
eg_cat_eg1_x =np.zeros(size,dtype='f4')
eg_cat_eg1_y =np.zeros(size,dtype='f4')
eg_cat_eg1_z =np.zeros(size,dtype='f4')
eg_cat_eg2_x =np.zeros(size,dtype='f4')
eg_cat_eg2_y =np.zeros(size,dtype='f4')
eg_cat_eg2_z =np.zeros(size,dtype='f4')
eg_cat_eg3_x = np.zeros(size,dtype='f4')
eg_cat_eg3_y =np.zeros(size,dtype='f4')
eg_cat_eg3_z =np.zeros(size,dtype='f4')
has_halo_shape_files = os.path.isfile(halo_shape_loc) and os.path.isfile(halo_shape_red_step_loc)
if has_halo_shape_files:
eg_cat_htag = dtk.gio_read(halo_shape_loc,'halo_id')
srt = np.argsort(eg_cat_htag)
indx = dtk.search_sorted(eg_cat_htag,halo_tag,sorter=srt)
slct_indx = indx != -1
indx_slct = indx[slct_indx]
print("num selected: ",np.sum(slct_indx))
eg_cat_eg1[slct_indx] = dtk.gio_read(halo_shape_loc,'eval1')[indx_slct]
eg_cat_eg2[slct_indx] = dtk.gio_read(halo_shape_loc,'eval2')[indx_slct]
eg_cat_eg3[slct_indx] = dtk.gio_read(halo_shape_loc,'eval3')[indx_slct]
eg_cat_eg1_x[slct_indx] = dtk.gio_read(halo_shape_loc,'evec1x')[indx_slct]
eg_cat_eg1_y[slct_indx] = dtk.gio_read(halo_shape_loc,'evec1y')[indx_slct]
eg_cat_eg1_z[slct_indx] = dtk.gio_read(halo_shape_loc,'evec1z')[indx_slct]
eg_cat_eg2_x[slct_indx] = dtk.gio_read(halo_shape_loc,'evec2x')[indx_slct]
eg_cat_eg2_y[slct_indx] = dtk.gio_read(halo_shape_loc,'evec2y')[indx_slct]
eg_cat_eg2_z[slct_indx] = dtk.gio_read(halo_shape_loc,'evec2z')[indx_slct]
eg_cat_eg3_x[slct_indx] = dtk.gio_read(halo_shape_loc,'evec3x')[indx_slct]
eg_cat_eg3_y[slct_indx] = dtk.gio_read(halo_shape_loc,'evec3y')[indx_slct]
eg_cat_eg3_z[slct_indx] = dtk.gio_read(halo_shape_loc,'evec3z')[indx_slct]
if not snapshot:
rotate_host_halo(halo_rot, eg_cat_eg1_x, eg_cat_eg1_y, eg_cat_eg1_z)
rotate_host_halo(halo_rot, eg_cat_eg2_x, eg_cat_eg2_y, eg_cat_eg2_z)
rotate_host_halo(halo_rot, eg_cat_eg3_x, eg_cat_eg3_y, eg_cat_eg3_z)
hgroup['hostHaloEigenValue1'] = eg_cat_eg1
hgroup['hostHaloEigenValue2'] = eg_cat_eg2
hgroup['hostHaloEigenValue3'] = eg_cat_eg3
hgroup['hostHaloEigenVector1X'] = eg_cat_eg1_x
hgroup['hostHaloEigenVector1Y'] = eg_cat_eg1_y
hgroup['hostHaloEigenVector1Z'] = eg_cat_eg1_z
hgroup['hostHaloEigenVector2X'] = eg_cat_eg2_x
hgroup['hostHaloEigenVector2Y'] = eg_cat_eg2_y
hgroup['hostHaloEigenVector2Z'] = eg_cat_eg2_z
hgroup['hostHaloEigenVector3X'] = eg_cat_eg3_x
hgroup['hostHaloEigenVector3Y'] = eg_cat_eg3_y
hgroup['hostHaloEigenVector3Z'] = eg_cat_eg3_z
if has_halo_shape_files:
eg_cat_htag = dtk.gio_read(halo_shape_red_step_loc,'halo_id')[indx_slct]
eg_cat_eg1[slct_indx] = dtk.gio_read(halo_shape_red_step_loc,'eval1')[indx_slct]
eg_cat_eg2[slct_indx] = dtk.gio_read(halo_shape_red_step_loc,'eval2')[indx_slct]
eg_cat_eg3[slct_indx] = dtk.gio_read(halo_shape_red_step_loc,'eval3')[indx_slct]
eg_cat_eg1_x[slct_indx] = dtk.gio_read(halo_shape_red_step_loc,'evec1x')[indx_slct]
eg_cat_eg1_y[slct_indx] = dtk.gio_read(halo_shape_red_step_loc,'evec1y')[indx_slct]
eg_cat_eg1_z[slct_indx] = dtk.gio_read(halo_shape_red_step_loc,'evec1z')[indx_slct]
eg_cat_eg2_x[slct_indx] = dtk.gio_read(halo_shape_red_step_loc,'evec2x')[indx_slct]
eg_cat_eg2_y[slct_indx] = dtk.gio_read(halo_shape_red_step_loc,'evec2y')[indx_slct]
eg_cat_eg2_z[slct_indx] = dtk.gio_read(halo_shape_red_step_loc,'evec2z')[indx_slct]
eg_cat_eg3_x[slct_indx] = dtk.gio_read(halo_shape_red_step_loc,'evec3x')[indx_slct]
eg_cat_eg3_y[slct_indx] = dtk.gio_read(halo_shape_red_step_loc,'evec3y')[indx_slct]
eg_cat_eg3_z[slct_indx] = dtk.gio_read(halo_shape_red_step_loc,'evec3z')[indx_slct]
if not snapshot:
rotate_host_halo(halo_rot, eg_cat_eg1_x, eg_cat_eg1_y, eg_cat_eg1_z)
rotate_host_halo(halo_rot, eg_cat_eg2_x, eg_cat_eg2_y, eg_cat_eg2_z)
rotate_host_halo(halo_rot, eg_cat_eg3_x, eg_cat_eg3_y, eg_cat_eg3_z)
hgroup['hostHaloEigenValueReduced1'] = eg_cat_eg1
hgroup['hostHaloEigenValueReduced2'] = eg_cat_eg2
hgroup['hostHaloEigenValueReduced3'] = eg_cat_eg3
hgroup['hostHaloEigenVectorReduced1X'] = eg_cat_eg1_x
hgroup['hostHaloEigenVectorReduced1Y'] = eg_cat_eg1_y
hgroup['hostHaloEigenVectorReduced1Z'] = eg_cat_eg1_z
hgroup['hostHaloEigenVectorReduced2X'] = eg_cat_eg2_x
hgroup['hostHaloEigenVectorReduced2Y'] = eg_cat_eg2_y
hgroup['hostHaloEigenVectorReduced2Z'] = eg_cat_eg2_z
hgroup['hostHaloEigenVectorReduced3X'] = eg_cat_eg3_x
hgroup['hostHaloEigenVectorReduced3Y'] = eg_cat_eg3_y
hgroup['hostHaloEigenVectorReduced3Z'] = eg_cat_eg3_z
return
def add_native_umachine(output_fname, umachine_native,
cut_small_galaxies_mass = None,
internal_step=None, snapshot=False):
t1 = time.time()
if snapshot:
h_in = h5py.File(umachine_native, 'r')['galaxyProperties']
elif internal_step is None:
h_in = h5py.File(umachine_native,'r')
else:
h_in = h5py.File(umachine_native,'r')[str(internal_step)]
hgroup = h5py.File(output_fname, 'r+')['galaxyProperties']
if cut_small_galaxies_mass is None:
for key in h_in.keys():
hgroup['baseDC2/'+key] = h_in[key].value
else:
sm = h_in['obs_sm'].value # in linear units
slct = sm > 10**cut_small_galaxies_mass #convert cut_small.. from log to linear
for key in h_in.keys():
hgroup['baseDC2/'+key] = h_in[key].value[slct]
print("done addign baseDC2 quantities. time: {:.2f}".format(time.time()-t1))
return
def add_blackhole_quantities(output_fname, redshift, percentile_sfr):
hgroup = h5py.File(output_fname,'r+')['galaxyProperties']
print(hgroup.keys())
bhm = monte_carlo_black_hole_mass(hgroup['spheroidMassStellar'].value)
eddington_ratio, bh_acc_rate = monte_carlo_bh_acc_rate(redshift, bhm, percentile_sfr)
hgroup['blackHoleMass'] = bhm
hgroup['blackHoleAccretionRate'] = bh_acc_rate*1e9
hgroup['blackHoleEddingtonRatio'] = eddington_ratio
def add_size_quantities(output_fname):
hgroup = h5py.File(output_fname,'r+')['galaxyProperties']
mag_r = hgroup['SDSS_filters/magnitude:SDSS_r:rest'].value
redshift = hgroup['redshift'].value
if len(redshift) > 0:
arcsec_per_kpc = interp1d(redshift,cosmo.arcsec_per_kpc_proper(redshift).value)
f = arcsec_per_kpc(redshift)
else:
f = np.zeros(0, dtype=np.float)
size_disk = mc_size_vs_luminosity_late_type(mag_r, redshift)
size_sphere = mc_size_vs_luminosity_early_type(mag_r, redshift)
hgroup['morphology/spheroidHalfLightRadius'] = size_sphere
hgroup['morphology/spheroidHalfLightRadiusArcsec'] = size_sphere*f
hgroup['morphology/diskHalfLightRadius'] = size_disk
hgroup['morphology/diskHalfLightRadiusArcsec'] = size_disk*f
def erase_ellipticity_quantities(output_fname):
print(output_fname)
def erase_if_has(hfile, output_fname):
if 'galaxyProperties/'+output_fname in hfile:
del hfile['galaxyProperties/'+output_fname]
hfile = h5py.File(output_fname,'r+')
erase_if_has(hfile, 'morphology/spheroidAxisRatio')
erase_if_has(hfile, 'morphology/spheroidAxisRatio')
erase_if_has(hfile, 'morphology/spheroidMajorAxisArcsec')
erase_if_has(hfile, 'morphology/spheroidMinorAxisArcsec')
erase_if_has(hfile, 'morphology/spheroidEllipticity')
erase_if_has(hfile, 'morphology/spheroidEllipticity1')
erase_if_has(hfile, 'morphology/spheroidEllipticity2')
erase_if_has(hfile, 'morphology/diskAxisRatio')
erase_if_has(hfile, 'morphology/diskMajorAxisArcsec')
erase_if_has(hfile, 'morphology/diskMinorAxisArcsec')
erase_if_has(hfile, 'morphology/diskEllipticity')
erase_if_has(hfile, 'morphology/diskEllipticity1')
erase_if_has(hfile, 'morphology/diskEllipticity2')
erase_if_has(hfile, 'morphology/totalEllipticity')
erase_if_has(hfile, 'morphology/totalAxisRatio')
erase_if_has(hfile, 'morphology/totalEllipticity1')
erase_if_has(hfile, 'morphology/totalEllipticity2')
erase_if_has(hfile, 'morphology/positionAngle')
def add_ellipticity_quantities(output_fname, verbose = False):
if verbose:
print("\tadding ellipticity")
def gal_zoo_dist(x):
val = np.zeros_like(x)
a = 2
slct = x<0.2
val[slct] = 0
slct = (0.1<=x) & (x<0.7)
val[slct] = np.tanh((x[slct]-.3)*np.pi*a) - np.tanh((-0.2)*np.pi*a)
slct = (0.7<=x) & (x<1.0)
val[slct] = np.tanh(-(x[slct]-.95)*np.pi*6.) - np.tanh((-0.2)*np.pi*a) -(np.tanh(-(0.7-0.95)*np.pi*6)-np.tanh(0.4*np.pi*a))
slct = 1.0<=x
val[slct] = 0
return val
hgroup = h5py.File(output_fname, 'r+')['galaxyProperties']
if 'inclination' in hgroup['morphology']:
inclination = hgroup['morphology/inclination'].value
else:
inclination = None
mag_r = hgroup['SDSS_filters/magnitude:SDSS_r:rest:dustAtlas'].value
size = np.size(mag_r)
pos_angle = np.random.uniform(size=size)*np.pi
print("pos_angle: ", pos_angle.size)
if False: # Old code for ellipticity
spheroid_axis_ratio = dtk.clipped_gaussian(0.8, 0.2, size, max_val = 1.0, min_val=0.0)
dist,lim = dtk.make_distribution(-inclination)
resamp = dtk.resample_distribution(dist,gal_zoo_dist,lim,[0.0,1.0])
disk_axis_ratio = resamp(-inclination)
else:
# Returns ellip = 1-q^2 / 1+q^2
# spheroid_ellip_cosmo = monte_carlo_ellipticity_bulge(mag_r)
# disk_ellip_cosmo = monte_carlo_ellipticity_disk(mag_r, inclination)
# We need to convert to q = sqrt((1-e)/(1+e))
spheroid_ellip_cosmos, disk_ellip_cosmos = monte_carlo_ellipticity_bulge_disk(mag_r)
spheroid_axis_ratio = np.sqrt((1-spheroid_ellip_cosmos**2)/(1+spheroid_ellip_cosmos**2))
disk_axis_ratio = np.sqrt((1-disk_ellip_cosmos**2)/(1+disk_ellip_cosmos**2))
# Calculate ellipticity from the axis ratios
ellip_disk = (1.0 - disk_axis_ratio)/(1.0 + disk_axis_ratio)
ellip_spheroid = (1.0 - spheroid_axis_ratio)/(1.0 + spheroid_axis_ratio)
hgroup['morphology/spheroidAxisRatio'] = np.array(spheroid_axis_ratio, dtype='f4')
hgroup['morphology/spheroidMajorAxisArcsec'] = np.array(hgroup['morphology/spheroidHalfLightRadiusArcsec'].value, dtype='f4')
hgroup['morphology/spheroidMinorAxisArcsec'] = np.array(hgroup['morphology/spheroidHalfLightRadiusArcsec'].value*spheroid_axis_ratio, dtype='f4')
hgroup['morphology/spheroidEllipticity'] = np.array(ellip_spheroid, dtype='f4')
hgroup['morphology/spheroidEllipticity1'] =np.array( np.cos(2.0*pos_angle)*ellip_spheroid, dtype='f4')
hgroup['morphology/spheroidEllipticity2'] =np.array( np.sin(2.0*pos_angle)*ellip_spheroid, dtype='f4')
hgroup['morphology/diskAxisRatio'] = np.array(disk_axis_ratio, dtype='f4')
hgroup['morphology/diskMajorAxisArcsec'] = np.array(hgroup['morphology/diskHalfLightRadiusArcsec'].value, dtype='f4')
hgroup['morphology/diskMinorAxisArcsec'] = np.array(hgroup['morphology/diskHalfLightRadiusArcsec'].value*disk_axis_ratio, dtype='f4')
hgroup['morphology/diskEllipticity'] = np.array(ellip_disk, dtype='f4')
hgroup['morphology/diskEllipticity1'] =np.array( np.cos(2.0*pos_angle)*ellip_disk, dtype='f4')
hgroup['morphology/diskEllipticity2'] =np.array( np.sin(2.0*pos_angle)*ellip_disk, dtype='f4')
lum_disk = hgroup['SDSS_filters/diskLuminositiesStellar:SDSS_r:rest'].value
lum_sphere = hgroup['SDSS_filters/spheroidLuminositiesStellar:SDSS_r:rest'].value
lum_tot = lum_disk + lum_sphere
tot_ellip = (lum_disk*ellip_disk + lum_sphere*ellip_spheroid)/(lum_tot)
hgroup['morphology/totalEllipticity'] = np.array(tot_ellip, dtype='f4')
hgroup['morphology/totalAxisRatio'] = np.array((1.0 - tot_ellip)/(1.0 + tot_ellip), dtype='f4')
hgroup['morphology/totalEllipticity1'] = np.array(np.cos(2.0*pos_angle)*tot_ellip, dtype='f4')
hgroup['morphology/totalEllipticity2'] = np.array(np.sin(2.0*pos_angle)*tot_ellip, dtype='f4')
hgroup['morphology/positionAngle'] = np.array(pos_angle*180.0/np.pi, dtype='f4')
# print("position angle writen: ", np.array(pos_angle*180.0/np.pi, dtype='f4'))
# print("position angle writen: ", np.array(pos_angle*180.0/np.pi, dtype='f4').size)
srsc_indx_disk = 1.0*np.ones(lum_disk.size,dtype='f4')
srsc_indx_sphere = 4.0*np.ones(lum_disk.size,dtype='f4')
srsc_indx_tot = (srsc_indx_disk*lum_disk + srsc_indx_sphere*lum_sphere)/(lum_tot)
hgroup['morphology/diskSersicIndex'] = srsc_indx_disk
hgroup['morphology/spheroidSersicIndex'] = srsc_indx_sphere
hgroup['morphology/totalSersicIndex'] = srsc_indx_tot
return
def combine_step_lc_into_one(step_fname_list, out_fname, healpix=False):
print("combining into one file")
print(out_fname)
print(step_fname_list)
hfile_out = h5py.File(out_fname,'w')
hfile_gp_out = hfile_out.create_group('galaxyProperties')
hfile_steps = []
hfile_steps_gp = []
for fname in step_fname_list:
hfile = h5py.File(fname,'r')
gp = hfile['galaxyProperties']
hfile_steps.append(hfile)
hfile_steps_gp.append(gp)
keys = get_keys(hfile_steps_gp[-1])
for i,key in enumerate(keys):
t1 = time.time()
print("{}/{} {}".format(i,len(keys),key))
if key == 'inclination':
print('skipping in final output')
data_list = []
#units = None
for h_gp in hfile_steps_gp:
if key in h_gp:
data_list.append(h_gp[key].value)
data = np.concatenate(data_list)
hfile_gp_out[key]=data
#hfile_gp_out[key].attrs['units']=units
print("\t time: {:.2f}".format(time.time()-t1))
if not healpix:
hfile_gp_out['galaxyID'] = np.arange(hfile_gp_out['redshift'].size,dtype='i8')
return
def add_metadata(gal_ref_fname, out_fname, version_major,
version_minor, version_minor_minor, healpix_ref=None,
param_file=None, snapshot=False):
"""
Takes the metadata group and copies it over the final output product.
Also for each data column, copies the units attribute.
"""
add_units(out_fname)
hfile_gf = h5py.File(gal_ref_fname,'r')
hfile_out = h5py.File(out_fname,'a')
if 'metaData' in hfile_out:
del hfile_out['/metaData']
hfile_out.copy(hfile_gf['metaData/GalacticusParameters'],'/metaData/GalacticusParameters/')
hfile_out['/metaData/versionMajor'] = version_major
hfile_out['/metaData/versionMinor'] = version_minor
hfile_out['/metaData/versionMinorMinor'] = version_minor_minor
hfile_out['/metaData/version'] = "{}.{}.{}".format(version_major, version_minor, version_minor_minor)
hfile_out['/metaData/catalogCreationDate']=datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC")
if healpix_ref is not None:
hfile_hp = h5py.File(healpix_ref,'r')['metaData']
hfile_out['metaData/H_0'] = hfile_hp['H_0'].value
hfile_out['metaData/Omega_b'] = hfile_hp['Omega_b'].value
hfile_out['metaData/Omega_matter'] = hfile_hp['Omega_matter'].value
if not snapshot:
hfile_out['metaData/skyArea'] = hfile_hp['skyArea'].value
hfile_out['metaData/cosmoDC2_Model/synthetic_halo_minimum_mass'] = hfile_hp['synthetic_halo_minimum_mass'].value
hfile_out['metaData/cosmoDC2_Model/commit_hash'] = hfile_hp['commit_hash'].value
hfile_out['metaData/cosmoDC2_Model/seed'] = hfile_hp['seed'].value
else:
if not snapshot:
hfile_out['metaData/skyArea'] = 25
try:
#cmd = 'git rev-parse HEAD'
cmd = 'cd {0} && git rev-parse HEAD'.format(path_to_cosmodc2)
commit_hash = subprocess.check_output(cmd, shell=True).strip()
except subprocess.CalledProcessError as cpe:
with open('git_commit_hash.txt') as gcf:
commit_hash = gcf.read().rstrip()
print("commit hash: ", commit_hash)
hfile_out['/metaData/cosmodDC2_Matchup/commit_hash']= commit_hash
if param_file is not None:
with open(param_file, 'r') as pfile:
data = pfile.read()
hfile_out['/metaData/cosmodDC2_Matchup/config_file'] = data
def add_units(out_fname):
hfile = h5py.File(out_fname,'a')['galaxyProperties']
#################################
###Add units to all fields
#################################
mag_list = ['magnitude']; mag_unit = 'AB magnitude'
arcsec_list= ['Arcsec']; arcsec_unit = 'arcsecond'
rad_list = []; rad_unit ='radians'
deg_list = ['ra','dec','ra_true', 'dec_true', 'morphology/positionAngle','inclination']; deg_unit = 'degrees'
phys_kpc_list = ['Radius']; phys_kpc_unit = 'physical kpc'
phys_mpc_list = []; phys_mpc_unit = 'physical Mpc'
reduced_dist_list =['Reduced','EigenVector', 'Eddington'];reduced_dist_unit = 'unitless'
eigen_val_list = ['EigenValue'];eigen_val_unit = 'comoving Mpc/h'
comv_mpc_list = ['x','y','z']; comv_mpc_unit = 'comoving Mpc/h'
vel_list = ['vx','vy','vz','Velocity']; vel_unit = 'km/s'
timeSFR_list =['TimeWeightedIntegratedSFR']; timeSFR_unit = 'Gyr*Msun'
sfr_list =['SFR','blackHoleAccretionRate','StarFormationRate']; sfr_unit = 'Msun/Gyr'
mass_list =['MassStellar','IntegratedSFR']; mass_unit = 'Msun'
halo_mass_list = ['HaloMass']; halo_mass_unit = 'Msun/h'
abundance_list =['Abundance'];abundance_unit = 'Msun'
luminosity_list =['Luminosities','Luminosity']; luminosity_unit = 'AB luminosity (4.4659e13 W/Hz)'
unitless_list = ['redshift','shear','magnification','convergence','Ellipticity','Sersic','AxisRatio','dustFactor']; unitless_unit ='unitless'
id_list = ['Index','Tag','placementType','galaxyID','lightcone_replication','lightcone_rotation', 'uniqueHaloID','isCentral']; id_unit = 'id/index'
angular_list = ['angularMomentum'];angular_unit = 'Msun*km/s*Mpc'
bool_list =['nodeIsIsolated'];bool_unit = 'boolean'
spinSpin_list =['spinSpin'];spinSpin_unit ='lambda'
step_list = ['step'];step_unit = 'simluation step'
umachine_list = ['UMachineNative', 'baseDC2', 'matchUp'];umachine_unit = 'Unspecified'
count_list =['NumberSelected'];count_unit = 'count'
print("assigning units")
keys = get_keys(hfile)
print( keys)
for key in keys:
print(key)
print('\t',hfile[key].dtype)
#add magnitude units
if(any(l in key for l in mag_list)):
hfile[key].attrs['units']=mag_unit
print("\t mag")
# umachine list
elif(any(l in key for l in umachine_list)):
hfile[key].attrs['units']=umachine_unit
#add arcsec units
elif(any(l in key for l in arcsec_list)):
hfile[key].attrs['units']=arcsec_unit
print( "\t ",arcsec_unit)
#add rad units
elif(any(l in key for l in rad_list)):
hfile[key].attrs['units']=rad_unit
print( "\t ",rad_unit)
#add degree units
elif(any(l == key for l in deg_list)):
hfile[key].attrs['units']=deg_unit
print( '\t',deg_unit)
#add kpc units
elif(any(l in key for l in phys_kpc_list)):
hfile[key].attrs['units']=phys_kpc_unit
print( "\t ",phys_kpc_unit)
#add mpc units
elif(any(l in key for l in phys_mpc_list)):
hfile[key].attrs['units']=phys_mpc_unit
print ("\t ",phys_mpc_unit)
#reduced distances units
elif(any(l in key for l in reduced_dist_list)):
hfile[key].attrs['units']=reduced_dist_unit
print ("\t ",reduced_dist_unit)
#eigen val units
elif(any(l in key for l in eigen_val_list)):
hfile[key].attrs['units']=eigen_val_unit
print ("\t ",reduced_dist_unit)
#add comoving mpc units
elif(any(l == key for l in comv_mpc_list)):
hfile[key].attrs['units']=comv_mpc_unit
print ("\t ",comv_mpc_unit)
#add velocity units
elif(any(l in key for l in vel_list)):
hfile[key].attrs['units']=vel_unit
print ("\t ",vel_unit)
#add timesfr
elif(any(l in key for l in timeSFR_list)):
hfile[key].attrs['units']=timeSFR_unit
print ("\t ",timeSFR_unit)
#add sfr
elif(any(l in key for l in sfr_list)):
hfile[key].attrs['units']=sfr_unit
print ("\t ",sfr_unit)
#add mass
elif(any(l in key for l in mass_list)):
hfile[key].attrs['units']=mass_unit
print ("\t ",mass_unit)
#add halo mass
elif(any(l in key for l in halo_mass_list)):
hfile[key].attrs['units'] = halo_mass_unit
print ("\t ",halo_mass_unit)
#add abundance
elif(any(l in key for l in abundance_list)):
hfile[key].attrs['units']=abundance_unit
print ("\t ",abundance_unit)
#add luminosity units
elif(any(l in key for l in luminosity_list)):
hfile[key].attrs['units']=luminosity_unit
print ("\t ",luminosity_unit)
#add unit less
elif(any(l in key for l in unitless_list)):
hfile[key].attrs['units']=unitless_unit
print ("\t ",unitless_unit)
#add mass units
elif(any(l in key for l in id_list)):
hfile[key].attrs['units']=id_unit
print ("\t ",id_unit)
#angular momentum
elif(any(l in key for l in angular_list)):
hfile[key].attrs['units']=angular_unit
print ("\t ",angular_unit)
#boolean
elif(any(l in key for l in bool_list)):
hfile[key].attrs['units']=bool_unit
print ("\t", bool_unit)
#spinSpin
elif(any(l in key for l in spinSpin_list)):
hfile[key].attrs['units']=spinSpin_unit
# step
elif(any(l in key for l in step_list)):
hfile[key].attrs['units']=step_unit
#counts
elif(any(l in key for l in count_list)):
hfile[key].attrs['units']=count_unit
#Everything should have a unit!
else:
print("column", key, "was not assigned a unit :(")
print("===================")
#raise;
def plot_differences(lc_data, gal_prop, index, fig_id='', plotdir='./plots', ext='.png'):
keys = ['Mag_r','clr_gr','clr_ri','m_star']
dist = {}
dist_all = None
for key in keys:
d = lc_data[key]-gal_prop[key][index]
dist[key] = d
if(dist_all is None):
dist_all = d*d
else:
dist_all += d*d
dist_all = np.sqrt(dist_all)
# get fig name
fig_id = 'Diffs_{}'.format(fig_id) if fig_id != '' else 'Diffs_'
fignum = len(plt.get_fignums())
plt.figure()
for key in keys:
slct_fnt = np.isfinite(dist[key])
bins = np.linspace(np.min(dist[key][slct_fnt]), np.max(dist[key][slct_fnt]), 100)
h,xbins = np.histogram(dist[key][slct_fnt],bins=bins)
plt.plot(dtk.bins_avg(xbins),h,label=key)
plt.yscale('log')
plt.grid()
plt.legend(loc='best')
plt.xlabel('original value - matched value')
plt.ylabel('count')
figname = os.path.join(plotdir, '{}_N_vs_match_{}{}'.format(fig_id, fignum + 1, ext))
plt.savefig(figname, bbox_inches='tight')
plt.close()
fig = plt.figure()
slct_fnt = | np.isfinite(dist_all) | numpy.isfinite |
#Utility Functions
import copy
from collections import defaultdict
import glob
import os
import random
from stl import mesh
#Math Functions
import alphashape
from descartes import PolygonPatch
import math
import numpy as np
import scipy.linalg as ling
from scipy.spatial import Delaunay
from scipy.special import jn
#Drawing Functios
import matplotlib.pyplot
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection
from matplotlib.colors import LightSource
from matplotlib import cm
#Other Modules
from faser_math import fsr
from faser_utils.disp.disp import disp, progressBar
# Create an instance of a LightSource and use it to illuminate the surface.
def alpha_shape_3D(pos, alpha):
"""
Compute the alpha shape (concave hull) of a set of 3D points.
Parameters:
pos - np.array of shape (n, 3) points.
alpha - alpha value.
return
outer surface vertex indices, edge indices, and triangle indices
"""
#Function found here https://stackoverflow.com/questions/26303878/alpha-shapes-in-3d
tetra = Delaunay(pos)
# Find radius of the circumsphere.
# By definition, radius of the sphere fitting inside the tetrahedral needs
# to be smaller than alpha value
# http://mathworld.wolfram.com/Circumsphere.html
tetrapos = np.take(pos, tetra.vertices, axis=0)
normsq = np.sum(tetrapos**2, axis=2)[:,:,None]
ones = np.ones((tetrapos.shape[0], tetrapos.shape[1], 1))
a = np.linalg.det(np.concatenate((tetrapos, ones), axis=2))
Dx = np.linalg.det(np.concatenate((normsq, tetrapos[:,:,[1, 2]], ones), axis=2))
Dy = -np.linalg.det(np.concatenate((normsq, tetrapos[:,:,[0, 2]], ones), axis=2))
Dz = np.linalg.det(np.concatenate((normsq, tetrapos[:,:,[0, 1]], ones), axis=2))
c = np.linalg.det(np.concatenate((normsq, tetrapos), axis=2))
r = np.sqrt(Dx**2+Dy**2+Dz**2-4*a*c)/(2*np.abs(a))
# Find tetrahedrals
tetras = tetra.vertices[r<alpha,:]
# triangles
TriComb = np.array([(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)])
Triangles = tetras[:,TriComb].reshape(-1, 3)
Triangles = np.sort(Triangles, axis=1)
# Remove triangles that occurs twice, because they are within shapes
TrianglesDict = defaultdict(int)
for tri in Triangles:TrianglesDict[tuple(tri)] += 1
Triangles=np.array([tri for tri in TrianglesDict if TrianglesDict[tri] ==1])
#edges
EdgeComb= | np.array([(0, 1), (0, 2), (1, 2)]) | numpy.array |
import unittest
import numpy as np
import scipy.stats as stats
from collections import defaultdict
import testGeneral
import randomArbitrary
class TestGeneralRandomInteger(testGeneral.TestRNG):
def testRandIntegerCoversAllTheValues(self):
'Sampling integer values should eventually cover all possible values'
nPoints = 10
SAMPLES = 100 * nPoints
TIMES = 10
for t in xrange(TIMES): #@UnusedVariable
xValues = []
while len(xValues) < 2:
xValues = np.random.randint(-100, 100, nPoints).tolist()
xValues.sort()
xValues = np.unique(xValues)
pValues = np.arange(len(xValues)) + 1
rng = randomArbitrary.RandomArbitraryInteger(xValues, pValues)
rValues = rng.random(SAMPLES)
count = defaultdict(int)
for v in rValues:
count[v] += 1
for i in range(nPoints):
if i in xValues:
self.assertTrue(count[i] > 0)
else:
self.assertEqual(count[i], 0)
def testRandIntegerExcludedValues(self):
nPoints = 10
TIMES = 100 * nPoints
xValues = range(nPoints)
for i in range(nPoints):
pValues = np.arange(nPoints) + 1
pValues[i] = 0.0
rng = randomArbitrary.RandomArbitraryInteger(x=xValues,
p=pValues)
r = rng.random(TIMES)
f = filter(lambda v: v==i, r)
self.assertTrue(len(f)==0)
@staticmethod
def _chi2testSampleAgainsProbability(observed, expectedProbabilities):
'''chi2 test to test whether a sample is consistent with expected prob.
This function works only with integer samples in the range [0, n), where
n is a natural number
@param observed: the observed sample
@param expectedProbabilities: list of expected probabilities. Value at
index `i` corresponds to the probability of integer `i`.
@return: (chi2, pval)
'''
expectedProbabilities = np.array(expectedProbabilities)
countO = defaultdict(int)
for o in observed: countO[o] += 1
keys = range(len(expectedProbabilities))
countObserved = np.array([countO[k] for k in keys], dtype=float)
countObserved = countObserved / countObserved.sum()
chi2 = | np.sum((countObserved - expectedProbabilities) ** 2 / expectedProbabilities) | numpy.sum |
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import matplotlib, warnings
import numpy as np
import CoolProp
from CoolProp.CoolProp import PropsSI
from CoolProp.Plots.Common import BasePlot, PropertyDict, SIunits
def SimpleCycle(Ref,Te,Tc,DTsh,DTsc,eta_a,Ts_Ph='Ph',**kwargs):
"""
This function plots a simple four-component cycle, on the current axis, or that given by the optional parameter *axis*
Required parameters:
* Ref : A string for the refrigerant
* Te : Evap Temperature in K
* Tc : Condensing Temperature in K
* DTsh : Evaporator outlet superheat in K
* DTsc : Condenser outlet subcooling in K
* eta_a : Adiabatic efficiency of compressor (no units) in range [0,1]
Optional parameters:
* Ts_Ph : 'Ts' for a Temperature-Entropy plot, 'Ph' for a Pressure-Enthalpy
* axis : An axis to use instead of the active axis
* skipPlot : If True, won't actually plot anything, just print COP
"""
warnings.warn("This function has been deprecated. Please consider converting it to an object inheriting from \"BaseCycle\".",DeprecationWarning)
for i in kwargs:
warnings.warn("This function has been deprecated, your input \"{0}: {1}\" will be ignored".format(i,kwargs[i]),DeprecationWarning)
from CoolProp.Plots import SimpleCompressionCycle
cycle = SimpleCompressionCycle(fluid_ref=Ref, graph_type=Ts_Ph)
cycle.simple_solve_dt(Te, Tc, DTsh, DTsc, eta_a, SI=True)
print(cycle.COP_cooling(),cycle.COP_heating())
def TwoStage(Ref,Q,Te,Tc,DTsh,DTsc,eta_oi,f_p,Tsat_ic,DTsh_ic,Ts_Ph='Ph',prints=False,skipPlot=False,axis=None,**kwargs):
"""
This function plots a two-stage cycle, on the current axis, or that given by the optional parameter *axis*
Required parameters:
* Ref : Refrigerant [string]
* Q : Cooling capacity [W]
* Te : Evap Temperature [K]
* Tc : Condensing Temperature [K]
* DTsh : Evaporator outlet superheat [K]
* DTsc : Condenser outlet subcooling [K]
* eta_oi : Adiabatic efficiency of compressor (no units) in range [0,1]
* f_p : fraction of compressor power lost as ambient heat transfer in range [0,1]
* Tsat_ic : Saturation temperature corresponding to intermediate pressure [K]
* DTsh_ic : Superheating at outlet of intermediate stage [K]
Optional parameters:
* Ts_Ph : 'Ts' for a Temperature-Entropy plot, 'Ph' for a Pressure-Enthalpy
* prints : True to print out some values
* axis : An axis to use instead of the active axis
* skipPlot : If True, won't actually plot anything, just print COP
"""
warnings.warn("This function has been deprecated. PLease consider converting it to an object inheriting from \"BaseCycle\".",DeprecationWarning)
T=np.zeros((8))
h=np.zeros_like(T)
p=np.zeros_like(T)
s=np.zeros_like(T)
rho=np.zeros_like(T)
T[0]=np.NAN
s[0]=np.NAN
T[1]=Te+DTsh
pe=PropsSI('P','T',Te,'Q',1.0,Ref)
pc=PropsSI('P','T',Tc,'Q',1.0,Ref)
pic=PropsSI('P','T',Tsat_ic,'Q',1.0,Ref)
Tbubble_c=PropsSI('T','P',pc,'Q',0,Ref)
Tbubble_e=PropsSI('T','P',pe,'Q',0,Ref)
h[1]=PropsSI('H','T',T[1],'P',pe,Ref)
s[1]=PropsSI('S','T',T[1],'P',pe,Ref)
rho[1]=PropsSI('D','T',T[1],'P',pe,Ref)
T[5]=Tbubble_c-DTsc
h[5]=PropsSI('H','T',T[5],'P',pc,Ref)
s[5]=PropsSI('S','T',T[5],'P',pc,Ref)
rho[5]=PropsSI('D','T',T[5],'P',pc,Ref)
mdot=Q/(h[1]-h[5])
rho1=PropsSI('D','T',T[1],'P',pe,Ref)
h2s=PropsSI('H','S',s[1],'P',pic,Ref)
Wdot1=mdot*(h2s-h[1])/eta_oi
h[2]=h[1]+(1-f_p)*Wdot1/mdot
T[2]=PropsSI('T','H',h[2],'P',pic,Ref)
s[2]=PropsSI('S','T',T[2],'P',pic,Ref)
rho[2]=PropsSI('D','T',T[2],'P',pic,Ref)
T[3]=288
p[3]=pic
h[3]=PropsSI('H','T',T[3],'P',pic,Ref)
s[3]=PropsSI('S','T',T[3],'P',pic,Ref)
rho[3]=PropsSI('D','T',T[3],'P',pic,Ref)
rho3=PropsSI('D','T',T[3],'P',pic,Ref)
h4s=PropsSI('H','T',s[3],'P',pc,Ref)
Wdot2=mdot*(h4s-h[3])/eta_oi
h[4]=h[3]+(1-f_p)*Wdot2/mdot
T[4]=PropsSI('T','H',h[4],'P',pc,Ref)
s[4]=PropsSI('S','T',T[4],'P',pc,Ref)
rho[4]=PropsSI('D','T',T[4],'P',pc,Ref)
sbubble_e=PropsSI('S','T',Tbubble_e,'Q',0,Ref)
sbubble_c=PropsSI('S','T',Tbubble_c,'Q',0,Ref)
sdew_e=PropsSI('S','T',Te,'Q',1,Ref)
sdew_c=PropsSI('S','T',Tc,'Q',1,Ref)
hsatL=PropsSI('H','T',Tbubble_e,'Q',0,Ref)
hsatV=PropsSI('H','T',Te,'Q',1,Ref)
ssatL=PropsSI('S','T',Tbubble_e,'Q',0,Ref)
ssatV=PropsSI('S','T',Te,'Q',1,Ref)
vsatL=1/PropsSI('D','T',Tbubble_e,'Q',0,Ref)
vsatV=1/PropsSI('D','T',Te,'Q',1,Ref)
x=(h[5]-hsatL)/(hsatV-hsatL)
s[6]=x*ssatV+(1-x)*ssatL
T[6]=x*Te+(1-x)*Tbubble_e
rho[6]=1.0/(x*vsatV+(1-x)*vsatL)
h[6]=h[5]
h[7]=h[1]
s[7]=s[1]
T[7]=T[1]
p=[np.nan,pe,pic,pic,pc,pc,pe,pe]
COP=Q/(Wdot1+Wdot2)
RE=h[1]-h[6]
if prints==True:
print('x5:',x)
print('COP:', COP)
print('COPH', (Q+Wdot1+Wdot2)/(Wdot1+Wdot2))
print(T[2]-273.15,T[4]-273.15,p[2]/p[1],p[4]/p[3])
print(mdot,mdot*(h[4]-h[5]),pic)
print('Vdot1',mdot/rho1,'Vdisp',mdot/rho1/(3500/60.)*1e6/0.7)
print('Vdot2',mdot/rho3,'Vdisp',mdot/rho3/(3500/60.)*1e6/0.7)
print(mdot*(h[4]-h[5]),Tc-273.15)
for i in range(1,len(T)-1):
print('%d & %g & %g & %g & %g & %g \\\\' %(i,T[i]-273.15,p[i],h[i],s[i],rho[i]))
else:
print(Tsat_ic,COP)
if skipPlot==False:
if axis==None:
ax=matplotlib.pyplot.gca()
else:
ax=axis
if Ts_Ph in ['ph','Ph']:
ax.plot(h,p)
elif Ts_Ph in ['Ts','ts']:
s_copy=s.copy()
T_copy=T.copy()
for i in range(1,len(s)-1):
ax.plot(s[i],T[i],'bo',mfc='b',mec='b')
dT=[0,-5,5,-20,5,5,5]
ds=[0,0.05,0,0,0,0,0]
ax.text(s[i]+ds[i],T[i]+dT[i],str(i))
s=list(s)
T=list(T)
s.insert(7,sdew_e)
T.insert(7,Te)
s.insert(5,sbubble_c)
T.insert(5,Tbubble_c)
s.insert(5,sdew_c)
T.insert(5,Tc)
ax.plot(s,T)
s=s_copy
T=T_copy
else:
raise TypeError('Type of Ts_Ph invalid')
return COP
def EconomizedCycle(Ref,Qin,Te,Tc,DTsh,DTsc,eta_oi,f_p,Ti,Ts_Ph='Ts',skipPlot=False,axis=None,**kwargs):
"""
This function plots an economized cycle, on the current axis, or that given by the optional parameter *axis*
Required parameters:
* Ref : Refrigerant [string]
* Qin : Cooling capacity [W]
* Te : Evap Temperature [K]
* Tc : Condensing Temperature [K]
* DTsh : Evaporator outlet superheat [K]
* DTsc : Condenser outlet subcooling [K]
* eta_oi : Adiabatic efficiency of compressor (no units) in range [0,1]
* f_p : fraction of compressor power lost as ambient heat transfer in range [0,1]
* Ti : Saturation temperature corresponding to intermediate pressure [K]
Optional parameters:
* Ts_Ph : 'Ts' for a Temperature-Entropy plot, 'Ph' for a Pressure-Enthalpy
* axis : An axis to use instead of the active axis
* skipPlot : If True, won't actually plot anything, just print COP
"""
warnings.warn("This function has been deprecated. Please consider converting it to an object inheriting from \"BaseCycle\".",DeprecationWarning)
from scipy.optimize import newton
m=1
T=np.zeros((11))
h=np.zeros_like(T)
p=np.zeros_like(T)
s= | np.zeros_like(T) | numpy.zeros_like |
import tensorflow as tf
import numpy as np
from skimage import transform, io, color
import os
test_pb_path = './final_output_stage3.pb'
raw_root = '/home/robot/Project/CPM_backup/data/test_pic/00008.bmp'
root = './'
def resize_to_imgsz(hm, img):
""" Create Tensor for joint position prediction
:param hm: Assuming input of shape (sz, w, h, c)
:param img: Assuming input of shape (sz, w, h, c)
:return:
"""
# assert len(hm.shape) == 4 and len(img.shape) == 4
ret_map = np.zeros((hm.shape[0], img.shape[1], img.shape[2], hm.shape[-1]), np.float32)
for n in range(hm.shape[0]):
for c in range(hm.shape[-1]):
ret_map[n,:,:,c] = transform.resize(hm[n,:,:,c], img.shape[1: 3])
return ret_map
with tf.Graph().as_default():
output_graph_def = tf.GraphDef()
with open(test_pb_path, "rb") as f:
output_graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(output_graph_def, name="")
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
input_x = sess.graph.get_tensor_by_name("input/img_in:0")
out_put = sess.graph.get_tensor_by_name("CPM/final_output_stage3:0")
t_img = io.imread(raw_root)
"""
#input_list.append(cv2.resize(t_img, (in_size_w, in_size_h)))
_input = np.array(t_img)
_input =_input.reshape((1, 560, 2448, 3))
"""
t_img = transform.resize(t_img, (280, 1224))
t_img = color.rgb2gray(t_img)
_input = np.array(t_img)
_input = _input.reshape((1, 280, 1224, 1))
print('input_shape:', _input.shape)
# pred_map = sess.run(out_put, feed_dict={input_x: _input / 255.0})[:, -1]
pred_map = sess.run(out_put, feed_dict={input_x: _input})
print('output_shape:', pred_map.shape)
print('output_dtype:', pred_map.dtype)
print('output_nbytes:', pred_map.nbytes)
print (pred_map[0, 0, 0, 0])
print (pred_map[0, 0, 0, 1])
print (pred_map[0, 14, 109, 0])
print (pred_map[0, 14, 109, 1])
print (np.where(pred_map==np.max(pred_map)))
print (np.max(pred_map[0, :, :, :]))
r_pred_map = resize_to_imgsz(np.expand_dims(pred_map[0], 0),
| np.expand_dims(_input[0], 0) | numpy.expand_dims |
import numpy as np
def test_posterior_fixture(test_posterior):
assert isinstance(test_posterior, dict)
assert isinstance(test_posterior["basis"], np.ndarray)
assert isinstance(test_posterior["dates"], np.ndarray)
assert isinstance(test_posterior["lineages"], np.ndarray)
assert isinstance(test_posterior["cases"], np.ndarray)
# def test_clock_reset_fixture(test_clock_reset_model):
# pass
def test_aggregate_log_R(clock_reset_model):
cluster = np.array([0, 0, 1, 1])
aggregated_lambda = clock_reset_model.aggregate_log_R(cluster)
assert aggregated_lambda.shape == (100, 2, 205, 1)
cluster = np.array([0, 0, 0, 0])
aggregated_lambda = clock_reset_model.aggregate_log_R(cluster)
assert aggregated_lambda.shape == (100, 1, 205, 1)
cluster = np.array([0, 0, 1, 2])
aggregated_lambda = clock_reset_model.aggregate_log_R(cluster)
assert aggregated_lambda.shape == (100, 3, 205, 1)
def test_aggregate_lambda_lineage(clock_reset_model):
cluster = np.array([0, 0, 1, 1])
aggregated_lambda = clock_reset_model.aggregate_lambda_lineage(cluster)
assert aggregated_lambda.shape == (100, 2, 205, 59)
cluster = np.array([0, 0, 0, 0])
aggregated_lambda = clock_reset_model.aggregate_lambda_lineage(cluster)
assert aggregated_lambda.shape == (100, 1, 205, 59)
cluster = np.array([0, 0, 1, 2])
aggregated_lambda = clock_reset_model.aggregate_lambda_lineage(cluster)
assert aggregated_lambda.shape == (100, 3, 205, 59)
def test_aggregate_lambda(clock_reset_model):
cluster = np.array([0, 0, 1, 1])
aggregated_lambda = clock_reset_model.aggregate_lambda(cluster)
assert aggregated_lambda.shape == (100, 2, 205, 1)
cluster = np.array([0, 0, 0, 0])
aggregated_lambda = clock_reset_model.aggregate_lambda(cluster)
assert aggregated_lambda.shape == (100, 1, 205, 1)
cluster = np.array([0, 0, 1, 2])
aggregated_lambda = clock_reset_model.aggregate_lambda(cluster)
assert aggregated_lambda.shape == (100, 3, 205, 1)
def test_aggregate_probabilities(clock_reset_model):
cluster = np.array([0, 0, 1, 1])
aggregated_lambda = clock_reset_model.aggregate_probabilities(cluster)
assert aggregated_lambda.shape == (100, 2, 205, 59)
cluster = np.array([0, 0, 0, 0])
aggregated_lambda = clock_reset_model.aggregate_probabilities(cluster)
assert aggregated_lambda.shape == (100, 1, 205, 59)
cluster = np.array([0, 0, 1, 2])
aggregated_lambda = clock_reset_model.aggregate_probabilities(cluster)
assert aggregated_lambda.shape == (100, 3, 205, 59)
def test_get_lambda_interface(
lineage_model, independent_clock_reset_model, clock_reset_model
):
for model in [lineage_model, independent_clock_reset_model, clock_reset_model]:
assert model.get_lambda().ndim == 4
assert model.get_lambda().shape == (100, 4, 205, 1)
# latla
assert model.get_lambda(1).ndim == 4
assert model.get_lambda(1).shape == (100, 1, 205, 1)
assert model.get_lambda([1, 2]).shape == (100, 2, 205, 1)
assert model.get_lambda(np.array([1, 2])).shape == (100, 2, 205, 1)
# time
assert model.get_lambda(None, np.arange(10)).ndim == 4
assert model.get_lambda(None, np.arange(10)).shape == (100, 4, 10, 1)
assert model.get_lambda(None, 1).ndim == 4
assert model.get_lambda(None, 1).shape == (100, 4, 1, 1)
assert model.get_lambda(None, [1, 2]).ndim == 4
assert model.get_lambda(None, [1, 2]).shape == (100, 4, 2, 1)
# both at the same time
assert model.get_lambda(np.arange(2), np.arange(10)).ndim == 4
assert model.get_lambda(np.arange(2), np.arange(10)).shape == (100, 2, 10, 1)
assert model.get_lambda(1, np.arange(10)).ndim == 4
assert model.get_lambda(1, np.arange(10)).shape == (100, 1, 10, 1)
def test_growthrate_interface(clock_reset_model):
model = clock_reset_model
assert model.get_growth_rate().ndim == 4
assert model.get_growth_rate().shape == (100, 4, 205, 1)
# latla
assert model.get_growth_rate(1).ndim == 4
assert model.get_growth_rate(1).shape == (100, 1, 205, 1)
assert model.get_growth_rate([1, 2]).shape == (100, 2, 205, 1)
assert model.get_growth_rate(np.array([1, 2])).shape == (100, 2, 205, 1)
# time
assert model.get_growth_rate(None, np.arange(10)).ndim == 4
assert model.get_growth_rate(None, np.arange(10)).shape == (100, 4, 10, 1)
assert model.get_growth_rate(None, 1).ndim == 4
assert model.get_growth_rate(None, 1).shape == (100, 4, 1, 1)
assert model.get_growth_rate(None, [1, 2]).ndim == 4
assert model.get_growth_rate(None, [1, 2]).shape == (100, 4, 2, 1)
# both at the same time
assert model.get_growth_rate(np.arange(2), np.arange(10)).ndim == 4
assert model.get_growth_rate(np.arange(2), np.arange(10)).shape == (100, 2, 10, 1)
assert model.get_growth_rate(1, np.arange(10)).ndim == 4
assert model.get_growth_rate(1, np.arange(10)).shape == (100, 1, 10, 1)
def test_get_logits_interface(
lineage_model, independent_clock_reset_model, clock_reset_model
):
for model in [lineage_model, independent_clock_reset_model, clock_reset_model]:
assert model.get_logits().ndim == 4
assert model.get_logits().shape == (100, 4, 205, 59)
assert model.get_logits(1).ndim == 4
assert model.get_logits(1).shape == (100, 1, 205, 59)
assert model.get_logits([1, 2]).shape == (100, 2, 205, 59)
assert model.get_logits(np.array([1, 2])).shape == (100, 2, 205, 59)
assert model.get_logits(None, np.arange(10)).ndim == 4
assert model.get_logits(None, np.arange(10)).shape == (100, 4, 10, 59)
assert model.get_logits(None, 1).ndim == 4
assert model.get_logits(None, 1).shape == (100, 4, 1, 59)
assert model.get_logits(None, [1, 2]).ndim == 4
assert model.get_logits(None, [1, 2]).shape == (100, 4, 2, 59)
assert model.get_logits(None, None, np.arange(10)).ndim == 4
assert model.get_logits(None, None, np.arange(10)).shape == (100, 4, 205, 10)
assert model.get_logits(None, None, 1).ndim == 4
assert model.get_logits(None, None, 1).shape == (100, 4, 205, 1)
assert model.get_logits(None, None, [1, 2]).ndim == 4
assert model.get_logits(None, None, [1, 2]).shape == (100, 4, 205, 2)
assert model.get_logits(None, None, np.array([1, 2])).shape == (100, 4, 205, 2)
assert model.get_logits(np.arange(2), np.arange(10)).ndim == 4
assert model.get_logits(np.arange(2), np.arange(10)).shape == (100, 2, 10, 59)
assert model.get_logits(1, | np.arange(10) | numpy.arange |
# scipy, simpleaudio, numpy
# Working only on Windows!
from ledcd import CubeDrawer as cd
from scipy.fft import rfft, rfftfreq
from scipy.io import wavfile
import numpy as np
import time
import simpleaudio as sa
from offset_sphere import OffsetSphere
def smooth_fourie(arr):
return 1
drawer = cd.get_obj()
drawer.translate(7.5, 7.5, 7.5)
drawer.set_fps_cap(0)
sp = OffsetSphere(drawer, 3)
file_path = "ENTER HERE PATH TO THE WAV FILE"
if file_path == "ENTER HERE PATH TO THE WAV FILE":
print("Please provide some wav file")
exit(0)
rate, data = wavfile.read(file_path)
# If single channeled copy it and make 2 equal channels
if len(data.shape) != 2:
(shape_size,) = data.shape
data = np.concatenate([data, data], axis=None).reshape((shape_size, 2))
start_frame = 0
frame_size = rate // 15
smooth_window = 30
norm_vec = np.exp(
np.arange(-1, stop=0, step=1 / ((frame_size + 3 - smooth_window * 2) / 2)) * 2
)
wave_obj = sa.WaveObject.from_wave_file(file_path)
play_obj = wave_obj.play()
start_time = time.time()
while True:
start_frame = int((time.time() - start_time) * rate)
yfl = np.abs(rfft(data[start_frame : start_frame + frame_size, 0]))
yfr = np.abs(rfft(data[start_frame : start_frame + frame_size, 1]))
cumsum_vecl = np.cumsum(np.insert(yfl, 0, 0))
cumsum_vecr = np.cumsum( | np.insert(yfr, 0, 0) | numpy.insert |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Support functions for the sindy toolkit.
Called by 'runToolkit.py', 'runToolkitExtended.py' and by 'plotSelectedIterations.py'.
For the full procedure, see "README.md".
For method details, please see "A toolkit for data-driven discovery of governing equations in
high-noise regimes" (2022) by <NAME> and <NAME>.
Copyright (c) 2021 <NAME>. <EMAIL>
MIT License
"""
import sys
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LinearRegression
from numpy.linalg import lstsq # since this accepts complex inputs and targets.
from scipy.integrate import solve_ivp
"""
---------------------------------------------------------------------------------------------
------------------------ Function Defs ------------------------------------------------------
--------------------------------------------------------------------------------------------- """
#%% Functions for various model systems, that return initial conditions for derivatives.
# These are used to simulate the system via odeint():
def lorenz_fn(z, t, p=({'p0': 10, 'p1': 28, 'p2': np.round(-8/3, 2), 'numExtraVars': 0},)):
""" xDot = -p0*x + p0*y
yDot = p1*x - y - x*z
zDot = p2*z + x*y
Inputs:
z: np.vector of floats (initial conditions)
t: np.vector of floats (timesteps)
p: dict (system parameters)
Output:
derivList: np.vector of floats (initial conditions of derivatives).
"""
derivList = [
p['p0'] * (z[1] - z[0]),
z[0] * (p['p1'] - z[2]) - z[1],
z[0] * z[1] + p['p2'] * z[2]
]
for i in range(p['numExtraVars']):
derivList.append(0)
return derivList
# End of lorenz attractor fn
# -------------------------------------------------------------------
def dampedHarmonicOscillatorLinear_fn(z, t, p=({'p0': 0.1, 'p1': 2, 'numExtraVars': 0})):
""" xDot = -p0*x + p1*y
yDot = -p1*x - p0*y
Inputs:
z: np.vector of floats (initial conditions)
t: np.vector of floats (timesteps)
p: dict (system parameters)
Output:
derivList: np.vector of floats (initial conditions of derivatives).
"""
derivList = [
-p['p0']*z[0] + p['p1']*z[1],
-p['p1']*z[0] - p['p0']*z[1]
]
for i in range(p['numExtraVars']):
derivList.append(0)
return derivList
# end of dampedHarmonicOscillatorLinear_fn
# -------------------------------------------------------------------
def dampedHarmonicOscillatorCubic_fn(z, t, p=({'p0': 0.1, 'p1': 2, 'numExtraVars': 0})):
""" xDot = -p0*x^3 + p1*y^3
yDot = -p1*x^3 - p0*y^3
Inputs:
z: np.vector of floats (initial conditions)
t: np.vector of floats (timesteps)
p: dict (system parameters)
Output:
derivList: np.vector of floats (initial conditions of derivatives).
"""
derivList = [
-p['p0']*pow(z[0], 3) + p['p1']*pow(z[1], 3),
-p['p1']*pow(z[0], 3) - p['p0']*pow(z[1], 3)
]
for i in range(p['numExtraVars']):
derivList.append(0)
return derivList
# end of dampedHarmonicOscillatorCubic_fn
#----------------------------------------------------------------------
def threeDimLinear_fn(z, t, p=({'p0': 0.1, 'p1': 2, 'p2': 0.3, 'numExtraVars': 0})):
""" xDot = -p0*x - p1*y
yDot = p1*x - p0*y
zDot = -p2*z
Inputs:
z: np.vector of floats (initial conditions)
t: np.vector of floats (timesteps)
p: dict (system parameters)
Output:
derivList: np.vector of floats (initial conditions of derivatives).
NOTE: >= 4th order library terms cause failure in Brunton
"""
derivList = [
-p['p0']*z[0] - p['p1']*z[1],
p['p1']*z[0] - p['p0']*z[1],
-p['p2']*z[2]
]
for i in range(p['numExtraVars']):
derivList.append(0)
return derivList
# end of threeDimLinear_fn
# -------------------------------------------------------------------
def hopfNormalForm2D_fn(z, t, p=({'p0': 0, 'p1': -1, 'p2': 1, 'numExtraVars': 0})):
""" Mean field model with zDot == 0:
xDot = p0*x + p1*y - p2*x*(x^2 + y^2)
yDot = -p1*x + p0*y - p2*y*(x^2 + y^2)
where p0 = mu, p1 = omega, p2 = A, p3 = lambda in Brunton paper.
Note that in the 3D model, zDot = -p2 * (z - x^2 - y^2). In this 2D version we assume
lambda is big, so zDot -> 0 rapidly and thus z = x^2 + y^2.
TO-DO: we need param values for this model. mu is in [-0.2, 0.6]. omega, A, and lambda
values are unknown.
Initial values estimate: x,y = {1, 0.75} or {0,0} (see fig 3 in Brunton paper)
Inputs:
z: np.vector of floats (initial conditions)
t: np.vector of floats (timesteps)
p: dict (system parameters)
Output:
derivList: np.vector of floats (initial conditions of derivatives).
"""
derivList = [
p['p0'] * z[0] - p['p1'] * z[1] + p['p2'] * z[0] * (pow(z[0], 2) + pow(z[1], 2)),
p['p1'] * z[0] + p['p0'] * z[1] + p['p2'] * z[1] * (pow(z[0], 2) + pow(z[1], 2))
]
for i in range(p['numExtraVars']):
derivList.append(0)
return derivList
# end of hopfNormalForm2D_fn
# -------------------------------------------------------------------
def hopfNormalForm3D_fn(z, t, p=({'p0': 0, 'p1': -1, 'p2': 1, 'p3': 0.5, 'numExtraVars': 0})):
""" Mean field model with zDot == 0:
xDot = p0*x + p1*y - p2*x*z
yDot = -p1*x +p0*y - p2*y*z
zDot = -p3 * (z - x^2 - y^2).
where p0 = mu, p1 = omega, p2 = A, p3 = lambda in Brunton paper.
In this 3D version of the model, we assume lambda is not too big, so zDot is not == 0.
TO-DO: We need param values for this model. mu is in [-0.2, 0.6]. omega, A, and lambda
values are unknown. See tables 10, 11 in Brunton paper S.I.
Question: is mu being used in two ways, as a coefficient and as a "bifurcation parameter"
(see eg table 13)?
Initial values estimate: x,y = {1, 0.75} or {0,0} (see fig 3 in Brunton paper)
Inputs:
z: np.vector of floats (initial conditions)
t: np.vector of floats (timesteps)
p: dict (system parameters)
Output:
derivList: np.vector of floats (initial conditions of derivatives).
"""
derivList = [
p['p0'] * z[0] - p['p1'] * z[1] + p['p2'] * z[0] * z[2], # (pow(z[0], 2) + pow(z[1], 2)),
p['p1'] * z[0] + p['p0'] * z[1] + p['p2'] * z[1] * z[2], # (pow(z[0], 2) + pow(z[1], 2)),
-p['p3'] * (z[2] - pow(z[0],2) - pow(z[1], 2))]
for i in range(p['numExtraVars']):
derivList.append(0)
return derivList
# end of hopfNormalForm3D_fn
# ------------------------------------------------------------------
def generateModelStrAndTrueArrays_fn(modelSystem, p):
"""
Build a string describing the model.
Parameters
----------
modelSystem : str
p : dict
Returns
-------
modelStr : str.
trueLib : tuple of lists of str
trueLibCoeffs : tuple of lists of floats
"""
if modelSystem == 'lorenz':
modelStr = \
"x' = -" + str(p['p0']) + ' x + ' + str(p['p0']) + ' y' + '\n' + \
"y' = " + str(p['p1']) + ' x - y - x*z' + '\n' + \
"z' = " + str(p['p2']) + ' z' + ' + x*y'
trueLib = (['x','y'], ['x','y','x*z'], ['z', 'x*y'])
trueLibCoeffs = ([-p['p0'], p['p0']], [p['p1'], -1, -1], [p['p2'], 1])
if modelSystem == 'harmOscLinear':
modelStr = \
"x' = -" + str(p['p0']) + ' x + ' + str(p['p1']) + ' y' + '\n' + \
"y' = -" + str(p['p1']) + " x -" + str(p['p0']) + ' y'
trueLib = (['x', 'y'], ['x', 'y'])
trueLibCoeffs = ([-p['p0'], p['p1']], [-p['p1'], -p['p0']])
if modelSystem == 'harmOscCubic':
modelStr = \
"x' = -" + str(p['p0']) + ' x^3 + ' + str(p['p1']) + ' y^3' + '\n' + \
"y' = -" + str(p['p1']) + " x^3 -" + str(p['p0']) + ' y^3'
trueLib = (['x^3', 'y^3'], ['x^3', 'y^3'])
trueLibCoeffs = ([-p['p0'], p['p1']], [-p['p1'], -p['p0']])
if modelSystem == 'threeDimLinear':
modelStr = \
"x' = -" + str(p['p0']) + ' x - ' + str(p['p1']) + ' y' + '\n' + \
"y' = " + str(p['p1']) + " x -" + str(p['p0']) + ' y' + '\n' + \
"z' = -" + str(p['p2']) + " z"
trueLib = (['x', 'y'], ['x', 'y'], ['z'])
trueLibCoeffs = ([-p['p0'], -p['p1']], [p['p1'], -p['p0']], [-p['p2']])
if modelSystem == 'hopfNormal2D':
modelStr = \
"x' = " + str(p['p0']) + ' x + ' + str(p['p1']) + ' y ' + "+ " + str(p['p2']) + \
'(x^3 + x*y^2)' + '\n' + \
"y' = " + str(p['p1']) + ' x + ' + str(p['p0']) + ' y ' + "+ " + str(p['p2']) + \
'(y*x^2 + y^3)'
trueLib = (['x', 'y', 'x^3', 'x*y^2'], ['x', 'y', 'y^3', 'x^2*y'])
trueLibCoeffs = ([p['p0'], p['p1'], p['p2'], p['p2']],
[p['p1'], p['p0'], p['p2'], p['p2']])
if modelSystem == 'hopfNormal3D':
modelStr = \
"x' = " + str(p['p0']) + ' x - ' + str(p['p1']) + ' y ' + "+ " + str(p['p2']) + \
' x*z' + '\n' + \
"y' = " + str(p['p1']) + ' x + ' + str(p['p0']) + ' y ' + "+ " + str(p['p2']) + \
' y*z' + '\n' + \
"z' = -" + str(p['p3']) + ' * (z - x^2 - y^2)'
trueLib = (['x', 'y', 'x*z'], ['x', 'y', 'y*z'], ['z', 'x^2', 'y^2'])
trueLibCoeffs = ([p['p0'], p['p1'], p['p2']],
[p['p1'], p['p0'], p['p2']], [-p['p3'], p['p3'], p['p3']])
return modelStr, trueLib, trueLibCoeffs
# End of generateModelStrAndTrueArrays_fn
# ---------------------------------------------------
def generateTrueFunctionalAndCoeffArrays_fn(trueLib, trueLibCoeffs, functionList):
"""
Given lists of functional names as str, and the function list, construct a true
'functionsToUseArray'
Parameters
----------
trueLib : list-like of lists of str. len of list-like = numVars, len of each list = num true
library functionals for that variable
trueLibCoeffs : list-like of lists of floats. Matches 'trueLib' above.
functionList : list of str. The functional names
Returns
-------
trueLibraryArray : np.array of bools, numVars x numFunctionals
"""
trueLibraryArray = np.zeros((len(trueLib), len(functionList)), dtype=bool)
trueCoeffArray = np.zeros((len(trueLib), len(functionList)))
for v in range(len(trueLib)): # v is the variable index
theseFnalNames = np.array(trueLib[v])
theseCoeffs = np.array(trueLibCoeffs[v])
for f in range(len(functionList)):
ind = np.where(theseFnalNames == functionList[f])[0]
if len(ind) > 0: # ie functionList[f] is a true functional
trueLibraryArray[v, f] = True
trueCoeffArray[v, f] = theseCoeffs[ind]
return trueLibraryArray, trueCoeffArray
# End of generateTrueFunctionalAndCoeffArrays_fn
# ----------------------------------------------------------
def generateFunctionStr_fn(v, varInds, variableNames):
"""
Given a list, generate a string. Used by generatePolynomialLibrary_fn.
Parameters
----------
v : list of ints
varInds : list of ints
variableNames : list of str
Returns
-------
fnStr : str
"""
fnStr = ''
for i in varInds:
if i in v:
if len(fnStr) > 0: # case: we need a multiplication sign:
fnStr += '*'
fnStr += variableNames[i]
if np.sum(np.array(v) == i) > 1: # case: we need an exponent:
fnStr += '^' + str(np.sum(np.array(v) == i))
return fnStr
# End of generateFunctionStr_fn
#------------------------------------------------------------------------
def generatePolynomialLibrary_fn(variableNames, degree):
"""
Generate a library of polynomials up to a certain degree. Return two things: a list of
functional names and a list of recipes for use in ode evolutions.
NOTE: If there is one variable, and its name is more that one character, this function will
fail because 'varInds' will equal the number of characters in the variable name.
Parameters
----------
variableNames : list-like of str
degree : int
Returns
-------
functionList : list of str
recipes : list of lists, length = numFunctionals
"""
varInds = np.arange(len(variableNames))
recipes = []
functionList = []
recipes.append(-1) # the constant function
functionList.append('1')
# Treat degree = 1:
combos = [] # initialize
for i in varInds:
combos.append(i)
recipes.append(i)
functionList.append(variableNames[i])
deg = 2 # initialize
while deg <= degree:
combos = [(i, j) for i in varInds for j in combos] # vector of {int, list} entries,
# entry has total len = deg. There are duplicates at >= degree 3, eg (0,(0,1)) and
# (1,(0,0)). So for each entry we must (a) make into a single list; and (b) check that it
# is new before appending it to 'recipes' and 'functionList'.
# (a) combine int and list:
keepCombos = [] # to keep the non-duplicates
for k in range(len(combos)):
c = combos[k]
this = []
for i in c:
if isinstance(i, (int, np.integer)):
this.append(i)
else:
for j in i:
this.append(j)
this = list(np.sort(np.array(this)))
# 'this' is now a single sorted list of ints.
# (b) If 'this' is new, append to recipes:
addFlag = True
for i in recipes:
if not isinstance(i, (int, np.integer)):
if len(this) == len(i) and np.sum(np.array(this) == np.array(i)) == len(i):
addFlag = False
break
if addFlag:
recipes.append(this)
keepCombos.append(this)
functionList.append(generateFunctionStr_fn(this, varInds, variableNames))
# Update combos with non-duplicate list:
combos = keepCombos
deg += 1
return functionList, recipes
# End of generatePolynomialLibrary_fn
#--------------------------------------------------------------
def calculateLibraryFunctionalValues_fn(x, recipes):
"""
For each functional, calculate its values at the timepoints.
Parameters
----------
x : np.array of floats, numTimepoints x numVars
recipes : list of lists. The i'th list gives the indices of variables to be multiplied together
to generate the i'th functional.
Returns
-------
fnVals : np.array of floats, numTimepoints x numFunctionals.
"""
fnVals = np.zeros((x.shape[0], len(recipes)))
for i in range(fnVals.shape[1]):
r = recipes[i]
temp = np.ones(x.shape[0])
if isinstance(r, (int, np.integer)): # constant or degree 1 monomial
if r != -1: # ie not the constant functional
temp = x[:, r]
else: # >= degree 2
for j in r:
temp = temp * x[:, j]
fnVals[:, i] = temp
return fnVals
# End of calculateLibraryFunctionalValues_fn
#------------------------------------------------------------
#%% Make a hamming window:
def makeHammingWindow_fn(hammingWindowLength, plateauRatio=0):
"""" Generate a hamming window, perhaps with a flat plateau in the middle (ie a smoothed step
function).
Inputs:
hammingWindowLength: int
usePlateauHammingFilterFlag: Boolean
plateauRatio: float 0 to 1
Outputs:
hamm: vector with sum = 1
"""
if plateauRatio > 0:
# add a plateau in the middle:
plateauRatio = min(1, plateauRatio)
ends = int(np.ceil(hammingWindowLength*(1 - plateauRatio)))
if ends%2 == 1:
ends = ends + 1 # make even
rise = int(ends/2)
ends = np.hamming(ends) # ends is now a hamming vector
hamm = np.ones((1, hammingWindowLength))
hamm = hamm.flatten()
hamm[0:rise] = ends[0:rise]
hamm[-rise:] = ends[-rise:]
else:
# normal hamming filter
hamm = np.hamming(hammingWindowLength)
# Normalize:
hamm = hamm / np.sum(hamm)
return hamm
# End of makeHammingWindow_fn
#---------------------------------------------------------
def calculateSlopeAndStd_fn(x, dt, w):
''' given a time-series, do two things:
1. calculate the deriv at each point by simple rise/run (Euler formula)
2. calculate the std of a window (size2*h) at each point, using the slope from (1) to
first tilt the data to roughly slope = 1.
Inputs:
z: np.vector
dt: float
w: int. Window length
Outputs:
slopeX: np.vector
stdX: np.vector
meanX: np.vector
'''
h = int(np.round(w/2)) # Half the window length
slopeX = np.zeros(x.shape)
stdX = np.zeros(x.shape)
meanX = np.zeros(x.shape)
# For efficiency, we take the mean of the first window, then update it at each new point:
for i in range(len(x)):
if i == h + 1: # First point's window
b = np.mean(x[i:i + h])
a = np.mean(x[i-h:i])
if i > h + 1 and i < len(x) - h: # all ensuing points' windows
b = b + (x[i + h] - x[i])/h
a = a + (x[i] - x[i-h])/h
if i > h and i < len(x) - h: # all points' windows (ie happens for both above cases)
slopeX[i] = (b-a)/h
tilted = x[i-h:i+h] - slopeX[i]*np.array(range(-h, h))
stdX[i] = | np.std(tilted) | numpy.std |
# import required libraries
import numpy as np
import cv2
print('OpenCV version: '+cv2.__version__)
import matplotlib.pyplot as plt
import pandas as pd
import datetime
import os
from collections import Counter
# Set source folder
SRC_FOLDER = "C:/Users/raksh/OneDrive - The Pennsylvania State University/PhD Research/Paper-4/SysID Experiment/OL Test 3/"
# open and read file containing start and end timestamps of the videos
df_vidTimes = pd.read_excel(SRC_FOLDER + "Video_Timestamps_1.xlsx")
df_vidTimes.drop(df_vidTimes.columns[0],axis=1,inplace=True)
################ ALL FUNCTIONS DEFINITIONS ################
def perspCorrection(img,pt1,pt2,pt3,pt4,scale_width,scale_height):
# Create a copy of the image
img_copy = np.copy(img)
# Convert to RGB so as to display via matplotlib
# Using Matplotlib we can easily find the coordinates of the 4 points that is essential for finding then transformation matrix
#img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
# to calculate the transformation matrix
input_pts = np.float32([pt1,pt2,pt3,pt4])
output_pts = np.float32([[0,0],[scale_width-1,0],[0,scale_height-1],[scale_width-1,scale_height-1]])
# Compute the perspective transform M
M = cv2.getPerspectiveTransform(input_pts,output_pts)
# Apply the perspective transformation to the image
imgPersp = cv2.warpPerspective(img,M,(scale_width, scale_height)) #,flags=cv2.INTER_LINEAR) cv2.INTER_CUBIC is also an option
imgGrayPersp = cv2.cvtColor(imgPersp, cv2.COLOR_BGR2GRAY)
# visulaize corners using cv2 circles
for x in range (0,4):
cv2.circle(img_copy,(round(input_pts[x][0]),round(input_pts[x][1])),5,(0,0,255),cv2.FILLED)
return [img_copy,imgPersp,imgGrayPersp]
def extractTopBottom(img,tStart,tEnd,bStart,bEnd):
img_top = img[tStart[1]:tEnd[1],tStart[0]:tEnd[0]]
img_bottom = img[bStart[1]:bEnd[1],bStart[0]:bEnd[0]]
return [img_top,img_bottom]
def gaussianBlur(img,fsize):
# gaussian blur
gblur = cv2.GaussianBlur(img,(fsize,fsize),0)
return gblur
def medianBlur(img,fsize=3):
# median blur - effective at removing salt and pepper noise
mblur = cv2.medianBlur(img,fsize)
return mblur
def bilateralFilter(img):
# Bilateral filter preserves edges while removing noise
bfblur = cv2.bilateralFilter(img,9,75,75)
return bfblur
def gAdaptiveThresholding(img):
# median filtering
adaptive_gaussian = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
cv2.THRESH_BINARY,11,2)
return adaptive_gaussian
def morphOps(img,kernel1,kernel2,k1_num_passes=2):
# Closing = Dilation + Erosion
# dilation
mask_dil = cv2.dilate(img,kernel1,iterations = k1_num_passes)
# erosion
mask_erode = cv2.erode(mask_dil,kernel2,iterations = 1)
return mask_erode
def computeW_Rev(img,img_debug):
avg_num_pixels = 159
scaling_factor = 1.0
mm_per_pixel = ((1/32)*25.4)/(scaling_factor*avg_num_pixels)
edge_length_threshold = 55
min_L_edge_threshold = False
min_R_edge_threshold = False
# Predefine arrays for data storage
approx_edges = 10
num_edges = np.zeros(img.shape[0]) #,dtype=np.uint16)
edge_start = np.zeros([img.shape[0],approx_edges])#,dtype=np.uint16)
edge_end = np.zeros([img.shape[0],approx_edges])#,dtype=np.uint16)
edge_count = 0
k=0
sse = False
tse = False
# start scanning from (0,0) until black pixel is found
# go across columns first
for i in range(img.shape[0]):
found_edge = False
temp_edge_count = 0
k=0
for j in range(img.shape[1]):
if(img[i,j]<=50):
# Black pixel found - edge
if(found_edge==False):
found_edge = True
temp_edge_count += 1
num_edges[i] = temp_edge_count
edge_start[i][k] = j
k += 1
else:
if(found_edge):
edge_end[i][k-1] = j-1
found_edge = False
x = Counter(num_edges)
y = {z:count for z, count in x.items() if count >= edge_length_threshold and z > 1}
#print(y)
if(len(y)!=0):
edge_condition = sorted(y,key=y.get)[0]
else:
print('num_edges > 1 and length(num_edges) >= threshold not satisfied . . . Lowering threshold to identify matches')
w = {z:count for z, count in x.items() if count < edge_length_threshold and z > 1}
if(len(w)!=0):
print('Found num_edges > 1 and length(num_edges) < threshold!')
edge_condition = sorted(w,key=w.get)[0]
else:
print('Unable to find edge condition . . . check image')
edge_condition = -1
if img_debug:
print('edge condition: ' + str(edge_condition))
if edge_condition == 2: #max(num_edges)==2:
# max num_edges = 2
L1_edge_start = edge_start[:,0][np.argwhere(num_edges==2)][np.logical_and(edge_start[:,0][np.argwhere(num_edges==2)]>60,edge_start[:,0][np.argwhere(num_edges==2)]<300)]
L1_edge_end = edge_end[:,0][np.argwhere(num_edges==2)][np.logical_and(edge_end[:,0][np.argwhere(num_edges==2)]>60,edge_end[:,0][np.argwhere(num_edges==2)]<300)]
if(np.max(L1_edge_start)-np.min(L1_edge_start)>13):
L1_edge_start = L1_edge_start[L1_edge_start >= (np.max(L1_edge_start)-10)]
if(np.max(L1_edge_end)-np.min(L1_edge_end)>15):
L1_edge_end = L1_edge_end[L1_edge_end >= (np.max(L1_edge_end)-10)]
trueLedge_start = L1_edge_start
trueLedge_end = L1_edge_end
R1_edge_start = edge_start[:,1][np.argwhere(num_edges==2)][edge_start[:,1][np.argwhere(num_edges==2)]>350]
R1_edge_end = edge_end[:,1][np.argwhere(num_edges==2)][edge_end[:,1][np.argwhere(num_edges==2)]>350]
if(np.max(R1_edge_start)-np.min(R1_edge_start)>13):
R1_edge_start = R1_edge_start[R1_edge_start <= (np.min(R1_edge_start)+10)]
if(np.max(R1_edge_end)-np.min(R1_edge_end)>13):
R1_edge_end = R1_edge_end[R1_edge_end <= (np.min(R1_edge_end)+10)]
trueRedge_start = R1_edge_start
trueRedge_end = R1_edge_end
if(len(trueLedge_start)>len(trueLedge_end)):
trueLedge_start = np.array([trueLedge_start[i] for i in range(len(trueLedge_end))])
if(len(trueLedge_start)<len(trueLedge_end)):
trueLedge_end = np.array([trueLedge_end[i] for i in range(len(trueLedge_start))])
if(len(trueRedge_start)>len(trueRedge_end)):
trueRedge_start = np.array([trueRedge_start[i] for i in range(len(trueRedge_end))])
if(len(trueRedge_start)<len(trueRedge_end)):
trueRedge_end = np.array([trueRedge_end[i] for i in range(len(trueRedge_start))])
line1_start = (round(np.mean((trueLedge_start+trueLedge_end)/2)),0)
line1_end = (round(np.mean((trueLedge_start+trueLedge_end)/2)),img.shape[0])
line2_start = (round(np.mean((trueRedge_start+trueRedge_end)/2)),0)
line2_end = (round(np.mean((trueRedge_start+trueRedge_end)/2)),img.shape[0])
edge_count = 2
case_cond = 1
elif edge_condition == 3: #max(num_edges)==3:
# max num_edges = 3
# logic for finding true left edge
L2_edge_start = edge_start[:,1][np.argwhere(num_edges==3)][edge_start[:,1][np.argwhere(num_edges==3)]<250]
if(len(L2_edge_start)>=edge_length_threshold):
trueLedge_start = L2_edge_start
trueLedge_end = edge_end[:,1][np.argwhere(num_edges==3)][edge_end[:,1][np.argwhere(num_edges==3)]<250]
else:
if(len(edge_start[:,0][np.argwhere(num_edges==3)][np.logical_and(edge_start[:,0][np.argwhere(num_edges==3)]<250,edge_start[:,0][np.argwhere(num_edges==3)]>60)])!=0):
L1_edge_start = edge_start[:,0][np.argwhere(num_edges==3)][np.logical_and(edge_start[:,0][np.argwhere(num_edges==3)]<250,edge_start[:,0][np.argwhere(num_edges==3)]>60)]
if(len(L2_edge_start)!=0):
L1_edge_start = np.hstack((L1_edge_start,L2_edge_start))
if(np.max(L1_edge_start)-np.min(L1_edge_start)>13):
L1_edge_start = L1_edge_start[L1_edge_start >= (np.max(L1_edge_start)-10)]
else:
L1_edge_start = edge_start[:,0][np.argwhere(num_edges==2)][edge_start[:,0][np.argwhere(num_edges==2)]<250]
if(len(L1_edge_start)>=edge_length_threshold):
trueLedge_start = L1_edge_start
if(len(edge_start[:,0][np.argwhere(num_edges==3)][np.logical_and(edge_start[:,0][np.argwhere(num_edges==3)]<250,edge_start[:,0][np.argwhere(num_edges==3)]>60)])!=0):
trueLedge_end = edge_end[:,0][np.argwhere(num_edges==3)][np.logical_and(edge_end[:,0][np.argwhere(num_edges==3)]<250,edge_end[:,0][np.argwhere(num_edges==3)]>60)]
if(len(L2_edge_start)!=0):
trueLedge_end = np.hstack((trueLedge_end,edge_end[:,1][np.argwhere(num_edges==3)][edge_end[:,1][np.argwhere(num_edges==3)]<250]))
if(np.max(trueLedge_end)-np.min(trueLedge_end)>13):
trueLedge_end = trueLedge_end[trueLedge_end >= (np.max(trueLedge_end)-10)]
else:
trueLedge_end = edge_end[:,0][np.argwhere(num_edges==2)][edge_end[:,0][np.argwhere(num_edges==2)]<250]
elif(len(L1_edge_start)!=0 and len(L1_edge_start)<edge_length_threshold):
trueLedge_start = L1_edge_start
trueLedge_end = edge_end[:,0][np.argwhere(num_edges==3)][edge_end[:,0][np.argwhere(num_edges==3)]<250]
trueLedge_end = np.hstack((trueLedge_end,edge_end[:,0][np.argwhere(num_edges==2)][edge_end[:,0][np.argwhere(num_edges==2)]<250]))
min_L_edge_threshold = True
else:
print('max(num_edges)=3 invalid true left edge condition encountered . . . check code')
# logic for finding true right edge
R2_edge_start = edge_start[:,1][np.argwhere(num_edges==3)][edge_start[:,1][np.argwhere(num_edges==3)]>350]
if(len(R2_edge_start)>=edge_length_threshold):
trueRedge_start = R2_edge_start
trueRedge_end = edge_end[:,1][np.argwhere(num_edges==3)][edge_end[:,1][np.argwhere(num_edges==3)]>350]
else:
R1_edge_start = edge_start[:,1][np.argwhere(num_edges==2)][edge_start[:,1][np.argwhere(num_edges==2)]>350]
if(len(R1_edge_start)==0):
# three definite edges
trueRedge_start = edge_start[:,2][np.argwhere(num_edges==3)][edge_start[:,2][np.argwhere(num_edges==3)]>350]
trueRedge_end = edge_end[:,2][np.argwhere(num_edges==3)][edge_end[:,2][np.argwhere(num_edges==3)]>350]
elif(len(R1_edge_start)>=edge_length_threshold):
trueRedge_start = R1_edge_start
trueRedge_end = edge_end[:,1][np.argwhere(num_edges==2)][edge_end[:,1][np.argwhere(num_edges==2)]>350]
elif(len(R1_edge_start)!=0 and len(R1_edge_start)<edge_length_threshold):
# there are some elements but edge length is minimal
trueRedge_start = R1_edge_start
trueRedge_end = edge_end[:,1][np.argwhere(num_edges==2)][edge_end[:,1][np.argwhere(num_edges==2)]>350]
min_R_edge_threshold = True
else:
print('max(num_edges)=3 invalid true right edge condition encountered . . . check code')
if(np.max(trueRedge_start)-np.min(trueRedge_start)>13):
trueRedge_start = trueRedge_start[trueRedge_start <= (np.min(trueRedge_start)+10)]
if(np.max(trueRedge_end)-np.min(trueRedge_end)>13):
trueRedge_end = trueRedge_end[trueRedge_end <= (np.min(trueRedge_end)+10)]
if(len(trueLedge_start)>len(trueLedge_end)):
trueLedge_start = np.array([trueLedge_start[i] for i in range(len(trueLedge_end))])
if(len(trueLedge_start)<len(trueLedge_end)):
trueLedge_end = np.array([trueLedge_end[i] for i in range(len(trueLedge_start))])
if(len(trueRedge_start)>len(trueRedge_end)):
trueRedge_start = np.array([trueRedge_start[i] for i in range(len(trueRedge_end))])
if(len(trueRedge_start)<len(trueRedge_end)):
trueRedge_end = np.array([trueRedge_end[i] for i in range(len(trueRedge_start))])
if(len(trueLedge_start)<edge_length_threshold):
min_L_edge_threshold = True
if(len(trueRedge_start)<edge_length_threshold):
min_R_edge_threshold = True
if(min_L_edge_threshold or min_R_edge_threshold):
line1_start = (round(np.mean((trueLedge_start + trueLedge_end)/2)),0)
line1_end = (round(np.mean((trueLedge_start + trueLedge_end)/2)),img.shape[0])
line2_start = (round(np.mean((trueRedge_start + trueRedge_end)/2)),0)
line2_end = (round(np.mean((trueRedge_start + trueRedge_end)/2)),img.shape[0])
edge_count = 3
case_cond = 2
elif(np.logical_and(len(trueLedge_start)>=edge_length_threshold,len(trueRedge_start)>=edge_length_threshold)):
line1_start = (round(np.mean((trueLedge_start + trueLedge_end)/2)),0)
line1_end = (round(np.mean((trueLedge_start + trueLedge_end)/2)),img.shape[0])
line2_start = (round(np.mean((trueRedge_start + trueRedge_end)/2)),0)
line2_end = (round(np.mean((trueRedge_start + trueRedge_end)/2)),img.shape[0])
edge_count = 3
case_cond = 3
else:
print('max(num_edges)=3 with no matching condition reached . . . check code')
elif edge_condition == 4: #max(num_edges)==4:
# max num_edges = 4
# logic for finding true left edge
L3_edge_start = edge_start[:,2][np.argwhere(num_edges==4)][edge_start[:,2][np.argwhere(num_edges==4)]<250]
if(len(L3_edge_start)>=edge_length_threshold):
trueLedge_start = L3_edge_start
trueLedge_end = edge_end[:,2][np.argwhere(num_edges==4)][edge_end[:,2][np.argwhere(num_edges==4)]<250]
else:
L2_edge_start = edge_start[:,1][np.argwhere(num_edges==4)][np.logical_and(edge_start[:,1][np.argwhere(num_edges==4)]<250,edge_start[:,1][np.argwhere(num_edges==4)]>60)]
L2_edge_start = np.hstack((L2_edge_start,edge_start[:,1][np.argwhere(num_edges==3)][edge_start[:,1][np.argwhere(num_edges==3)]<250]))
if(len(L2_edge_start)>=edge_length_threshold):
trueLedge_start = L2_edge_start
trueLedge_end = edge_end[:,1][np.argwhere(num_edges==4)][np.logical_and(edge_end[:,1][np.argwhere(num_edges==4)]<250,edge_end[:,1][np.argwhere(num_edges==4)]>60)]
trueLedge_end = np.hstack((trueLedge_end,edge_end[:,1][np.argwhere(num_edges==3)][edge_end[:,1][np.argwhere(num_edges==3)]<250]))
else:
L1_edge_start = edge_start[:,0][np.argwhere(num_edges==2)][edge_start[:,0][np.argwhere(num_edges==2)]<250]
L1_edge_start = np.hstack((L1_edge_start,edge_start[:,0][np.argwhere(num_edges==3)][edge_start[:,0][np.argwhere(num_edges==3)]<250]))
L1_edge_start = np.hstack((L1_edge_start,edge_start[:,0][np.argwhere(num_edges==4)][edge_start[:,0][np.argwhere(num_edges==4)]<250]))
if(len(L1_edge_start)>= edge_length_threshold):
trueLedge_start = L1_edge_start
trueLedge_end = edge_end[:,0][np.argwhere(num_edges==2)][edge_end[:,0][np.argwhere(num_edges==2)]<250]
trueLedge_end = np.hstack((trueLedge_end,edge_end[:,0][np.argwhere(num_edges==3)][edge_end[:,0][np.argwhere(num_edges==3)]<250]))
trueLedge_end = np.hstack((trueLedge_end,edge_end[:,0][np.argwhere(num_edges==4)][edge_end[:,0][np.argwhere(num_edges==4)]<250]))
else:
print('max(num_edges)=4 invalid true left edge condition encountered . . . check code')
# logic for finding true right edge
R3_edge_start = edge_start[:,1][np.argwhere(num_edges==4)][edge_start[:,1][np.argwhere(num_edges==4)]>350]
if(len(R3_edge_start)>=edge_length_threshold):
trueRedge_start = R3_edge_start
trueRedge_end = edge_end[:,1][np.argwhere(num_edges==4)][edge_end[:,1][np.argwhere(num_edges==4)]>350]
else:
R2_edge_start = edge_start[:,2][np.argwhere(num_edges==4)][edge_start[:,2][np.argwhere(num_edges==4)]>350]
R2_edge_start = np.hstack((R2_edge_start,edge_start[:,1][np.argwhere(num_edges==3)][edge_start[:,1][np.argwhere(num_edges==3)]>350]))
if(len(R2_edge_start)>=edge_length_threshold):
trueRedge_start = R2_edge_start
trueRedge_end = edge_end[:,2][np.argwhere(num_edges==4)][edge_end[:,2][np.argwhere(num_edges==4)]>350]
trueRedge_end = np.hstack((trueRedge_end,edge_end[:,1][np.argwhere(num_edges==3)][edge_end[:,1][np.argwhere(num_edges==3)]>350]))
else:
R1_edge_start = edge_start[:,1][np.argwhere(num_edges==2)][edge_start[:,1][np.argwhere(num_edges==2)]>350]
R1_edge_start = np.hstack((R1_edge_start,edge_start[:,2][np.argwhere(num_edges==3)][edge_start[:,2][np.argwhere(num_edges==3)]>350]))
R1_edge_start = np.hstack((R1_edge_start,edge_start[:,3][np.argwhere(num_edges==4)][edge_start[:,3][np.argwhere(num_edges==4)]>350]))
if(len(R1_edge_start)>= edge_length_threshold):
trueRedge_start = R1_edge_start
trueRedge_end = edge_end[:,1][np.argwhere(num_edges==2)][edge_end[:,1][np.argwhere(num_edges==2)]>350]
trueRedge_end = np.hstack((trueRedge_end,edge_end[:,2][np.argwhere(num_edges==3)][edge_end[:,2][np.argwhere(num_edges==3)]>350]))
trueRedge_end = np.hstack((trueRedge_end,edge_end[:,3][np.argwhere(num_edges==4)][edge_end[:,3][np.argwhere(num_edges==4)]>350]))
else:
print('max(num_edges)=4 invalid true right edge condition encountered . . . check code')
if(len(trueLedge_start)>len(trueLedge_end)):
trueLedge_start = np.array([trueLedge_start[i] for i in range(len(trueLedge_end))])
if(len(trueLedge_start)<len(trueLedge_end)):
trueLedge_end = np.array([trueLedge_end[i] for i in range(len(trueLedge_start))])
if(len(trueRedge_start)>len(trueRedge_end)):
trueRedge_start = np.array([trueRedge_start[i] for i in range(len(trueRedge_end))])
if(len(trueRedge_start)<len(trueRedge_end)):
trueRedge_end = np.array([trueRedge_end[i] for i in range(len(trueRedge_start))])
if(np.logical_and(len(trueLedge_start)>=edge_length_threshold,len(trueRedge_start)>=edge_length_threshold)):
line1_start = (round(np.mean((trueLedge_start + trueLedge_end)/2)),0)
line1_end = (round(np.mean((trueLedge_start + trueLedge_end)/2)),img.shape[0])
line2_start = (round(np.mean((trueRedge_start + trueRedge_end)/2)),0)
line2_end = (round(np.mean((trueRedge_start + trueRedge_end)/2)),img.shape[0])
edge_count = 4
case_cond = 4
else:
print('max(num_edges)=4 with no matching condition reached . . . check code')
elif edge_condition > 4:
# greater than 4 max edges case is typically - stringing or rother artifact causing psuedo edges
# Identify true left edge
L4_edge_start = edge_start[:,3][np.argwhere(num_edges==5)][edge_start[:,3][np.argwhere(num_edges==5)]<250]
if(len(L4_edge_start)>=edge_length_threshold):
trueLedge_start = L4_edge_start
trueLedge_end = edge_end[:,3][np.argwhere(num_edges==5)][edge_end[:,3][np.argwhere(num_edges==5)]<250]
else:
L3_edge_start = edge_start[:,2][np.argwhere(num_edges==5)][edge_start[:,2][np.argwhere(num_edges==5)]<250]
L3_edge_start = np.hstack((L3_edge_start,edge_start[:,2][np.argwhere(num_edges==4)][edge_start[:,2][np.argwhere(num_edges==4)]<250]))
L3_edge_start = np.hstack((L3_edge_start,edge_start[:,1][np.argwhere(num_edges==3)][np.logical_and(edge_start[:,1][np.argwhere(num_edges==3)]<250,edge_start[:,1][np.argwhere(num_edges==3)]>60)]))
if(len(L3_edge_start)>=edge_length_threshold):
trueLedge_start = L3_edge_start
trueLedge_end = edge_end[:,2][np.argwhere(num_edges==5)][edge_end[:,2][np.argwhere(num_edges==5)]<250]
trueLedge_end = np.hstack((trueLedge_end,edge_end[:,2][np.argwhere(num_edges==4)][edge_end[:,2][np.argwhere(num_edges==4)]<250]))
trueLedge_end = np.hstack((trueLedge_end,edge_end[:,1][np.argwhere(num_edges==3)][edge_end[:,1][np.argwhere(num_edges==3)]<250]))
elif(len(L3_edge_start)!= 0 and len(L3_edge_start)<edge_length_threshold):
trueLedge_start = L3_edge_start
trueLedge_end = edge_end[:,2][np.argwhere(num_edges==5)][edge_end[:,2][np.argwhere(num_edges==5)]<250]
trueLedge_end = np.hstack((trueLedge_end,edge_end[:,2][np.argwhere(num_edges==4)][edge_end[:,2][np.argwhere(num_edges==4)]<250]))
trueLedge_end = np.hstack((trueLedge_end,edge_end[:,1][np.argwhere(num_edges==3)][edge_end[:,1][np.argwhere(num_edges==3)]<250]))
min_L_edge_threshold = True
else:
# L2_edge_start = edge_start[:,1][np.argwhere(num_edges==3)][edge_start[:,1][np.argwhere(num_edges==3)]<250]
# L2_edge_start = np.hstack((L2_edge_start,edge_start[:,0][np.argwhere(num_edges==3)][edge_start[:,0][np.argwhere(num_edges==3)]<250]))
# if(len(L2_edge_start)>=edge_length_threshold):
# trueLedge_start = L2_edge_start
# trueLedge_end = edge_end[:,1][np.argwhere(num_edges==3)][edge_end[:,1][np.argwhere(num_edges==3)]<250]
# trueLedge_end = np.hstack((trueLedge_end,edge_end[:,0][np.argwhere(num_edges==3)][edge_end[:,0][np.argwhere(num_edges==3)]<250]))
# else:
print('max(num_edges)>4 invalid true left edge condition encountered . . . check code')
# Identify true right edge
sse_Redge_start = edge_start[:,3][np.argwhere(num_edges==5)][edge_start[:,3][np.argwhere(num_edges==5)]>350]
sse_Redge_start = np.hstack((sse_Redge_start,edge_start[:,2][np.argwhere(num_edges==4)][edge_start[:,2][np.argwhere(num_edges==4)]>350]))
if(len(sse_Redge_start)>=edge_length_threshold):
trueRedge_start = sse_Redge_start
trueRedge_end = edge_end[:,3][ | np.argwhere(num_edges==5) | numpy.argwhere |
# <NAME> 2014-2020
# mlxtend Machine Learning Library Extensions
#
# Bootstrap functions
# Author: <NAME> <<EMAIL>>
#
# License: BSD 3 clause
import numpy as np
from .bootstrap_outofbag import BootstrapOutOfBag
from sklearn.base import clone
from itertools import product
def _check_arrays(X, y=None):
if isinstance(X, list):
raise ValueError('X must be a numpy array')
if not len(X.shape) == 2:
raise ValueError('X must be a 2D array. Try X[:, numpy.newaxis]')
try:
if y is None:
return
except(AttributeError):
if not len(y.shape) == 1:
raise ValueError('y must be a 1D array.')
if not len(y) == X.shape[0]:
raise ValueError('X and y must contain the'
'same number of samples')
def no_information_rate(targets, predictions, loss_fn):
combinations = np.array(list(product(targets, predictions)))
return loss_fn(combinations[:, 0], combinations[:, 1])
def accuracy(targets, predictions):
return np.mean(np.array(targets) == np.array(predictions))
def mse(targets, predictions):
return np.mean(( | np.array(targets) | numpy.array |
import numpy as np
import pytest
from numpy.testing import (
assert_array_almost_equal, assert_array_equal,
assert_almost_equal
)
from mne.utils import assert_object_equal
from mne_connectivity import vector_auto_regression, select_order
warning_str = dict(
sm_depr='ignore:Using or importing*.:DeprecationWarning', # noqa
)
def bivariate_var_data():
"""A bivariate dataset for VAR estimation."""
rng = np.random.RandomState(12345)
e = rng.standard_normal((252, 2))
y = np.zeros_like(e)
y[:2] = e[:2]
for i in range(2, 252):
y[i] = 0.2 * y[i - 1] + 0.1 * y[i - 2] + e[i]
return y
def create_noisy_data(
add_noise,
sigma=1e-4,
m=100,
random_state=12345,
):
"""Create noisy test data.
Generate a 2x2 linear system, and perturb
observations of the state variables with Gaussian noise.
Parameters
----------
add_noise : bool
Whether to add noise or not.
sigma : float
noise standard deviation.
m : int
The number of samples.
return_A : bool
Whether to return the A matrix
random_state : None | int | instance of ~numpy.random.RandomState
If ``random_state`` is an :class:`int`, it will be used as a seed for
:class:`~numpy.random.RandomState`. If ``None``, the seed will be
obtained from the operating system (see
:class:`~numpy.random.RandomState` for details). Default is
``None``.
Returns
-------
sample_data : ndarray, shape (n_channels, n_samples)
Observed sample data. Possibly with noise.
sample_eigs : np.ndarray
The true eigenvalues of the system.
sample_A : np.ndarray
(Optional) if ``return_A`` is True, then returns the
true linear system matrix.
"""
rng = np.random.RandomState(random_state)
mu = 0.0
noise = rng.normal(mu, sigma, m) # gaussian noise
A = np.array([[1.0, 1.0], [-1.0, 2.0]])
A /= np.sqrt(3)
# compute true eigenvalues
true_eigvals = | np.linalg.eigvals(A) | numpy.linalg.eigvals |
import string
import numpy as np
from scipy.constants import codata
from scipy.fftpack import fft, ifft
eV = codata.value("electron volt")
me = codata.value("electron mass") * 1e15 # convert to pico grams
hbar = codata.value("Planck constant over 2 pi") * 1e27 # convert to pico-compatible values
class TransmissionCalculator():
"""
Calculates the probability of an electron tunneling through an potential barrier.
Parameters
----------
E : float
Energy of the electron in meV
dx : float
Distance between two neighboring sample points in pm
barrier : Array
Potenital barrier to be tunneled through with values in meV
"""
def __init__(
self,
step_callback = None,
step_exit = None,
value_callback = None,
_me = None,
x0 = None,
_hbar = None,
package_wdh = None,
disable_electron_potential_validation = None
):
"""
Dependency-Injection constructor for injecting functionality and/or configuration
via external components. This enables full testability of this module without having
to modify or rely on production-components.
This constructor is not relevant for production purposes. Use the default (empty)
constructor instead.
"""
global me
global hbar
self.step_callback = step_callback
self.step_exit = step_exit
self.value_callback = value_callback
self.mock_package_width = package_wdh
self.disable_electron_potential_validation = disable_electron_potential_validation
self.mock_x0 = x0
if (_me):
me = _me
if (_hbar):
hbar = _hbar
def validate_input(self, E, barrier, dx):
"""
This function tests the input parameters for validity.
It tests both the data types aswell the vaulue range and shows an error message for all upcoming issues.
The error message is alwats of the form: Validation Error: $message Details: $details
"""
error_msg_tmpl = string.Template("Validation Error: $message Details: $details")
if (not hasattr(barrier, "__iter__") or np.array(barrier).ndim != 1):
message = "The potential must be an array of one dimension"
details = f"Dimension: {np.array(barrier).ndim}. Instance: {barrier.__class__.__name__}"
raise ValueError(error_msg_tmpl.substitute(message = message, details = details))
max_V = max(barrier)
min_V = min(barrier)
if (E < 0):
message = "Electron energy must be greater than 0."
details = f"Electron energy given: {E}."
raise ValueError(error_msg_tmpl.substitute(message = message, details = details))
if (E > max_V and not self.disable_electron_potential_validation):
message = "Electron energy cannot be bigger than max potential value."
details = f"Electron energy given: {E}. Max Potential: {max_V}."
raise ValueError(error_msg_tmpl.substitute(message = message, details = details))
if (max_V == 0 and min_V == 0 and not self.disable_electron_potential_validation):
message = "Potential must contain values other than 0."
details = f"Empty."
raise ValueError(error_msg_tmpl.substitute(message = message, details = details))
if (dx <= 0):
message = "dx must be greater than 0"
details = f"dx: {dx}."
raise ValueError(error_msg_tmpl.substitute(message = message, details = details))
def calculate_transmission(self, E, barrier, dx):
"""
Here the actual calculation happens.
First it builds up the potential and the position grid. If needed it also fits sizes.
Then it creates the wavenumber grind based on the length of the position grid.
As soon as we built up all of that we can use the Split-Step-Method to simulate
the transmission of our electron, representet by a gaussian wave. The algorith works like that:
Transforming the wavepackage into pulse space with the Fouriertransformation.
Multiplying the package with the diagonal elements of the pulse operator for half a time step:
.. math::
\\exp(-i* \\delta t * hbar * (k_i)^2 / (4*m))
Reverse Fourier Transformation
Multiplying with diganoal elements of pulse operator:
.. math::
\\exp(-i*V_i * \\delta t / hbar)
Fourier Transformation again
Multiplying with the diagonal elements of the pulse operator for a full time step:
.. math::
\\exp(-i* \\delta t * hbar * (k_i)^2 / (2*m))
Repeat that until you reach the last time step and finish it with a multiplication of the
package with the diagonal elements of the pulse operator for half a time step instead.
For every step it calculates the transmission propability by dividing the current square
of the absolute value by the original one.
It compares every vaule with the one before and as soon as the diffrence
drops below a very low value the chain breaks.
"""
self.validate_input(E, barrier, dx)
E = E * eV * 1e40 # 1e-3 * 1e12 * 1e31
barrier = barrier * eV * 1e40 # * 1e-3 * 1e12 * 1e31
# dx = dx * 1e-12
#input parameters
self.E = E
self.dx = dx
self.barrier = barrier
#build potential and helper objects
self.N = barrier.size
self.V = self.get_potential()
self.trans_index = self.get_first_index_behind_barrier()
#build position grid and fix sizes with respect to V if needed. This could be nessesary if N is odd
self.x = self.get_position_grid()
while self.x.size<self.V.size:
self.x = np.append(self.x,[self.x[-1]+self.dx])
while self.x.size>self.V.size:
self.V = np.append(self.V,[0])
#build wavenumbergrid depending on the now known length len(self.x)
self.M = self.V.size
self.k_min = -np.pi/self.dx
self.dk = 2*np.pi/(self.x[-1]-self.x[0])
self.k = self.get_wavenumber_grid()
max_k = self.get_wavenumber_grid()[-1]
self.k0 = np.sqrt(2*me*self.E)/hbar
max_E = max_k**2 * hbar**2 / (2 * me)
if (self.k0 >= max_k and self.disable_electron_potential_validation != True):
error_msg_tmpl = string.Template("Validation Error: $message Details: $details")
message = "The energy provided results in too much intertia. The algorithm cannot provide results for such energies."
details = f"Energy: {E}. Allowed energy range: (0, {max_E / eV} eV]."
raise ValueError(error_msg_tmpl.substitute(message = message, details = details))
#choose parameters for the initial state (gaussian package)
self.sigma = self.dx*self.N / 10 if self.mock_package_width is None else self.mock_package_width #initial width of the package
self.x0 = self.x[self.trans_index-self.N-5*int(self.sigma/self.dx+1)] if self.mock_x0 is None else self.mock_x0 #initial width of the package
#build initial state (gaussian package)
self.psi0 = (2/(np.pi*self.sigma**2))**(1/4) * np.exp(1j*self.k0*(self.x-self.x0)) * np.exp(-((self.x-self.x0)/self.sigma)**2)
before_barrier = 25 * self.N * self.dx
in_barrier = self.barrier.size * self.dx
after_barrier = 15 * self.sigma * self.dx
self.v_max = (hbar / me) * np.sqrt(2*me*(self.E))
if (max(self.V) == self.E):
self.E = self.E - self.E / 1000
self.v_min = (hbar / me) * np.sqrt(2*me*np.abs((max(self.V) - self.E)))
t_in = in_barrier / self.v_min
t_after = after_barrier/ self.v_max
t_before = before_barrier / self.v_max
self.t = t_after + t_before + t_in
#build initial state (gaussian package)
self.psi0 = (2/(np.pi*self.sigma**2))**(1/4) * np.exp(1j*self.k0*(self.x-self.x0)) * np.exp(-((self.x-self.x0)/self.sigma)**2)
#chosse time between to two neigbourt time sample points (to be used in the split step algorithm)
self.dt = self.t * 1e-11
#build operators for the accelorated algorithm
self.V_op = np.exp(-(1j*self.V*self.dt/hbar))
self.T_op_first_final = np.exp(-(1j*self.dt*np.multiply(self.k,self.k)*hbar/(4*me)))
self.T_op_step = np.exp(-(1j*self.dt*hbar*np.multiply(self.k,self.k)/(2*me)))
if (self.value_callback != None):
self.value_callback(self)
#performing z steps and calculate the probability of presence behind the barrier
self.psi_after_steps = self.perform_split_steps()
#calculate density of presence
self.density_after_steps = self.get_density_of_probability(self.psi_after_steps)
#calculate transmission probability after 1500 steps
return self.get_transmission(self.density_after_steps)
def get_potential(self):
zeros = | np.zeros(25*self.N) | numpy.zeros |
#! /usr/bin/python3
print('this is cell-analyzer v0.1.0' + '\n')
print('preparing image segmentation run...' + '\n')
import os
import glob
import numpy as np
import pandas as pd
import skimage as sk
import seaborn as sns
import matplotlib.pyplot as plt
import scipy.cluster.hierarchy as shc
from datetime import datetime as dt
from matplotlib.colors import ListedColormap, LogNorm
from matplotlib import cm
from skimage import exposure, feature, filters, measure, morphology, segmentation
from scipy import ndimage as ndi
from sklearn.cluster import AgglomerativeClustering
from sklearn.preprocessing import StandardScaler
from sklearn.manifold import TSNE
import umap
import warnings
warnings.filterwarnings("ignore")
def process_image(img, norm_window, min_hole_size, min_cell_size, extrema_blur, peak_sep, name='temp.TIF', save_path = '.'):
img_dims = np.shape(img)
print('image dimensions: ', img_dims)
if len(img_dims) < 3:
n_chan = 1
content = img
v_min, v_max = np.percentile(content, (1,99))
content_scaled = exposure.rescale_intensity(content, in_range=(v_min, v_max))
else:
# handle if first channel is blank
if np.mean(img[:,:,0]) < 1:
img = img[:,:,1:]
img_dims = np.shape(img)
# handle other blank channels
n_chan = img_dims[2]
base = img[:,:,0]
# restack image, excluding blank channels
for channel in range(1, n_chan):
if np.sum(img[:,:,channel]) > (img_dims[0] * img_dims[1] * 0.2):
base = np.stack((base, img[:,:,channel]), axis=2)
img = base
img_dims = np.shape(img)
n_chan = img_dims[2]
### custom colormaps
N = 256
blank = np.zeros(N)
gray = np.linspace(0, 1, N)
# blue
blues = np.ones((N,4))
blues[:,0] = blank
blues[:,1] = blank
blues[:,2] = gray
blue_cmap = ListedColormap(blues)
# green
greens = np.ones((N,4))
greens[:,0] = blank
greens[:,1] = gray
greens[:,2] = blank
green_cmap = ListedColormap(greens)
# red
reds = np.ones((N,4))
reds[:,0] = gray
reds[:,1] = blank
reds[:,2] = blank
red_cmap = ListedColormap(reds)
# separate and scale channels for vis
content = np.sum(img, axis=2)
v_min, v_max = np.percentile(content, (1,99))
content_scaled = exposure.rescale_intensity(content, in_range=(v_min, v_max))
if n_chan >= 1:
dapi = img[:,:,0]
v_min, v_max = np.percentile(dapi, (1,99))
dapi_scaled = exposure.rescale_intensity(dapi, in_range=(v_min, v_max))
if n_chan >= 2:
gfp = img[:,:,1]
v_min, v_max = np.percentile(gfp, (1,99))
gfp_scaled = exposure.rescale_intensity(gfp, in_range=(v_min, v_max))
if n_chan >= 3:
txred = img[:,:,2]
v_min, v_max = np.percentile(txred, (1,99))
txred_scaled = exposure.rescale_intensity(txred, in_range=(v_min, v_max))
if n_chan == 4:
cy5 = img[:,:,3]
v_min, v_max = np.percentile(cy5, (1,99))
cy5_scaled = exposure.rescale_intensity(cy5, in_range=(v_min, v_max))
if n_chan > 4:
print('handling of more than 4 image channels not supported')
### handle single high-res or stitched low-res images (large dimensions)
if np.logical_and(np.shape(img)[0] < 2500, np.shape(img)[1] < 2500):
# correct image and create content mask
bg = filters.threshold_local(content, norm_window)
norm = content / bg
blur = filters.gaussian(norm, sigma=2)
# blur = filters.gaussian(content, sigma=2)
otsu = filters.threshold_otsu(blur)
mask = blur > otsu
mask_filled = morphology.remove_small_holes(mask, min_hole_size)
selem = morphology.disk(3)
mask_opened = morphology.binary_opening(mask_filled, selem)
mask_filtered = morphology.remove_small_objects(mask_opened, min_cell_size)
heavy_blur = filters.gaussian(content, extrema_blur)
blur_masked = heavy_blur * mask_filtered
else:
blur = filters.gaussian(content, sigma=2)
otsu = filters.threshold_otsu(blur)
mask = blur > otsu
mask_filtered = mask
blur_masked = mask * blur
# find local maxima
coords = feature.peak_local_max(blur_masked, min_distance=peak_sep)
coords_T = []
coords_T += coords_T + [[point[1], point[0]] for point in coords]
coords_T = np.array(coords_T)
markers = np.zeros( | np.shape(content) | numpy.shape |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# CODE NAME HERE
# CODE DESCRIPTION HERE
Created on 2019-10-25 at 13:25
@author: cook
"""
import numpy as np
import warnings
from apero import core
from apero.core import math as mp
from apero import lang
from apero.core import constants
from apero.core.core import drs_log
from apero.core.core import drs_file
from apero.io import drs_table
from apero.science import extract
# =============================================================================
# Define variables
# =============================================================================
__NAME__ = 'polar.general.py'
__INSTRUMENT__ = 'None'
# Get constants
Constants = constants.load(__INSTRUMENT__)
# Get version and author
__version__ = Constants['DRS_VERSION']
__author__ = Constants['AUTHORS']
__date__ = Constants['DRS_DATE']
__release__ = Constants['DRS_RELEASE']
# get param dict
ParamDict = constants.ParamDict
DrsFitsFile = drs_file.DrsFitsFile
# Get Logging function
WLOG = core.wlog
# Get function string
display_func = drs_log.display_func
# Get the text types
TextEntry = lang.drs_text.TextEntry
TextDict = lang.drs_text.TextDict
# alias pcheck
pcheck = core.pcheck
# =============================================================================
# Define class
# =============================================================================
class PolarObj:
def __init__(self, params, **kwargs):
self.infile = kwargs.get('infile', None)
self.fiber = kwargs.get('fiber', 'NOFIBER')
self.exposure = kwargs.get('exposure', 'NAN')
self.stoke = kwargs.get('stoke', 'NAN')
self.sequence = kwargs.get('seqs', 'NAN')
self.sequencetot = kwargs.get('seqtot', 'NAN')
# infile related properties
self.data = kwargs.get('data', None)
self.filename = kwargs.get('filename', None)
self.basename = kwargs.get('basename', None)
self.header = kwargs.get('header', None)
self.exptime = None
self.mjd = None
self.mjdend = None
self.dprtype = None
self.berv = None
self.bjd = None
self.bervmax = None
# if infile is set, set data from infile
if self.infile is not None:
self._get_properites(params)
# set name
self.name = self.__gen_key__()
def __gen_key__(self):
return '{0}_{1}'.format(self.fiber, self.exposure)
def _get_properites(self, params):
self.data = self.infile.data
self.filename = self.infile.filename
self.basename = self.infile.basename
self.header = self.infile.header
# get keys from header
self.exptime = self.infile.get_key('KW_EXPTIME', dtype=float)
self.mjd = self.infile.get_key('KW_ACQTIME', dtype=float)
self.mjdend = self.infile.get_key('KW_MJDEND', dtype=float)
self.dprtype = self.infile.get_key('KW_DPRTYPE', dtype=str)
# get berv properties
bprops = extract.get_berv(params, self.infile, dprtype=self.dprtype)
# store berv properties
self.berv = bprops['USE_BERV']
self.bjd = bprops['USE_BJD']
self.bervmax = bprops['USE_BERV_MAX']
def __str__(self):
return 'PolarObj[{0}]'.format(self.name)
def __repr__(self):
return 'PolarObj[{0}]'.format(self.name)
# =============================================================================
# Define functions
# =============================================================================
def validate_polar_files(params, infiles, **kwargs):
# set function name
func_name = display_func(params, 'validate_polar_files', __NAME__)
# get parameters from params
valid_fibers = pcheck(params, 'POLAR_VALID_FIBERS', 'valid_fibers', kwargs,
func_name, mapf='list', dtype=str)
valid_stokes = pcheck(params, 'POLAR_VALID_STOKES', 'valid_stokes', kwargs,
func_name, mapf='list', dtype=str)
# this is a constant and should not be changed
min_files = 4
# ----------------------------------------------------------------------
# right now we can only do this with two fibers - break if more fibers are
# defined
if len(valid_fibers) != min_files // 2:
eargs = ['({0})'.format(','.join(valid_fibers)), 'POLAR_VALID_FIBERS',
func_name]
WLOG(params, 'error', TextEntry('00-021-00001', args=eargs))
# ----------------------------------------------------------------------
# get the number of infiles
num_files = len(infiles)
# ----------------------------------------------------------------------
# storage dictionary
pobjects = ParamDict()
stokes, fibers, basenames = [], [] ,[]
# loop around files
for it in range(num_files):
# print file iteration progress
core.file_processing_update(params, it, num_files)
# ge this iterations file
infile = infiles[it]
# extract polar values and validate file
pout = valid_polar_file(params, infile)
stoke, exp, seq, seqtot, fiber, valid = pout
# skip any invalid files
if not valid:
continue
# ------------------------------------------------------------------
# log file addition
wargs = [infile.basename, fiber, stoke, exp, seq, seqtot]
WLOG(params, '', TextEntry('40-021-00001', args=wargs))
# ------------------------------------------------------------------
# get polar object for each
pobj = PolarObj(params, infile=infile, fiber=fiber, exposure=exp,
stoke=stoke, seq=seq, seqtot=seqtot)
# get name
name = pobj.name
# push into storage dictionary
pobjects[name] = pobj
# set source
pobjects.set_source(name, func_name)
# append lists (for checks)
stokes.append(stoke)
fibers.append(fiber)
basenames.append(infile.basename)
# ----------------------------------------------------------------------
# deal with having no files
if len(pobjects) == 0:
eargs = ['\n\t'.join(basenames)]
WLOG(params, 'error', TextEntry('09-021-00001', args=eargs))
# deal with having less than minimum number of required files
if len(pobjects) < 4:
eargs = [4, '\n\t'.join(basenames)]
WLOG(params, 'error', TextEntry('09-021-00002', args=eargs))
# ----------------------------------------------------------------------
# make sure we do not have multiple stokes parameters
if len(np.unique(stokes)) != 1:
eargs = [', '.join(np.unique(stokes))]
WLOG(params, 'error', TextEntry('09-021-00003', args=eargs))
# ----------------------------------------------------------------------
# find number of A and B files
num_a = np.sum(np.array(fibers) == valid_fibers[0])
num_b = np.sum(np.array(fibers) == valid_fibers[1])
# make sure we have 2 or 4 A fibers and 2 or 4 B fibers
if len(fibers) == min_files * 2:
# make sure number of A and B files is correct length
if (num_a == min_files) and (num_b == min_files):
kind = min_files
else:
eargs = [valid_fibers[0], valid_fibers[1], num_a, num_b, min_files]
WLOG(params, 'error', TextEntry('09-021-00004', args=eargs))
kind = None
elif len(fibers) == min_files:
# make sure number of A and B files is correct length
if (num_a == min_files // 2) and (num_b == min_files // 2):
kind = min_files // 2
else:
eargs = [valid_fibers[0], valid_fibers[1], num_a, num_b,
min_files // 2]
WLOG(params, 'error', TextEntry('09-021-00004', args=eargs))
kind = None
else:
eargs = [valid_fibers[0], valid_fibers[1],
' or '.join([str(min_files * 2), str(min_files)])]
WLOG(params, 'error', TextEntry('09-021-00005', args=eargs))
kind = None
# ----------------------------------------------------------------------
# set the output parameters
props = ParamDict()
props['NEXPOSURES'] = kind
props['STOKES'] = np.unique(stokes)[0]
props['MIN_FILES'] = min_files
props['VALID_FIBERS'] = valid_fibers
props['VALID_STOKES'] = valid_stokes
# set sources
keys = ['STOKES', 'NEXPOSURES', 'MIN_FILES', 'VALID_FIBERS', 'VALID_STOKES']
props.set_sources(keys, func_name)
# ----------------------------------------------------------------------
# return polar object and properties
return pobjects, props
def calculate_polarimetry(params, pobjs, props, **kwargs):
# set function name
func_name = display_func(params, 'calculate_polarimetry', __NAME__)
# get parameters from params/kwargs
method = pcheck(params, 'POLAR_METHOD', 'method', kwargs, func_name)
# if method is not a string then break here
if not isinstance(method, str):
eargs = [method]
WLOG(params, 'error', TextEntry('09-021-00006', args=eargs))
# decide which method to use
if method.lower() == 'difference':
return polar_diff_method(params, pobjs, props)
elif method.lower() == 'ratio':
return polar_ratio_method(params, pobjs, props)
else:
eargs = [method]
WLOG(params, 'error', TextEntry('09-021-00007', args=eargs))
return 0
def calculate_stokes_i(params, pobjs, pprops):
"""
Function to calculate the Stokes I polarization
:param params: ParamDict, parameter dictionary of constants
:param pobjs: dict, dictionary of polar object instance
:param pprops: parameter dictionary, ParamDict containing data
Must contain at least:
NEXPOSURES: int, number of exposures in polar sequence
:return pprops: parameter dictionary, the updated parameter dictionary
Adds/updates the following:
STOKESI: numpy array (2D), the Stokes I parameters, same shape as
DATA
STOKESIERR: numpy array (2D), the Stokes I error parameters, same
shape as DATA
"""
# set the function
func_name = display_func(params, 'calculate_stokes_i', __NAME__)
# log start of polarimetry calculations
WLOG(params, '', TextEntry('40-021-00003'))
# get parameters from props
nexp = pprops['NEXPOSURES']
# get the first file for reference
pobj = pobjs['A_1']
# storage of stokes parameters
stokes_i = np.zeros(pobj.infile.shape)
stokes_i_err = np.zeros(pobj.infile.shape)
# storage of flux and variance
flux, var = [], []
# loop around exposures
for it in range(1, int(nexp) + 1):
# get a and b data for this exposure
data_a = pobjs['A_{0}'.format(it)].data
data_b = pobjs['B_{0}'.format(it)].data
# Calculate sum of fluxes from fibers A and B
flux_ab = data_a + data_b
# Save A+B flux for each exposure
flux.append(flux_ab)
# Calculate the variances for fiber A+B, assuming Poisson noise
# only. In fact the errors should be obtained from extraction, i.e.
# from the error extension in the e2ds files.
var_ab = data_a + data_b
# Save varAB = sigA^2 + sigB^2, ignoring cross-correlated terms
var.append(var_ab)
# Sum fluxes and variances from different exposures
for it in range(len(flux)):
stokes_i += flux[it]
stokes_i_err += var[it]
# Calcualte errors -> sigma = sqrt(variance)
with warnings.catch_warnings(record=True) as _:
stokes_i_err = | np.sqrt(stokes_i_err) | numpy.sqrt |
from logistic_regression import LogisticRegression
from uWaveGestureHandler import *
from sklearn.datasets import make_blobs
from sklearn.model_selection import KFold
import matplotlib.pyplot as plt
import numpy as np
directory = "../Datasets/uWaveGestureLibrary"
n_samples = 4481
n_training = int((50/100) * n_samples)
n_validation = int((20/100) * n_samples)
# Generate synthetic dataset
# X, y = make_blobs(n_samples=n_samples, random_state=None, centers=4, n_features=2)
# print(X.shape, y.shape)
# plt.scatter(X[:, 0], X[:, 1], c=y)
# plt.xlabel('First feature')
# plt.ylabel('Second feature')
# plt.show()
# Extract uWaveGesture dataset
gesture_1 = extract_gesture(1, directory)
gesture_2 = extract_gesture(2, directory)
gesture_3 = extract_gesture(3, directory)
gesture_4 = extract_gesture(4, directory)
gesture_5 = extract_gesture(5, directory)
gesture_6 = extract_gesture(6, directory)
gesture_7 = extract_gesture(7, directory)
gesture_8 = extract_gesture(8, directory)
X, y = create_dataset([gesture_1, gesture_2, gesture_3, gesture_4, gesture_5, gesture_6, gesture_7, gesture_8], shuffle=True)
print(X.shape, y.shape)
# Build logistic regression model
log_reg = LogisticRegression(regularization_factor=.001)
# Training
X_train = X[:n_training]
y_train = y[:n_training]
X_val = X[n_training:n_training + n_validation]
y_val = y[n_training:n_training + n_validation]
training_accuracy, training_cross_entropy, validation_accuracy, validation_cross_entropy = log_reg.train_early_stopping(X_train, y_train, X_val, y_val, n_early_stopping=100, epochs=2000)
# Test & Visualization
plt.plot(training_accuracy, 'b', label="Training accuracy")
plt.plot(validation_accuracy, 'r', label="Test accuracy")
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.show()
plt.plot(training_cross_entropy, 'b', label="Training cross entropy")
plt.plot(validation_cross_entropy, 'r', label="Test cross entropy")
plt.xlabel('Epoch')
plt.ylabel('Cross entropy')
plt.show()
X_test = X[n_training+n_validation:]
y_test = y[n_training+n_validation:]
print(log_reg.regularized_cross_entropy(X_test, y_test), log_reg.accuracy(X_test, y_test))
confusion_map = log_reg.confusion_map(X_test, y_test)
plt.imshow(confusion_map, cmap='Reds', interpolation='nearest')
plt.show()
training_accuracies = []
training_cross_entropies = []
test_accuracies = []
test_cross_entropies = []
kf = KFold(n_splits=4)
for train_index, test_index in kf.split(X):
log_reg = LogisticRegression(regularization_factor=.001)
training_accuracy, training_cross_entropy = log_reg.train(X[train_index], y[train_index], epochs=1200)
training_accuracies.append(log_reg.accuracy(X[train_index], y[train_index]))
training_cross_entropies.append(log_reg.regularized_cross_entropy(X[train_index], y[train_index]))
test_accuracies.append(log_reg.accuracy(X[test_index], y[test_index]))
test_cross_entropies.append(log_reg.regularized_cross_entropy(X[test_index], y[test_index]))
plt.plot(training_accuracies, 'b', label="Training accuracies")
plt.axhline(y= | np.mean(training_accuracies) | numpy.mean |
# ProDy: A Python Package for Protein Dynamics Analysis
#
# Copyright (C) 2010-2012 <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
"""Refine MSA application."""
__author__ = '<NAME>, <NAME>'
__copyright__ = 'Copyright (C) 2010-2012 <NAME>'
from ..apptools import DevelApp
import prody
import numpy as np
__all__ = ['evol_rankorder']
APP = DevelApp('rankorder', 'identify highly coevolving pairs of residues')
APP.setExample(
"""This application identifies that top ranking pairs of residues that \
coevolve based on their mutual information. By default coevolution is \
reported for pairs that are at least 3 residues apart in sequence. A z-score \
normalization can be applied to the mutinfo matrix to identify coevolving \
pairs. The following examples show how to use with default as well as \
additional options:
$ evol rankorder piwi_refined_mutinfo.txt -z
$ evol rankorder piwi_refined_mutinfo.txt --msa piwi_refined.slx \
--label AGO6_ARATH""", [])
APP.addArgument('mutinfo',
help='mutual information matrix')
APP.addGroup('input', 'input options')
APP.addArgument('-z', '--zscore',
dest='zscore',
action='store_true',
help='apply zscore for identifying top ranked coevolving pairs',
group='input'
)
APP.addArgument('-d', '--delimiter',
dest='delimiter',
help='delimiter used in mutual information matrix file',
type=str,
metavar='STR',
default=None,
group='input'
)
APP.addArgument('-p', '--pdb',
dest='pdb',
help='PDB file that contains same number of residues as the mutual '
'information matrix, output residue numbers will be based on PDB file',
default=None,
type=str,
metavar='STR',
group='input'
)
APP.addArgument('-m', '--msa',
dest='msa',
help='MSA file used for building the mutual info matrix, '
'output residue numbers will be based on the most complete sequence '
'in MSA if a PDB file or sequence label is not specified',
default=None,
type=str,
metavar='STR',
group='input'
)
APP.addArgument('-l', '--label',
dest='label',
help='label in MSA file for output residue numbers',
default=None,
type=str,
metavar='STR',
group='input'
)
APP.addGroup('output', 'output options')
APP.addArgument('-n', '--num-pairs',
dest='numpairs',
help='number of top ranking residue pairs to list',
default=100,
type=int,
metavar='INT',
group='output'
)
APP.addArgument('-q', '--seq-sep',
dest='seqsep',
help='report coevolution for residue pairs that are sequentially '
'separated by input value',
default=3,
type=int,
metavar='INT',
group='output'
)
APP.addArgument('-t', '--min-dist',
dest='dist',
help='report coevolution for residue pairs whose CA atoms are spatially '
'separated by at least the input value, used when a PDB file is given '
'and --use-dist is true',
default=10.0,
type=float,
metavar='FLOAT',
group='output'
)
APP.addArgument('-u', '--use-dist',
dest='usedist',
action='store_true',
help='use structural separation to report coevolving pairs',
group='output'
)
APP.addArgument('-o', '--outname',
dest='outname',
help='output filename, default is mutinfo_rankorder.txt',
type=str,
metavar='STR',
group='output'
)
def calcAllDist(coordset):
from prody import calcDistance
shape = coordset.shape
distance = np.zeros((shape[1], shape[1]))
for i in range(shape[1]):
temp = | np.tile(coordset[0,i,:], (1, shape[1], 1)) | numpy.tile |
from utils import load_data
import torch
import argparse
import numpy as np
import torch.optim as optim
import random
import pickle
import torch.nn as nn
import sklearn
from modularity import greedy_modularity_communities, partition, baseline_spectral, make_modularity_matrix
from utils import make_normalized_adj, edge_dropout, negative_sample
from models import GCNLink, GCNClusterNet, GCNDeep, GCNDeepSigmoid, GCN, GCNClusterGAT,GINClusterNet
from loss_functions import loss_kcenter, loss_modularity
import copy
from kcenter import CenterObjective, make_all_dists, gonzalez_kcenter, greedy_kcenter, make_dists_igraph, rounding
parser = argparse.ArgumentParser()
parser.add_argument('--no-cuda', action='store_true', default=True,
help='Disables CUDA training.')
parser.add_argument('--seed', type=int, default=24, help='Random seed.')
parser.add_argument('--lr', type=float, default=0.01,
help='Initial learning rate.')
parser.add_argument('--weight_decay', type=float, default=5e-4,
help='Weight decay (L2 loss on parameters).')
parser.add_argument('--hidden', type=int, default=50,
help='Number of hidden units.')
parser.add_argument('--dropout', type=float, default=0.5,
help='Dropout rate (1 - keep probability).')
parser.add_argument('--embed_dim', type=int, default=50,
help='Dimensionality of node embeddings')
parser.add_argument('--K', type=int, default=5,
help='How many partitions')
parser.add_argument('--negsamplerate', type=int, default=1,
help='How many negative examples to include per positive in link prediction training')
parser.add_argument('--edge_dropout', type=float, default=0.2,
help='Rate at which to remove edges in link prediction training')
parser.add_argument('--objective', type=str, default='kcenter',
help='What objective to optimize (currently partitioning or modularity')
parser.add_argument('--dataset', type=str, default='synthetic_spa',
help='which network to load')
parser.add_argument('--clustertemp', type=float, default=20,
help='how hard to make the softmax for the cluster assignments')
parser.add_argument('--kcentertemp', type=float, default=100,
help='how hard to make seed selection softmax assignment')
parser.add_argument('--kcentermintemp', type=float, default=0,
help='how hard to make the min over nodes in kcenter training objective')
parser.add_argument('--use_igraph', action='store_true', default=True, help='use igraph to compute shortest paths in twostage kcenter')
parser.add_argument('--train_iters', type=int, default=1000,
help='number of training iterations')
parser.add_argument('--num_cluster_iter', type=int, default=1,
help='number of iterations for clustering')
parser.add_argument('--singletrain', action='store_true', default=False, help='only train on a single instance')
parser.add_argument('--pure_opt', action='store_true', default=False, help='do only optimization, no link prediction needed')
parser.add_argument('--graph_embedding', type=str, default='GCN',
help='embedding layer GCN,GAT or GIN')
args = parser.parse_args()
args.cuda = not args.no_cuda and torch.cuda.is_available()
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.cuda:
torch.cuda.manual_seed(args.seed)
if 'synthetic_spa' not in args.dataset:
directory = args.dataset
else:
directory = 'synthetic_spa'
# Load data
reload_data = True
pure_optimization = args.pure_opt
train_pct = 0.4
if 'synthetic' in args.dataset:
num_graphs = 60
numtest = 30
else: #pubmed dataset
num_graphs = 20
numtest = 8
if reload_data:
bin_adj_all = []
adj_all = []
#features = []
adj_train = []
bin_adj_train = []
features_train = []
features_all = []
dist_all = []
dist_train = []
for i in range(num_graphs):
adj_i, features_i, labels_i, idx_train, idx_val, idx_test = load_data('data/{}/'.format(directory), '{}_{}'.format(args.dataset, i))
bin_adj_i = (adj_i.to_dense() > 0).float()
bin_adj_all.append(bin_adj_i)
adj_all.append(adj_i.coalesce())
features_all.append(features_i)
adj_train_i, features_train_i, labels_train_i, idx_train, idx_val, idx_test = load_data('data/{}/'.format(directory), '{0}_{1}_train_{2:.2f}'.format(args.dataset, i, train_pct))
bin_adj_train_i = (adj_train_i.to_dense() > 0).float()
bin_adj_train.append(bin_adj_train_i)
adj_train.append(adj_train_i.coalesce())
features_train.append(features_train_i)
vals = {}
algs = ['ClusterNet', 'ClusterNet-ft', 'ClusterNet-ft-only', 'GCN-e2e', 'GCN-e2e-ft', 'GCN-e2e-ft-only']
if args.objective == 'modularity':
ts_algos = ['agglomerative', 'recursive', 'spectral']
elif args.objective == 'kcenter':
ts_algos = ['gonzalez', 'greedy']
for algo in ts_algos:
algs.append('train-' + algo)
algs.append('ts-' + algo)
algs.append('ts-ft-' + algo)
algs.append('ts-ft-only-' + algo)
for algo in algs:
vals[algo] = np.zeros(numtest)
aucs_algs = ['ts', 'ts-ft', 'ts-ft-only']
aucs = {}
for algo in aucs_algs:
aucs[algo] = np.zeros(numtest)
if args.objective == 'modularity':
mods_test = [make_modularity_matrix(A) for A in bin_adj_all]
mods_train = [make_modularity_matrix(A) for A in bin_adj_train]
test_object = mods_test
train_object = mods_train
loss_fn = loss_modularity
elif args.objective == 'kcenter':
for i in range(num_graphs):
try:
dist_all.append(torch.load('{}_{}_test_dist.pt'.format(args.dataset, i)))
dist_train.append(torch.load('{}_{}_{:.2f}_train_dist.pt'.format(args.dataset, i, train_pct)))
diameter = dist_all[-1].max()
except:
dist_all_i = make_all_dists(bin_adj_all[i], 100)
diameter = dist_all_i[dist_all_i < 100].max()
dist_all_i[dist_all_i == 100] = diameter
torch.save(dist_all_i, '{}_{}_test_dist.pt'.format(args.dataset, i))
dist_all.append(dist_all_i)
dist_train_i = make_all_dists(bin_adj_train[i], 100)
dist_train_i[dist_train_i == 100] = diameter
torch.save(dist_train_i, '{}_{}_{:.2f}_train_dist.pt'.format(args.dataset, i, train_pct))
dist_train.append(dist_train_i)
obj_train = [CenterObjective(d, diameter, args.kcentermintemp) for d in dist_train]
obj_train_hardmax = [CenterObjective(d, diameter, args.kcentermintemp, hardmax=True) for d in dist_train]
obj_test = [CenterObjective(d, diameter, args.kcentertemp, hardmax=True) for d in dist_all]
obj_test_softmax = [CenterObjective(d, diameter, args.kcentermintemp) for d in dist_all]
test_object = obj_test
train_object = obj_train
loss_fn = loss_kcenter
if pure_optimization:
train_object = test_object
adj_train = adj_all
bin_adj_train = bin_adj_all
dist_train = dist_all
for test_idx in range(1):
if 'pubmed' in args.dataset:
valid_instances = list(range(10, 12))
test_instances= list(range(12, 20))
if 'synthetic' in args.dataset:
test_instances = list(range(20, 50))
valid_instances = list(range(50, 60))
if not args.singletrain:
train_instances = [x for x in range(num_graphs) if x not in test_instances and x not in valid_instances]
else:
train_instances = [0]
nfeat = features_all[0].shape[1]
K = args.K
# Model and optimizer
model_ts = GCNLink(nfeat=nfeat,
nhid=args.hidden,
nout=args.embed_dim,
dropout=args.dropout)
if args.graph_embedding=='GAT':
model_cluster = GCNClusterGAT(nfeat=nfeat,
nhid=args.hidden,
nout=args.embed_dim,
dropout=args.dropout,
K = args.K,
cluster_temp = args.clustertemp)
if args.graph_embedding == 'GCN':
model_cluster = GCNClusterNet(nfeat=nfeat,
nhid=args.hidden,
nout=args.embed_dim,
dropout=args.dropout,
K = args.K,
cluster_temp = args.clustertemp)
if args.graph_embedding == 'GIN':
model_cluster = GINClusterNet(nfeat=nfeat,
nhid=args.hidden,
nout=args.embed_dim,
dropout=args.dropout,
K = args.K,
cluster_temp = args.clustertemp)
#keep a couple of initializations here so that the random seeding lines up
#with results reported in the paper -- removing these is essentially equivalent to
#changing the seed
_ = GCN(nfeat, args.hidden, args.embed_dim, args.dropout)
_ = nn.Parameter(torch.rand(K, args.embed_dim))
#
if args.objective == 'modularity':
model_gcn = GCNDeep(nfeat=nfeat,
nhid=args.hidden,
nout=args.K,
dropout=args.dropout,
nlayers=2)
elif args.objective == 'kcenter':
model_gcn = GCNDeepSigmoid(nfeat=nfeat,
nhid=args.hidden,
nout=1,
dropout=args.dropout,
nlayers=2)
optimizer = optim.Adam(model_cluster.parameters(),
lr=args.lr, weight_decay=args.weight_decay)
losses = []
losses_test = []
num_cluster_iter = args.num_cluster_iter
def get_average_loss(model, adj, bin_adj, bin_adj_for_loss, objectives, instances, features, num_reps = 10, hardmax = False, update = False, algoname = None):
if hardmax:
model.eval()
loss = 0
for _ in range(num_reps):
for idx, i in enumerate(instances):
mu, r, embeds, dist = model(features[i], adj[i], num_cluster_iter)
if hardmax:
r = torch.softmax(100*r, dim=1)
this_loss = loss_fn(mu, r, embeds, dist, bin_adj_for_loss[i], objectives[i], args)
loss += this_loss
if update:
vals[algoname][test_instances.index(i)] = this_loss.item()
if hardmax:
model.train()
return loss/(len(instances)*num_reps)
def get_kcenter_test_loss(model, adj, bin_adj, train_objectives, test_objectives, instances, features, num_reps = 10, hardmax = False, update = False, algoname = None):
loss = 0
for idx, i in enumerate(instances):
best_loss = 100
x_best = None
for _ in range(num_reps):
mu, r, embeds, dist = model(features[i], adj[i], num_cluster_iter)
x = torch.softmax(dist*args.kcentertemp, 0).sum(dim=1)
x = 2*(torch.sigmoid(4*x) - 0.5)
if x.sum() > args.K:
x = args.K*x/x.sum()
train_loss = loss_fn(mu, r, embeds, dist, bin_adj[i], train_objectives[i], args)
if train_loss.item() < best_loss:
best_loss = train_loss.item()
x_best = x
testvals = []; trainvals = []
for _ in range(50):
y = rounding(x_best)
testvals.append(test_objectives[i](y).item())
trainvals.append(train_objectives[i](y).item())
loss += testvals[np.argmin(trainvals)]
if update:
vals[algoname][test_instances.index(i)] = testvals[np.argmin(trainvals)]
return loss/(len(instances))
#Decision-focused training
if True:
for t in range(args.train_iters):
i = np.random.choice(train_instances)
mu, r, embeds, dist = model_cluster(features_train[i], adj_train[i], num_cluster_iter)
if args.objective == 'modularity':
loss = loss_fn(mu, r, embeds, dist, bin_adj_all[i], test_object[i], args)
else:
loss = loss_fn(mu, r, embeds, dist, bin_adj_all[i], obj_test_softmax[i], args)
if args.objective != 'kcenter':
loss = -loss
optimizer.zero_grad()
loss.backward()
if t % 100 == 0 and t != 0:
num_cluster_iter = 5
if t % 10 == 0:
if args.objective == 'modularity':
r = torch.softmax(100*r, dim=1)
loss_train = get_average_loss(model_cluster, adj_train, bin_adj_train, bin_adj_all, test_object, train_instances, features_train, hardmax=True)
loss_test = get_average_loss(model_cluster, adj_train, bin_adj_train, bin_adj_all, test_object, test_instances, features_train, hardmax=True)
loss_valid = get_average_loss(model_cluster, adj_train, bin_adj_train, bin_adj_all, test_object, valid_instances, features_train, hardmax=True)
losses_test.append(loss_test.item())
print(t, loss_train.item(), loss_test.item(), loss_valid.item())
losses.append(loss.item())
optimizer.step()
if args.objective == 'kcenter':
loss_round = get_kcenter_test_loss(model_cluster, adj_train, bin_adj_train, train_object, test_object, test_instances, features_train, update = True, algoname = 'ClusterNet')
elif args.objective == 'modularity':
loss_test = get_average_loss(model_cluster, adj_train, bin_adj_train, bin_adj_all, test_object, test_instances, features_train, hardmax=True, update = True, algoname = 'ClusterNet')
print('after training', np.mean(vals['ClusterNet'][:numtest]), np.std(vals['ClusterNet']))
if args.singletrain:
pickle.dump((vals, aucs), open('results_distributional_singletrain_{}_{}_{}.pickle'.format(args.dataset, args.objective, args.K), 'wb'))
break
def fine_tune(model, features, adj, bin_adj, objective, num_training_iters = 1000):
optimizer = optim.Adam(model.parameters(),
lr=args.lr, weight_decay=args.weight_decay)
for t in range(num_training_iters):
mu, r, embeds, dist = model(features, adj, num_cluster_iter)
loss = loss_fn(mu, r, embeds, dist, bin_adj, objective, args)
if args.objective != 'kcenter':
loss = -loss
optimizer.zero_grad()
loss.backward()
optimizer.step()
num_cluster_iter = 1
loss_finetune = 0
loss_round = 0
for i in test_instances:
model_i = copy.deepcopy(model_cluster)
fine_tune(model_i, features_train[i], adj_train[i], bin_adj_train[i], train_object[i], num_training_iters = 50)
loss_finetune += get_average_loss(model_i, adj_train, bin_adj_train, bin_adj_all, test_object, [i], features_train, hardmax=True, update = True, algoname = 'ClusterNet-ft').item()
if args.objective == 'kcenter':
loss_round += get_kcenter_test_loss(model_i, adj_train, bin_adj_train, train_object, test_object, [i], features_train, update = True, algoname = 'ClusterNet-ft')
print('finetune', np.mean(vals['ClusterNet-ft']), np.std(vals['ClusterNet-ft']))
loss_finetune = 0
loss_round = 0
for i in test_instances:
model_i = GCNClusterNet(nfeat=nfeat,
nhid=args.hidden,
nout=args.embed_dim,
dropout=args.dropout,
K = args.K,
cluster_temp = args.clustertemp)
fine_tune(model_i, features_train[i], adj_train[i], bin_adj_train[i], train_object[i], num_training_iters = 500)
loss_finetune += get_average_loss(model_i, adj_train, bin_adj_train, bin_adj_all, test_object, [i], features_train, hardmax=True, update = True, algoname = 'ClusterNet-ft-only').item()
if args.objective == 'kcenter':
loss_round += get_kcenter_test_loss(model_i, adj_train, bin_adj_train, train_object, test_object, [i], features_train, update = True, algoname = 'ClusterNet-ft-only')
print('finetune only', np.mean(vals['ClusterNet-ft-only']), np.std(vals['ClusterNet-ft-only']))
#Train a two-stage model for link prediction with cross-entropy loss and
#negative sampling
def train_twostage(model_ts, train_instances, test_instances, features, algoname):
optimizer_ts = optim.Adam(model_ts.parameters(),
lr=args.lr, weight_decay=args.weight_decay)
edges = {}
edges_eval = {}
labels_eval = {}
for i in train_instances + test_instances:
edges[i] = adj_train[i].indices().t()
edges_eval_i, labels_eval_i = negative_sample(adj_all[i].indices().t(), 1, bin_adj_all[i])
edges_eval[i] = edges_eval_i
labels_eval[i] = labels_eval_i
def get_evaluation(instances):
test_ce = 0
test_auc = 0
for i in instances:
preds_test_eval = model_ts(features[i], adj_train[i], edges_eval[i])
test_ce += torch.nn.BCEWithLogitsLoss()(preds_test_eval, labels_eval[i])
test_auc_i = sklearn.metrics.roc_auc_score(labels_eval[i].long().detach().numpy(), nn.Sigmoid()(preds_test_eval).detach().numpy())
aucs[algoname][test_instances.index(i)] = test_auc
test_auc += test_auc_i
return test_ce/len(instances), test_auc/len(instances)
for t in range(150):
i = np.random.choice(train_instances)
adj_input = make_normalized_adj(edge_dropout(edges[i], args.edge_dropout), bin_adj_train[i].shape[0])
edges_eval_i, labels_i = negative_sample(edges[i], args.negsamplerate, bin_adj_train[i])
preds = model_ts(features[i], adj_input, edges_eval_i)
loss = torch.nn.BCEWithLogitsLoss()(preds, labels_i)
optimizer_ts.zero_grad()
loss.backward()
if t % 10 == 0:
test_ce, test_auc = get_evaluation(test_instances)
print(t, loss.item(), test_ce.item(), test_auc)
optimizer_ts.step()
def test_twostage(model_ts, test_instances_eval, algoname):
for test_i in test_instances_eval:
#predict probability that all unobserved edges exist
n = adj_train[test_i].shape[0]
indices = torch.tensor(np.arange(n))
to_pred = torch.zeros(n**2, 2)
to_pred[:, 1] = indices.repeat(n)
for i in range(n):
to_pred[i*n:(i+1)*n, 0] = i
to_pred = to_pred.long()
preds = model_ts(features_train[test_i], adj_train[test_i], to_pred)
preds = nn.Sigmoid()(preds).view(n, n)
preds = bin_adj_train[test_i] + (1 - bin_adj_train[test_i])*preds
if args.objective == 'modularity':
r = greedy_modularity_communities(preds, K)
loss = loss_fn(None, r, None, None, bin_adj_all[test_i], test_object[test_i], args).item()
vals[algoname + '-agglomerative'][test_instances.index(test_i)] = loss
r = partition(preds, K)
loss = loss_fn(None, r, None, None, bin_adj_all[test_i], test_object[test_i], args).item()
vals[algoname + '-recursive'][test_instances.index(test_i)] = loss
degrees = preds.sum(dim=1)
preds = torch.diag(1./degrees)@preds
mod_pred = make_modularity_matrix(preds)
r = baseline_spectral(mod_pred, K)
loss = loss_fn(None, r, None, None, bin_adj_all[test_i], test_object[test_i], args).item()
vals[algoname + '-spectral'][test_instances.index(test_i)] = loss
elif args.objective == 'kcenter':
print('making dists')
if args.use_igraph:
dist_ts = make_dists_igraph(preds)
else:
dist_ts = make_all_dists(preds, 100)
diameter = dist_ts[dist_ts < 100].max()
dist_ts[dist_ts == 100] = diameter
print(test_i)
dist_ts = dist_ts.float()
diameter = dist_ts.max()
x = gonzalez_kcenter(dist_ts, K)
loss = obj_test[test_i](x)
vals[algoname + '-gonzalez'][test_instances.index(test_i)] = loss.item()
x = greedy_kcenter(dist_ts, diameter, K)
loss = obj_test[test_i](x)
vals[algoname + '-greedy'][test_instances.index(test_i)] = loss.item()
if True:
print('two stage')
#do pretrained two stage
train_twostage(model_ts, train_instances, test_instances, features_train, 'ts')
test_twostage(model_ts, test_instances, 'ts')
for algo in algs:
if 'ts' in algo and 'ft' not in algo:
print(algo, np.mean(vals[algo]), np.std(vals[algo]))
# do finetuning
loss_agglom_ft = 0; loss_recursive_ft = 0; loss_spectral_ft = 0
loss_greedy_ft = 0; loss_gonzalez_ft = 0
for i in test_instances:
model_i = copy.deepcopy(model_ts)
train_twostage(model_i, [i], [i], features_train, 'ts-ft')
test_twostage(model_ts, [i], 'ts-ft')
for algo in algs:
if 'ts-ft' in algo and 'only' not in algo:
print(algo, np.mean(vals[algo]), np.std(vals[algo]))
#do only finetuning
loss_agglom_ft_only = 0; loss_recursive_ft_only = 0; loss_spectral_ft_only = 0
loss_greedy_ft_only = 0; loss_gonzalez_ft_only = 0
for i in test_instances:
model_i = GCNLink(nfeat=nfeat,
nhid=args.hidden,
nout=args.embed_dim,
dropout=args.dropout)
train_twostage(model_i, [i], [i], features_train, 'ts-ft-only')
test_twostage(model_ts, [i], 'ts-ft-only')
for algo in algs:
if 'ts-ft-only' in algo:
print(algo, np.mean(vals[algo]), np.std(vals[algo]))
if True:
def get_average_loss(model, adj, bin_adj, bin_adj_for_loss, objectives, instances, features, num_reps = 1, hardmax = False, update = False, algoname = None):
loss = 0
for _ in range(num_reps):
for i in instances:
if args.objective == 'modularity':
r = model(features[i], adj[i])
r = torch.softmax(r, dim = 1)
if hardmax:
r = torch.softmax(100*r, dim=1)
this_loss = -loss_fn(None, r, None, None, bin_adj_for_loss[i], objectives[i], args)
elif args.objective == 'kcenter':
x = model(features[i], adj[i])
if x.sum() > K:
x = K*x/x.sum()
this_loss = objectives[i](x)
loss += this_loss
if update:
vals[algoname][test_instances.index(i)] = this_loss.item()
return loss/(len(instances)*num_reps)
def get_kcenter_test_loss(model, adj, bin_adj, train_objectives, test_objectives, instances, features, num_reps = 10, hardmax = False, update = False, algoname = None):
loss = 0
for i in instances:
best_loss = 100
x_best = None
for _ in range(num_reps):
x = model(features[i], adj[i])
if x.sum() > args.K:
x = args.K*x/x.sum()
train_loss = train_objectives[i](x)
if train_loss.item() < best_loss:
best_loss = train_loss.item()
x_best = x
testvals = []; trainvals = []
for _ in range(50):
y = rounding(x_best)
testvals.append(test_objectives[i](y).item())
trainvals.append(train_objectives[i](y).item())
loss += testvals[np.argmin(trainvals)]
if update:
vals[algoname][test_instances.index(i)] = testvals[np.argmin(trainvals)]
return loss/(len(instances))
print('just GCN')
optimizer_gcn = optim.Adam(model_gcn.parameters(), lr = args.lr,
weight_decay = args.weight_decay)
def train_gcn_model(model, train_instances, num_iters = 1000, verbose=False):
for t in range(num_iters):
i = random.choice(train_instances)
loss = get_average_loss(model_gcn, adj_train, bin_adj_train, bin_adj_train, train_object, [i], features_train)
optimizer.zero_grad()
loss.backward()
losses.append(loss.item())
optimizer.step()
if t % 100 == 0 and verbose:
loss_train = get_average_loss(model_gcn, adj_all, bin_adj_all, bin_adj_all, test_object, train_instances, features_all)
loss_test = get_average_loss(model_gcn, adj_train, bin_adj_train, bin_adj_all, test_object, test_instances, features_train, hardmax=True)
losses_test.append(loss_test.item())
print(t, loss.item(), loss_train.item(), loss_test.item())
train_gcn_model(model_gcn, train_instances, num_iters = 1000, verbose = True)
if args.objective == 'kcenter':
loss_round = get_kcenter_test_loss(model_gcn, adj_train, bin_adj_train, train_object, test_object, test_instances, features_train , update = True, algoname = 'GCN-e2e')
elif args.objective == 'modularity':
loss_gcne2e = get_average_loss(model_gcn, adj_train, bin_adj_train, bin_adj_all, test_object, test_instances, features_train, hardmax=True, update = True, algoname = 'GCN-e2e').item()
print('GCN-e2e', np.mean(vals['GCN-e2e']), np.std(vals['GCN-e2e']))
#################
#GCN FINETUNE
#################
loss_finetune = 0
loss_round = 0
for i in test_instances:
model_i = copy.deepcopy(model_gcn)
train_gcn_model(model_i, [i], num_iters = 500)
loss_finetune += get_average_loss(model_i, adj_train, bin_adj_train, bin_adj_all, test_object, [i], features_train, hardmax=True, update = True, algoname = 'GCN-e2e-ft').item()
if args.objective == 'kcenter':
loss_round += get_kcenter_test_loss(model_i, adj_train, bin_adj_train, train_object, test_object, [i], features_train, update = True, algoname = 'GCN-e2e-ft')
print('GCN-e2e-ft', np.mean(vals['GCN-e2e-ft']), | np.std(vals['GCN-e2e-ft']) | numpy.std |
"""
Copyright (c) 2006-2011, NIPY Developers
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the NIPY Developers nor the names of any
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Nitime 0.6 code slightly adapted by <NAME>, Aug 2016
<EMAIL>
CONTENT OF THIS FILE:
Spectral transforms are used in order to estimate the frequency-domain
representation of time-series. Several methods can be used and this module
contains implementations of several algorithms for the calculation of spectral
transforms.
"""
import numpy as np
# import matplotlib.mlab as mlab
import scipy.linalg as linalg
import scipy.signal as sig
import scipy.interpolate as interpolate
import scipy.fftpack as fftpack
import spectral as spectral
import warnings
import multitaper_utils as utils
# Set global variables for the default NFFT to be used in spectral analysis and
# the overlap:
default_nfft = 64
default_n_overlap = int(np.ceil(default_nfft // 2))
def get_spectra(time_series, method=None):
r"""
Compute the spectra of an n-tuple of time series and all of
the pairwise cross-spectra.
Parameters
----------
time_series : float array
The time-series, where time is the last dimension
method : dict, optional
contains: this_method:'welch'
indicates that :func:`mlab.psd` will be used in
order to calculate the psd/csd, in which case, additional optional
inputs (and default values) are:
NFFT=64
Fs=2pi
detrend=mlab.detrend_none
window=mlab.window_hanning
n_overlap=0
this_method:'multi_taper_csd'
indicates that :func:`multi_taper_psd` used in order to calculate
psd/csd, in which case additional optional inputs (and default
values) are:
BW=0.01
Fs=2pi
sides = 'onesided'
Returns
-------
f : float array
The central frequencies for the frequency bands for which the spectra
are estimated
fxy : float array
A semi-filled matrix with the cross-spectra of the signals. The csd of
signal i and signal j is in f[j][i], but not in f[i][j] (which will be
filled with zeros). For i=j fxy[i][j] is the psd of signal i.
"""
if method is None:
method = {'this_method': 'multi_taper_csd'} # The default
# If no choice of method was explicitly set, but other parameters were
# passed, assume that the method is multitapering:
this_method = method.get('this_method', 'multi_taper_csd')
if this_method == 'welch':
NFFT = method.get('NFFT', default_nfft)
Fs = method.get('Fs', 2 * np.pi)
detrend = method.get('detrend', 'constant') #mlab.detrend_none)
window = method.get('window', 'hanning') #mlab.window_hanning)
noverlap = method.get('noverlap', int(np.ceil(NFFT / 2)))
scaling = method.get('scaling', 'spectrum')
# The length of the spectrum depends on how many sides are taken, which
# depends on whether or not this is a complex object:
if np.iscomplexobj(time_series):
fxy_len = NFFT
else:
fxy_len = NFFT // 2 + 1
# If there is only 1 channel in the time-series:
if len(time_series.shape) == 1 or time_series.shape[0] == 1:
temp, f = spectral._welch( # mlab.csd(
time_series, time_series,
fs=Fs, window=window, noverlap=noverlap,
nfft=NFFT, detrend=detrend) # scale_by_freq=True)
fxy = temp.squeeze() # the output of mlab.csd has a weird shape
else:
fxy = np.zeros((time_series.shape[0],
time_series.shape[0],
fxy_len), dtype=complex) # Make sure it's complex
for i in range(time_series.shape[0]):
for j in range(i, time_series.shape[0]):
#Notice funny indexing, in order to conform to the
#convconventions of the other methods:
temp, f = spectral._welch(time_series[j], time_series[i],
fs=Fs, window=window,
noverlap=noverlap,
nfft=NFFT, detrend=detrend)
# scale_by_freq=True)
fxy[i][j] = temp.squeeze() # the output of mlab.csd has a
# weird shape
if this_method == 'multi_taper_csd':
mdict = method.copy()
func = eval(mdict.pop('this_method'))
freqs, fxy = func(time_series, **mdict)
f = utils._circle_to_hz(freqs, mdict.get('Fs', 2 * np.pi))
else:
raise ValueError("Unknown method provided")
return f, fxy.squeeze()
def get_spectra_bi(x, y, method=None):
r"""
Computes the spectra of two timeseries and the cross-spectrum between them
Parameters
----------
x,y : float arrays
Time-series data
method : dict, optional
See :func:`get_spectra` documentation for details
Returns
-------
f : float array
The central frequencies for the frequency
bands for which the spectra are estimated
fxx : float array
The psd of the first signal
fyy : float array
The psd of the second signal
fxy : float array
The cross-spectral density of the two signals
"""
f, fij = get_spectra(np.vstack((x, y)), method=method)
fxx = fij[ 0, 0 ].real
fyy = fij[ 1, 1 ].real
fxy = fij[ 0, 1 ]
return f, fxx, fyy, fxy
# The following spectrum estimates are normalized to the convention
# adopted by MATLAB (or at least spectrum.psd)
# By definition, Sxx(f) = DTFT{Rxx(n)}, where Rxx(n) is the autocovariance
# function of x(n). Therefore the integral from
# [-Fs/2, Fs/2] of Sxx(f)*df is Rxx(0).
# And from the definition of Rxx(n),
# Rxx(0) = Expected-Value{x(n)x*(n)} = Expected-Value{ |x|^2 },
# which is estimated as (x*x.conj()).mean()
# In other words, sum(Sxx) * Fs / NFFT ~ var(x)
def dpss_windows(N, NW, Kmax, interp_from=None, interp_kind='linear'):
"""
Returns the Discrete Prolate Spheroidal Sequences of orders [0,Kmax-1]
for a given frequency-spacing multiple NW and sequence length N.
Parameters
----------
N : int
sequence length
NW : float, unitless
standardized half bandwidth corresponding to 2NW = BW/f0 = BW*N*dt
but with dt taken as 1
Kmax : int
number of DPSS windows to return is Kmax (orders 0 through Kmax-1)
interp_from : int (optional)
The dpss can be calculated using interpolation from a set of dpss
with the same NW and Kmax, but shorter N. This is the length of this
shorter set of dpss windows.
interp_kind : str (optional)
This input variable is passed to scipy.interpolate.interp1d and
specifies the kind of interpolation as a string ('linear', 'nearest',
'zero', 'slinear', 'quadratic, 'cubic') or as an integer specifying the
order of the spline interpolator to use.
Returns
-------
v, e : tuple,
v is an array of DPSS windows shaped (Kmax, N)
e are the eigenvalues
Notes
-----
Tridiagonal form of DPSS calculation from:
<NAME>. Prolate spheroidal wave functions, Fourier analysis, and
uncertainty V: The discrete case. Bell System Technical Journal,
Volume 57 (1978), 1371430
"""
Kmax = int(Kmax)
W = float(NW) / N
nidx = np.arange(N, dtype='d')
# In this case, we create the dpss windows of the smaller size
# (interp_from) and then interpolate to the larger size (N)
if interp_from is not None:
if interp_from > N:
e_s = 'In dpss_windows, interp_from is: %s ' % interp_from
e_s += 'and N is: %s. ' % N
e_s += 'Please enter interp_from smaller than N.'
raise ValueError(e_s)
dpss = [ ]
d, e = dpss_windows(interp_from, NW, Kmax)
for this_d in d:
x = np.arange(this_d.shape[ -1 ])
I = interpolate.interp1d(x, this_d, kind=interp_kind)
d_temp = I(np.arange(0, this_d.shape[ -1 ] - 1,
float(this_d.shape[ -1 ] - 1) / N))
# Rescale:
d_temp = d_temp / np.sqrt( | np.sum(d_temp ** 2) | numpy.sum |
from math import sqrt, log
from numpy import asarray, dot, outer, identity, matmul, array, transpose
from numpy.random import uniform
from numpy.linalg import inv
from data import x, d, N, K, theta, gamma, delta, R, L, A_inv
# function that returns a reward = scalar product + noise
def pull(i):
return dot(x[i], theta) + uniform(-R, R)
# print the "real" rewards associated to each arm
#for i in range(K):
# print (i, dot(x[i], theta))
# Initialization: Pull an arm and initialize variables
i = 0
r = pull(i)
s = r
b = r * | asarray(x[i]) | numpy.asarray |
"""
Copyright (C) 2020 ETH Zurich. All rights reserved.
Author: <NAME>, ETH Zurich
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import numpy as np
SPEED_OF_SOUND = 1540 # meters per second
class Transducer:
def __init__(self,
num_of_x_elements=1,
num_of_y_elements=1,
x_pitch=0,
y_pitch=0,
x_width=0,
y_width=0,
f_central_hz=0,
bandwidth_hz=0,
active_elements=None):
self._num_of_x_elements = num_of_x_elements
self._num_of_y_elements = num_of_y_elements
self._num_of_elements = num_of_y_elements * num_of_x_elements
self._x_pitch = x_pitch
self._y_pitch = y_pitch
self._x_width = x_width
self._y_width = y_width
self._f_central_hz = f_central_hz
self._bandwidth_hz = bandwidth_hz
self._speed_of_sound = SPEED_OF_SOUND
# Calculate X, Y coordinates of transducer elements
self._calc_elements_coords()
# Check if active elements were specified
# By default all the elements are active
if active_elements is not None:
self.set_active_elements(active_elements)
else:
self._active_elements = None
return
# Returns x,y coords for the elements of transducer
def _calc_elements_coords(self):
# Calc x coords
x_coords = np.arange(0, self._num_of_x_elements)*(self._x_pitch)
x_coords = x_coords.reshape(-1,)
# Put zero to the center of array
x_coords = x_coords - (x_coords[-1] - x_coords[0])/2
# Cals y coords
y_coords = np.arange(0, self._num_of_y_elements)*(self._y_pitch)
y_coords = y_coords.reshape(-1,)
# Put zero to the center of array
y_coords = y_coords - (y_coords[-1] - y_coords[0])/2
self._elements_coords = np.transpose(np.dstack(np.meshgrid(x_coords, y_coords)).reshape(-1, 2))
return
# Set the active elements of the transducer by list of indices
# Attention: elements numeration starts from 0
def set_active_elements(self, active_elements):
self._active_elements = | np.array(active_elements, dtype=np.int) | numpy.array |
#
# Let's use this python script to:
# - perform transit "Quick fit"
# - Search for dips in a lightcurve which match that detected
# - Search for secondaries
# - Perform quick/dirty EB modelling
#
import numpy as np
import pandas as pd
import pickle
import os
import glob
from copy import deepcopy
from datetime import datetime
from scipy import optimize
import exoplanet as xo
import scipy.interpolate as interp
import scipy.optimize as optim
import matplotlib.pyplot as plt
import matplotlib
from astropy.coordinates import SkyCoord
from astropy import units as u
import seaborn as sns
import logging
logging.getLogger('matplotlib.font_manager').disabled = True
MonoData_tablepath = os.path.join('/'.join(os.path.dirname( __file__ ).split('/')[:-1]),'data','tables')
if os.environ.get('MONOTOOLSPATH') is None:
MonoData_savepath = os.path.join('/'.join(os.path.dirname( __file__ ).split('/')[:-1]),'data')
else:
MonoData_savepath = os.environ.get('MONOTOOLSPATH')
if not os.path.isdir(MonoData_savepath):
os.mkdir(MonoData_savepath)
os.environ["CXXFLAGS"]="-fbracket-depth=512" if not "CXXFLAGS" in os.environ else "-fbracket-depth=512,"+os.environ["CXXFLAGS"]
os.environ["CFLAGS"] = "-fbracket-depth=512" if not "CFLAGS" in os.environ else "-fbracket-depth=512,"+os.environ["CFLAGS"]
#creating new hidden directory for theano compilations:
theano_dir=MonoData_savepath+'/.theano_dir_'+str(np.random.randint(8))
theano_pars={'device':'cpu','floatX':'float64',
'base_compiledir':theano_dir,"gcc.cxxflags":"-fbracket-depth=1024"}
'''if MonoData_savepath=="/Users/hosborn/python/MonoToolsData" or MonoData_savepath=="/Volumes/LUVOIR/MonoToolsData":
theano_pars['cxx']='/usr/local/Cellar/gcc/9.3.0_1/bin/g++-9'
if MonoData_savepath=="/Users/hosborn/python/MonoToolsData" or MonoData_savepath=="/Volumes/LUVOIR/MonoToolsData":
theano_pars['cxx']='cxx=/Library/Developer/CommandLineTools/usr/bin/g++'
'''
if os.environ.get('THEANO_FLAGS') is None:
os.environ["THEANO_FLAGS"]=''
for key in theano_pars:
if key not in os.environ["THEANO_FLAGS"]:
os.environ["THEANO_FLAGS"] = os.environ["THEANO_FLAGS"]+','+key+"="+theano_pars[key]
import theano.tensor as tt
import pymc3 as pm
import theano
theano.config.print_test_value = True
theano.config.exception_verbosity='high'
from . import tools
from . import fit
def transit(pars,x):
log_per,b,t0,log_r_pl,u1,u2=pars
# Compute a limb-darkened light curve using starry
light_curve = (
xo.LimbDarkLightCurve([np.clip(u1,0,1),np.clip(u2,0,1)]).get_light_curve(orbit=xo.orbits.KeplerianOrbit(period=np.power(10,log_per), b=b, t0=t0),
r=np.power(10,log_r_pl), t=x).eval()
)
return light_curve.ravel()
def least_sq(pars,x,y,yerr):
model=transit(pars,x)
chisq=-1*np.sum((y-model)**2*yerr**-2)
return chisq
def QuickMonoFit(lc,it0,dur,Rs=None,Ms=None,Teff=None,useL2=False,fit_poly=True,force_tdur=False,
polyorder=2, ndurs=4.2, how='mono', init_period=None,fluxindex='flux_flat',mask=None, **kwargs):
# Performs simple planet fit to monotransit dip given the detection data.
#Initial depth estimate:
dur=0.3 if dur/dur!=1.0 else dur #Fixing duration if it's broken/nan.
winsize=np.clip(dur*ndurs,0.75,3.5)
if mask is None and ((fluxindex=='flux_flat')|(fluxindex=='flux')):
mask=lc['mask']
elif mask is None:
mask=np.isfinite(lc[fluxindex])
timeindex='bin_time' if 'bin_' in fluxindex else 'time'
fluxerrindex='bin_flux_err' if 'bin_' in fluxindex else 'flux_err'
if how=='periodic':
assert init_period is not None
xinit=(lc[timeindex]-it0-init_period*0.5)%init_period-init_period*0.5
nearby=(abs(xinit)<winsize)
else:
xinit=lc[timeindex]-it0
nearby=abs(xinit)<winsize
assert np.sum(nearby)>0
cad = np.nanmedian(np.diff(lc[timeindex])) if 'bin_' in fluxindex else float(int(max(set(list(lc['cadence'][nearby])), key=list(lc['cadence'][nearby]).count)[1:]))/1440
if fluxindex=='flux_flat' and 'flux_flat' not in lc:
#Reflattening and masking transit:
lc=tools.lcFlatten(lc, winsize=9*dur, stepsize=0.1*dur, transit_mask=abs(xinit)>dur*0.5)
if how=='periodic':
assert np.sum(nearby&mask)>0
#print(lc[timeindex][nearby])
x = xinit[nearby&mask]+it0 #re-aligning this fake "mono" with the t0 provided
y = lc[fluxindex][nearby&mask][np.argsort(x)]
y-=np.nanmedian(y)
yerr=lc[fluxerrindex][nearby&mask][np.argsort(x)]
x=np.sort(x).astype(np.float64)
oot_flux=np.nanmedian(y[(abs(x-it0)>0.65*dur)])
int_flux=np.nanmedian(y[(abs(x-it0)<0.35*dur)])
#print(it0,dur,oot_flux,int_flux,abs(oot_flux-int_flux)/lc['flux_unit'],x,y,yerr)
fit_poly=False
init_poly=None
else:
#Mono case:
x=lc[timeindex][nearby&mask].astype(np.float64)
yerr=lc[fluxerrindex][nearby&mask]
if not fit_poly or np.sum(abs(x-it0)<0.6)==0.0:
y=lc[fluxindex][nearby&mask]
y-=np.nanmedian(y)
oot_flux=np.nanmedian(y[(abs(x-it0)>0.65*dur)])
int_flux=np.nanmedian(y[(abs(x-it0)<0.35*dur)])
fit_poly=False
init_poly=None
else:
y=lc[fluxindex][nearby&mask]
y-=np.nanmedian(y)
#print(np.sum(abs(x-it0)<0.6),it0,np.min(x),np.max(x))
init_poly=np.polyfit(x[abs(x-it0)>0.7*dur]-it0,y[abs(x-it0)>0.7*dur],polyorder)
oot_flux=np.nanmedian((y-np.polyval(init_poly,x-it0))[abs(x-it0)>0.65*dur])
int_flux=np.nanmedian((y-np.polyval(init_poly,x-it0))[abs(x-it0)<0.35*dur])
dep=abs(oot_flux-int_flux)*lc['flux_unit']
#print(dep,dur,it0,x,y,init_poly)
with pm.Model() as model:
# Parameters for the stellar properties
if fit_poly:
trend = pm.Normal("trend", mu=0, sd=10.0 ** -np.arange(polyorder+1)[::-1], shape=polyorder+1,testval=init_poly)
flux_trend = pm.Deterministic("flux_trend", tt.dot(np.vander(x - it0, polyorder+1), trend))
#trend = pm.Uniform("trend", upper=np.tile(1,polyorder+1), shape=polyorder+1,
# lower=np.tile(-1,polyorder+1), testval=init_poly)
#trend = pm.Normal("trend", mu=np.zeros(polyorder+1), sd=5*(10.0 ** -np.arange(polyorder+1)[::-1]),
# shape=polyorder+1, testval=np.zeros(polyorder+1))
#trend = pm.Uniform("trend", upper=np.tile(10,polyorder+1),lower=np.tile(-10,polyorder+1),
# shape=polyorder+1, testval=np.zeros(polyorder+1))
else:
mean = pm.Normal("mean", mu=0.0, sd=3*np.nanstd(y))
flux_trend = mean
r_star = Rs if Rs is not None and not np.isnan(Rs) else 1.0
m_star = Ms if Ms is not None and not np.isnan(Ms) else 1.0
Ts = Teff if Teff is not None and not np.isnan(Teff) else 5500.0
u_star = tools.getLDs(Ts)[0]
#xo.distributions.QuadLimbDark("u_star")
if how=='periodic' and init_period is not None:
log_per = pm.Normal("log_per", mu=np.log(init_period),sd=0.4)
else:
rhostar=m_star/r_star**3
init_per = abs(18226*rhostar*((2*np.sqrt((1+dep**0.5)**2-0.41**2))/dur)**-3)
# Orbital parameters for the planets
log_per = pm.Uniform("log_per", lower=np.log(dur*5),upper=np.log(3000),
testval=np.clip(np.log(init_per),np.log(dur*6),np.log(3000))
)
tcen = pm.Bound(pm.Normal, lower=it0-0.7*dur, upper=it0+0.7*dur)("tcen",
mu=it0,sd=0.25*dur,testval=it0)
b = pm.Uniform("b",upper=1.0,lower=0.0,testval=0.2)
log_ror = pm.Uniform("log_ror",lower=-6,upper=-0.5,testval=np.clip(0.5*np.log(dep),-6,-0.5))
ror = pm.Deterministic("ror", tt.exp(log_ror))
#ror, b = xo.distributions.get_joint_radius_impact(min_radius=0.0075, max_radius=0.25,
# testval_r=np.sqrt(dep), testval_b=0.41)
#logror = pm.Deterministic("logror",tt.log(ror))
#pm.Potential("ror_prior", -logror) #Prior towards larger logror
r_pl = pm.Deterministic("r_pl", ror*r_star*109.1)
period = pm.Deterministic("period", tt.exp(log_per))
# Orbit model
orbit = xo.orbits.KeplerianOrbit(r_star=r_star,m_star=m_star,
period=period,t0=tcen,b=b)
vx, vy, vz = orbit.get_relative_velocity(tcen)
vrel=pm.Deterministic("vrel",tt.sqrt(vx**2 + vy**2)/r_star)
#tdur=pm.Deterministic("tdur",(2*tt.sqrt(1-b**2))/vrel)
#correcting for grazing transits by multiplying b by 1-rp/rs
tdur=pm.Deterministic("tdur",(2*tt.sqrt((1+ror)**2-b**2))/vrel)
if force_tdur:
#Adding a potential to force our transit towards the observed transit duration:
pm.Potential("tdur_prior", -0.05*len(x)*abs(tt.log(tdur/dur)))
# The 2nd light (not third light as companion light is not modelled)
# This quantity is in delta-mag
if useL2:
deltamag_contam = pm.Uniform("deltamag_contam", lower=-20.0, upper=20.0)
third_light = pm.Deterministic("third_light", tt.power(2.511,-1*deltamag_contam)) #Factor to multiply normalised lightcurve by
else:
third_light = 0.0
# Compute the model light curve using starry
light_curves = (
xo.LimbDarkLightCurve(u_star).get_light_curve(
orbit=orbit, r=r_pl/109.1, t=x, texp=cad))*(1+third_light)/lc['flux_unit']
transit_light_curve = pm.math.sum(light_curves, axis=-1)
light_curve = pm.Deterministic("light_curve", transit_light_curve + flux_trend)
pm.Normal("obs", mu=light_curve, sd=yerr, observed=y)
#print(model.check_test_point())
if fit_poly:
map_soln = xo.optimize(start=model.test_point,vars=[trend],verbose=False)
map_soln = xo.optimize(start=map_soln,vars=[trend,log_ror,log_per,tcen],verbose=False)
# Fit for the maximum a posteriori parameters
else:
map_soln = xo.optimize(start=model.test_point,vars=[mean],verbose=False)
map_soln = xo.optimize(start=map_soln,vars=[mean,log_ror,log_per,tcen],verbose=True)
'''
map_soln = xo.optimize(start=map_soln,vars=[b, log_ror, log_per, tcen],verbose=False)
if useL2:
map_soln = xo.optimize(start=map_soln,vars=[log_ror, b, deltamag_contam],verbose=False)
map_soln = xo.optimize(start=map_soln,verbose=False)
if fit_poly:
map_soln = xo.optimize(start=map_soln,vars=[trend],verbose=False)
map_soln = xo.optimize(start=map_soln,verbose=False)
map_soln = xo.optimize(start=map_soln,verbose=False)
'''
map_soln, func = xo.optimize(start=map_soln,verbose=False,return_info=True)
'''
interpy=xo.LimbDarkLightCurve(map_soln['u_star']).get_light_curve(
r=float(map_soln['r_pl']),
orbit=xo.orbits.KeplerianOrbit(
r_star=float(map_soln['r_star']),
m_star=float(map_soln['m_star']),
period=float(map_soln['period']),
t0=float(map_soln['t0']),
b=float(map_soln['b'])),
t=interpt
)/(1+map_soln['third_light'])
'''
#print(func)
interpt=np.linspace(map_soln['tcen']-winsize,map_soln['tcen']+winsize,600)
if 'third_light' not in map_soln:
map_soln['third_light']=np.array(0.0)
transit_zoom = (xo.LimbDarkLightCurve(u_star).get_light_curve(
orbit=xo.orbits.KeplerianOrbit(r_star=r_star,m_star=m_star,
period=map_soln['period'],t0=map_soln['tcen'],b=map_soln['b']),
r=map_soln['r_pl']/109.1, t=interpt, texp=cad
)*(1+map_soln['third_light'])
).eval().ravel()/lc['flux_unit']
#Reconstructing best-fit model into a dict:
best_fit={'log_lik_mono':-1*func['fun'],'model_success':str(func['success'])}
for col in map_soln:
if 'interval__' not in col:
if map_soln[col].size==1:
best_fit[col]=float(map_soln[col])
else:
best_fit[col]=map_soln[col].astype(float)
#print({bf:type(best_fit[bf]) for bf in best_fit})
#print(best_fit["vrel"],best_fit["b"],map_soln["tdur"],best_fit["tcen"])
if np.isnan(map_soln["tdur"]):
best_fit['tdur']=dur
#Adding depth:
best_fit['transit_zoom']=transit_zoom
best_fit['monofit_x']=x
best_fit['monofit_ymodel']=map_soln['light_curve']
best_fit['monofit_y']=y
best_fit['monofit_yerr']=yerr
best_fit['depth']=np.max(transit_zoom)-np.min(transit_zoom)
#err = std / sqrt(n_pts in transit)
best_fit['depth_err']=np.nanstd(y[abs(x-best_fit['tcen'])<0.475*best_fit["tdur"]])/\
np.sqrt(np.sum(abs(x-best_fit['tcen'])<0.475*best_fit["tdur"]))
best_fit['snr']=best_fit['depth']/(best_fit['depth_err'])
'''
print("time stuff:", best_fit['tcen'],interpt[0],interpt[-1],
"\nfit stuff:",best_fit['r_pl'],best_fit['b'], best_fit['logror'],best_fit['tdur'],(1+best_fit['third_light'])/lc['flux_unit'],
"\ndepth stuff:",best_fit['depth'],best_fit['depth_err'],lc['flux_unit'],np.min(transit_zoom),np.min(map_soln['light_curve']))'''
#Calculating std in typical bin with width of the transit duration, to compute SNR_red
if how=='mono' or init_period is None:
oot_mask=mask*(abs(lc[timeindex]-best_fit['tcen'])>0.5)*(abs(lc[timeindex]-best_fit['tcen'])<25)
binlc=tools.bin_lc_segment(np.column_stack((lc[timeindex][oot_mask],lc[fluxindex.replace('_flat','')][oot_mask],
lc[fluxerrindex][oot_mask])),best_fit['tdur'])
best_fit['cdpp'] = np.nanmedian(abs(np.diff(binlc[:,1])))#np.nanstd(binlc[:,1])
best_fit['Ntrans']=1
else:
phase=(abs(lc['time']-best_fit['tcen']+0.5*best_fit['tdur'])%init_period)
if len(mask)==len(phase):
oot_mask=mask*(phase>best_fit['tdur'])
else:
oot_mask=lc['mask']*(phase>best_fit['tdur'])
binlc=tools.bin_lc_segment(np.column_stack((lc['time'][oot_mask],lc['flux'][oot_mask],
lc['flux_err'][oot_mask])),best_fit['tdur'])
#Counting in-transit cadences:
durobs=0
for cad in np.unique(lc['cadence']):
if len(mask)==len(phase):
durobs+=np.sum(phase[mask&(lc['cadence']==cad)]<best_fit['tdur'])*float(int(cad[1:]))/1440
else:
durobs+=np.sum(phase[lc['mask']&(lc['cadence']==cad)]<best_fit['tdur'])*float(int(cad[1:]))/1440
best_fit['Ntrans']=durobs/best_fit['tdur']
best_fit['cdpp'] = np.nanmedian(abs(np.diff(binlc[:,1])))#np.nanstd(binlc[:,1])
best_fit['snr_r']=best_fit['depth']/(best_fit['cdpp']/np.sqrt(best_fit['Ntrans']))
best_fit['interpmodel']=interp.interp1d(np.hstack((-10000,interpt-best_fit['tcen'],10000)),
np.hstack((0.0,transit_zoom,0.0)))
if how=='periodic':
for col in ['period','vrel']:
par = best_fit.pop(col) #removing things which may spoil the periodic detection info (e.g. derived period)
best_fit[col+'_mono']=par
assert 'period' not in best_fit
best_fit['period']=init_period
return best_fit
def MonoTransitSearch(lc,ID,mission, Rs=None,Ms=None,Teff=None,
mono_SNR_thresh=6.5,mono_BIC_thresh=-6,n_durs=5,poly_order=3,
n_oversamp=20,binsize=15/1440.0,custom_mask=None,
transit_zoom=3.5,use_flat=False,use_binned=True,use_poly=True,
plot=False, plot_loc=None ,n_max_monos=8, use_stellar_dens=True, **kwargs):
#Searches LC for monotransits - in this case without minimizing for duration, but only for Tdur
'''
lc
ID
mono_SNR_thresh=6.5 - threshold in sigma
mono_BIC_thresh=-10 - threshold in BIC to be used for a significant monotransit
n_durs=5
poly_order=3 - polynomial order to use for a "no transit" fit
n_oversamp=10 - oversampling factor wrt to durations from which to match to lightcurve
binsize=1/96. - size of bins in days
transit_zoom=3.5 - size (in transit durations) to cut around transit when minimizing transit model
use_flat=True - flattens lightcurve before monotransit search
use_binned=True
use_poly=True - fits transits (and sin) with a polynomial (order = poly_order-1) to account for variability
Rs=None
Ms=None
Teff=None
plot=False
plot_loc=None
use_stellar_dens=True - use stellar density to produce transit templates to search.
'''
#Computing a fine x-range to search:
search_xrange=[]
Rs=1.0 if (Rs is None or not use_stellar_dens or np.isnan(Rs)) else float(Rs)
Ms=1.0 if (Ms is None or not use_stellar_dens or np.isnan(Ms)) else float(Ms)
Teff=5800.0 if Teff is None else float(Teff)
mincad=np.min([float(cad[1:])/1440 for cad in np.unique(lc['cadence'])])
interpmodels, tdurs = get_interpmodels(Rs,Ms,Teff,lc['time'],lc['flux_unit'],
n_durs=n_durs,texp=mincad, mission=mission)
#print("Checking input model matches. flux:",np.nanmedian(uselc[:,0]),"std",np.nanstd(uselc[:,1]),"transit model:",
# interpmodels[0](10.0),"depth:",interpmodels[0](0.0))
search_xranges=[]
mask = lc['mask'] if custom_mask is None else custom_mask
#Removing gaps bigger than 2d (with no data)
for n in range(n_durs):
search_xranges_n=[]
if np.max(np.diff(lc['time'][mask]))<tdurs[n]:
lc_regions=[lc['time'][mask]]
else:
lc_regions = np.array_split(lc['time'][mask],1+np.where(np.diff(lc['time'][mask])>tdurs[n])[0])
for arr in lc_regions:
search_xranges_n+=[np.arange(arr[0]+0.33*tdurs[n],arr[-1]-0.33*tdurs[n],tdurs[n]/n_oversamp)]
search_xranges+=[np.hstack(search_xranges_n)]
print(str(ID)+" - Searching "+str(np.sum([len(xr) for xr in search_xranges]))+" positions with "+str(n_durs)+" durations:",','.join(list(np.round(tdurs,3).astype(str))))
#Looping through search and computing chi-sq at each position:
outparams=pd.DataFrame()
def trans_model_neglnlik(params,x,y,sigma2,init_log_dep,interpmodel):
#Returns chi-squared for transit model, plus linear background flux trend
# pars = depth, duration, poly1, poly2
model=np.exp(params[0]-init_log_dep)*interpmodel(x)
return 0.5 * np.sum((y - model)**2 / sigma2 + np.log(sigma2))
def sin_model_neglnlik(params,x,y,sigma2,tcen,dur):
#Returns chi-squared for transit model, plus linear background flux trend
# pars = depth, duration, poly1, poly2
newt=x/(2.6*dur)*2*np.pi
amp=np.exp(-1*np.power(newt, 2.) / (2 * np.power(np.pi, 2.)))
model=params[0]*(amp*np.sin(newt-np.pi*0.5)-0.1)
return 0.5 * np.sum((y - model)**2 / sigma2 + np.log(sigma2))
def trans_model_poly_neglnlik(params,x,y,sigma2,init_log_dep,interpmodel):
#Returns chi-squared for transit model, plus linear background flux trend
# pars = depth, gradient
model=x*params[1]+np.exp(params[0]-init_log_dep)*interpmodel(x)
return 0.5 * np.sum((y - model)**2 / sigma2 + np.log(sigma2))
def sin_model_poly_neglnlik(params,x,y,sigma2,tcen,dur):
#Returns chi-squared for transit model, plus linear background flux trend
# pars = log_depth, poly1, poly2
newt=x/(2*dur)*2*np.pi
amp=np.exp(-1*np.power(newt, 2.) / (2 * np.power(np.pi, 2.)))
model=x*params[1]+np.exp(params[0])*(amp*np.sin(newt-np.pi*0.5)-0.1)
return 0.5 * np.sum((y - model)**2 / sigma2 + np.log(sigma2))
#from progress.bar import IncrementalBar
#bar = IncrementalBar('Searching for monotransit', max = np.sum([len(xr) for xr in search_xranges]))
#For each duration we scan across the lightcurve and compare a transit model to others:
for n,search_xrange in enumerate(search_xranges):
tdur=tdurs[n%n_durs]
#flattening and binning as a function of the duration we are searching in order to avoid
if use_binned:
#Having may points in a lightcurve makes flattening difficult (and fitting needlessly slow)
# So let's bin to a fraction of the tdur - say 9 in-transit points.
lc=tools.lcBin(lc,binsize=tdur/9, use_flat=False, extramask=custom_mask)
if use_flat and not use_poly:
lc=tools.lcFlatten(lc,winsize=tdur*13,stepsize=tdur*0.333,use_bin=True)
uselc=np.column_stack((lc['bin_time'],lc['bin_flux_flat'],lc['bin_flux_err']))
else:
uselc=np.column_stack((lc['bin_time'],lc['bin_flux'],lc['bin_flux_err']))
else:
if use_flat and not use_poly:
lc=tools.lcFlatten(lc,winsize=tdur*13,stepsize=tdur*0.333)
uselc=np.column_stack((lc['time'][mask],lc['flux_flat'][mask],lc['flux_err'][mask]))
else:
uselc=np.column_stack((lc['time'][mask],lc['flux'][mask],lc['flux_err'][mask]))
#Making depth vary from 0.1 to 1.0
init_dep_shifts=np.exp(np.random.normal(0.0,n_oversamp*0.01,len(search_xrange)))
randns=np.random.randint(2,size=(len(search_xrange),2))
cad=np.nanmedian(np.diff(uselc[:,0]))
p_transit = np.clip(3/(len(uselc[:,0])*cad),0.0,0.05)
#What is the probability of transit given duration (used in the prior calculation) - duration
methods=['SLSQP','Nelder-Mead','Powell']
logmodeldep=np.log(abs(interpmodels[n](0.0)))
for n_mod,x2s in enumerate(search_xrange):
#bar.next()
#minimise single params - depth
round_tr=abs(uselc[:,0]-x2s)<(transit_zoom*tdur)
#Centering x array on epoch to search
x=uselc[round_tr,0]-x2s
in_tr=abs(x)<(0.45*tdur)
if len(x[in_tr])>0 and not np.isnan(x[in_tr]).all() and len(x[~in_tr])>0 and not np.isnan(x[~in_tr]).all():
y=uselc[round_tr,1]
oot_median=np.nanmedian(y[~in_tr])
y-=oot_median
yerr=uselc[round_tr,2]
sigma2=yerr**2
init_log_dep=np.log(np.clip(-1*(np.nanmedian(y[in_tr]))*init_dep_shifts[n_mod],0.00000001,1000))
init_noise=np.std(y)
poly_fit=np.polyfit(x,y,poly_order)
poly_neg_llik=0.5 * np.sum((y - np.polyval(poly_fit,x))**2 / sigma2 + np.log(sigma2))
if use_poly:
init_grad=np.polyfit(x[~in_tr],y[~in_tr],1)[0]
res_trans=optim.minimize(trans_model_poly_neglnlik,np.hstack((init_log_dep,init_grad)),
args=(x,y,sigma2,
logmodeldep,interpmodels[n%n_durs]),
method = methods[randns[n_mod,0]])
res_sin=optim.minimize(sin_model_poly_neglnlik,
np.hstack((init_log_dep,init_grad)),
args=(x,y,sigma2,x2s,tdur),
method = methods[randns[n_mod,1]])
else:
res_trans=optim.minimize(trans_model_neglnlik,(init_log_dep),
args=(x,y,sigma2,
logmodeldep,interpmodels[n%n_durs]),
method = methods[randns[n_mod,0]])
res_sin=optim.minimize(sin_model_neglnlik, (init_log_dep),
args=(x,y,sigma2,x2s,tdur),
method = methods[randns[n_mod,1]])
log_len=np.log(np.sum(round_tr))
#BIC = log(n_points)*n_params - 2*(log_likelihood + log_prior)
#BIC = log(n_points)*n_params + 2*(neg_log_likelihood-log_prior).
# Setting log prior of transit as sum of:
# - 0.5*tdur/len(x) - the rough probability that, given some point in time, it's in the centre of a transit
# - normal prior on log(duration) to be within 50% (0.5 in logspace)
# 'BIC_trans':log_len*len(res_trans.x)+2*(res_trans.fun-np.log(p_transit)),
# 'BIC_sin':log_len*len(res_sin.x)+2*(res_sin.fun-np.log(1-p_transit)),
# 'BIC_poly':log_len*len(poly_fit)+2*(poly_neg_llik-np.log(1-p_transit)),
n_params=np.array([len(res_trans.x),len(res_sin.x),len(poly_fit)])
outdic={'tcen':x2s,
'llk_trans':-1*res_trans.fun,
'llk_sin':-1*res_sin.fun,
'llk_poly':-1*poly_neg_llik,
'BIC_trans':log_len*n_params[0]+2*(res_trans.fun-np.log(p_transit)),
'BIC_sin':log_len*n_params[1]+2*(res_sin.fun-np.log(5*p_transit)),
'BIC_poly':log_len*n_params[2]+2*(poly_neg_llik-np.log(1-(6*p_transit))),
'init_dep':np.exp(init_log_dep),
'init_dur':tdur,
'trans_dep':np.exp(res_trans.x[0]),
'sin_dep':np.exp(res_sin.x[0]),
'n_mod':n,
'tran_success':int(res_trans.success),'sin_success':int(res_sin.success),
'all_success':int(res_trans.success&res_sin.success)}
outdic['trans_snr']=outdic['trans_dep']/(init_noise/np.sqrt(outdic['init_dur']/cad))
outdic.update({'poly_'+str(n):poly_fit[n] for n in range(poly_order+1)})
if use_poly:
outdic['trans_grad']=res_trans.x[1]
#outdic.update({'trans_poly_'+str(n):res_trans.x[1+n] for n in range(poly_order)})
outdic['sin_grad']=res_sin.x[1]
#outdic.update({'sin_poly_'+str(n):res_sin.x[1+n] for n in range(poly_order)})
outparams=outparams.append(pd.Series(outdic,name=len(outparams)))
#print(n,len(outparams))
#bar.finish()
outparams=outparams.sort_values('tcen')
#Transit model has to be better than the sin model AND the DeltaBIC w.r.t to the polynomial must be <-10.
# transit depth must be <0.0,
# the sum of DeltaBICs has to be < threshold (e.g. -10)
outparams['sin_llk_ratio']=outparams['llk_trans'].values-outparams['llk_sin'].values
outparams['poly_llk_ratio']=outparams['llk_trans'].values-outparams['llk_poly'].values
outparams['sin_DeltaBIC']=outparams['BIC_trans'].values-outparams['BIC_sin'].values
outparams['poly_DeltaBIC']=outparams['BIC_trans'].values-outparams['BIC_poly'].values
outparams['sum_DeltaBICs']=outparams['sin_DeltaBIC']+outparams['poly_DeltaBIC']
outparams['mean_DeltaBICs']=0.5*outparams['sum_DeltaBICs']
#if use_poly:
#In the case of co-fitting for polynomials, BICs fail, but log likelihoods still work.
#We will use 1.5 (4.5x) over sin and 3 (20x) over polynomial as our threshold:
# signfct=np.where((outparams['sin_llk_ratio']>1.5)&(outparams['poly_llk_ratio']>3)&(outparams['trans_dep']>0.0))[0]
#else:
# signfct=np.where((outparams['sin_llk_ratio']>1.0)&(outparams['poly_DeltaBIC']<mono_BIC_thresh)&(outparams['trans_dep']>0.0))[0]
signfct=(outparams['sin_llk_ratio']>1.5)&(outparams['poly_llk_ratio']>1.5)&(outparams['poly_DeltaBIC']<mono_BIC_thresh)&(outparams['trans_snr']>(mono_SNR_thresh-0.5))
n_sigs=np.sum(signfct)
if n_sigs>0:
best_ix=[]
nix=0
detns={}
while n_sigs>0 and nix<=n_max_monos:
#Getting the best detection:
signfct_df=outparams.loc[signfct]
#Placing the best detection info into our dict:
detn_row=signfct_df.iloc[np.argmin(signfct_df['poly_DeltaBIC'])]
detns[str(nix).zfill(2)]={}
detns[str(nix).zfill(2)]['llk_trans'] = detn_row['llk_trans']
detns[str(nix).zfill(2)]['llk_sin'] = detn_row['llk_sin']
detns[str(nix).zfill(2)]['llk_poly'] = detn_row['llk_poly']
detns[str(nix).zfill(2)]['BIC_trans'] = detn_row['BIC_trans']
detns[str(nix).zfill(2)]['BIC_sin'] = detn_row['BIC_sin']
detns[str(nix).zfill(2)]['BIC_poly'] = detn_row['BIC_poly']
detns[str(nix).zfill(2)]['sin_DeltaBIC']= detn_row['sin_DeltaBIC']
detns[str(nix).zfill(2)]['poly_DeltaBIC']=detn_row['poly_DeltaBIC']
detns[str(nix).zfill(2)]['tcen'] = detn_row['tcen']
detns[str(nix).zfill(2)]['period'] = np.nan
detns[str(nix).zfill(2)]['period_err'] = np.nan
detns[str(nix).zfill(2)]['DeltaBIC'] = detn_row['poly_DeltaBIC']
detns[str(nix).zfill(2)]['tdur'] = detn_row['init_dur']
detns[str(nix).zfill(2)]['depth'] = detn_row['trans_dep']
detns[str(nix).zfill(2)]['orbit_flag'] = 'mono'
detns[str(nix).zfill(2)]['snr'] = detn_row['trans_snr']
#Calculating minimum period:
detns[str(nix).zfill(2)]['P_min'] = calc_min_P(uselc[:,0],detn_row['tcen'],detn_row['init_dur'])
#Removing the regions around this detection from our array
#print(np.sum(abs(outparams['tcen']-detn_row['tcen'])<np.where(outparams['init_dur']<detn_row['init_dur'],
# 0.66*detn_row['init_dur'], 0.66*outparams['init_dur'])))
#print(np.sum(signfct[abs(outparams['tcen']-detn_row['tcen'])<np.where(outparams['init_dur']<detn_row['init_dur'],
# 0.66*detn_row['init_dur'], 0.66*outparams['init_dur'])]))
away_from_this_detn=abs(outparams['tcen']-detn_row['tcen'])>np.where(outparams['init_dur']<detn_row['init_dur'],
0.66*detn_row['init_dur'], 0.66*outparams['init_dur'])
signfct=signfct&away_from_this_detn
n_sigs=np.sum(signfct)
#print(n_sigs,detns[str(nix).zfill(2)]['poly_DeltaBIC'],np.sum(signfct[abs(outparams['tcen']-detn_row['tcen'])<np.where(outparams['init_dur']<detn_row['init_dur'],0.66*detn_row['init_dur'], 0.66*outparams['init_dur'])]))
nix+=1
#print(np.percentile(outparams['poly_DeltaBIC'],[5,16,50,84,95]))
else:
print("n_sigs == 0")
detns={}
if plot:
fig_loc= PlotMonoSearch(lc,ID,outparams,detns,interpmodels,tdurs,custom_mask=custom_mask,
use_flat=use_flat,use_binned=use_binned,use_poly=use_poly,plot_loc=plot_loc)
return detns, outparams, fig_loc
else:
return detns, outparams, None
def calc_min_P(time,tcen,tdur):
abs_times=abs(time-tcen)
abs_times=np.sort(abs_times)
whr=np.where(np.diff(abs_times)>tdur*0.75)[0]
if len(whr)>0:
return abs_times[whr[0]]
else:
return np.max(abs_times)
def PlotMonoSearch(lc, ID, monosearchparams, mono_dic, interpmodels, tdurs,
use_flat=True,use_binned=True,use_poly=False,transit_zoom=2.5,plot_loc=None,custom_mask=None,**kwargs):
if plot_loc is None:
plot_loc = str(ID).zfill(11)+"_Monotransit_Search.pdf"
elif plot_loc[-1]=='/':
plot_loc = plot_loc+str(ID).zfill(11)+"_Monotransit_Search.pdf"
if use_flat and not use_poly:
lc=tools.lcFlatten(lc,winsize=np.median(tdurs)*7.5,stepsize=0.2*np.median(tdurs))
lc=tools.lcBin(lc, 30/1440, use_masked=True, use_flat=True, extramask = custom_mask)
flux_key='flux_flat'
else:
flux_key='flux'
lc=tools.lcBin(lc,30/1440,use_masked=True,use_flat=False)
mask = lc['mask'] if custom_mask is None else custom_mask
fig = plt.figure(figsize=(11.69,8.27))
import seaborn as sns
sns.set_palette(sns.set_palette("RdBu",14))
axes=[]
axes +=[fig.add_subplot(411)]
axes[0].set_title(str(ID).zfill(7)+" - Monotransit Search")
#rast=True if np.sum(lc['mask']>12000) else False
axes[0].plot(lc['time'][mask],lc[flux_key][mask],'.k',alpha=0.28,markersize=0.75, rasterized=True)
if use_flat:
axes[0].plot(lc['bin_time'],lc['bin_flux_flat'],'.k',alpha=0.7,markersize=1.75, rasterized=True)
else:
axes[0].plot(lc['bin_time'],lc['bin_flux'],'.k',alpha=0.7,markersize=1.75, rasterized=True)
axes[0].set_ylim(np.percentile(lc[flux_key][mask],(0.25,99.75)))
axes[0].set_ylabel("flux")
axes[0].set_xticks([])
axes[0].set_xticklabels([])
axes +=[fig.add_subplot(412)]
axes[1].plot([monosearchparams['tcen'].values[0],monosearchparams['tcen'].values[-1]],[-10,-10],'--k',alpha=0.25)
#plt.plot(monosearchparams_2['tcen'],monosearchparams_2['worstBIC'],'.',c='C5',alpha=0.4)
for n,dur in enumerate(np.unique(monosearchparams['init_dur'])):
if n==0:
axes[1].plot(monosearchparams.loc[monosearchparams['init_dur']==dur,'tcen'],
monosearchparams.loc[monosearchparams['init_dur']==dur,'poly_DeltaBIC'],
c=sns.color_palette()[n],alpha=0.6,label='Transit - polynomial', rasterized=True)
axes[1].plot(monosearchparams.loc[monosearchparams['init_dur']==dur,'tcen'],
monosearchparams.loc[monosearchparams['init_dur']==dur,'sin_DeltaBIC'],
c=sns.color_palette()[-1*(n+1)],alpha=0.6,label='Transit - wavelet', rasterized=True)
else:
axes[1].plot(monosearchparams.loc[monosearchparams['init_dur']==dur,'tcen'],
monosearchparams.loc[monosearchparams['init_dur']==dur,'poly_DeltaBIC'],
c=sns.color_palette()[n],alpha=0.6, rasterized=True)
axes[1].plot(monosearchparams.loc[monosearchparams['init_dur']==dur,'tcen'],
monosearchparams.loc[monosearchparams['init_dur']==dur,'sin_DeltaBIC'],
c=sns.color_palette()[-1*(n+1)],alpha=0.6, rasterized=True)
axes[1].legend(prop={'size': 5})
ix=(np.isfinite(monosearchparams['sum_DeltaBICs']))&(monosearchparams['sin_DeltaBIC']<1e8)&(monosearchparams['poly_DeltaBIC']<1e8)
min_bic=np.nanmin(monosearchparams.loc[ix,'poly_DeltaBIC'])
maxylim=np.nanmax([np.percentile(monosearchparams.loc[ix,'poly_DeltaBIC'],98),
np.percentile(monosearchparams.loc[ix,'sin_DeltaBIC'],98)])
axes[1].set_ylim(maxylim,min_bic)
axes[1].set_ylabel("Delta BIC")
axes[1].set_xlabel("Time [BJD-"+str(lc['jd_base'])+"]")
if len(mono_dic)>1:
trans_model_mins=[]
n_poly=int(np.sum([1 for n in range(10) if 'poly_'+str(n) in mono_dic[list(mono_dic.keys())[0]]]))
for nm,monopl in enumerate(mono_dic):
tdur=mono_dic[monopl]['tdur']
tcen=mono_dic[monopl]['tcen']
transit_zoom=2.25
axes[1].text(tcen,np.clip(np.min([mono_dic[monopl]['sin_DeltaBIC'],mono_dic[monopl]['poly_DeltaBIC']]),
min_bic,1e6),monopl)
axes +=[fig.add_subplot(4,len(mono_dic),nm+2*len(mono_dic)+1)]
axes[-1].set_xticks([])
axes[-1].set_xticklabels([])
axes[-1].text(tcen+0.1,np.clip(np.min([mono_dic[monopl]['sin_DeltaBIC'],mono_dic[monopl]['poly_DeltaBIC']]),
min_bic,1e6),
monopl)
for n,dur in enumerate(np.unique(monosearchparams['init_dur'])):
index=(monosearchparams['init_dur']==dur)&(abs(monosearchparams['tcen']-tcen)<transit_zoom*tdur)
axes[-1].plot(monosearchparams.loc[index,'tcen'],
monosearchparams.loc[index,'BIC_trans']-monosearchparams.loc[index,'BIC_poly'],
c=sns.color_palette()[n], alpha=0.6, rasterized=True)
axes[-1].plot(monosearchparams.loc[index,'tcen'],
monosearchparams.loc[index,'BIC_trans']-monosearchparams.loc[index,'BIC_sin'],
c=sns.color_palette()[-1*n], alpha=0.6, rasterized=True)
#plt.plot(monosearchparams['tcen'],monosearchparams['worstBIC'],',k')
axes[-1].plot([tcen,tcen],[-150,130],'--k',linewidth=1.5,alpha=0.25)
axes[-1].set_xlim(tcen-tdur*transit_zoom,tcen+tdur*transit_zoom)
axes[-1].set_ylim(maxylim,min_bic)
if nm==0:
axes[-1].set_ylabel("Delta BIC")
else:
axes[-1].set_yticks([])
axes[-1].set_yticklabels([])
mono_dets=monosearchparams.loc[monosearchparams['tcen']==mono_dic[monopl]['tcen']].iloc[0]
axes +=[fig.add_subplot(4,len(mono_dic),nm+3*len(mono_dic)+1)]
nmod=np.arange(len(tdurs))[np.argmin(abs(tdurs-tdur))]
round_tr=mask&(abs(lc['time']-tcen)<(transit_zoom*tdur))
x=(lc['time'][round_tr]-tcen)
y=lc[flux_key][round_tr]
y_offset=np.nanmedian(lc[flux_key][round_tr&(abs(lc['time']-tcen)>(0.7*tdur))]) if use_poly else 0
y-=y_offset
#Plotting polynomial:
axes[-1].plot(lc['time'][round_tr],np.polyval([mono_dets['poly_'+str(n)].values[0] for n in range(n_poly)],x),'--',
c=sns.color_palette()[-4],linewidth=2.0,alpha=0.6, rasterized=True)
#Plotting transit:
modeldep=abs(interpmodels[nmod](0.0))
if use_flat and not use_poly:
trans_model=(mono_dets['trans_dep']/modeldep)*interpmodels[nmod](x)
else:
trans_model=mono_dets['trans_grad']*x+(mono_dets['trans_dep']/modeldep)*interpmodels[nmod](x)
#Plotting sin wavelet:
newt=x/(2*tdur)*2*np.pi
amp=np.exp(-1*np.power(newt*1.25, 2.) / (2 * np.power(np.pi, 2.)))
if use_flat and not use_poly:
sin_model=mono_dets['sin_dep']*(amp*np.sin(newt-np.pi*0.5)-0.1)
else:
sin_model=mono_dets['sin_grad']*x+mono_dets['sin_dep']*(amp*np.sin(newt-np.pi*0.5)-0.1)
if nm==0:
axes[-1].set_ylabel("Flux")
else:
axes[-1].set_yticks([])
axes[-1].set_yticklabels([])
axes[-1].plot(lc['time'][round_tr],y,'.k',markersize=1.5,alpha=0.3, rasterized=True)
round_tr_bin=abs(lc['bin_time']-tcen)<(transit_zoom*tdur)
axes[-1].plot(lc['bin_time'][round_tr_bin],lc['bin_flux'][round_tr_bin]-y_offset,
'.k',alpha=0.7,markersize=2.5, rasterized=True)
axes[-1].plot(lc['time'][round_tr],trans_model,'-',
c=sns.color_palette()[0],linewidth=2.0,alpha=0.85, rasterized=True)
axes[-1].plot(lc['time'][round_tr],sin_model,'-.',
c=sns.color_palette()[-1],linewidth=2.0,alpha=0.6, rasterized=True)
axes[-1].set_xlim(tcen-tdur*transit_zoom,tcen+tdur*transit_zoom)
trans_model_mins+=[np.min(trans_model)]
#print(trans_model_mins)
trans_model_min=np.min(np.array(trans_model_mins))
for nm,monopl in enumerate(mono_dic):
axes[2+2*nm+1].set_ylim(trans_model_min*1.2,np.percentile(lc['bin_flux'],97.5))
fig.subplots_adjust(wspace=0, hspace=0.15)
#plt.tight_layout()
fig.savefig(plot_loc, dpi=400)
#plt.xlim(1414,1416)
return plot_loc
'''
#smearing this out by 0.3*tdur to avoid "micro peaks" in the array making multiple detections
def gaussian(x , s):
#Simple gaussian given position-adjusted x and sigma in order to convolve chisq spectrum
return 1./np.sqrt( 2. * np.pi * s**2 ) * np.exp( -x**2 / ( 2. * s**2 ) )
chisqs_conv=np.convolve(chisqs, np.fromiter( (gaussian(x, n_oversamp*0.5) for x in range(-1*n_oversamp, n_oversamp, 1 ) ), np.float ), mode='same' )
#Finding all points below some threshold:
rms_chisq=np.std(chisqs_conv[chisqs_conv>np.percentile(chisqs_conv,20)])
bool_in_trans=chisqs_conv<(-1*sigma_threshold*rms_chisq)
print("N_trans_points",np.sum(bool_in_trans))
ix_in_trans=[]
#Looping through each "region" where chisq is lower than threshold and finding minimum value:
starts = search_xrange[:-1][np.diff(bool_in_trans.astype(int))>0]
stops = search_xrange[1:][np.diff(bool_in_trans.astype(int))<0]
for ns in range(len(starts)):
ix_bool=(search_xrange>starts[ns])&(search_xrange<stops[ns])
ix_in_trans+=[search_xrange[ix_bool][np.argmin(chisqs[ix_bool])]]
if len(ix_in_trans)==0:
#No extra eclipse found
return None
elif len(ix_in_trans)==1:
#Found single eclipse-like feature.
return {'t0':search_xrange[ix_in_trans[0]],'chisq':chisqs[ix_in_trans[0]],
'dep':outparams[ix_in_trans[0],0],'dur':outparams[ix_in_trans[0],1]}
elif len(ix_in_trans)>1:
#Found multiple eclipse-like features?
peak=ix_in_trans[np.argmax(chisqs[ix_in_trans])]
return {'t0':search_xrange[peak],'chisq':chisqs[peak],
'dep':outparams[peak,0],'dur':outparams[peak,1]}
'''
def PeriodicPlanetSearch(lc, ID, planets, use_binned=False, use_flat=True, binsize=15/1440.0, n_search_loops=5,
rhostar=None, Ms=1.0, Rs=1.0, Teff=5800,
multi_FAP_thresh=0.00125, multi_SNR_thresh=7.0,
plot=False, plot_loc=None, mask_prev_planets=True, **kwargs):
#Searches an LC (ideally masked for the monotransiting planet) for other *periodic* planets.
from transitleastsquares import transitleastsquares
print("Using TLS on ID="+str(ID)+" to search for multi-transiting planets")
#Using bins if we have a tonne of points (eg >1 sector). If not, we can use unbinned data.
use_binned=True if len(lc['flux'])>10000 else use_binned
#Max period is half the total observed time NOT half the distance from t[0] to t[-1]
p_max=0.66*np.sum(np.diff(lc['time'])[np.diff(lc['time'])<0.4])
#np.clip(0.75*(np.nanmax(lc[prefix+'time'])-np.nanmin(lc[prefix+'time'])),10,80)
suffix='_flat' if use_flat else ''
if use_flat:
#Setting the window to fit over as 5*maximum duration
rhostar=1.0 if rhostar==0.0 or rhostar is None else rhostar
durmax = (p_max/(3125*rhostar))**(1/3)
plmask_0 = np.tile(False,len(lc['time']))
if mask_prev_planets:
#Masking each of those transit events we detected during the MonoTransit search
for pl in planets:
plmask_0+=abs(lc['time']-planets[pl]['tcen'])<0.6*planets[pl]['tdur']
lc=tools.lcFlatten(lc,winsize=11*durmax,transit_mask=~plmask_0)
print("after flattening:",np.sum(lc['mask']))
if use_binned:
lc=tools.lcBin(lc,binsize=binsize,use_flat=use_flat)
#print("binned",lc.keys,np.sum(lc['mask']))
suffix='_flat'
#else:
# print(use_binned, 'bin_flux' in lc)
prefix='bin_' if use_binned else ''
if plot:
sns.set_palette("viridis",10)
fig = plt.figure(figsize=(11.69,8.27))
rast=True if np.sum(lc['mask']>12000) else False
#plt.plot(lc['time'][lc['mask']],lc['flux_flat'][lc['mask']]*lc['flux_unit']+(1.0-np.nanmedian(lc['flux_flat'][lc['mask']])*lc['flux_unit']),',k')
#if prefix=='bin_':
# plt.plot(lc[prefix+'time'],lc[prefix+'flux'+suffix]*lc['flux_unit']+(1.0-np.nanmedian(lc[prefix+'flux'+suffix])*lc['flux_unit']),'.k')
plt.subplot(312)
plt.plot(lc['time'][lc['mask']],
lc['flux_flat'][lc['mask']]*lc['flux_unit']+(1.0-np.nanmedian(lc['flux_flat'][lc['mask']])*lc['flux_unit']),
'.k', markersize=0.5,rasterized=rast)
lc=tools.lcBin(lc, binsize=1/48, use_flat=True)
plt.plot(lc['bin_time'],
lc['bin_flux_flat']*lc['flux_unit']+(1.0-np.nanmedian(lc['bin_flux_flat'])*lc['flux_unit']),
'.k', markersize=4.0)
#Looping through, masking planets, until none are found.
#{'01':{'period':500,'period_err':100,'FAP':np.nan,'snr':np.nan,'tcen':tcen,'tdur':tdur,'rp_rs':np.nan}}
if prefix+'mask' in lc:
anommask=lc[prefix+'mask'][:]
else:
anommask=~np.isnan(lc[prefix+'flux'+suffix][:])
plmask=np.tile(False,len(anommask))
t_zero=np.nanmin(lc['time'])
SNR_last_planet=100;init_n_pl=len(planets);n_pl=len(planets);results=[]
while SNR_last_planet>multi_SNR_thresh and n_pl<(n_search_loops+init_n_pl):
if len(planets)>1:
planet_name=str(int(1+np.max([float(key) for key in planets]))).zfill(2)
else:
planet_name='00'
#Making model. Making sure lc is at 1.0 and in relatie flux, not ppt/ppm:
'''
if np.sum(plmask)>0:
#Re-doing flattening with other transits now masked (these might be causing
lc=tools.lcFlatten(lc,winsize=11*durmax,use_binned=use_binned,transit_mask=~plmask)
'''
modx = lc[prefix+'time']-t_zero
mody = lc[prefix+'flux'+suffix] * lc['flux_unit']+(1.0-np.nanmedian(lc[prefix+'flux'+suffix][anommask])*lc['flux_unit'])
#print(n_pl,len(mody),len(anommask),np.sum(anommask),len(plmask),np.sum(plmask))
if np.sum(plmask)>0:
mody[plmask] = mody[anommask][np.random.choice(np.sum(anommask),np.sum(plmask))][:]
#anommask *= tools.CutAnomDiff(mody)
#print(n_pl,"norm_mask:",np.sum(lc['mask']),"anoms:",np.sum(anommask),"pl mask",np.sum(plmask),"total len",len(anommask))
model = transitleastsquares(modx[anommask], mody[anommask])
results+=[model.power(period_min=1.1,period_max=p_max,duration_grid_step=1.0625,Rstar=Rs,Mstar=Ms,
use_threads=1,show_progress_bar=False, n_transits_min=3)]
#print(results[-1])
if 'FAP' in results[-1] and 'snr' in results[-1] and not np.isnan(results[-1]['snr']) and 'transit_times' in results[-1]:
#Defining transit times as those times where the SNR in transit is consistent with expectation (>-3sigma)
snr_per_trans_est=np.sqrt(np.sum(results[-1].snr_per_transit>0))
trans=np.array(results[-1]['transit_times'])[results[-1].snr_per_transit>snr_per_trans_est/2]
else:
trans=[]
phase_nr_trans=(lc[prefix+'time'][~plmask&anommask]-results[-1]['T0']-0.5*results[-1]['period'])%results[-1]['period']-0.5*results[-1]['period']
if 'FAP' in results[-1] and 'snr' in results[-1] and np.sum(abs(phase_nr_trans)<0.5*np.clip(results[-1]['duration'],0.2,2))>3:
plparams = QuickMonoFit(deepcopy(lc),results[-1]['T0'],np.clip(results[-1]['duration'],0.15,3),
init_period=results[-1]['period'],how='periodic',ndurs=4.5,Teff=Teff,Rs=Rs,Ms=Ms,
fluxindex=prefix+'flux'+suffix,mask=~plmask&anommask, **kwargs)
SNR=np.max([plparams['snr'],results[-1].snr])
FAP=results[-1]['FAP']
else:
SNR=0;FAP=0
if (FAP<multi_FAP_thresh) and SNR>multi_SNR_thresh and len(trans)>2:
SNR_last_planet=SNR
planets[planet_name]=plparams
planets[planet_name]['tcen']+=t_zero
planets[planet_name].update({'period':results[-1].period, 'period_err':results[-1].period_uncertainty,
'P_min':results[-1].period,
'snr_tls':results[-1].snr, 'FAP':results[-1].FAP,
'orbit_flag':'periodic',
'xmodel':results[-1].model_lightcurve_time+t_zero,
'ymodel':results[-1].model_lightcurve_model, 'N_trans':len(trans)})
if plot:
plt.subplot(311)
plt.plot([results[-1].period,results[-1].period],[0,1.4*results[-1].snr],'-',
linewidth=4.5,alpha=0.4,c=sns.color_palette()[n_pl-init_n_pl],label=planet_name+'/det_'+str(n_pl))
plt.plot(results[-1].periods,results[-1].power,c=sns.color_palette()[n_pl-init_n_pl])
plt.subplot(312)
plt.plot(results[-1]['model_lightcurve_time']+t_zero,results[-1]['model_lightcurve_model'],'.',
alpha=0.75,c=sns.color_palette()[n_pl-init_n_pl],label=planet_name+'/det='+str(n_pl),
rasterized=True)
'''#Special cases for mono and duos:
if len(trans)==2:
planets[planet_name]['period_err']=np.nan
planets[planet_name]['tcen_2']=trans[1]
planets[planet_name]['orbit_flag']='duo'
elif len(trans)==1:
planets[planet_name]['period']=np.nan
planets[planet_name]['period_err']=np.nan
planets[planet_name]['orbit_flag']='mono'
'''
#Removing planet from future data to be searched
this_pl_masked=(((lc[prefix+'time']-planets[planet_name]['tcen']+0.7*planets[planet_name]['tdur'])%planets[planet_name]['period'])<(1.4*planets[planet_name]['tdur']))
plmask=plmask+this_pl_masked#Masking previously-detected transits
#print(n_pl,results[-1].period,plparams['tdur'],np.sum(this_pl_masked),np.sum(plmask))
#print(n_pl,"pl_mask",np.sum(this_pl_masked)," total:",np.sum(plmask))
elif SNR>multi_SNR_thresh:
# pseudo-fails - we have a high-SNR detection but it's a duo or a mono.
#print(plparams['tcen'],plparams['tdur'],"fails with transits at ",trans,"with durations",plparams['tdur'],"transits. Reserching")
this_pl_masked=np.min(abs((lc[prefix+'time'][np.newaxis,:]-t_zero)-np.array(trans)[:,np.newaxis]),axis=0)<(0.7*plparams['tdur'])
#this_pl_masked=(((lc[prefix+'time']-plparams['tcen']+0.7*plparams['tdur'])%results[-1].period)<(1.4*plparams['tdur']))
#print(n_pl,results[-1].period,plparams['tdur'],np.sum(this_pl_masked))
plmask = plmask+this_pl_masked
SNR_last_planet=SNR
else:
# Fails
#print(n_pl,"detection at ",results[-1].period," with ",len(trans)," transits does not meet SNR ",SNR,"or FAP",results[-1].FAP)
SNR_last_planet=0
n_pl+=1
if plot:
multis=[pl for pl in planets if planets[pl]['orbit_flag']=='periodic']
if len(multis)==0:
plt.subplot(311)
plt.plot(results[0].periods,results[0].power)
else:
for n_m,mult in enumerate(multis):
#print(planets[mult]['depth'], planets[mult]['interpmodel'](0.0), np.nanstd(lc[prefix+'flux'+suffix]),
# np.min(lc[prefix+'flux'+suffix]),np.max(lc[prefix+'flux'+suffix]))
phase=(lc['time']-planets[mult]['tcen']-0.5*planets[mult]['period'])%planets[mult]['period']-0.5*planets[mult]['period']
lc=tools.lcFlatten(lc,winsize=11*durmax,transit_mask=abs(phase)>0.6*planets[mult]['tdur'])
plt.subplot(3, len(multis), len(multis)*2+1+n_m)
#print("subplot ",3, len(multis), len(multis)*2+1+n_m)
bin_phase=tools.bin_lc_segment(np.column_stack((np.sort(phase[abs(phase)<1.2]),
lc['flux'][abs(phase)<1.2][np.argsort(phase[abs(phase)<1.2])],
lc['flux_err'][abs(phase)<1.2][np.argsort(phase[abs(phase)<1.2])])),binsize=planets[mult]['tdur']*0.15)
time_shift=0.4*np.nanstd(bin_phase[:,1])*(lc['time'][abs(phase)<1.2][np.argsort(phase[abs(phase)<1.2])] - \
planets[mult]['tcen'])/planets[mult]['period']
#plt.scatter(phase[abs(phase)<1.2],time_shift+lc['flux'][abs(phase)<1.2],
plt.scatter(phase[abs(phase)<1.2],lc['flux'][abs(phase)<1.2],
s=3,c='k',alpha=0.4)
plt.scatter(bin_phase[:,0],bin_phase[:,1],s=8,
c=sns.color_palette()[n_pl-init_n_pl])
plt.plot(np.sort(phase[abs(phase)<1.2]),
planets[mult]['interpmodel'](phase[abs(phase)<1.2][np.argsort(phase[abs(phase)<1.2])]),
c=sns.color_palette()[n_pl-init_n_pl],alpha=0.4)
#plt.ylim(np.nanmin(bin_phase[:,1])-2*np.nanstd(bin_phase[:,1]),
# np.nanmax(bin_phase[:,1])+2*np.nanstd(bin_phase[:,1]))
plt.gca().set_title(planet_name+'/det='+str(n_pl))
if plot_loc is None:
plot_loc = str(ID).zfill(11)+"_multi_search.pdf"
elif plot_loc[-1]=='/':
plot_loc = plot_loc+str(ID).zfill(11)+"_multi_search.pdf"
plt.subplot(311)
plt.legend(prop={'size': 5})
plt.subplot(312)
plt.plot(results[-1]['model_lightcurve_time']+t_zero,results[-1]['model_lightcurve_model'],
alpha=0.5,c=sns.color_palette()[n_pl-init_n_pl],label=planet_name+'/det_'+str(n_pl),linewidth=4)
plt.legend(prop={'size': 5})
if 'jd_base' in lc:
plt.xlabel("time [BJD-"+str(lc['jd_base'])+"]")
else:
plt.xlabel("time")
plt.subplot(311)
plt.suptitle(str(ID).zfill(11)+"- Multi-transit search")
plt.tight_layout()
plt.savefig(plot_loc, dpi=400)
if plot:
return planets, plot_loc
else:
return planets, None
def GenModelLc(lc,all_pls,mission,Rstar=1.0,rhostar=1.0,Teff=5800,logg=4.43):
#Generates model planet lightcurve from dictionary of all planets
u = tools.getLDs(Teff,logg=logg,FeH=0.0,mission=mission).ravel()
cad=np.nanmedian(np.diff(lc['time']))
light_curves=[]
for pl in all_pls:
if all_pls[pl]['orbit_flag']=='periodic':
#generating periodic planet
# The light curve calculation requires an orbit
orbit = xo.orbits.KeplerianOrbit(r_star=Rstar, rho_star=rhostar,
period=all_pls[pl]['period'], t0=all_pls[pl]['tcen'], b=0.4)
# Compute a limb-darkened light curve using starry
light_curves+=[xo.LimbDarkLightCurve(u).get_light_curve(orbit=orbit, r=np.sqrt(all_pls[pl]['depth']),
t=lc['time'], texp=cad*0.98).eval()]
elif all_pls[pl]['orbit_flag'] in ['mono','duo']:
#generating two monos for duo
per_guess=18226*rhostar*(2*np.sqrt(1-0.4**2)/all_pls[pl]['tdur'])**-3#from circular orbit and b=0.4
orbit = xo.orbits.KeplerianOrbit(r_star=Rstar, rho_star=rhostar,
period=per_guess, t0=all_pls[pl]['tcen'], b=0.4)
light_curve = xo.LimbDarkLightCurve(u).get_light_curve(orbit=orbit, r=np.sqrt(all_pls[pl]['depth']),
t=lc['time'], texp=cad*0.98
).eval()
light_curve[abs(lc['time']-all_pls[pl]['tcen'])>per_guess*0.4]=0.0
if all_pls[pl]['orbit_flag'] == 'duo' and 'tcen_2' in all_pls[pl]:
orbit2 = xo.orbits.KeplerianOrbit(r_star=Rstar, rho_star=rhostar,
period=per_guess, t0=all_pls[pl]['tcen_2'], b=0.4)
light_curve2 = xo.LimbDarkLightCurve(u).get_light_curve(orbit=orbit, r=np.sqrt(all_pls[pl]['depth']),
t=lc['time'], texp=cad*0.98
).eval()
light_curve2[abs(lc['time']-all_pls[pl]['tcen_2'])>per_guess*0.4]=0.0
light_curve=light_curve+light_curve2
light_curves+=[light_curve]
return np.column_stack(light_curves)
def DoEBfit(lc,tc,dur):
# Performs EB fit to primary/secondary.
return None
def dipmodel_step(params,x,npolys):
return np.hstack((np.polyval( params[1:1+npolys[0]], x[x<params[0]]),
np.polyval( params[-npolys[1]:], x[x>=params[0]]) ))
def log_likelihood_step(params,x,y,yerr,npolys):
model=dipmodel_step(params,x,npolys)
sigma2 = yerr ** 2
return -0.5 * np.sum((y - model) ** 2 / sigma2 + np.log(sigma2))
def Step_neg_lnprob(params, x, y, yerr, priors, polyorder,npolys):
#Getting log prior - we'll leave the polynomials to wander and us:
lnprior=0
lnp=log_gaussian(params[0], priors[0], priors[1])
if lnp<-0.5 and lnp>-20:
lnprior+=3*lnp
elif lnp<-20:
lnprior+=1e6*lnp
#Getting log likelihood:
llk=log_likelihood_step(params,x,y,yerr,npolys)
return -1*(lnprior + llk)
def Poly_neg_lnprob(params,x,y,yerr,priors,polyorder):
return -1*Poly_lnprob(params, x, y, yerr, priors, polyorder=polyorder)
def Poly_lnprob(params, x, y, yerr, priors, polyorder=2):
# Trivial improper prior: uniform in the log.
lnprior=0
for p in np.arange(polyorder+1):
#Simple log gaussian prior here:
lnp=log_gaussian(params[p], 0.0, priors[p],weight=1)
if lnp<-0.5 and lnp>-20:
lnprior+=3*lnp
elif lnp<-20:
lnprior+=1e6*lnp
llk = log_likelihood_poly(params, x, y, yerr)
return lnprior + llk
def log_likelihood_poly(params, x, y, yerr):
model=np.polyval(params,x)
sigma2 = yerr ** 2
return -0.5 * np.sum((y - model) ** 2 / sigma2 + np.log(sigma2))
def Sinusoid_neg_lnprob(params, x, y, yerr, priors, polyorder):
return -1*Sinusoid_lnprob(params, x, y, yerr, priors, polyorder=polyorder)
def Sinusoid_lnprob(params, x, y, yerr, priors, polyorder=2):
# Trivial improper prior: uniform in the log.
lnprior=0
for p in np.arange(3):
#Simple log gaussian prior here:
lnp=log_gaussian(params[p], priors[p,0], priors[p,1],weight=1)
if lnp<-0.5 and lnp>-20:
lnprior+=3*lnp
elif lnp<-20:
lnprior+=1e6*lnp
llk = log_likelihood_sinusoid(params, x, y, yerr)
return lnprior + llk
def log_likelihood_sinusoid(params, x, y, yerr):
model=dipmodel_sinusoid(params,x)
sigma2 = yerr ** 2
return -0.5 * np.sum((y - model) ** 2 / sigma2 + np.log(sigma2))
def dipmodel_sinusoid(params,x):
#Sinusoidal model aligned with dip.
# tcen, log(dur), log(dep), [n x polynomials]
newt=(x-params[0])/(4.5*np.exp(params[1]))*2*np.pi-np.pi*0.5
return np.polyval(params[3:],x) + np.exp(params[2])*(np.sin(newt))
def Gaussian_neg_lnprob(params, x, y, yerr, priors, order=3):
return -1*Gaussian_lnprob(params, x, y, yerr, priors, order=order)
def Gaussian_lnprob(params, x, y, yerr, priors, order=3):
# Trivial improper prior: uniform in the log.
lnprior=0
for p in np.arange(3):
#Simple log gaussian prior here:
lnp=log_gaussian(params[p], priors[p,0], priors[p,1],weight=1)
if lnp<-0.5 and lnp>-20:
lnprior+=3*lnp
elif lnp<-20:
lnprior+=1e6*lnp
llk = log_likelihood_gaussian_dip(params, x, y, yerr)
return lnprior + llk
def log_gaussian(x, mu, sig, weight=0.1):
return -1*weight*np.power(x - mu, 2.) / (2 * np.power(sig, 2.))
def log_likelihood_gaussian_dip(params, x, y, yerr):
model=dipmodel_gaussian(params,x)
sigma2 = yerr ** 2
return -0.5 * np.sum((y - model) ** 2 / sigma2)
def dipmodel_gaussian(params,x):
dip=1.0+np.exp(params[0])*np.exp(-1*np.power(x - params[2], 2.) / (2 * np.power((0.075*np.exp(params[1])), 2.)))
mod = np.polyval(params[3:],x)*dip
return mod
def centroid_neg_lnprob(params, t, x, y, xerr, yerr, priors, interpmodel, order=3):
return -1*centroid_lnprob(params, t, x, y, xerr, yerr, priors, interpmodel, order=order)
def centroid_lnprob(params, t, x, y, xerr, yerr, priors, interpmodel, order=3):
# Trivial improper prior: uniform in the log.
lnprior=0
for p in np.arange(2):
#Simple log gaussian prior here:
gauss=log_gaussian(params[p], priors[p,0], priors[p,1],weight=1)
#gauss=0.0 if gauss>-0.5 else gauss
lnprior+=gauss
llk = log_likelihood_centroid(params, t, x, y, xerr,yerr, interpmodel, order)
return lnprior + llk
def log_likelihood_centroid(params, t, x, y, xerr, yerr, interpmodel, order):
xmodel,ymodel=dipmodel_centroid(params,t,interpmodel,order)
xsigma2 = xerr ** 2
xllk=-0.5 * np.sum((x - xmodel) ** 2 / xsigma2 + np.log(xsigma2))
ysigma2 = yerr ** 2
yllk=-0.5 * np.sum((y - ymodel) ** 2 / ysigma2 + np.log(ysigma2))
return xllk+yllk
def dipmodel_centroid(params,t,interpmodel,order):
#params=xdep, ydep, xpolyvals, ypolyvals
xdip = params[0]*interpmodel(t)
ydip = params[1]*interpmodel(t)
xmod = np.polyval(params[2:2+(order+1)],t)+xdip
ymod = np.polyval(params[2+(order+1):],t)+ydip
return xmod,ymod
def AsteroidCheck(lc,monoparams,ID,order=3,dur_region=3.5,
plot=False,plot_loc=None, return_fit_lcs=False, remove_earthshine=True, **kwargs):
# Checking lightcure for background flux boost during transit due to presence of bright asteroid
# Performing two model fits
# - one with a gaussian "dip" roughly corresponding to the transit combined with a polynomial trend for out-of-transit
# - one with only a polynomial trend
# These are then compared, and the BIC returned to judge model fit
#Need the region around the model to be at least 1.5d, otherwise the polynomial will absorb it:
dur_region=np.clip(dur_region,2/monoparams['tdur'],5/monoparams['tdur'])
nearish_region=np.max([4.5,monoparams['tdur']*dur_region]) #For the background fit, we'll take a region 9d long
nearishTrans=(abs(lc['time']-monoparams['tcen'])<nearish_region)&lc['mask']
cad=np.nanmedian(np.diff(lc['time'][nearishTrans]))
if 'bg_flux' in lc and np.sum(np.isfinite(lc['bg_flux'][nearishTrans]))>0:
# Fits two models - one with a 2D polynomial spline and the interpolated "dip" model from the fit, and one with only a spline
#If there's a big gap, we'll remove the far side of that
if np.max(np.diff(lc['time'][nearishTrans]))>0.4:
jump_n=np.argmax(np.diff(lc['time'][nearishTrans]))
jump_time=0.5*(lc['time'][nearishTrans][jump_n]+lc['time'][nearishTrans][jump_n+1])
if jump_time < monoparams['tcen']:
nearishTrans=(lc['time']>jump_time)&((lc['time']-monoparams['tcen'])<nearish_region)&lc['mask']
elif jump_time > monoparams['tcen']:
nearishTrans=((lc['time']-monoparams['tcen'])>(-1*nearish_region))&(lc['time']<jump_time)&lc['mask']
nearishTrans[nearishTrans]=np.isfinite(lc['bg_flux'][nearishTrans])
bg_lc=np.column_stack((lc['time'][nearishTrans],
lc['bg_flux'][nearishTrans],
np.tile(np.nanstd(lc['bg_flux'][nearishTrans]),np.sum(nearishTrans))
))
bg_lc[:,0]-=monoparams['tcen']
nearTrans=(abs(bg_lc[:,0])<monoparams['tdur']*dur_region)
sigma2 = bg_lc[:,2]**2
outTransit=(abs(bg_lc[:,0])>monoparams['tdur']*0.75)
inTransit=(abs(bg_lc[:,0])<monoparams['tdur']*0.35)
bg_lc[:,1:]/=np.nanmedian(bg_lc[outTransit,1])
if remove_earthshine and lc['cadence'][np.argmin(abs(lc['time']-monoparams['tcen']))].lower()[0]=='t':
#Removing Earthshine with a filter on frequencies of 1/0.5/0.33 days (for TESS lightcurves only):
newt=np.arange(bg_lc[0,0],bg_lc[-1,0],cad)
#Preparing the signal timeseries:
init_poly=np.polyfit(bg_lc[outTransit,0],bg_lc[outTransit,1],order) #do polynomial fit to make time series flat
news = (bg_lc[:,1]-np.polyval(init_poly,bg_lc[:,0]))[np.argmin(abs(bg_lc[:,0][:,np.newaxis]-newt[np.newaxis,:]),axis=0)] #Making sure the timeseries is uniform
# Doing an FFT fit for the known frequencies associated with Earth rotation:
n=news.size
fr=np.fft.fftfreq(n,cad) # a nice helper function to get the frequencies
fou=np.fft.fft(news)
freqs=[1,2,3] #Frequencies to filter - all multiples of 1
#make up a narrow bandpass with a Gaussian
df=0.066
gpl= np.sum([np.exp(- ((fr-f)/(2*df))**2) for f in freqs],axis=0) # pos. frequencies
gmn= np.sum([np.exp(- ((fr+f)/(2*df))**2) for f in freqs],axis=0) # neg. frequencies
g=gpl+gmn
#ifft
s2=np.fft.ifft(fou*g) #filtered spectrum = spectrum * bandpass
fft_model = np.real(s2)[np.argmin(abs(newt[:,np.newaxis] - bg_lc[:,0][np.newaxis,:]),axis=0)]
#fft_model += np.polyval(init_poly, bg_lc[nearTrans,0]
#print(len(fft_model),len(bg_lc[:,0]))
#Checking model is actually a good fit around transit by doing 1D poly + FFT model vs 2D poly:
bg_fft_model = np.polyval(np.polyfit(bg_lc[nearTrans&outTransit,0],
bg_lc[nearTrans&outTransit,1] - fft_model[nearTrans&outTransit],0),
bg_lc[:,0]) + \
fft_model
llk_bg_model = -0.5 * np.sum((bg_lc[nearTrans&outTransit,1] - bg_fft_model[nearTrans&outTransit]) ** 2 / \
sigma2[nearTrans&outTransit])
bg_model = np.polyval(np.polyfit(bg_lc[nearTrans&outTransit,0],bg_lc[nearTrans&outTransit,1],2),
bg_lc[:,0])
llk_polyfit = -0.5 * np.sum((bg_lc[nearTrans&outTransit,1] - bg_model[nearTrans&outTransit]) ** 2 / \
sigma2[nearTrans&outTransit])
#print("polyfit llk:", llk_polyfit, "fft llk:", llk_bg_model)
if llk_polyfit > llk_bg_model-1:
print("Earthshine model not useful in this case - polynomial model is better by", llk_polyfit - llk_bg_model)
fft_model=np.tile(0,len(bg_lc[:,0]))
else:
fft_model=np.tile(0,len(bg_lc[:,0]))
outTransit*=nearTrans
#print(bg_lc)
log_height_guess=np.log(2*np.clip((np.nanmedian(bg_lc[inTransit,1])-np.nanmedian(bg_lc[nearTrans&outTransit,1])),
0.00001,1000) )
priors= np.column_stack(([log_height_guess,np.log(np.clip(1.4*monoparams['tdur'],6*cad,3.0)),0.0],
[3.0,0.25,0.75*monoparams['tdur']]))
best_nodip_res={'fun':1e30,'bic':1e9,'llk':-1e20}
best_dip_res={'fun':1e30,'bic':1e9,'llk':-1e20}
methods=['L-BFGS-B', 'Nelder-Mead', 'Powell']
n=0
while n<21:
#Running the minimization 7 times with different initial params to make sure we get the best fit
#non-dip is simple poly fit. Including 10% cut in points to add some randomness over n samples
rand_choice=np.random.random(len(bg_lc))<0.9
nodip_res={'x':np.polyfit(bg_lc[nearTrans&rand_choice,0],
bg_lc[nearTrans&rand_choice,1] - fft_model[nearTrans&rand_choice],
order)}
nodip_model = fft_model[nearTrans] + np.polyval(nodip_res['x'],bg_lc[nearTrans,0])
nodip_res['llk'] = log_likelihood_gaussian_dip(np.hstack((-30,-30,0,nodip_res['x'])),
bg_lc[nearTrans,0], bg_lc[nearTrans,1], bg_lc[nearTrans,2])
#nodip_res['llk'] = -0.5 * np.sum((bg_lc[nearTrans,1] - nodip_model)**2 / sigma2[nearTrans])
nodip_res['prior']=0
#np.sum((y - model) ** 2 / sigma2 + np.log(sigma2))
#BIC = 2*(neg_log_likelihood-log_prior) + log(n_points)*n_params
nodip_res['bic'] = np.log(np.sum(nearTrans))*len(nodip_res['x']) - 2 * nodip_res['llk']
#print('no dip:',nodip_res['bic'])
if nodip_res['bic']<best_nodip_res['bic']:
best_nodip_res=nodip_res
#log10(height), log10(dur), tcen
dip_args= np.hstack(([np.random.normal(log_height_guess,0.25)-(n%4)/2.0,
np.log10(1.5*monoparams['tdur'])+abs(np.random.normal(0.0,0.5)),
np.random.normal(0.0,0.5*monoparams['tdur'])],
np.polyfit(bg_lc[outTransit&rand_choice,0],
bg_lc[outTransit&rand_choice,1] - fft_model[outTransit&rand_choice],
order)))
dip_res=optim.minimize(Gaussian_neg_lnprob, dip_args,
args=(bg_lc[nearTrans,0],
bg_lc[nearTrans,1]-fft_model[nearTrans],
bg_lc[nearTrans,2],
priors,
order),method=methods[n%3])
dip_res['llk']=log_likelihood_gaussian_dip(dip_res['x'],
bg_lc[nearTrans,0],
bg_lc[nearTrans,1]-fft_model[nearTrans],
bg_lc[nearTrans,2])
dip_res['prior']=dip_res['fun']-dip_res['llk']
dip_res['bic']= np.log(np.sum(nearTrans))*len(dip_args) - 2 * dip_res['llk']
#print('dip:',dip_args,dip_res,dip_bic)
if dip_res['bic']<best_dip_res['bic']:
best_dip_res=dip_res
#Increasing the polynomial order every odd number if we haven't yet found a good solution:
if n>7 and n%2==1:
order+=1
#Need to expand on priors to include new polynomial orders in this case:
#print(n,"dip:",dip_res['fun'],dip_res['bic'],dip_args,"nodip:",nodip_res['fun'],nodip_res['bic'],"order:",order)
if n>=7 and (best_dip_res['llk']>-1e20) and (best_nodip_res['llk']>-1e20):
break
n+=1
fit_dict={'asteroid_dip_'+col:best_dip_res[col] for col in best_dip_res}
fit_dict.update({'asteroid_nodip_'+col:best_nodip_res[col] for col in best_nodip_res})
# Also doing correlation coefficient between bg flux and real flux during transit:
# In the case that the BG causes the lc to dip, we should find a negative correlation coefficient & low p-value:
from scipy.stats import pearsonr
fluxkey='rawflux' if 'rawflux' in lc else 'flux'
just_oot=lc['mask'] * \
(abs(lc['time']-monoparams['tcen'])>monoparams['tdur']*0.75) * \
(abs(lc['time']-monoparams['tcen'])<monoparams['tdur']*2)
inTransit=lc['mask'] * (abs(lc['time']-monoparams['tcen'])<monoparams['tdur']*0.625)
#Removing a just-out-of-transit polynomial fit to both sets of in-transit data, so we should only have the dip
bg_poly=np.polyval(np.polyfit(lc['time'][just_oot],
lc['bg_flux'][just_oot], 1), lc['time'][inTransit])
lc_poly=np.polyval(np.polyfit(lc['time'][just_oot],
lc[fluxkey][just_oot], 1), lc['time'][inTransit])
R=pearsonr(lc['bg_flux'][inTransit] - bg_poly, lc[fluxkey][inTransit]-lc_poly)
fit_dict['R_bg_flux_corr']=R[0]
fit_dict['P_bg_flux_corr']=R[1]
if (best_dip_res['llk']>-1e20) and (best_nodip_res['llk']>-1e20):
fit_dict['asteroid_DeltaBIC']=best_dip_res['bic']-best_nodip_res['bic'] # [prefer dip] < 0 < [prefer no dip]
fit_dict['asteroid_log_llk_ratio']=(best_dip_res['llk'])-(best_nodip_res['llk'])
fit_dict['asteroid_ampl']=np.exp(best_dip_res['x'][0])
fit_dict['asteroid_dur']=np.exp(best_dip_res['x'][1])
best_model_resids = bg_lc[nearTrans&outTransit,1] - \
(fft_model[nearTrans&outTransit] + dipmodel_gaussian(best_dip_res['x'],bg_lc[nearTrans&outTransit,0]))
fit_dict['asteroid_bg_stdw']=np.nanmedian(abs(np.diff(best_model_resids)))
fit_dict['asteroid_bg_stdr']=np.nanstd(best_model_resids)
fit_dict['asteroid_snrw'] = fit_dict['asteroid_ampl'] / \
( fit_dict['asteroid_bg_stdw'] / np.sqrt(fit_dict['asteroid_dur']/cad) )
fit_dict['asteroid_snrr'] = fit_dict['asteroid_ampl'] / \
( fit_dict['asteroid_bg_stdr'] / np.sqrt(fit_dict['asteroid_dur']/cad) )
#print(ID,"| Ran Asteroid fitting "+str(n)+" times, and DeltaBIC="+str(DeltaBIC),
# "| params:",best_dip_res['x'],best_nodip_res['x'])
#else:
# print(lc['bg_flux'][nearTrans]-fft_model[nearTrans])
if plot:
if plot_loc is not None and type(plot_loc)!=str:
ax = plot_loc
else:
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111)
if plot_loc is None:
plot_loc=str(ID)+"_asteroid_check.pdf"
elif plot_loc[-1]=='/':
plot_loc=plot_loc+str(ID)+"_asteroid_check.pdf"
#print("Plotting asteroid",ID, np.sum(bg_lc[nearTrans,1]/bg_lc[nearTrans,1]==1.0),
# len(bg_lc[nearTrans,1]),plot_loc,best_nodip_res)
if plot:
#### PLOTTING ###
ax.scatter(bg_lc[nearTrans,0],bg_lc[nearTrans,1],s=2,alpha=0.75,rasterized=True,zorder=1)
ax.plot(bg_lc[nearTrans,0],np.nanmedian(bg_lc[nearTrans,1])+fft_model[nearTrans],':k',
alpha=0.2,linewidth=4,label='ft model of earthshine',zorder=2)
ax.plot([-0.5*monoparams['tdur'],-0.5*monoparams['tdur']],[-2.0,2.0],':k',alpha=0.4,rasterized=True)
ax.plot([0.0,0.0],[-2.0,2.0],'--k',linewidth=3,alpha=0.6,rasterized=True)
ax.plot([0.5*monoparams['tdur'],0.5*monoparams['tdur']],[-2.0,2.0],':k',alpha=0.4,rasterized=True)
ax.set_ylabel("Relative background flux")
if (best_nodip_res['llk']>-1e20):
ax.plot(bg_lc[nearTrans,0],fft_model[nearTrans]+
np.polyval(best_nodip_res['x'],bg_lc[nearTrans,0]),c='C3',linewidth=2,
label='pure trend',alpha=0.6,rasterized=True,zorder=2)
if (best_dip_res['llk']>-1e20):
ax.plot(bg_lc[nearTrans,0],
fft_model[nearTrans]+dipmodel_gaussian(best_dip_res.x,bg_lc[nearTrans,0]),c='C4',linewidth=2.5,
label='trend+asteroid',alpha=0.8,rasterized=True,zorder=3)
try:
ax.set_ylim(np.nanmin(fft_model[nearTrans]+bg_lc[nearTrans,1]),
np.nanmax(fft_model[nearTrans]+bg_lc[nearTrans,1]))
except:
b=0
#plt.ylim(np.percentile(bg_lc[inTransit,1],[0.2,99.8]))
ax.legend(prop={'size': 5})
if (best_dip_res['llk']>-1e20) and (best_nodip_res['llk']>-1e20):
ax.set_title(str(ID)+" Asteroid. - "+["pass","fail"][int(fit_dict['asteroid_DeltaBIC']<-10)])
else:
ax.set_title(str(ID)+" Asteroid. No fit ???")
if type(plot_loc)==str:
fig.savefig(plot_loc, dpi=400)
if return_fit_lcs:
return fit_dict, ax, np.column_stack((bg_lc[:,0],bg_lc[:,1],bg_lc[:,2],fft_model,
np.polyval(best_nodip_res['x'],bg_lc[:,0]),
dipmodel_gaussian(best_dip_res.x,bg_lc[:,0])))
else:
return fit_dict, ax
elif (best_dip_res['llk']>-1e20) and (best_nodip_res['llk']>-1e20):
if return_fit_lcs:
return fit_dict, None, None
else:
return fit_dict, None
else:
if return_fit_lcs:
return None, None, None
else:
return None, None
else:
if return_fit_lcs:
return None, None, None
else:
return None, None
def VariabilityCheck(lc, params, ID, modeltype='all',plot=False,plot_loc=None,ndurs=2.4,
polyorder=1, return_fit_lcs=False, **kwargs):
# Checking lightcure for variability flux boost during transit due to presence of bright asteroid
# Performs two potential models:
# - 1) 'sin': Variability sinusoid+polynomial model
# - 2) 'step': Discontinuity Model (two polynomials and a gap between them)
# the BIC returned to judge against the transit model fit
#assuming QuickMonoFit has been run, we can replicate the exact x/y/yerr used there:
x = params['monofit_x']-params['tcen']
round_trans=(abs(x)<ndurs*np.clip(params['tdur'],0.1,5.0))
x = x[round_trans]
y = params['monofit_y'][round_trans]
#mask = lc['mask'][np.isin(lc['time'],params['monofit_x'][abs(params['monofit_x']-params['tcen'])<ndurs*params['tdur']])]
#assert len(mask)==len(x)
#print(params['tdur'],np.sum(abs(x)>0.6*params['tdur']))
yerr = params['monofit_yerr'][round_trans]
y_trans = params['monofit_ymodel'][round_trans]
sigma2 = yerr ** 2
outTransit=abs(x)>0.6*params['tdur']
yspan=np.diff(np.percentile(y,[5,95]))[0]
priors={}
best_mod_res={}
mods=[]
if modeltype=='sin' or modeltype=='both' or modeltype=='all':
priors['sin']= np.column_stack(([0.0,np.log(params['tdur']),np.log(yspan)],
[0.5*params['tdur'],3.0,4.0]))
best_mod_res['sin']={'fun':1e30,'bic':1e9,'sin_llk':-1e9}
mods+=['sin']
if modeltype=='step' or modeltype=='both' or modeltype=='all':
priors['step']= [0.0,0.5*params['tdur']]
best_mod_res['step']={'fun':1e30,'bic':1e9,'sin_llk':-1e9,'npolys':[]}
mods+=['step']
if modeltype=='poly' or modeltype=='both' or modeltype=='all':
best_mod_res['poly']={'fun':1e30,'bic':1e9,'sin_llk':-1e9,'npolys':[]}
mods+=['poly']
if modeltype!='none' and len(x)>polyorder+1 and len(y)>polyorder+1:
methods=['L-BFGS-B','Nelder-Mead','Powell']
n=0
while n<21:
#print(np.sum(outTransit))
#Running the minimization 7 times with different initial params to make sure we get the best fit
if np.sum(outTransit)>20:
rand_choice=np.random.random(len(x))<0.95
else:
rand_choice=np.tile(True,len(x))
#non-dip is simple poly fit. Including 10% cut in points to add some randomness over n samples
#log10(height), log10(dur), tcen
if modeltype=='sin' or modeltype=='both' or modeltype=='all':
mod_args= np.hstack(([np.random.normal(0.0,0.5*params['tdur']),
np.log(params['tdur'])+np.random.normal(0.0,0.5)],
np.log(params['depth'])+np.random.normal(0.0,0.5),
np.polyfit(x[outTransit&rand_choice],
y[outTransit&rand_choice],polyorder)
))
mod_res_sin=optim.minimize(Sinusoid_neg_lnprob, mod_args,
args=(x[np.argsort(x)],y[np.argsort(x)],yerr[np.argsort(x)],priors['sin'],polyorder),
method=methods[n%3])
mod_res_sin['llk']=log_likelihood_sinusoid(mod_res_sin['x'], x[np.argsort(x)],
y[np.argsort(x)],yerr[np.argsort(x)])
mod_res_sin['bic']=np.log(len(x))*len(mod_res_sin['x']) - 2 * mod_res_sin['llk']
#print('dip:',dip_args,dip_res,dip_bic)
if mod_res_sin['bic']<best_mod_res['sin']['bic']:
best_mod_res['sin']=mod_res_sin
if modeltype=='step' or modeltype=='both' or modeltype=='all':
points_either_side=False
#Making sure we start off with a position that has points both before and afer the step:
step_guess=np.random.normal(0.0,0.5*params['tdur'])
if np.sum(x<step_guess)==0:
step_guess=x[4]
elif np.sum(x>step_guess)==0:
step_guess=x[-5]
#Making one side randomly have polyorder 1, and the other 3->6
side=np.random.random()<0.5
npolys=[np.clip(polyorder+1-int(side)*20,1,6),np.clip(polyorder+1-int(side)*20,1,6)]
mod_args= np.hstack((step_guess,
np.polyfit(x[(x<step_guess)&rand_choice],
y[(x<step_guess)&rand_choice],npolys[0]),
np.polyfit(x[(x>=step_guess)&rand_choice],
y[(x>=step_guess)&rand_choice],npolys[1])
))
#print(x[np.argsort(x)], y[np.argsort(x)], yerr[np.argsort(x)],
# mod_args, dipmodel_step(mod_args,x[np.argsort(x)],npolys))
mod_res_step=optim.minimize(Step_neg_lnprob, mod_args,
args=(x[np.argsort(x)],y[np.argsort(x)],yerr[np.argsort(x)],priors['step'],
np.clip(polyorder+1,1,5),npolys),
method=methods[n%3])
mod_res_step['llk']=log_likelihood_step(mod_res_step['x'],x[np.argsort(x)],y[np.argsort(x)],
yerr[np.argsort(x)],npolys)
mod_res_step['bic']=np.log(len(x))*len(mod_res_step['x']) - 2 * mod_res_step['llk']
#(2*mod_res_step.fun + np.log(len(x))*len(mod_res_step.x))
#print('dip:',dip_args,dip_res,dip_bic)
if mod_res_step['bic']<best_mod_res['step']['bic']:
best_mod_res['step']=mod_res_step
best_mod_res['step']['npolys']=npolys
if modeltype=='poly' or modeltype=='all':
priors['poly'] = 10.0 ** -np.arange(polyorder+1)[::-1]
mod_res_poly=optim.minimize(Poly_neg_lnprob, np.polyfit(x,y,polyorder),
args=(x,y,yerr,priors['poly'],polyorder),
method=methods[n%3])
mod_res_poly['llk']=log_likelihood_poly(mod_res_poly['x'],x,y,yerr)
mod_res_poly['bic']=np.log(len(x))*len(mod_res_poly['x']) - 2 * mod_res_poly['llk']
#=(2*mod_res_poly.fun + np.log(len(x))*len(mod_res_poly.x))
#print('dip:',dip_args,dip_res,dip_bic)
if mod_res_poly['bic']<best_mod_res['poly']['bic']:
best_mod_res['poly']=mod_res_poly
best_mod_res['poly']['npolys']=npolys
#Increasing the polynomial order every odd number if we haven't yet found a good solution:
if n>7 and n%2==1:
polyorder+=1
#Need to expand on priors to include new polynomial orders in this case:
#print(n,"dip:",dip_res['fun'],dip_res['bic'],dip_args,"nodip:",nodip_res['fun'],nodip_res['bic'],"order:",order)
#
if n>=7 and np.all([best_mod_res[mod]['fun']<1e9 for mod in mods]):
break
n+=1
best_mod_res['trans']={}
best_mod_res['trans']['llk']= -0.5 * np.sum((y - y_trans)**2 / sigma2 + np.log(sigma2))
best_mod_res['trans']['bic']= np.log(len(x))*6 - 2 * best_mod_res['trans']['llk']
if 'sin' in best_mod_res and best_mod_res['sin']['bic']<1e9:
best_mod_res['sin']['llk_ratio']=log_likelihood_sinusoid(best_mod_res['sin']['x'], x, y, yerr) - best_mod_res['trans']['llk']
best_mod_res['sin']['DeltaBIC']=(8-len(best_mod_res['sin']['x'])) - (best_mod_res['trans']['llk'] - best_mod_res['sin']['llk'])
elif 'sin' in best_mod_res:
best_mod_res['sin']['DeltaBIC']=np.nan;best_mod_res['sin']['llk_ratio']=np.nan
if 'step' in best_mod_res and best_mod_res['step']['bic']<1e9:
best_mod_res['step']['llk_ratio']=log_likelihood_step(best_mod_res['step']['x'], x, y, yerr,best_mod_res['step']['npolys']) - best_mod_res['trans']['llk']
best_mod_res['step']['DeltaBIC']=(8-len(best_mod_res['step']['x'])) - (best_mod_res['trans']['llk'] - best_mod_res['step']['llk'])
elif 'step' in best_mod_res:
best_mod_res['step']['DeltaBIC']=np.nan;best_mod_res['step']['llk_ratio']=np.nan
if 'poly' in best_mod_res and best_mod_res['poly']['bic']<1e9:
best_mod_res['poly']['llk_ratio']=log_likelihood_poly(best_mod_res['poly']['x'], x, y, yerr) - best_mod_res['trans']['llk']
best_mod_res['poly']['DeltaBIC']=(8-len(best_mod_res['poly']['x'])) - (best_mod_res['trans']['llk'] - best_mod_res['poly']['llk'])
elif 'poly' in best_mod_res:
best_mod_res['poly']['DeltaBIC']=np.nan;best_mod_res['poly']['llk_ratio']=np.nan
else:
best_mod_res={}
#print("Variability models:",best_mod_res)
#print("sin:", best_mod_res['sin_llk'], "trans:", best_mod_res['trans_llk'], "llk_ratio:", best_mod_res['llk_ratio'])
#print("plot:",plot,kwargs)
if plot:
#### PLOTTING ###
if plot_loc is not None and type(plot_loc)!=str:
ax = plot_loc
else:
fig = plt.figure(figsize=(8,4))
ax = fig.add_subplot(111)
if plot_loc is None:
plot_loc=str(ID)+"_variability_check.pdf"
elif plot_loc[-1]=='/':
plot_loc=plot_loc+str(ID)+"_variability_check.pdf"
markers, caps, bars = ax.errorbar(x,y,yerr=yerr,
fmt='.k',ecolor='#AAAAAA',markersize=3.5,alpha=0.6,rasterized=True)
[bar.set_alpha(0.2) for bar in bars]
[cap.set_alpha(0.2) for cap in caps]
ax.plot([-0.5*params['tdur'],-0.5*params['tdur']],[-2.0,2.0],':k',alpha=0.6,zorder=2,rasterized=True)
ax.plot([0.0,0.0],[-2.0,2.0],'--k',linewidth=3,alpha=0.8,zorder=2,rasterized=True)
ax.plot([0.5*params['tdur'],0.5*params['tdur']],[-2.0,2.0],':k',alpha=0.6,zorder=2,rasterized=True)
if lc['flux_unit']==0.001:
ax.set_ylabel("Relative flux [ppm]")
elif lc['flux_unit']==1:
ax.set_ylabel("Relative flux [ppm]")
if 'sin' in best_mod_res and best_mod_res['sin']['fun']<1e30:
ax.plot(x[np.argsort(x)],dipmodel_sinusoid(best_mod_res['sin']['x'],x[np.argsort(x)]),c='C3',alpha=0.5,
label='sinusoid',linewidth=2.25,zorder=10,rasterized=True)
if 'step' in best_mod_res and best_mod_res['step']['fun']<1e30:
ax.plot(x[np.argsort(x)],dipmodel_step(best_mod_res['step']['x'],x[np.argsort(x)],best_mod_res['step']['npolys']),
c='C4',alpha=0.5,label='step model',linewidth=2.25,zorder=10,rasterized=True)
if 'poly' in best_mod_res and best_mod_res['poly']['fun']<1e30:
ax.plot(x, np.polyval(best_mod_res['poly']['x'],x),
c='C2',alpha=0.5,label='polynomial model',linewidth=2.25,zorder=2,rasterized=True)
ax.plot(x, y_trans, '-', c='C1', alpha=0.75, label='transit model', linewidth=2.25, zorder=3, rasterized=True)
try:
ax.set_ylim(np.nanmin(y),np.nanmax(y))
except:
b=0
#plt.ylim(np.percentile(bg_lc[inTransit,1],[0.2,99.8]))
ax.legend(prop={'size': 5})
if len(best_mod_res.keys())>0 and np.all([best_mod_res[mod]['fun']<1e30 for mod in mods]):
ax.set_title(str(ID)+" ' - "+["pass","fail"][int(np.any([best_mod_res[mod]['llk_ratio']>0 for mod in mods]))])
else:
ax.set_title(str(ID)+" Variability. Bad fits ???")
if plot_loc is not None and type(plot_loc)==str:
fig.savefig(plot_loc, dpi=400)
print("Saved varble plot to",plot_loc)
if return_fit_lcs:
return best_mod_res, plot_loc, np.column_stack((x[np.argsort(x)],y,y_trans,
dipmodel_sinusoid(best_mod_res['sin']['x'],x[np.argsort(x)]),
dipmodel_step(best_mod_res['step']['x'],x[np.argsort(x)],best_mod_res['step']['npolys']),
np.polyval(best_mod_res['poly']['x'],x)))
else:
return best_mod_res, plot_loc
else:
if return_fit_lcs:
return best_mod_res, ax, np.column_stack((x[np.argsort(x)],y,y_trans,
dipmodel_sinusoid(best_mod_res['sin']['x'],x[np.argsort(x)]),
dipmodel_step(best_mod_res['step']['x'],x[np.argsort(x)],best_mod_res['step']['npolys']),
np.polyval(best_mod_res['poly']['x'],x)))
else:
return best_mod_res, ax
elif np.all([best_mod_res[mod]['fun']<1e30 for mod in mods]):
return best_mod_res, None, None
else:
return None, None, None
def CheckInstrumentalNoise(lc,monodic,jd_base=None, **kwargs):
'''# Using the processed "number of TCEs per cadence" array, we try to use this as a proxy for Instrumental noise in TESS
# Here we simply use the detected SNR over the instrumental noise SNR as a proxy
INPUTS:
- lc
- monotransit dic
- jd_base (assumed to be that of TESS)'''
import io
import gzip
f=gzip.open(MonoData_tablepath+'/tces_per_cadence.txt.gz','rb')
tces_per_cadence=np.loadtxt(io.BytesIO(f.read()))
if 'jd_base' in lc and jd_base is None:
jd_base=lc['jd_base']
elif jd_base is None:
jd_base=2457000
tces_per_cadence[:,0]-=(jd_base-2457000)
#print(jd_base,tces_per_cadence[0,0],tces_per_cadence[-1,0], np.nanmin(lc['time']),np.nanmax(lc['time']))
tces_per_cadence=tces_per_cadence[(tces_per_cadence[:,0]>np.nanmin(lc['time']))*(tces_per_cadence[:,0]<np.nanmax(lc['time']))]
inst_snr=1+np.average(tces_per_cadence[abs(tces_per_cadence[:,0]-monodic['tcen'])<monodic['tdur'],1])
return monodic['snr']/np.clip(inst_snr,1.0,1000)
def GapCull(t0,t,dat,std_thresh=10,boolean=None,time_jump_thresh=0.4):
#Removes data before/after gaps and jumps in t & y
#If there's a big gap or a big jump, we'll remove the far side of that
if boolean is None:
boolean=np.tile(True,len(t))
if np.max(np.diff(t[boolean]))>time_jump_thresh:
jump_n=np.argmax(np.diff(t[boolean]))
jump_time=0.5*(t[boolean][jump_n]+t[boolean][jump_n+1])
#print("TIME JUMP IN CENTROID AT",jump_time)
if jump_time < t0:
boolean*=(t>jump_time)
elif jump_time > t0:
boolean*=(t<jump_time)
#data must be iterable list
for arr in dat:
noise=np.nanmedian(abs(np.diff(arr[boolean])))
#5-sigma x centroid jump - need to cut
if np.sum(boolean)>0 and np.nanmax(abs(np.diff(arr[boolean])))>std_thresh*noise:
jump_n=np.argmax(np.diff(arr[boolean]))
jump_time=0.5*(t[boolean][jump_n]+t[boolean][jump_n+1])
#print("X JUMP IN CENTROID AT",jump_time)
if jump_time < t0:
boolean*=(t>jump_time)
elif jump_time > t0:
boolean*=(t<jump_time)
return boolean
def CentroidCheck(lc,monoparams,interpmodel,ID,order=2,dur_region=3.5, plot=True,plot_loc=None, return_fit_lcs=False, **kwargs):
# Checking lightcure for centroid shift during transit.
# Performing two model fits
# - one with a "dip" correlated to the transit combined with a polynomial trend
# - one with only a polynomial trend
# These are then compared, and the BIC returned to judge
if 'cent_1' in lc:
if monoparams['orbit_flag']=='mono':
roundTransit=(abs(lc['time']-monoparams['tcen'])<monoparams['tdur']*dur_region)&lc['mask']
t=lc['time'][roundTransit]-monoparams['tcen']
roundTransit=GapCull(monoparams['tcen'],lc['time'],[lc['cent_1'],lc['cent_2']],boolean=roundTransit)
t = lc['time'][roundTransit*np.isfinite(lc['cent_1'])*np.isfinite(lc['cent_2'])]-monoparams['tcen']
x = lc['cent_1'][roundTransit*np.isfinite(lc['cent_1'])*np.isfinite(lc['cent_2'])]
y = lc['cent_2'][roundTransit*np.isfinite(lc['cent_1'])*np.isfinite(lc['cent_2'])]
outTransit=(abs(t)>monoparams['tdur']*0.65)
inTransit=(abs(t)<monoparams['tdur']*0.35)
elif monoparams['orbit_flag']=='periodic':
#Checking for centroid in periodic array.
#This needs more care as we have to sum each transit without adding noise/trends from each
phase=(lc['time']-monoparams['tcen']-0.5*monoparams['period'])%monoparams['period']-0.5*monoparams['period']
dur_region=np.min([0.25*monoparams['period'],dur_region*monoparams['tdur']])
roundTransit=(abs(phase)<monoparams['tdur']*dur_region)&lc['mask']
#roundtransit now becomes "islands" around each transit in time space:
jumps=np.hstack((0,np.where(np.diff(lc['time'][roundTransit])>monoparams['period']*0.25)[0]+1,len(lc['time'][roundTransit]) )).astype(int)
ts=[]
cent1s=[]
cent2s=[]
for nj in range(len(jumps)-1):
#Iteratively cutting jumps for each transit
cent1_loc=lc['cent_1'][roundTransit][jumps[nj]:jumps[nj+1]]
cent2_loc=lc['cent_2'][roundTransit][jumps[nj]:jumps[nj+1]]
t_loc=phase[roundTransit][jumps[nj]:jumps[nj+1]]
newbool=GapCull(0.0,t_loc,[cent1_loc,cent2_loc])&np.isfinite(cent1_loc)&np.isfinite(cent2_loc)
#Using non-removed regions to fit 2D polynomial and subtract from cent curves
if np.sum(newbool)>0:
ts+=[t_loc[newbool]]
cent1s+=[cent1_loc[newbool] - \
np.polyval(np.polyfit(t_loc[newbool],cent1_loc[newbool],order),t_loc[newbool])]
cent2s+=[cent2_loc[newbool] - \
np.polyval(np.polyfit(t_loc[newbool],cent2_loc[newbool],order),t_loc[newbool])]
t=np.hstack(ts)
x=np.hstack(cent1s)
y=np.hstack(cent2s)
y=y[np.argsort(t)]
x=x[np.argsort(t)]
t=np.sort(t)
outTransit=(abs(t)>monoparams['tdur']*0.65)
inTransit=(abs(t)<monoparams['tdur']*0.35)
#At the point all arrays should be flat, so we can make order==1
order=0
if len(x)>order+1 and len(y)>order+1:
xerr=np.std(x)
x-=np.median(x)
if len(x[inTransit])>0 and len(x[outTransit])>0:
#Calculating candidate shift. Setting as ratio to depth
xdep_guess=(np.median(x[inTransit])-np.median(x[outTransit]))/monoparams['depth']
init_poly_x=np.polyfit(t[outTransit],x[outTransit],order)
else:
xdep_guess=0.0
if len(x[inTransit])>0:
init_poly_x=np.polyfit(t,x,np.clip(order-1,0,10))
else:
init_poly_x=np.zeros(np.clip(order,1,11))
y-=np.median(y)
yerr=np.std(y)
if len(y[inTransit])>0 and len(y[outTransit])>0:
#Calculating candidate shift. Setting as ratio to depth
ydep_guess=(np.median(y[inTransit])-np.median(y[outTransit]))/monoparams['depth']
init_poly_y=np.polyfit(t[outTransit],y[outTransit],order)
else:
ydep_guess=0.0
if len(y[inTransit])>0:
init_poly_y=np.polyfit(t,x,np.clip(order-1,0,10))
else:
init_poly_y=np.zeros(np.clip(order,1,11))
else:
return None, None, None
#Prior on centroid shifts such that values within 4sigma of 0.0 are enhanced.
n_sig = [4*xerr/np.sqrt(np.sum(inTransit)),4*yerr/np.sqrt(np.sum(inTransit))]
#priors= np.column_stack(([0,0],[n_sig[0]/monoparams['depth'],n_sig[1]/monoparams['depth']]))
priors = np.column_stack(([0,0],[xdep_guess,ydep_guess]))
poly_priors = 10.0 ** -np.arange(order+1)[::-1]
best_nodip_res={'fun':1e30,'bic':1e6}
best_dip_res={'fun':1e30,'bic':1e6}
methods=['L-BFGS-B','Nelder-Mead','Powell']
for n in range(7):
#Doing simple polynomial fits for non-dips. Excluding 10% of data each time to add some randomness
rand_choice=np.random.choice(len(x),int(len(x)//1.06),replace=False)
xfit=optim.minimize(Poly_neg_lnprob, np.polyfit(t[rand_choice],x[rand_choice],order),
args=(t,x,xerr,poly_priors,
order),method=methods[n%3])
yfit=optim.minimize(Poly_neg_lnprob, np.polyfit(t[rand_choice],y[rand_choice],order),
args=(t,y,yerr,poly_priors,
order),method=methods[n%3])
nodip_res={'fun':yfit.fun+xfit.fun}
nodip_res['x']=[xfit.x,yfit.x]
#nodip_res['bic']=2*nodip_res['fun'] + np.log(2*np.sum(roundTransit))*(len(xfit)+len(yfit))
nodip_res['llk']=log_likelihood_poly(xfit.x, t,y,yerr)+log_likelihood_poly(yfit.x, t,y,yerr)
nodip_res['bic']=np.log(len(x)+len(y))*(len(xfit.x)+len(xfit.x)) - 2 * nodip_res['llk']
if nodip_res['bic']<best_nodip_res['bic']:
best_nodip_res=nodip_res
dip_args= np.hstack((np.random.normal(xdep_guess,abs(0.25*xdep_guess)),
np.random.normal(ydep_guess,abs(0.25*ydep_guess)),
init_poly_x,init_poly_y ))
dip_res=optim.minimize(centroid_neg_lnprob, dip_args,
args=(t,x,y,xerr,yerr,
priors,
interpmodel,
order),method=methods[n%3])
dip_res['llk']=log_likelihood_centroid(dip_res['x'], t, x, y, xerr, yerr, interpmodel, order)
#-1*dip_res['fun']
dip_res['bic']=np.log(len(x)+len(y))*len(dip_res['x']) - 2 * dip_res['llk']
#2*dip_res.fun + np.log(2*np.sum(roundTransit))*len(dip_res['x'])
if dip_res['bic']<best_dip_res['bic']:
best_dip_res=dip_res
#Computing difference in Bayesian Information Criterium - DeltaBIC - between "dip" and "no dip models"
centinfo={}
centinfo['centroid_DeltaBIC'] = best_dip_res['bic'] - best_nodip_res['bic'] # dip is better < 0 < no dip is better
centinfo['centroid_llk_ratio'] = best_dip_res['fun'] - best_nodip_res['fun']
#print(best_dip_res)
if 'x' in best_dip_res:
centinfo['x_centroid'] = best_dip_res['x'][0]*monoparams['depth']
centinfo['y_centroid'] = best_dip_res['x'][1]*monoparams['depth']
centinfo['x_centroid_SNR'] = np.sqrt(np.sum(inTransit))*abs(centinfo['x_centroid']) / \
np.nanmedian(1.06*abs(np.diff(x[outTransit])))
centinfo['y_centroid_SNR'] = np.sqrt(np.sum(inTransit))*abs(centinfo['y_centroid']) / \
np.nanmedian(1.06*abs(np.diff(y[outTransit])))
#print("init_guesses:",xdep_guess,ydep_guess,"best_fits:",best_dip_res['x'][0],best_dip_res['x'][1])
#print("with centroid:",best_dip_res,"| without:",best_nodip_res)
if 'x' in best_dip_res and return_fit_lcs:
arrs=np.column_stack((t,x,np.polyval(best_nodip_res['x'][0],t),
dipmodel_centroid(best_dip_res.x,t,interpmodel,order)[0],
y,np.polyval(best_nodip_res['x'][1],t),
dipmodel_centroid(best_dip_res.x,t,interpmodel,order)[1]))
else:
arrs=None
if plot:
if plot_loc is not None and type(plot_loc)!=str:
ax = plot_loc
else:
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(133)
if plot_loc is None:
plot_loc = str(ID)+"_centroid_shift.pdf"
elif plot_loc[-1]=='/':
plot_loc=plot_loc+str(ID)+"_centroid_shift.pdf"
'''
#### PLOTTING ###
if monoparams['orbit_flag']=='periodic':
ax.plot(phase,lc['cent_1']-np.nanmedian(lc['cent_1'][roundTransit]),',k',rasterized=True)
ax.plot(phase,lc['cent_2']-np.nanmedian(lc['cent_2'][roundTransit]),',k',rasterized=True)
elif monoparams['orbit_flag']=='mono':
ax.plot(lc['time']-monoparams['tcen'],lc['cent_1']-np.nanmedian(lc['cent_1'][roundTransit]),',k',rasterized=True)
ax.plot(lc['time']-monoparams['tcen'],lc['cent_2']-np.nanmedian(lc['cent_2'][roundTransit]),',k',rasterized=True)
'''
ax.scatter(t,y,s=1.5,rasterized=True)
ax.scatter(t,x,s=1.5,rasterized=True)
ax.plot([-0.5*monoparams['tdur'],-0.5*monoparams['tdur']],[-2.0,2.0],':k',alpha=0.6,rasterized=True)
ax.plot([0.0,0.0],[-2.0,2.0],'--k',linewidth=3,alpha=0.8,rasterized=True)
ax.plot([0.5*monoparams['tdur'],0.5*monoparams['tdur']],[-2.0,2.0],':k',alpha=0.6,rasterized=True)
ax.set_ylabel("Relative centroid [px]")
try:
if best_dip_res['fun']<1e29 and best_nodip_res['fun']<1e29 and len(best_nodip_res['x'])==2:
ax.plot(t,np.polyval(best_nodip_res['x'][0],t),'--',c='C3',linewidth=2.25,alpha=0.6,
label='pure trend - x',rasterized=True)
ax.plot(t,np.polyval(best_nodip_res['x'][1],t),'--',c='C4',linewidth=2.25,alpha=0.6,
label='pure trend - y',rasterized=True)
ax.plot(t,dipmodel_centroid(best_dip_res.x,t,interpmodel,order)[0],c='C3',
linewidth=2.25,alpha=0.6,label='trend+centroid - x',rasterized=True)
ax.plot(t,dipmodel_centroid(best_dip_res.x,t,interpmodel,order)[1],c='C4',
linewidth=2.25,alpha=0.6,label='trend+centroid - y',rasterized=True)
ax.legend(prop={'size': 5})
ax.set_title(str(ID)+" Centroid - "+["pass","fail"][int(centinfo['centroid_llk_ratio']<-6)])
else:
ax.set_title(str(ID)+" Centroid - No fit ???")
except:
ax.set_title(str(ID)+" Centroid - No fit ???")
xlim=np.percentile(x,[0.2,99.8])
ylim=np.percentile(y,[0.2,99.8])
ax.set_ylim(np.min([xlim[0],ylim[0]]),np.max([xlim[1],ylim[1]]))
ax.set_xlim(np.min(t),np.max(t))
if plot_loc is not None and type(plot_loc)==str:
fig.savefig(plot_loc, dpi=400)
return centinfo, plot_loc, arrs
else:
return centinfo, ax, arrs
elif not plot:
return centinfo, None,arrs
else:
return None, None
def CheckPeriodConfusedPlanets(lc,all_dets,mono_mono=True,multi_multi=True,mono_multi=True):
#Merges dic of mono detections with a dic of periodic planet detections
#Performs 3 steps:
# - Checks monos against themselves
# - Checks periodic planets (and duos detected in the periodic search) against themselves
# - Checks periodic planets (and duos detected in the periodic search) against monotransits
# In each case, the signal with the highest SNR is kept (and assumed to be the correct one)
# The other signal is removed from the list, but kept in the detn dictionary
#
#INPUTS:
# - lc dict
# - detection dict
#RETURNS:
# - detection dict
# - list of monos
# - list of multis/duos
mono_detns=[pl for pl in all_dets if (all_dets[pl]['orbit_flag']=='mono')&(all_dets[pl]['flag'] not in ['asteroid','EB','instrumental','lowSNR','variability'])]
#print([all_dets[pl]['flag'] for pl in mono_detns])
if len(mono_detns)>1 and mono_mono:
#removing monos which are effectively the same. Does this through tcen/tdur matching.
for monopl in mono_detns:
if all_dets[monopl]['orbit_flag'][:2]!='FP':
other_dets = np.array([[other,all_dets[other]['tcen'],all_dets[other]['tdur']] for other in mono_detns if other !=monopl])
trans_prox = np.min(abs(all_dets[monopl]['tcen']-other_dets[:,1].astype(float))) #Proximity to a transit
prox_stats = abs(trans_prox/(0.5*(all_dets[monopl]['tdur']+other_dets[:,2].astype(float))))
print("Mono-mono compare", monopl, all_dets[monopl]['tcen'], other_dets[:,1], prox_stats)
if np.min(prox_stats)<0.5:
other=other_dets[np.argmin(prox_stats),0]
if all_dets[other]['snr']>all_dets[monopl]['snr']:
all_dets[monopl]['orbit_flag']='FP - confusion with '+other
else:
all_dets[other]['orbit_flag']='FP - confusion with '+monopl
mono_detns=[pl for pl in all_dets if (all_dets[pl]['orbit_flag']=='mono')&(all_dets[pl]['flag'] not in ['asteroid','EB','instrumental','lowSNR','variability'])]
perdc_detns=[pl for pl in all_dets if (all_dets[pl]['orbit_flag'] in ['periodic','duo'])&(all_dets[pl]['orbit_flag']!='variability')]
if len(perdc_detns)>1 and multi_multi:
#removing periodics which are effectively the same. Does this through cadence correlation.
for perpl in perdc_detns:
new_trans_arr=((lc['time'][lc['mask']]-all_dets[perpl]['tcen']+0.5*all_dets[perpl]['tdur'])%all_dets[perpl]['period'])<all_dets[perpl]['tdur']
for perpl2 in perdc_detns:
if perpl!=perpl2 and all_dets[perpl]['orbit_flag'][:2]!='FP' and all_dets[perpl2]['orbit_flag'][:2]!='FP':
new_trans_arr2=((lc['time'][lc['mask']]-all_dets[perpl2]['tcen']+0.5*all_dets[perpl2]['tdur'])%all_dets[perpl2]['period'])<all_dets[perpl2]['tdur']
sum_overlap=np.sum(new_trans_arr&new_trans_arr2)
prox_arr=np.hypot(sum_overlap/np.sum(new_trans_arr),sum_overlap/np.sum(new_trans_arr2))
#print("Multi-multi compare",perpl,all_dets[perpl]['period'],perpl2,all_dets[perpl2]['period'],prox_arr)
if prox_arr>0.6:
#These overlap - taking the highest SNR signal
if all_dets[perpl]['snr']>all_dets[perpl2]['snr']:
all_dets[perpl2]['orbit_flag']='FP - confusion with '+perpl2
else:
all_dets[perpl]['orbit_flag']='FP - confusion with '+perpl
perdc_detns=[pl for pl in all_dets if (all_dets[pl]['orbit_flag'] in ['periodic','duo'])&(all_dets[pl]['orbit_flag']!='variability')]
trans_arr=[]
#print(mono_detns,perdc_detns,len(mono_detns)>0 and len(perdc_detns)>0)
if len(mono_detns)>0 and len(perdc_detns)>0 and mono_multi:
confused_mono=[]
#Looping over periodic signals and checking if the array of transit times (and durations) matches
for perpl in perdc_detns:
new_trans_arr=((lc['time'][lc['mask']]-all_dets[perpl]['tcen']+0.5*all_dets[perpl]['tdur'])%all_dets[perpl]['period'])<all_dets[perpl]['tdur']
#trans_arr=np.hstack((np.arange(all_dets[perpl]['tcen'],np.nanmin(lc['time'])-all_dets[perpl]['tdur'],-1*all_dets[perpl]['period'])[::-1],np.arange(all_dets[perpl]['tcen']+all_dets[perpl]['period'],np.nanmax(lc['time'])+all_dets[perpl]['tdur'],all_dets[perpl]['period'])))
#print(perpl,trans_arr)
for monopl in mono_detns:
if all_dets[monopl]['orbit_flag'][:2]!='FP' and all_dets[perpl]['orbit_flag'][:2]!='FP':
roundtr=abs(lc['time'][lc['mask']]-all_dets[monopl]['tcen'])<(2.5*all_dets[monopl]['tdur'])
new_trans_arr2=abs(lc['time'][lc['mask']][roundtr]-all_dets[monopl]['tcen'])<(0.5*all_dets[monopl]['tdur'])
sum_overlap=np.sum(new_trans_arr[roundtr]&new_trans_arr2)
prox_stat=sum_overlap/np.hypot(np.sum(new_trans_arr[roundtr]),np.sum(new_trans_arr2))
#adding depth comparison - if depths are a factor of >3different we start reducing prox_stat by the log ratio
prox_stat/=np.clip(abs(np.log(all_dets[perpl]['depth']/all_dets[monopl]['depth'])),1.0,20)
'''
nearest_trans=trans_arr[np.argmin(abs(all_dets[monopl]['tcen']-trans_arr))] #Proximity to a transit
trans_perdic=abs(lc['time'][lc['mask']]-nearest_trans)<(0.5*all_dets[perpl]['tdur'])
trans_mono=abs(lc['time'][lc['mask']]-all_dets[monopl]['tcen'])<(0.5*all_dets[monopl]['tdur'])
prox_stat=np.hypot(np.sum(trans_perdic&trans_mono)/np.sum(trans_perdic),
np.sum(trans_perdic&trans_mono)/np.sum(trans_mono))
'''
#print("Multi-mono compare",perpl,all_dets[perpl]['tdur'],"|",monopl,all_dets[monopl]['tcen'],all_dets[monopl]['tdur'],prox_stat)
if prox_stat>0.33:
#These overlap - taking the highest SNR signal
#print("correlation - ",all_dets[perpl]['snr'],all_dets[monopl]['snr'])
if all_dets[perpl]['snr']>=all_dets[monopl]['snr']:
all_dets[monopl]['orbit_flag']= 'FP - confusion with '+perpl
elif all_dets[perpl]['snr']<all_dets[monopl]['snr']:
all_dets[perpl]['orbit_flag']= 'FP - confusion with '+monopl
mono_detns=[pl for pl in all_dets if (all_dets[pl]['orbit_flag']=='mono')&(all_dets[pl]['flag'] not in ['asteroid','EB','instrumental','lowSNR','variability','step'])]
perdc_detns=[pl for pl in all_dets if (all_dets[pl]['orbit_flag'] in ['periodic','duo'])&(all_dets[pl]['orbit_flag']!='variability')]
return all_dets, mono_detns, perdc_detns
def CheckMonoPairs(lc_time, all_pls,prox_thresh=3.5, **kwargs):
#Loop through each pair of monos without a good period, and check:
# - if they correspond in terms of depth/duration
# - and whether they could be periodic given other data
all_monos=[pl for pl in all_pls if (all_pls[pl]['orbit_flag']=='mono')&(all_pls[pl]['flag'] not in ['asteroid','EB','instrumental','lowSNR','variability','FP - confusion'])]
all_others=[pl for pl in all_pls if (all_pls[pl]['orbit_flag'] in ['periodic', 'duo'])&(all_pls[pl]['flag'] not in ['asteroid','EB','instrumental','lowSNR','variability','FP - confusion'])]
if len(all_monos)>1:
prox_arr=np.tile(1e9,(len(all_monos),len(all_monos)))
ordered_monos=np.array(all_monos)[np.argsort(np.array([all_pls[mon]['snr'] for mon in all_monos]))[::-1]]
#print(ordered_monos,np.array([all_pls[mon]['snr'] for mon in ordered_monos]))
found=[]
for n1,m1 in enumerate(ordered_monos):
proxs=[]
for n2,m2 in enumerate(ordered_monos[n1+1:]):
if m1 not in found and m2 not in found:
# 1) How close are these monos in terms of depth & duration? (0.5 ~ 10% different here)
proxs+=[(np.log(all_pls[m1]['depth'])-np.log(all_pls[m2]['depth']))**2/0.25**2+\
(np.log(all_pls[m1]['tdur'])-np.log(all_pls[m2]['tdur']))**2/0.2**2]
# 2) Can these monos even possibly produce a "duo" given the other phase coverage?
period = abs(all_pls[m1]['tcen']-all_pls[m2]['tcen'])
average_dur=np.average([all_pls[m1]['tdur'],all_pls[m2]['tdur']])
phase=(lc_time-all_pls[m1]['tcen']-period*0.5)%period-period*0.5
Npts_in_tr=np.sum(abs(phase)<0.3*average_dur)
Npts_from_known_transits=np.sum(abs(lc_time-all_pls[m1]['tcen'])<0.3*average_dur)+np.sum(abs(lc_time-all_pls[m2]['tcen'])<0.3*average_dur)
# Let's multiply the prox_arr from duration/depth with the square of the number of points in transit
# Here, if there's ~10% of a transit in the right phase, we get prox_arr==1.0
# Here, if there's ~25% of a transit in the right phase, we get prox_arr==6.0
proxs[-1]+=(20*(Npts_in_tr/Npts_from_known_transits-1))**2
proxs[-1]/=(all_pls[m2]['snr']/all_pls[m1]['snr'])**0.5 #Including SNR factor - higher SNR is favoured
#print(m1,m2,all_pls[m1]['depth'],all_pls[m2]['depth'],all_pls[m1]['tdur'],all_pls[m2]['tdur'],Npts_in_tr,Npts_from_known_transits,(all_pls[m2]['snr']/all_pls[m1]['snr'])**0.5,proxs[-1])
#print("Mono pair searching",m1,proxs)
#Taking the best-fitting lower-SNR detection which matches:
proxs=np.array(proxs)
if np.any(proxs<prox_thresh):
n2=np.argmin(proxs)
m2=ordered_monos[n1+1:][n2]
newm1=deepcopy(all_pls[m1])
#MATCH with threshold of 2
for key in all_pls[m1]:
if key in all_pls[m2]:
if key=='period':
#print("tcens = ",all_pls[m1]['tcen'],all_pls[m2]['tcen'])
newm1['period']=abs(all_pls[m1]['tcen']-all_pls[m2]['tcen'])
elif key in ['snr','snr_r']:
newm1[key]=np.hypot(all_pls[m1][key],all_pls[m2][key])
elif type(all_pls[m2][key])==float and key!='tcen':
#Average of two:
#print(key,all_pls[m1][key],all_pls[m2][key],0.5*(all_pls[m1][key]+all_pls[m2][key]))
newm1[key]=0.5*(all_pls[m1][key]+all_pls[m2][key])
newm1['tcen_2']=all_pls[m2]['tcen']
newm1['orbit_flag']='duo'
check_pers = newm1['period']/np.arange(1,np.ceil(newm1['period']/10),1.0)
check_pers_ix=np.tile(False,len(check_pers))
Npts_from_known_transits=np.sum(abs(lc_time-newm1['tcen'])<0.35*newm1['tdur']) + \
np.sum(abs(lc_time-newm1['tcen_2'])<0.35*newm1['tdur'])
#print("check pers duos",check_pers,Npts_from_known_transits)
for nper,per in enumerate(check_pers):
phase=(lc_time-newm1['tcen']-per*0.5)%per-per*0.5
Npts_in_tr=np.sum(abs(phase)<0.35*newm1['tdur'])
check_pers_ix[nper]=Npts_in_tr<1.075*Npts_from_known_transits #Less than 15% of another eclipse is covered
newm1['period_aliases']=check_pers[check_pers_ix]
if len(newm1['period_aliases'])>1:
newm1['P_min'] = newm1['period_aliases'] if type(newm1['period_aliases'])==float else np.min(newm1['period_aliases'])
elif len(newm1['period_aliases'])==1:
newm1['P_min'] = newm1['period_aliases'][0]
else:
newm1['P_min'] = 999
#print("period aliases:",newm1['period_aliases'],"P_min:",newm1['P_min'])
all_pls[m1]=newm1
all_pls[m2]['orbit_flag']='FP - Confusion with '+m1
all_pls[m2]['flag']='FP - confusion'
found+=[m1,m2]
return all_pls
def EB_modelPriors(params,priors):
lnprior=0.0
for p in range(len(params)):
if priors[p,1]=='Gaussian':
lnprior+=log_gaussian(params[p],float(priors[p,2]),float(priors[p,3]))
elif priors[p,1]=='Uniform':
#Outside uniform priors, give extremely harsh restrictions that get worse with distance:
if params[p]<(float(priors[p,2])-float(priors[p,3])):
lnprior-=1e3*((float(priors[p,2])-params[p])/float(priors[p,3]))**2
elif params[p]>(float(priors[p,2])+float(priors[p,3])):
lnprior-=1e3*((params[p]-float(priors[p,2]))/float(priors[p,3]))**2
else:
lnprior-=0.0
return lnprior
def EBmodel_lnprob(params, x, y, yerr, priors, Ms, tsec=False):
# Trivial improper prior: uniform in the log.
lnprior=EB_modelPriors(params,priors)
llk = log_likelihood_EBmodel(params, x, y, yerr, Ms,tsec=tsec)
if np.isnan(llk):
llk=-1e25
#print("llk:",llk,"prior:",lnprior,"minimise:",-1*(lnprior + llk))
return lnprior + llk
'''
def log_likelihood_EBmodel(params, x, y, yerr):
model=EBmodel(params,x)
sigma2 = yerr ** 2
return -0.5 * np.sum((y - model) ** 2 / sigma2 + np.log(sigma2))
'''
def log_likelihood_EBmodel(params, x, y, yerr, Ms,tsec=False):
model=EBmodel(params,x, Ms,tsec=tsec)
'''
if abs(np.median(model))>1e100:
r_1,log_r2_r1,log_sbratio,b,log_light_3,t_zero,log_period,log_sma,log_q,f_c,f_s,ldc_1 = params
sma=np.exp(log_sma)
r_1=np.clip(r_1/sma,1e-7,0.5)
r_2=np.clip(r_1*np.exp(log_r2_r1)/sma,1e-7,0.5)
print("r1",np.clip(r_1/sma,1e-7,1-1e-7),"|r2",np.clip(r_1*np.exp(log_r2_r1)/sma,1e-7,1-1e-7),
"|sb",np.exp(log_sbratio),"|b",b,"|incl",np.arccos(abs(b)/sma)*(180/np.pi),"|light_3:",np.exp(log_light_3),
"|t_zero",t_zero,"|period",np.exp(log_period),"|a",np.exp(log_sma),
"|q",np.exp(np.clip(log_q,-20,1.0)),"|f_c",f_c,"|f_s",f_s,
"|ldc_1",ldc_1)
'''
inv_sigma2 = 1.0/(yerr**2 + model**2)
return -0.5*(np.sum((y-model)**2*inv_sigma2 - np.log(inv_sigma2)))
def EBmodel_neg_lnprob(params, x, y, yerr, priors, Ms,tsec=False):
return -1*EBmodel_lnprob(params, x, y, yerr, priors, Ms,tsec=tsec)
def EBmodel(params, t, Ms, tsec=False):
if not tsec:
#given omega directly as parameter:
r_1,log_r2_r1,log_sbratio,b,log_light_3,t_zero,log_period,log_q,ecc,omega,ldc_1 = params
incl=np.arccos(abs(b)/sma)
else:
#deriving omega from secondary position:
r_1,log_r2_r1,log_sbratio,b,log_light_3,t_zero,log_period,log_q,ecc,t_sec,ldc_1 = params
incl=np.arccos(abs(b)/sma)
omega = np.arccos(np.pi*(((t_sec-t_zero)%period)/np.exp(log_period)-0.5)/(ecc*(1+np.sin(incl)**-1)))
#Modified these parameters to be:
# R_1 (in Rsun)
# R_2/R_1,
# log of sb ratio
# b - impact parameter
# log light 3
# t_zero
# log_period
# sma
# q - mass ratio
# f_c - ecos omega
# f_s - esin omega
# ldc_1 - limb darkening
#Using Kepler's laws to derive SMA
sma=((6.67e-11*(1+np.exp(log_q))*Ms*1.96e30*(np.exp(log_period)*86400)**2)/(4*np.pi**2))**(1/3)/(6.955e8)
r_1=np.clip(r_1/sma,1e-7,0.75)
r_2=np.clip(r_1*np.exp(log_r2_r1),1e-7,0.75)
ymodel=ellc.lc(t,r_1,r_2,
np.exp(log_sbratio),incl*(180/np.pi),
light_3=np.exp(log_light_3),
t_zero=t_zero,period=np.exp(log_period),a=sma,
f_c=np.sqrt(np.clip(ecc,0.0,1.0-0.5*(r_1+r_2)))*np.cos(omega),
f_s=np.sqrt(np.clip(ecc,0.0,1.0-0.5*(r_1+r_2)))*np.sin(omega),
q=np.exp(log_q),ldc_1=np.clip(ldc_1,0.0,1.0),ld_1="lin",verbose=0)
return ymodel
def pri_sec_const(time,t_pri,dur_pri,t_sec=None,dur_sec=None):
#Uses observed times, plus positions of primary and secondary eclipses
# to estimate minimum period and minimum eccentricity of eclipsing binary
# Requites:
# - time
# - t_pri - time of primary
# - dur_pri - duration of primary (in days)
# - t_sec - time of secondary
# - dur_sec - duration of secondary (in days)
dist_from_pri=np.sort(abs(time-t_pri))
if t_sec is not None:
dist_from_sec=np.sort(abs(time-t_sec))
if np.max(np.diff(dist_from_pri))>(0.6*dur_pri):
#Gaps in lightcurve - finding closest gap from primary
if t_sec is not None:
min_per=np.min([dist_from_pri[np.diff(dist_from_pri)>(0.5*dur_pri)][0],
dist_from_sec[np.diff(dist_from_sec)>(0.5*dur_pri)][0]])
max_per=np.max([dist_from_pri[-1]+dur_pri,dist_from_sec[-1]+dur_sec])
durstep=np.min([dur_pri,dur_sec])*0.25
cut_time=time[(abs(time-t_pri)<0.5*dur_pri)&(abs(time-t_sec)<0.5*dur_sec)]
else:
min_per=dist_from_pri[np.diff(dist_from_pri)>(0.5*dur_pri)][0]
max_per=dist_from_pri[-1]+dur_pri
durstep=dur_pri*0.25
cut_time=time[abs(time-t_pri)<0.5*dur_pri]
else:
#No gaps - can return simply the furthest timestamp from primary or secondary and compute min_ecc
if t_sec is not None:
min_per=np.max(np.hstack([dist_from_pri,dist_from_sec]))
min_ecc=1/(2*np.pi)*(abs(t_pri-t_sec)/min_per - 0.5)
else:
min_per=np.max(dist_from_pri)
min_ecc=0.0
return min_per,min_ecc
#Boolean array that will show if period is OK, given pri/sec and gaps, or if it fails:
per_bool=[]
psteps=np.arange(min_per-durstep,max_per+durstep,durstep)
for pstep in psteps:
phase=(cut_time-t_pri)%pstep
pbool=(np.min(phase)>(dur_pri*0.4))&(np.max(phase)<(pstep-dur_pri*0.4))
if pbool and t_sec is not None:
phase_sec=(t_sec-t_pri)%pstep
if np.min(abs(phase-phase_sec))<(dur_sec*0.4):
pbool=False
per_bool+=[pbool]
#The minimum period is therefore the first per for which a period is ok:
min_per = psteps[np.array(per_bool)][0]
if t_sec is not None:
pri_to_sec=(t_pri-t_sec)%min_per
min_ecc=1/(2*np.pi)*(((t_pri-t_sec)%min_per)/min_per - 0.5)
else:
print("No good period here?")
def exoplanet_EB_model(lc, objects, Teffs, Rs, Ms, nrep=9,try_sec=False,use_ellc=False):
with pm.Model() as model:
return None
def xoEB(lc,planets):
EBs=[pl for pl in planets if planets['pl']['flag']=='EB']
if len(EBs)==1:
eb=EBs[0]
else:
eb=EBs[np.argmax([planets[eb]['logror'] for eb in EBs])]
with pm.Model() as model:
# Systemic parameters
mean_lc = pm.Normal("mean_lc", mu=0.0, sd=5.0)
u1 = xo.QuadLimbDark("u1")
u2 = xo.QuadLimbDark("u2")
# Parameters describing the primary
M1 = pm.Lognormal("M1", mu=Ms[0], sigma=abs(Ms[1]+Ms[2]))
R1 = pm.Lognormal("R1", mu=Rs[0], sigma=abs(Rs[1]+Rs[2]))
# Secondary ratios
k = pm.Lognormal("k", mu=0.0, sigma=10.0, testval=np.exp(planets['pl']['logror'])) # radius ratio
q = pm.Lognormal("q", mu=0.0, sigma=10.0) # mass ratio
s = pm.Lognormal("s", mu=np.log(0.5), sigma=10.0) # surface brightness ratio
# Prior on flux ratio
pm.Beta("flux_prior",a=0.5, b=0.5,
observed=k ** 2 * s)
pm.Normal(
"flux_prior",
mu=lit_flux_ratio[0],
sigma=lit_flux_ratio[1],
observed=k ** 2 * s,
)
# Parameters describing the orbit
b = xo.ImpactParameter("b", ror=k, testval=1.5)
if planets[eb]['orbit_flag']=='mono':
period = pm.Pareto("period", m=planets[eb]['minP'], alpha=1.0)
newmask=lc['mask']&(abs(lc['time']-planets[eb]['tcen'])<planets[eb]['tdur']*2.5)
else:
period = pm.Lognormal("period", mu=np.log(planets[eb]['period']), sigma=0.1)
newmask=lc['mask']&(abs((lc['time']-planets[eb]['tcen']-0.5*planets[eb]['period'])%planets[eb]['period'] - \
0.5*planets[eb]['period'])<planets[eb]['tdur']*2.5)
#period = pm.Lognormal("period", mu=np.log(lit_period), sigma=1.0)
t0 = pm.Normal("t0", mu=planets[eb]['tcen'], sigma=1.0)
# Parameters describing the eccentricity: ecs = [e * cos(w), e * sin(w)]
ecs = xo.UnitDisk("ecs", testval=np.array([1e-5, 0.0]))
ecc = pm.Deterministic("ecc", tt.sqrt(tt.sum(ecs ** 2)))
omega = pm.Deterministic("omega", tt.arctan2(ecs[1], ecs[0]))
# Build the orbit
R2 = pm.Deterministic("R2", k * R1)
M2 = pm.Deterministic("M2", q * M1)
orbit = xo.orbits.KeplerianOrbit(
period=period,
t0=t0,
ecc=ecc,
omega=omega,
b=b,
r_star=R1,
m_star=M1,
m_planet=M2,
)
# Track some other orbital elements
pm.Deterministic("incl", orbit.incl)
pm.Deterministic("a", orbit.a)
# Noise model for the light curve
sigma_lc = pm.InverseGamma(
"sigma_lc", testval=1.0, **xo.estimate_inverse_gamma_parameters(0.1, 2.0)
)
S_tot_lc = pm.InverseGamma(
"S_tot_lc", testval=2.5, **xo.estimate_inverse_gamma_parameters(1.0, 5.0)
)
ell_lc = pm.InverseGamma(
"ell_lc", testval=2.0, **xo.estimate_inverse_gamma_parameters(1.0, 5.0)
)
kernel_lc = xo.gp.terms.SHOTerm(
S_tot=S_tot_lc, w0=2 * np.pi / ell_lc, Q=1.0 / 3
)
# Set up the light curve model
model_lc = xo.SecondaryEclipseLightCurve(u1, u2, s)
def get_model_lc(t):
return (
mean_lc
+ 1e3 * model_lc.get_light_curve(orbit=orbit, r=R2, t=t, texp=texp)[:, 0]
)
# Condition the light curve model on the data
gp_lc = xo.gp.GP(
kernel_lc, lc['time'][newmask], lc['flux_err'][newmask] ** 2 + sigma_lc ** 2, mean=get_model_lc
)
gp_lc.marginal("obs_lc", observed=lc['flux'][newmask])
# Optimize the logp
map_soln = model.test_point
# Then the LC parameters
map_soln = xo.optimize(map_soln, [mean_lc, R1, k, s, b])
map_soln = xo.optimize(map_soln, [mean_lc, R1, k, s, b, u1, u2])
map_soln = xo.optimize(map_soln, [mean_lc, sigma_lc, S_tot_lc, ell_lc, q])
map_soln = xo.optimize(map_soln, [t0, period])
# Then all the parameters together
map_soln = xo.optimize(map_soln)
model.gp_lc = gp_lc
model.get_model_lc = get_model_lc
model.x = lc['time'][newmask]
model.y = lc['flux'][newmask]
return model, map_soln
def minimize_EBmodel(lc, objects, Teffs, Rs, Ms, nrep=9,try_sec=False,use_ellc=False):
#Running a quick EB model:
multis=[key for key in objects if objects[key]['orbit_flag'] in ['periodic','duo']]
if len(objects)>1:
SNRs=np.array([objects[key]['snr'] for key in objects])
planet=objects[list(objects.keys())[np.argmax(SNRs)]]
#secmodel is None
bestfit,interp=QuickMonoFit(lc,planet['tcen'],planet['tdur'],Rs=Rs[0],Ms=Ms[0],useL2=True)
'''
#check periodic secondary at different phase - e.g. sec
if len(multis)==2:
per_objs = np.array([[objects[key]['period'],objects[key]['tcen']] for key in multis])
if (abs(per_objs[0,0]-per_objs[1,0])/0.02)<1:
epch_diff=(abs(per_objs[0,1]-per_objs[1,1])%per_objs[0,0])/per_objs[0,0]
if epch_diff>0.08 and epch_diff<0.92:
#Secondary found with same period at different epoch -
secmodel=objects[list(objects.keys())[np.argsort(SNRs)==1]]
secmodel['min_p']=per_objs[0,0]*0.95
elif len(multis)==1 and len(objects)==2:
bestfit,interp=QuickMonoFit(lc,planet['tcen'],planet['tdur'],Rs=Rs[0],Ms=Ms[0],useL2=True)
#secmodel=SearchForSecondary(lc, interpmodel, bestfit)
#Secondary position can constrain our eccentricity & omega position considerations
#If primary-to-secondary distance
e_min = abs(np.pi*0.5*(((secmodel['tcen']-bestfit['tcen'])%secmodel['min_p'])/secmodel['min_p']-0.5))
'''
if not use_ellc:
return bestfit,None
else:
import ellc
# Getting minimum period:
per_arr=np.sort(abs(lc['time']-bestfit['tcen']))
per_arr_jumps=np.where(np.diff(per_arr)>(0.75*bestfit['tdur']))[0]
if planet['orbit_flag'] in ['periodic', 'duo']:
min_per= planet['period']*0.95
init_per=planet['period']
else:
min_per= np.max(per_arr) if len(per_arr_jumps)==0 else per_arr[np.min(per_arr_jumps)]
init_per=bestfit['period']
#Calculating minimum SMA in Rsun given minimum period (scaled by 0.5 for eccentricity), Mass (scaled by 2 for q) & Radius
best_res={'fun':np.inf};
all_models=[]
init_params_0=np.array([Rs[0],bestfit['logror'],-1.0,0.25,np.log(bestfit['third_light']),bestfit['tcen'],
np.log(init_per),-2,0.0,0.0,0.5])
#priors are Name, [Gaussian OR Uniform], [mu, 2*sd] OR [lower bound, width]
init_uniform_priors=np.vstack([['R1','Gaussian',Rs[0],(abs(Rs[1])+abs(Rs[2]))],
['log_R2_R1','Uniform',-1.5,1.5],
['log_sbratio','Uniform',-2,3.25],
['b','Uniform',1.5,1.5],
['log_light_3','Uniform',-3.5,3.5],
['t_zero','Gaussian',bestfit['tcen'], 0.33*bestfit['tdur']],
['log_period','Uniform',np.log(min_per)+3.5,3.5],
['log_q','Uniform',-2,2],
['ecc','Uniform',0.5,0.5],
['omega','Uniform',0.0,np.pi],
['ldc_1','Uniform',0.5,0.5]])
if planet['orbit_flag'] in ['periodic', 'duo']:
init_uniform_priors[6]=['log_period','Uniform',np.log(min_per)+0.1,0.1]
if secmodel is not None:
init_uniform_priors[9]=['t_sec','Gaussian',secmodel['tcen'],0.33*secmodel['tdur']]
use_t_sec=True
else:
use_t_sec=False
if try_sec:
init_uniform_priors[0,2]=Rs[0]*0.5#Making radius R_2
init_uniform_priors[0,3]=Rs[0]*0.5
init_params_0[0]=Rs[0]*np.exp(bestfit['logror'])#Inverting log_ror, log_sbratio and log_q
init_uniform_priors[1,2]=float(init_uniform_priors[1,2])*-1; init_params_0[1]*=-1
init_uniform_priors[2,2]=float(init_uniform_priors[2,2])*-1; init_params_0[2]*=-1
init_uniform_priors[7,2]=float(init_uniform_priors[7,2])*-1; init_params_0[7]*=-1
newmask=lc['mask']&(abs(lc['time']-bestfit['tcen'])<5)
newmask[(abs(lc['time']-bestfit['tcen'])<5)]*=CutAnomDiff(lc['flux_flat'][abs(lc['time']-bestfit['tcen'])<5])
methods=['L-BFGS-B','Nelder-Mead','Powell']
#Doing N initial minimizatio using random parameters near initialised ones:
for n in range(nrep):
#Initialising priors and parameters for EB model:
#radius_1 = R1/sma,radius_2 = R2/sma,log_sbratio = 0.25,
#incl=90pm20,light_3=,t_zero,period,a,q,f_c,f_s,ldc_1
#Taking initial parameters as uniform between priors:
init_params=init_params_0+\
np.random.normal(np.tile(0.0,len(init_params_0)),0.15*init_uniform_priors[:,3].astype(float))
#print("depth:",1.0-np.min(EBmodel(init_params,lc['time'],Ms[0])),"@",lc['time'][np.argmin(EBmodel(init_params,lc['time'],Ms[0]))])
#print("init_q:",np.exp(init_params[7]))
res=optimize.minimize(EBmodel_neg_lnprob,init_params,args=(lc['time'][newmask],
1.0+lc['flux_flat'][newmask]-np.nanmedian(lc['flux_flat'][newmask]),
lc['flux_err'][newmask],
init_uniform_priors,Ms[0],use_t_sec),
method=methods[nrep%3])
all_models+=[EBmodel(res['x'],lc['time'],Ms[0])]
#print("OUT:",res['fun'],res['x'])
if res['fun']<best_res['fun']:
best_res=res
'''
#Doing N more initial minimizations using random parameters near the best-fit ones:
for n in range(nrep):
init_params=np.random.normal(best_res['x'],0.15*init_uniform_priors[:,3].astype(float))
res=optimize.minimize(EBmodel_neg_lnprob,init_params,
args=(lc['time'][newmask],lc['flux_flat'][newmask]-np.nanmedian(lc['flux_flat'][newmask]),
1.0+lc['flux_err'][newmask],init_uniform_priors,Ms[0]),method=methos[nrep%3])
if res['fun']<best_res['fun']:
best_res=res
'''
#Organising parameters to become best-fit:
if use_t_sec:
#deriving omega used from t_sec, t_pri and e:
r_1,r2_r1,log_sbratio,b,log_light_3,t_zero,log_period,log_q,ecc,t_sec,ldc_1 = best_res.x
omega=np.arccos(np.pi*(((t_sec-t_zero)%period)/np.exp(period)-0.5)/(ecc*(1+np.sqrt(1-(b/sma)**2)**-1)))
else:
#deriving t_sec in model from t_pri, omega and e:
r_1,r2_r1,log_sbratio,b,log_light_3,t_zero,log_period,log_q,ecc,omega,ldc_1 = best_res.x
t_sec = t_zero + np.exp(log_period)*((ecc*(1+np.sqrt(1-(b/sma)**2)**-1))*np.cos(omega)/np.pi + 0.5)
sma=((6.67e-11*(1+np.exp(log_q))*Ms[0]*1.96e30*(np.exp(log_period)*86400)**2)/(4*np.pi**2))**(1/3),
newres={"final_EBmodel":EBmodel(best_res['x'],lc['time'],Ms[0]),
"final_pars":best_res.x,"final_lnprior":EB_modelPriors(best_res.x,init_uniform_priors),
"final_lnprob":log_likelihood_EBmodel(best_res.x, lc['time'][lc['mask']],
lc['flux_flat'][lc['mask']]-np.nanmedian(lc['flux_flat'][lc['mask']]),
lc['flux_err'][lc['mask']],Ms[0]),
"R_1":r_1,"R_2":r_1*r2_r1,"R2_R1":np.exp(r2_r1),
"sbratio":np.exp(log_sbratio),"light_3":np.exp(log_light_3),"ldc_1":ldc_1,
"sma":sma,"sma_R1":sma/(r_1*6.955e8),
"ecc":ecc,"omega":omega,"t_sec":t_sec,
"b":b,"incl":np.arccos(b/sma)*(180/np.pi),"tcen":t_zero,"period":np.exp(log_period),
"M_1":Ms[0],"M_2":np.exp(log_q)*Ms[0],"q":np.exp(log_q),
"T_1":Teffs[0],"T_2":Teffs[0]*np.exp(log_sbratio)**(1/4),
"init_EBmodel":EBmodel(init_params_0,lc['time'],Ms[0]),'init_pars':init_params_0}
newres['uniform_priors']=init_uniform_priors;newres['init_lnprior']=EB_modelPriors(init_params_0,init_uniform_priors)
newres['init_prob']=log_likelihood_EBmodel(init_params_0, lc['time'][lc['mask']],
lc['flux_flat'][lc['mask']]-np.nanmedian(lc['flux_flat'][lc['mask']]),
lc['flux_err'][lc['mask']],Ms[0])
return newres,all_models
def CutAnomDiff(flux,thresh=4.2):
#Uses differences between points to establish anomalies.
#Only removes single points with differences to both neighbouring points greater than threshold above median difference (ie ~rms)
#Fast: 0.05s for 1 million-point array.
#Must be nan-cut first
diffarr=np.vstack((np.diff(flux[1:]),np.diff(flux[:-1])))
diffarr/=np.median(abs(diffarr[0,:]))
#Adding a test for the first and last points if they are >3*thresh from median RMS wrt next two points.
anoms=np.hstack((abs(flux[0]-np.median(flux[1:3]))<(np.median(abs(diffarr[0,:]))*thresh*5),
((diffarr[0,:]*diffarr[1,:])>0)+(abs(diffarr[0,:])<thresh)+(abs(diffarr[1,:])<thresh),
abs(flux[-1]-np.median(flux[-3:-1]))<(np.median(abs(diffarr[0,:]))*thresh*5)))
return anoms
def get_interpmodels(Rs,Ms,Teff,lc_time,lc_flux_unit,mission='tess',n_durs=3,gap_thresh=2.0,texp=None):
#Uses radius, mass and lightcurve duration to create fake transit models to use in monotransit search
if texp is None:
texp=np.nanmedian(np.diff(lc_time))
u_star = tools.getLDs(Teff,logg=np.log10(Ms/Rs**2)+4.431,FeH=0.0)[0]
#Computing monotransit minimum P from which to estimate durations:
cadence=np.nanmedian(np.diff(lc_time))
jumps=np.hstack((0,np.where(np.diff(lc_time)>gap_thresh)[0],len(lc_time)-1))
#Using the maximum uninterupted patch of lightcurve as the period guess:
P_guess=np.clip(np.max(lc_time[jumps[1:]]-lc_time[jumps[:-1]]),5.0,250)
#print(jumps,jumps[np.argmax(np.diff(jumps))],jumps[1+np.argmax(np.diff(jumps))],P_guess)
# Orbit models - for every n_dur over 4, we add longer durations to check:
per_steps=np.logspace(np.log10(0.4)-0.03*np.clip(n_durs-9,0.0,7.0),np.log10(2.5+0.33*np.clip(n_durs-4,0.0,2.0)),n_durs)
b_steps=np.linspace(0.88,0,n_durs)
orbits = xo.orbits.KeplerianOrbit(r_star=Rs,m_star=Ms,period=P_guess*per_steps,t0=np.tile(0.0,n_durs),b=b_steps)
vx, vy, vz = orbits.get_relative_velocity(0.0)
tdurs=((2*1.1*np.clip(Rs,0.1,10)*np.sqrt(1-b_steps**2))/tt.sqrt(vx**2 + vy**2)).eval().ravel()
# Compute the model light curve using starry
interpt=np.linspace(-0.6*np.max(tdurs),0.6*np.max(tdurs),600).astype(np.float64)
ys=xo.LimbDarkLightCurve(u_star).get_light_curve(orbit=orbits, r=np.tile(0.1*np.clip(Rs,0.1,10),n_durs),
t=interpt, texp=texp
).eval()/lc_flux_unit
interpmodels=[]
for row in range(n_durs):
interpmodels+=[interp.interp1d(interpt.astype(float).ravel(),ys[:,row].astype(float).ravel(),
bounds_error=False,fill_value=(0.0,0.0),kind = 'cubic')]
return interpmodels,tdurs
def VetCand(pl_dic,pl,ID,lc,mission,Rs=1.0,Ms=1.0,Teff=5800,
mono_SNR_thresh=6.5,mono_SNR_r_thresh=5,variable_llk_thresh=5,
plot=False,file_loc=None,vet_do_fit=True,return_fit_lcs=False,do_cent=True,**kwargs):
#Best-fit model params for the mono transit:
if pl_dic['orbit_flag']=='mono' and vet_do_fit:
#Making sure our lightcurve mask isn't artificially excluding in-transit points:
in_trans=abs(lc['time']-pl_dic['tcen'])<(0.6*pl_dic['tdur'])
lc['mask'][in_trans]=np.isfinite(lc['flux'][in_trans])& | np.isfinite(lc['flux_err'][in_trans]) | numpy.isfinite |
'''
Copyright (c) 2021 <NAME>
Classify climate databases
'''
import pickle
import h5py
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from pyjets.averages import get_avg_mag, get_avg_lat, get_avg_lon
from pyjets.classifiers import fulldataset_selected, classify_composite
from pyjets.plots_misc import plot_onemonth
from pyjets.read_nc import find_file
from pyjets.standard_method import standard
from setup_pyjets import *
def pnj_classify(classify_model, classify_period, plot_path_d):
''' ua and other data '''
file = find_file('ua', file_path_h5, classify_level, classify_model, classify_period)
h5file = h5py.File(file_path_h5 + file, 'r')
nc_lat_data = h5file['nc_lat_data'][:]
nc_lon_data = h5file['nc_lon_data'][:]
ua2classify = h5file['x_data_sel'][:]
grid_type = h5file['grid_type'][()]
if not isinstance(grid_type, str):
grid_type = h5file['grid_type'][()].decode("utf-8")
h5file.close()
'''zg data'''
file = find_file('zg', file_path_h5, classify_level, classify_model, classify_period)
h5file = h5py.File(file_path_h5 + file, 'r')
zg_data = h5file['x_data_sel'][:]
h5file.close()
nmonths = ua2classify.shape[0]
month2classify = np.arange(0, nmonths)
# month2classify = np.arange(0, 6) # solo para pruebas
seedsx = []
seedsy = []
for idx, month in enumerate(month2classify):
img = ua2classify[idx, :, :] + abs(np.min(ua2classify[idx, :, :]))
seed_x, seed_y = np.where(img == np.max(img))
seedsx.append(seed_x[0].item())
seedsy.append(seed_y[0].item())
'''Feature 1 for classification'''
x1 = | np.zeros_like(ua2classify) | numpy.zeros_like |
"""
Utility functions for the validation scripts.
"""
from htof.parse import DataParser, HipparcosOriginalData, HipparcosRereductionDVDBook, HipparcosRereductionJavaTool
from htof.fit import AstrometricFitter
from htof.sky_path import parallactic_motion, earth_ephemeris
from astropy import time
from astropy.coordinates import Angle
from astropy.table import Table
from glob import glob
import os
import warnings
import numpy as np
def refit_hip_fromdata(data: DataParser, fit_degree, cntr_RA=Angle(0, unit='degree'), cntr_Dec=Angle(0, unit='degree'),
use_parallax=False):
data.calculate_inverse_covariance_matrices()
# generate parallax motion
jyear_epoch = time.Time(data.julian_day_epoch(), format='jd', scale='tcb').jyear
# note that ra_motion and dec_motion are in degrees here.
# generate sky path
year_epochs = jyear_epoch - time.Time(1991.25, format='decimalyear', scale='tcb').jyear
ra_motion, dec_motion = parallactic_motion(jyear_epoch, cntr_RA.degree, cntr_Dec.degree, 'degree',
time.Time(1991.25, format='decimalyear', scale='tcb').jyear,
ephemeris=earth_ephemeris) # Hipparcos was in a geostationary orbit.
ra_resid = Angle(data.residuals.values * np.sin(data.scan_angle.values), unit='mas')
dec_resid = Angle(data.residuals.values * np.cos(data.scan_angle.values), unit='mas')
# instantiate fitter
fitter = AstrometricFitter(data.inverse_covariance_matrix, year_epochs,
use_parallax=use_parallax, fit_degree=fit_degree,
parallactic_pertubations={'ra_plx': Angle(ra_motion, 'degree').mas,
'dec_plx': Angle(dec_motion, 'degree').mas})
fit_coeffs, errors, chisq = fitter.fit_line(ra_resid.mas, dec_resid.mas, return_all=True)
parallax_factors = ra_motion * np.sin(data.scan_angle.values) + dec_motion * np.cos(data.scan_angle.values)
# technically this could be data.parallax_factors.values, but then we have to deal with
# getting the RA and Dec components of that.
if not use_parallax:
fit_coeffs = np.hstack([[0], fit_coeffs])
errors = | np.hstack([[0], errors]) | numpy.hstack |
"""
author: <NAME>
"""
import numpy as np
import time
import copy
from numba import njit
from numba.typed import List
from gglasso.solver.ggl_helper import phiplus, prox_od_1norm, prox_2norm, prox_rank_norm
from gglasso.helper.ext_admm_helper import check_G
def ext_ADMM_MGL(S, lambda1, lambda2, reg , Omega_0, G,\
X0 = None, X1 = None, tol = 1e-5 , rtol = 1e-4, stopping_criterion = 'boyd',\
rho= 1., max_iter = 1000, verbose = False, measure = False, latent = False, mu1 = None):
"""
This is an ADMM algorithm for solving the Group Graphical Lasso problem
where not all instances have the same number of dimensions, i.e. some variables are present in some instances and not in others.
A group sparsity penalty is applied to all pairs of variables present in multiple instances.
IMPORTANT: As the arrays are non-conforming in dimensions here, we operate on dictionaries with keys 1,..,K (as int) and each value is a array of shape :math:`(p_k,p_k)`.
If ``latent=False``, this function solves
.. math::
\min_{\Omega,\Theta,\Lambda} \sum_{k=1}^K - \log \det(\Omega^{(k)}) + \mathrm{Tr}(S^{(k)}\Omega^{(k)}) + \sum_{k=1}^K \lambda_1 ||\Theta^{(k)}||_{1,od}
+ \sum_{l} \lambda_2 \\beta_l ||\Lambda_{[l]}||_2
s.t. \quad \Omega^{(k)} = \Theta^{(k)} \quad k=1,\dots,K
\quad \quad \Lambda^{(k)} = \Theta^{(k)} \quad k=1,\dots,K
where l indexes the groups of overlapping variables and :math:`\Lambda_{[l]}` is the array of all respective components.
To account for differing group sizes we multiply with :math:`\\beta_l`, the square root of the group size.
If ``latent=True``, this function solves
.. math::
\min_{\Omega,\Theta,\Lambda,L} \sum_{k=1}^K - \log \det(\Omega^{(k)}) + \mathrm{Tr}(S^{(k)}\Omega^{(k)}) + \sum_{k=1}^K \lambda_1 ||\Theta^{(k)}||_{1,od}
+ \sum_{l} \lambda_2 \\beta_l ||\Lambda_{[l]}||_2 +\sum_{k=1}^{K} \mu_{1,k} \|L^{(k)}\|_{\star}
s.t. \quad \Omega^{(k)} = \Theta^{(k)} - L^{(k)} \quad k=1,\dots,K
\quad \quad \Lambda^{(k)} = \Theta^{(k)} \quad k=1,\dots,K
Note:
* Typically, ``sol['Omega']`` is positive definite and ``sol['Theta']`` is sparse.
* We use scaled ADMM, i.e. X0 and X1 are the scaled (with 1/rho) dual variables for the equality constraints.
Parameters
----------
S : dict
empirical covariance matrices. S should have keys 1,..,K (as integers) and S[k] contains the :math:`(p_k,p_k)`-array of the empirical cov. matrix of the k-th instance.
Each S[k] needs to be symmetric and positive semidefinite.
lambda1 : float, positive
sparsity regularization parameter.
lambda2 : float, positive
group sparsity regularization parameter.
reg : str
so far only Group Graphical Lasso is available, hence choose 'GGL'.
Omega_0 : dict
starting point for the Omega variable. Should be of same form as S. If no better starting point is available, choose
Omega_0[k] = np.eye(p_k) for k=1,...,K
G : array
bookkeeping arrays which contains information where the respective entries for each group can be found.
X0 : dict, optional
starting point for the X0 variable. If not specified, it is set to zeros.
X1 : dict, optional
starting point for the X1 variable. If not specified, it is set to zeros.
rho : float, positive, optional
step size paramater for the augmented Lagrangian in ADMM. The default is 1. Tune this parameter for optimal performance.
max_iter : int, optional
maximum number of iterations. The default is 1000.
tol : float, positive, optional
tolerance for the primal residual. See "Distributed Optimization and Statistical Learning via the Alternating Direction Method of Multipliers", Boyd et al. for details.
The default is 1e-7.
rtol : float, positive, optional
tolerance for the dual residual. The default is 1e-4.
stopping_criterion : str, optional
* 'boyd': Stopping criterion after Boyd et al.
* 'kkt': KKT residual is chosen as stopping criterion. This is computationally expensive to compute.
The default is 'boyd'.
verbose : boolean, optional
verbosity of the solver. The default is False.
measure : boolean, optional
turn on/off measurements of runtime per iteration. The default is False.
latent : boolean, optional
Solve the GGL problem with or without latent variables (see above for the exact formulations).
The default is False.
mu1 : float, positive, optional
low-rank regularization parameter, possibly different for each instance k=1,..,K. Only needs to be specified if latent=True.
Returns
-------
sol : dict
contains the solution, i.e. Omega, Theta, X0, X1 (and L if latent=True) after termination. All elements are dictionaries with keys 1,..,K and (p_k,p_k)-arrays as values.
info : dict
status and measurement information from the solver.
"""
K = len(S.keys())
p = np.zeros(K, dtype= int)
for k in np.arange(K):
p[k] = S[k].shape[0]
if type(lambda1) == np.float64 or type(lambda1) == float:
lambda1 = lambda1*np.ones(K)
if latent:
if type(mu1) == np.float64 or type(mu1) == float:
mu1 = mu1*np.ones(K)
assert mu1 is not None
assert np.all(mu1 > 0)
assert min(lambda1.min(), lambda2) > 0
assert reg in ['GGL']
check_G(G, p)
assert rho > 0, "ADMM penalization parameter must be positive."
# initialize
Omega_t = Omega_0.copy()
Theta_t = Omega_0.copy()
L_t = dict()
for k in np.arange(K):
L_t[k] = np.zeros((p[k],p[k]))
# helper and dual variables
Lambda_t = Omega_0.copy()
Z_t = dict()
if X0 is None:
X0_t = dict()
for k in np.arange(K):
X0_t[k] = np.zeros((p[k],p[k]))
else:
X0_t = X0.copy()
if X1 is None:
X1_t = dict()
for k in np.arange(K):
X1_t[k] = np.zeros((p[k],p[k]))
else:
X1_t = X1.copy()
runtime = np.zeros(max_iter)
residual = np.zeros(max_iter)
status = ''
if verbose:
print("------------ADMM Algorithm for Multiple Graphical Lasso----------------")
if stopping_criterion == 'boyd':
hdr_fmt = "%4s\t%10s\t%10s\t%10s\t%10s"
out_fmt = "%4d\t%10.4g\t%10.4g\t%10.4g\t%10.4g"
print(hdr_fmt % ("iter", "r_t", "s_t", "eps_pri", "eps_dual"))
elif stopping_criterion == 'kkt':
hdr_fmt = "%4s\t%10s"
out_fmt = "%4d\t%10.4g"
print(hdr_fmt % ("iter", "kkt residual"))
##################################################################
### MAIN LOOP STARTS
##################################################################
for iter_t in np.arange(max_iter):
if measure:
start = time.time()
# Omega Update
Omega_t_1 = Omega_t.copy()
for k in np.arange(K):
W_t = Theta_t[k] - L_t[k] - X0_t[k] - (1/rho) * S[k]
eigD, eigQ = np.linalg.eigh(W_t)
Omega_t[k] = phiplus(beta = 1/rho, D = eigD, Q = eigQ)
# Theta Update
for k in np.arange(K):
V_t = (Omega_t[k] + L_t[k] + X0_t[k] + Lambda_t[k] - X1_t[k]) * 0.5
Theta_t[k] = prox_od_1norm(V_t, lambda1[k]/(2*rho))
#L Update
if latent:
for k in np.arange(K):
C_t = Theta_t[k] - X0_t[k] - Omega_t[k]
C_t = (C_t.T + C_t)/2
eigD, eigQ = np.linalg.eigh(C_t)
L_t[k] = prox_rank_norm(C_t, mu1[k]/rho, D = eigD, Q = eigQ)
# Lambda Update
Lambda_t_1 = Lambda_t.copy()
for k in np.arange(K):
Z_t[k] = Theta_t[k] + X1_t[k]
Lambda_t = prox_2norm_G(Z_t, G, lambda2/rho)
# X Update
for k in np.arange(K):
X0_t[k] += Omega_t[k] - Theta_t[k] + L_t[k]
X1_t[k] += Theta_t[k] - Lambda_t[k]
if measure:
end = time.time()
runtime[iter_t] = end-start
# Stopping condition
if stopping_criterion == 'boyd':
r_t,s_t,e_pri,e_dual = ADMM_stopping_criterion(Omega_t, Omega_t_1, Theta_t, L_t, Lambda_t, Lambda_t_1, X0_t, X1_t,\
S, rho, p, tol, rtol, latent)
residual[iter_t] = max(r_t,s_t)
if verbose:
print(out_fmt % (iter_t,r_t,s_t,e_pri,e_dual))
if (r_t <= e_pri) and (s_t <= e_dual):
status = 'optimal'
break
elif stopping_criterion == 'kkt':
eta_A = kkt_stopping_criterion(Omega_t, Theta_t, L_t, Lambda_t, dict((k, rho*v) for k,v in X0_t.items()), dict((k, rho*v) for k,v in X1_t.items()),\
S , G, lambda1, lambda2, reg, latent, mu1)
residual[iter_t] = eta_A
if verbose:
print(out_fmt % (iter_t,eta_A))
if eta_A <= tol:
status = 'optimal'
break
##################################################################
### MAIN LOOP FINISHED
##################################################################
# retrieve status (partially optimal or max iter)
if status != 'optimal':
if stopping_criterion == 'boyd':
if (r_t <= e_pri):
status = 'primal optimal'
elif (s_t <= e_dual):
status = 'dual optimal'
else:
status = 'max iterations reached'
else:
status = 'max iterations reached'
print(f"ADMM terminated after {iter_t+1} iterations with status: {status}.")
for k in np.arange(K):
assert abs(Omega_t[k].T - Omega_t[k]).max() <= 1e-5, "Solution is not symmetric"
assert abs(Theta_t[k].T - Theta_t[k]).max() <= 1e-5, "Solution is not symmetric"
assert abs(L_t[k].T - L_t[k]).max() <= 1e-5, "Solution is not symmetric"
D = np.linalg.eigvalsh(Theta_t[k]-L_t[k])
if D.min() <= 1e-5:
print("WARNING: Theta (Theta-L resp.) may be not positive definite -- increase accuracy!")
if latent:
D = np.linalg.eigvalsh(L_t[k])
if D.min() <= -1e-5:
print("WARNING: L may be not positive semidefinite -- increase accuracy!")
sol = {'Omega': Omega_t, 'Theta': Theta_t, 'L': L_t, 'X0': X0_t, 'X1': X1_t}
if measure:
info = {'status': status , 'runtime': runtime[:iter_t+1], 'residual': residual[:iter_t+1]}
else:
info = {'status': status}
return sol, info
def ADMM_stopping_criterion(Omega, Omega_t_1, Theta, L, Lambda, Lambda_t_1, X0, X1, S, rho, p, eps_abs, eps_rel, latent=False):
# X0, X1 are inputed as scaled dual vars., this is accounted for by factor rho in e_dual
K = len(S.keys())
if not latent:
for k in np.arange(K):
assert np.all(L[k]==0)
dim = ((p ** 2 + p) / 2).sum() # number of elements of off-diagonal matrix
D1 = np.sqrt(sum([np.linalg.norm(Omega[k])**2 + np.linalg.norm(Lambda[k])**2 for k in np.arange(K)] ))
D2 = np.sqrt(sum([np.linalg.norm(Theta[k] - L[k])**2 + np.linalg.norm(Theta[k])**2 for k in np.arange(K)] ))
D3 = np.sqrt(sum([np.linalg.norm(X0[k])**2 + np.linalg.norm(X1[k])**2 for k in np.arange(K)] ))
e_pri = dim * eps_abs + eps_rel * np.maximum(D1, D2)
e_dual = dim * eps_abs + eps_rel * rho * D3
r = np.sqrt(sum([ | np.linalg.norm(Omega[k] - Theta[k] + L[k]) | numpy.linalg.norm |
def as_partitioning(power_plant_inputs):
from apcd_partitioning_dictionaries import as_dict
import numpy as np
arsenic_input = power_plant_inputs.Share_Arsenic
pm_control = power_plant_inputs.PM_Control
so2_control = power_plant_inputs.SO2_Control
nox_control = power_plant_inputs.NOx_Control
hg_control = power_plant_inputs.Hg_Control
sorbent = power_plant_inputs.DSI_Usage
#Boiler Partitioning
bottom_ash_solid = arsenic_input * np.mean(as_dict['Bottom_Ash']['solid'])
bottom_ash_liquid = arsenic_input * np.mean(as_dict['Bottom_Ash']['liquid'])
bottom_ash_gas = arsenic_input * np.mean(as_dict['Bottom_Ash']['gas'])
#SCR Partitioning
scr_solid = bottom_ash_gas * np.mean(as_dict[nox_control]['solid'])
scr_liquid = bottom_ash_gas * np.mean(as_dict[nox_control]['liquid'])
scr_gas = bottom_ash_gas * np.mean(as_dict[nox_control]['gas'])
#ACI Partitioning
aci_solid = scr_gas * np.mean(as_dict[hg_control]['solid'])
aci_liquid = scr_gas * np.mean(as_dict[hg_control]['liquid'])
aci_gas = scr_gas * np.mean(as_dict[hg_control]['gas'])
#DSI Partitioning
dsi_solid = aci_gas * np.mean(as_dict[sorbent]['solid'])
dsi_liquid = aci_gas * np.mean(as_dict[sorbent]['liquid'])
dsi_gas = aci_gas * np.mean(as_dict[sorbent]['gas'])
#Partitioning in PM Control Systems
pm_solid = dsi_gas * np.mean(as_dict[pm_control]['solid'])
pm_liquid = dsi_gas * np.mean(as_dict[pm_control]['liquid'])
pm_gas = dsi_gas * np.mean(as_dict[pm_control]['gas'])
#Partitioning in SO2 Control Systems
so2_solid = pm_gas * np.mean(as_dict[so2_control]['solid'])
so2_liquid = pm_gas * np.mean(as_dict[so2_control]['liquid'])
so2_gas = pm_gas * np.mean(as_dict[so2_control]['gas'])
#Calucalate total partitioning
as_solid = bottom_ash_solid + scr_solid + aci_solid + pm_solid + dsi_solid + so2_solid
as_liquid = bottom_ash_liquid + scr_liquid + aci_liquid + pm_liquid + dsi_liquid + so2_liquid
as_gas = so2_gas
return as_solid, as_liquid, as_gas
def cl_partitioning(power_plant_inputs):
from apcd_partitioning_dictionaries import cl_dict
import numpy as np
chlorine_input = power_plant_inputs.Share_Chloride
pm_control = power_plant_inputs.PM_Control
so2_control = power_plant_inputs.SO2_Control
nox_control = power_plant_inputs.NOx_Control
hg_control = power_plant_inputs.Hg_Control
sorbent = power_plant_inputs.DSI_Usage
#Boiler Partitioning
bottom_ash_solid = chlorine_input * np.mean(cl_dict['Bottom_Ash']['solid'])
bottom_ash_liquid = chlorine_input * np.mean(cl_dict['Bottom_Ash']['liquid'])
bottom_ash_gas = chlorine_input * np.mean(cl_dict['Bottom_Ash']['gas'])
#SCR Partitioning
scr_solid = bottom_ash_gas * np.mean(cl_dict[nox_control]['solid'])
scr_liquid = bottom_ash_gas * np.mean(cl_dict[nox_control]['liquid'])
scr_gas = bottom_ash_gas * np.mean(cl_dict[nox_control]['gas'])
#ACI Partitioning
aci_solid = scr_gas * np.mean(cl_dict[hg_control]['solid'])
aci_liquid = scr_gas * np.mean(cl_dict[hg_control]['liquid'])
aci_gas = scr_gas * np.mean(cl_dict[hg_control]['gas'])
#DSI Partitioning
dsi_solid = aci_gas * np.mean(cl_dict[sorbent]['solid'])
dsi_liquid = aci_gas * np.mean(cl_dict[sorbent]['liquid'])
dsi_gas = aci_gas * np.mean(cl_dict[sorbent]['gas'])
#Partitioning in PM Control Systems
pm_solid = dsi_gas * np.mean(cl_dict[pm_control]['solid'])
pm_liquid = dsi_gas * np.mean(cl_dict[pm_control]['liquid'])
pm_gas = dsi_gas * np.mean(cl_dict[pm_control]['gas'])
#Partitioning in SO2 Control Systems
so2_solid = pm_gas * np.mean(cl_dict[so2_control]['solid'])
so2_liquid = pm_gas * np.mean(cl_dict[so2_control]['liquid'])
so2_gas = pm_gas * np.mean(cl_dict[so2_control]['gas'])
#Calucalate total partitioning
cl_solid = bottom_ash_solid + scr_solid + aci_solid + dsi_solid + pm_solid + so2_solid
cl_liquid = bottom_ash_liquid + scr_liquid + aci_liquid + dsi_liquid + pm_liquid + so2_liquid
cl_gas = so2_gas
return cl_solid, cl_liquid, cl_gas
def se_partitioning(power_plant_inputs):
from apcd_partitioning_dictionaries import se_dict
import numpy as np
selenium_input = power_plant_inputs.Share_Selenium
pm_control = power_plant_inputs.PM_Control
so2_control = power_plant_inputs.SO2_Control
nox_control = power_plant_inputs.NOx_Control
hg_control = power_plant_inputs.Hg_Control
sorbent = power_plant_inputs.DSI_Usage
#Boiler Partitioning
bottom_ash_solid = selenium_input * np.mean(se_dict['Bottom_Ash']['solid'])
bottom_ash_liquid = selenium_input * np.mean(se_dict['Bottom_Ash']['liquid'])
bottom_ash_gas = selenium_input * np.mean(se_dict['Bottom_Ash']['gas'])
#SCR Partitioning
scr_solid = bottom_ash_gas * np.mean(se_dict[nox_control]['solid'])
scr_liquid = bottom_ash_gas * np.mean(se_dict[nox_control]['liquid'])
scr_gas = bottom_ash_gas * np.mean(se_dict[nox_control]['gas'])
#ACI Partitioning
aci_solid = scr_gas * np.mean(se_dict[hg_control]['solid'])
aci_liquid = scr_gas * np.mean(se_dict[hg_control]['liquid'])
aci_gas = scr_gas * np.mean(se_dict[hg_control]['gas'])
#DSI Partitioning
dsi_solid = aci_gas * np.mean(se_dict[sorbent]['solid'])
dsi_liquid = aci_gas * np.mean(se_dict[sorbent]['liquid'])
dsi_gas = aci_gas * np.mean(se_dict[sorbent]['gas'])
#Partitioning in PM Control Systems
pm_solid = dsi_gas * np.mean(se_dict[pm_control]['solid'])
pm_liquid = dsi_gas * np.mean(se_dict[pm_control]['liquid'])
pm_gas = dsi_gas * np.mean(se_dict[pm_control]['gas'])
#Partitioning in SO2 Control Systems
so2_solid = pm_gas * np.mean(se_dict[so2_control]['solid'])
so2_liquid = pm_gas * np.mean(se_dict[so2_control]['liquid'])
so2_gas = pm_gas * np.mean(se_dict[so2_control]['gas'])
#Calucalate total partitioning
se_solid = bottom_ash_solid + scr_solid + aci_solid + dsi_solid + pm_solid + so2_solid
se_liquid = bottom_ash_liquid + scr_liquid + aci_liquid + dsi_liquid + pm_liquid + so2_liquid
se_gas = so2_gas
return se_solid, se_liquid, se_gas
def hg_partitioning(power_plant_inputs):
from apcd_partitioning_dictionaries import hg_dict
import numpy as np
mercury_input = power_plant_inputs.Share_Mercury
pm_control = power_plant_inputs.PM_Control
so2_control = power_plant_inputs.SO2_Control
nox_control = power_plant_inputs.NOx_Control
hg_control = power_plant_inputs.Hg_Control
sorbent = power_plant_inputs.DSI_Usage
#Boiler Partitioning
bottom_ash_solid = mercury_input * np.mean(hg_dict['Bottom_Ash']['solid'])
bottom_ash_liquid = mercury_input * np.mean(hg_dict['Bottom_Ash']['liquid'])
bottom_ash_gas = mercury_input * np.mean(hg_dict['Bottom_Ash']['gas'])
#SCR Partitioning
scr_solid = bottom_ash_gas * np.mean(hg_dict[nox_control]['solid'])
scr_liquid = bottom_ash_gas * np.mean(hg_dict[nox_control]['liquid'])
scr_gas = bottom_ash_gas * np.mean(hg_dict[nox_control]['gas'])
#ACI Partitioning
aci_solid = scr_gas * np.mean(hg_dict[hg_control]['solid'])
aci_liquid = scr_gas * np.mean(hg_dict[hg_control]['liquid'])
aci_gas = scr_gas * np.mean(hg_dict[hg_control]['gas'])
#DSI Partitioning
dsi_solid = aci_gas * np.mean(hg_dict[sorbent]['solid'])
dsi_liquid = aci_gas * np.mean(hg_dict[sorbent]['liquid'])
dsi_gas = aci_gas * np.mean(hg_dict[sorbent]['gas'])
#Partitioning in PM Control Systems
pm_solid = dsi_gas * np.mean(hg_dict[pm_control]['solid'])
pm_liquid = dsi_gas * np.mean(hg_dict[pm_control]['liquid'])
pm_gas = dsi_gas * np.mean(hg_dict[pm_control]['gas'])
#Partitioning in SO2 Control Systems
so2_solid = pm_gas * np.mean(hg_dict[so2_control]['solid'])
so2_liquid = pm_gas * np.mean(hg_dict[so2_control]['liquid'])
so2_gas = pm_gas * np.mean(hg_dict[so2_control]['gas'])
#Calucalate total partitioning
hg_solid = bottom_ash_solid + scr_solid + aci_solid + dsi_solid + pm_solid + so2_solid
hg_liquid = bottom_ash_liquid + scr_liquid + aci_liquid + dsi_liquid + pm_liquid + so2_liquid
hg_gas = so2_gas
return hg_solid, hg_liquid, hg_gas
def br_partitioning(power_plant_inputs):
from apcd_partitioning_dictionaries import br_dict
import numpy as np
bromine_input = power_plant_inputs.Share_Bromide
pm_control = power_plant_inputs.PM_Control
so2_control = power_plant_inputs.SO2_Control
nox_control = power_plant_inputs.NOx_Control
hg_control = power_plant_inputs.Hg_Control
sorbent = power_plant_inputs.DSI_Usage
#Boiler Partitioning
bottom_ash_solid = bromine_input * np.mean(br_dict['Bottom_Ash']['solid'])
bottom_ash_liquid = bromine_input * np.mean(br_dict['Bottom_Ash']['liquid'])
bottom_ash_gas = bromine_input * np.mean(br_dict['Bottom_Ash']['gas'])
#SCR Partitioning
scr_solid = bottom_ash_gas * np.mean(br_dict[nox_control]['solid'])
scr_liquid = bottom_ash_gas * np.mean(br_dict[nox_control]['liquid'])
scr_gas = bottom_ash_gas * np.mean(br_dict[nox_control]['gas'])
#ACI Partitioning
aci_solid = scr_gas * np.mean(br_dict[hg_control]['solid'])
aci_liquid = scr_gas * np.mean(br_dict[hg_control]['liquid'])
aci_gas = scr_gas * np.mean(br_dict[hg_control]['gas'])
#DSI Partitioning
dsi_solid = aci_gas * np.mean(br_dict[sorbent]['solid'])
dsi_liquid = aci_gas * np.mean(br_dict[sorbent]['liquid'])
dsi_gas = aci_gas * np.mean(br_dict[sorbent]['gas'])
#Partitioning in PM Control Systems
pm_solid = dsi_gas * np.mean(br_dict[pm_control]['solid'])
pm_liquid = dsi_gas * np.mean(br_dict[pm_control]['liquid'])
pm_gas = dsi_gas * np.mean(br_dict[pm_control]['gas'])
#Partitioning in SO2 Control Systems
so2_solid = pm_gas * np.mean(br_dict[so2_control]['solid'])
so2_liquid = pm_gas * np.mean(br_dict[so2_control]['liquid'])
so2_gas = pm_gas * np.mean(br_dict[so2_control]['gas'])
#Calucalate total partitioning
br_solid = bottom_ash_solid + scr_solid + aci_solid + dsi_solid + pm_solid + so2_solid
br_liquid = bottom_ash_liquid + scr_liquid + aci_liquid + +dsi_liquid + pm_liquid + so2_liquid
br_gas = so2_gas
return br_solid, br_liquid, br_gas
def b_partitioning(power_plant_inputs):
from apcd_partitioning_dictionaries import b_dict
import numpy as np
boron_input = power_plant_inputs.Share_Boron
pm_control = power_plant_inputs.PM_Control
so2_control = power_plant_inputs.SO2_Control
nox_control = power_plant_inputs.NOx_Control
hg_control = power_plant_inputs.Hg_Control
sorbent = power_plant_inputs.DSI_Usage
#Boiler Partitioning
bottom_ash_solid = boron_input * np.mean(b_dict['Bottom_Ash']['solid'])
bottom_ash_liquid = boron_input * np.mean(b_dict['Bottom_Ash']['liquid'])
bottom_ash_gas = boron_input * np.mean(b_dict['Bottom_Ash']['gas'])
#SCR Partitioning
scr_solid = bottom_ash_gas * np.mean(b_dict[nox_control]['solid'])
scr_liquid = bottom_ash_gas * np.mean(b_dict[nox_control]['liquid'])
scr_gas = bottom_ash_gas * np.mean(b_dict[nox_control]['gas'])
#ACI Partitioning
aci_solid = scr_gas * np.mean(b_dict[hg_control]['solid'])
aci_liquid = scr_gas * np.mean(b_dict[hg_control]['liquid'])
aci_gas = scr_gas * np.mean(b_dict[hg_control]['gas'])
#DSI Partitioning
dsi_solid = aci_gas * np.mean(b_dict[sorbent]['solid'])
dsi_liquid = aci_gas * np.mean(b_dict[sorbent]['liquid'])
dsi_gas = aci_gas * np.mean(b_dict[sorbent]['gas'])
#Partitioning in PM Control Systems
pm_solid = dsi_gas * np.mean(b_dict[pm_control]['solid'])
pm_liquid = dsi_gas * np.mean(b_dict[pm_control]['liquid'])
pm_gas = dsi_gas * np.mean(b_dict[pm_control]['gas'])
#Partitioning in SO2 Control Systems
so2_solid = pm_gas * np.mean(b_dict[so2_control]['solid'])
so2_liquid = pm_gas * np.mean(b_dict[so2_control]['liquid'])
so2_gas = pm_gas * np.mean(b_dict[so2_control]['gas'])
#Calucalate total partitioning
b_solid = bottom_ash_solid + scr_solid + aci_solid + dsi_solid + pm_solid + so2_solid
b_liquid = bottom_ash_liquid + scr_liquid + aci_liquid + dsi_liquid + pm_liquid + so2_liquid
b_gas = so2_gas
return b_solid, b_liquid, b_gas
def pb_partitioning(power_plant_inputs):
from apcd_partitioning_dictionaries import pb_dict
import numpy as np
lead_input = power_plant_inputs.Share_Lead
pm_control = power_plant_inputs.PM_Control
so2_control = power_plant_inputs.SO2_Control
nox_control = power_plant_inputs.NOx_Control
hg_control = power_plant_inputs.Hg_Control
sorbent = power_plant_inputs.DSI_Usage
#Boiler Partitioning
bottom_ash_solid = lead_input * np.mean(pb_dict['Bottom_Ash']['solid'])
bottom_ash_liquid = lead_input * np.mean(pb_dict['Bottom_Ash']['liquid'])
bottom_ash_gas = lead_input * np.mean(pb_dict['Bottom_Ash']['gas'])
#SCR Partitioning
scr_solid = bottom_ash_gas * np.mean(pb_dict[nox_control]['solid'])
scr_liquid = bottom_ash_gas * np.mean(pb_dict[nox_control]['liquid'])
scr_gas = bottom_ash_gas * np.mean(pb_dict[nox_control]['gas'])
#ACI Partitioning
aci_solid = scr_gas * np.mean(pb_dict[hg_control]['solid'])
aci_liquid = scr_gas * np.mean(pb_dict[hg_control]['liquid'])
aci_gas = scr_gas * np.mean(pb_dict[hg_control]['gas'])
#DSI Partitioning
dsi_solid = aci_gas * np.mean(pb_dict[sorbent]['solid'])
dsi_liquid = aci_gas * np.mean(pb_dict[sorbent]['liquid'])
dsi_gas = aci_gas * np.mean(pb_dict[sorbent]['gas'])
#Partitioning in PM Control Systems
pm_solid = dsi_gas * np.mean(pb_dict[pm_control]['solid'])
pm_liquid = dsi_gas * np.mean(pb_dict[pm_control]['liquid'])
pm_gas = dsi_gas * | np.mean(pb_dict[pm_control]['gas']) | numpy.mean |
#!/usr/bin/python
import sys
import warnings
from time import time
from pathlib import Path
import ftplib
import pandas as pd
import numpy as np
import matplotlib.dates as mdates
from netCDF4 import Dataset
from . import util
global module_path
module_path = Path('fake_directory_name')
i = 0
while not module_path.exists():
module_path = Path(sys.path[i]) / 'bgcArgo/ref'
i += 1
def read_index(mission='B'):
'''
Function to read and extract information from Argo global index,
then save it to a dataframe for faster access
'''
if mission == 'B':
filename = module_path / 'argo_bio-profile_index.txt.gz'
elif mission == 'C':
filename = module_path / 'ar_index_global_prof.txt.gz'
elif mission == 'S':
filename = module_path / 'argo_synthetic-profile_index.txt.gz'
df = pd.read_csv(filename, compression='gzip', header=8)
df['dac'] = np.array([f.split('/')[0] for f in df.file])
df['wmo'] = np.array([int(f.split('/')[1]) for f in df.file])
df['cycle'] = np.array([int(f.split('/')[-1].split('.')[-2].split('_')[-1].replace('D','')) for f in df.file])
return df
def update_index(ftype=None):
'''
Function to access FTP server to download Argo metadata and profile global
index files
'''
ftp = ftplib.FTP('ftp.ifremer.fr')
ftp.login()
ftp.cwd('/ifremer/argo/')
meta = 'ar_index_global_meta.txt.gz'
index = 'ar_index_global_prof.txt.gz'
bgc = 'argo_bio-profile_index.txt.gz'
synth = 'argo_synthetic-profile_index.txt.gz'
local_meta = module_path / meta
lf = open(local_meta, 'wb')
if ftype is None or ftype == 'meta':
ftp.retrbinary('RETR ' + meta, lf.write)
local_index = module_path / index
lf = open(local_index, 'wb')
if ftype is None or ftype =='profile':
ftp.retrbinary('RETR ' + index, lf.write)
local_bgc = module_path / bgc
lf = open(local_bgc, 'wb')
if ftype is None or ftype =='bgc':
ftp.retrbinary('RETR ' + bgc, lf.write)
local_synth = module_path / synth
lf = open(local_synth, 'wb')
if ftype is None or ftype =='synthetic':
ftp.retrbinary('RETR ' + synth, lf.write)
return ftp
def check_index(mode=None):
'''
Function to check age of Argo metadata and profile global index files,
warn if they have not been updated in more than 1 week. Runs on import.
'''
if mode is None:
meta = 'ar_index_global_meta.txt.gz'
index = 'ar_index_global_prof.txt.gz'
bgc = 'argo_bio-profile_index.txt.gz'
synth = 'argo_synthetic-profile_index.txt.gz'
local_meta = module_path / meta
local_index = module_path / index
local_bgc = module_path / bgc
local_synth = module_path / synth
meta_mtime = local_meta.stat().st_mtime
index_mtime = local_index.stat().st_mtime
bgc_mtime = local_bgc.stat().st_mtime
synth_mtime = local_index.stat().st_mtime
# get time since last update
curr_time = time()
meta_delta = curr_time - meta_mtime
index_delta = curr_time - index_mtime
bgc_delta = curr_time - bgc_mtime
synth_delta = curr_time - synth_mtime
if meta_delta / 60 / 60 / 24 > 7:
d = meta_delta / 60 / 60 / 24
warnings.warn('Argo global metadata index is more than 7 days old - has not been updated in {:d} days - consider running update_index()'.format(int(d)), Warning)
if index_delta / 60 / 60 / 24 > 7:
d = index_delta / 60 / 60 / 24
warnings.warn('Argo global profile index is more than 7 days old - has not been updated in {:d} days - consider running update_index()'.format(int(d)), Warning)
if bgc_delta / 60 / 60 / 24 > 7:
d = bgc_delta / 60 / 60 / 24
warnings.warn('Argo global BGC index is more than 7 days old - has not been updated in {:d} days - consider running update_index()'.format(int(d)), Warning)
if synth_delta / 60 / 60 / 24 > 7:
d = synth_delta / 60 / 60 / 24
warnings.warn('Argo global synthetic profile index is more than 7 days old - has not been updated in {:d} days - consider running update_index()'.format(int(d)), Warning)
elif mode == 'install':
meta = 'ar_index_global_meta.txt.gz'
index = 'ar_index_global_prof.txt.gz'
bgc = 'argo_bio-profile_index.txt.gz'
synth = 'argo_synthetic-profile_index.txt.gz'
local_meta = module_path / meta
local_index = module_path / index
local_bgc = module_path / bgc
local_synth = module_path / synth
if not ((local_meta.exists() and local_index.exists()) and (local_bgc.exists() and local_synth.exists())):
sys.stdout.write('At least one index file does not exist - downloading now - this may take some time depending on your internet connection\n')
update_index()
else:
meta_mtime = local_meta.stat().st_mtime
index_mtime = local_index.stat().st_mtime
bgc_mtime = local_bgc.stat().st_mtime
synth_mtime = local_synth.stat().st_mtime
# get time since last update
curr_time = time()
meta_delta = curr_time - meta_mtime
index_delta = curr_time - index_mtime
if meta_delta / 60 / 60 / 24 > 7:
d = meta_delta / 60 / 60 / 24
sys.stdout.write('Argo global metadata index is more than 7 days old - has not been updated in {:d} days - downloading now - this may take some time depending on your internet connection\n'.format(int(d)))
update_index(ftype='meta')
if index_delta / 60 / 60 / 24 > 7:
d = index_delta / 60 / 60 / 24
sys.stdout.write('Argo global profile index is more than 7 days old - has not been updated in {:d} days - downloading now - this may take some time depending on your internet connection\n'.format(int(d)))
update_index(ftype='profile')
if bgc_delta / 60 / 60 / 24 > 7:
d = bgc_delta / 60 / 60 / 24
sys.stdout.write('Argo global BGC index is more than 7 days old - has not been updated in {:d} days - downloading now - this may take some time depending on your internet connection\n'.format(int(d)))
update_index(ftype='bgc')
if synth_delta / 60 / 60 / 24 > 7:
d = synth_delta / 60 / 60 / 24
sys.stdout.write('Argo global synthetic profile index is more than 7 days old - has not been updates in {:d} days - downloading now - this may take some time depending on your internet connection\n'.format(int(d)))
update_index(ftype='synthetic')
def get_woa18(varname, local_path='./', ftype='netcdf', overwrite=False):
'''
Function to download WOA data for a given variable
INPUT:
varname: woa18 variable to download data for - one of:
T: temperature
S: salinity
O2: dissolved oxygen
O2sat: oxygen percent saturation
NO3: nitrate
Si: silicate
PO4: phosphate
local_path: path to save files to (inside variable folder, ex.
if local_path = '../data/woa', and varname = 'T', files
will be saved in ../data/woa/temperature/*.nc. Defaults
to current directory
ftype: file format to download, defaults to netcdf (.nc):
ascii: .dat
csv: .csv
netcdf: .nc
overwrite: boolean flag, if False, does not re-download
existing files, if true, will download no matter what,
defaults to False
OUTPUT:
ftp: the ftplib server object
AUTHOR: <NAME>
Fisheries and Oceans Canada
<EMAIL>
LAST UPDATE: 29-04-2020
CHANGE LOG:
'''
local_path = Path(local_path)
url = 'ftp.nodc.noaa.gov'
param, dtype, ftpdir = util.decode_woa_var(varname)
ftp = ftplib.FTP(url, 'anonymous', '<EMAIL>')
ftp.cwd('pub/woa/WOA18/DATA/{}/{}/{}/1.00/'.format(ftpdir, ftype, dtype))
local_path = local_path / ftpdir
if not local_path.is_dir():
local_path.mkdir()
for fn in ftp.nlst():
local_file = local_path / fn
if not local_file.exists() | overwrite:
print(local_file)
# open the local file
lf = open(local_file, 'wb')
# retrieve the file on FTP server,
ftp.retrbinary('RETR ' + fn, lf.write)
return ftp
def get_ncep(varname, local_path='./', overwrite=False):
'''
Function to download NCEP reanalysis gaussian gridded surface air
pressure data
INPUT:
varname: 'pres' (pressure) or 'rhum' (relative humidity)
or 'land' (to get land mask)
local_path: path to save files to, defaults
to current directory
overwrite: boolean flag, if False, does not re-download
existing files, if true, will download no matter what,
defaults to False
OUTPUT:
ftp: the ftplib server object
AUTHOR: <NAME>
Fisheries and Oceans Canada
<EMAIL>
LAST UPDATE: 29-04-2020
CHANGE LOG:
'''
local_path = Path(local_path)
url = 'ftp.cdc.noaa.gov'
ftp = ftplib.FTP(url, 'anonymous', '<EMAIL>')
if varname == 'pres':
ftp.cwd('Datasets/ncep.reanalysis2/gaussian_grid/')
local_path = local_path / varname
if not local_path.is_dir():
local_path.mkdir()
for yr in range(2010, 2021):
fn = 'pres.sfc.gauss.{}.nc'.format(yr)
local_file = local_path / fn
if not local_file.exists() | overwrite:
print(local_file)
# open the local file
lf = open(local_file, 'wb')
# retrieve the file on FTP server,
ftp.retrbinary('RETR ' + fn, lf.write)
elif varname == 'rhum':
ftp.cwd('Datasets/ncep.reanalysis/surface/')
local_path = local_path / varname
if not local_path.is_dir():
local_path.mkdir()
for yr in range(2010, 2021):
fn = 'rhum.sig995.{}.nc'.format(yr)
local_file = local_path / fn
if not local_file.exists() | overwrite:
print(local_file)
# open the local file
lf = open(local_file, 'wb')
# retrieve the file on FTP server,
ftp.retrbinary('RETR ' + fn, lf.write)
elif varname == 'land':
local_path = local_path / varname
if not local_path.is_dir():
local_path.mkdir()
ftp.cwd('Datasets/ncep.reanalysis2/gaussian_grid/')
fn = 'land.sfc.gauss.nc'
local_file = local_path / fn
if not local_file.exists() | overwrite:
lf = open(local_file, 'wb')
ftp.retrbinary('RETR ' + fn, lf.write)
ftp.cwd('../../ncep.reanalysis/surface/')
fn = 'land.nc'
local_file = local_path / fn
if not local_file.exists() | overwrite:
lf = open(local_file, 'wb')
ftp.retrbinary('RETR ' + fn, lf.write)
else:
raise ValueError('Invalid varname input')
return ftp
def get_argo(*args, local_path='./', url='ftp.ifremer.fr', overwrite=False, ftype=None, mission=None, mode='RD'):
'''
Function to download all data from a single float, or individual
profiles
INPUT:
Inputs may vary depending on desired performance. Multiple
arguments may be provided to download all files from a certain
float or argo defined geographical area. A single path to a
file may be provided to download that file. A list of files
may be provided as well.
overwrite: boolean flag, if False, does not re-download
existing files, if true, will download no matter what,
defaults to False
OUTPUT:
AUTHOR: <NAME>
Fisheries and Oceans Canada
<EMAIL>
LAST UPDATE: 29-04-2020
CHANGE LOG:
'''
if len(args) == 1:
local_path = Path(local_path)
ftp = ftplib.FTP(url)
ftp.login()
for a in args[0]:
# if its a file
if a[-2:] == 'nc':
# if its a profile file
if 'profiles' in a:
ftp_wmo_path = ''.join(a.split('/')[:-2])
wmo = ftp_wmo_path.split('/')[-1]
dac = ftp_wmo_path.split('/')[-2]
ftp.cwd(ftp_wmo_path)
# if not - so Sprof, Mprof, BRtraj or meta
else:
ftp_wmo_path = ''.join(a.split('/')[:-1])
wmo = ftp_wmo_path.split('/')[-1]
dac = ftp_wmo_path.split('/')[-2]
ftp.cwd(ftp_wmo_path)
# if its a float
else:
ftp_wmo_path = a
wmo = ftp_wmo_path.split('/')[-1]
dac = ftp_wmo_path.split('/')[-2]
ftp.cwd(ftp_wmo_path)
files = ftp.nlst('*.nc')
# define local location to save file
dac_path = local_path / dac
wmo_path = local_path / dac / wmo
# make the directory if it doesn't exist
if not dac_path.is_dir():
dac_path.mkdir()
if not wmo_path.is_dir():
wmo_path.mkdir()
# download the files
for fn in files:
# define the local file to have the same name as on the FTP server
wmo_file = wmo_path / fn
# only download the file if it doesn't already exist locally
if not wmo_file.exists() | overwrite:
print(wmo_file)
# open the local file
lf = open(wmo_file, 'wb')
# retrieve the file on FTP server,
ftp.retrbinary('RETR ' + fn, lf.write)
# repeat as above
if 'profiles' in ftp.nlst() and ftype != 'summary':
ftp.cwd('profiles')
if mission is None or mission == 'CB':
if mode == 'RD':
files = ftp.nlst('*.nc')
elif mode == 'R':
files = ftp.nlst('*.nc')
ix = np.array(['D' in fn for fn in files])
files = list( | np.array(files) | numpy.array |
# -*- coding: utf-8 -*-
# This file is part of the pyMOR project (http://www.pymor.org).
# Copyright 2013-2016 pyMOR developers and contributors. All rights reserved.
# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
from numbers import Number
import numpy as np
from pymor.core.interfaces import BasicInterface, abstractmethod, abstractclassmethod, abstractproperty
from pymor.vectorarrays.interfaces import VectorArrayInterface, _INDEXTYPES
class VectorInterface(BasicInterface):
"""Interface for vectors.
This Interface is intended to be used in conjunction with |ListVectorArray|.
All pyMOR algorithms operate on |VectorArrays| instead of single vectors!
All methods of the interface have a direct counterpart in the |VectorArray|
interface.
"""
@abstractclassmethod
def make_zeros(cls, subtype=None):
pass
@classmethod
def from_data(cls, data, subtype):
raise NotImplementedError
@abstractproperty
def dim(self):
pass
@property
def subtype(self):
return None
@abstractmethod
def copy(self, deep=False):
pass
@abstractmethod
def scal(self, alpha):
pass
@abstractmethod
def axpy(self, alpha, x):
pass
@abstractmethod
def dot(self, other):
pass
@abstractmethod
def l1_norm(self):
pass
@abstractmethod
def l2_norm(self):
pass
@abstractmethod
def l2_norm2(self):
pass
def sup_norm(self):
if self.dim == 0:
return 0.
else:
_, max_val = self.amax()
return max_val
@abstractmethod
def components(self, component_indices):
pass
@abstractmethod
def amax(self):
pass
def __add__(self, other):
result = self.copy()
result.axpy(1, other)
return result
def __iadd__(self, other):
self.axpy(1, other)
return self
__radd__ = __add__
def __sub__(self, other):
result = self.copy()
result.axpy(-1, other)
return result
def __isub__(self, other):
self.axpy(-1, other)
return self
def __mul__(self, other):
result = self.copy()
result.scal(other)
return result
def __imul__(self, other):
self.scal(other)
return self
def __neg__(self):
result = self.copy()
result.scal(-1)
return result
class CopyOnWriteVector(VectorInterface):
@abstractclassmethod
def from_instance(cls, instance):
pass
@abstractmethod
def _copy_data(self):
pass
@abstractmethod
def _scal(self, alpha):
pass
@abstractmethod
def _axpy(self, alpha, x):
pass
def copy(self, deep=False):
c = self.from_instance(self)
if deep:
c._copy_data()
else:
try:
self._refcount[0] += 1
except AttributeError:
self._refcount = [2]
c._refcount = self._refcount
return c
def scal(self, alpha):
self._copy_data_if_needed()
self._scal(alpha)
def axpy(self, alpha, x):
self._copy_data_if_needed()
self._axpy(alpha, x)
def __del__(self):
try:
self._refcount[0] -= 1
except AttributeError:
pass
def _copy_data_if_needed(self):
try:
if self._refcount[0] > 1:
self._refcount[0] -= 1
self._copy_data()
self._refcount = [1]
except AttributeError:
self._refcount = [1]
class NumpyVector(CopyOnWriteVector):
"""Vector stored in a NumPy 1D-array."""
def __init__(self, instance, dtype=None, copy=False, order=None, subok=False):
if isinstance(instance, np.ndarray) and not copy:
self._array = instance
else:
self._array = np.array(instance, dtype=dtype, copy=copy, order=order, subok=subok, ndmin=1)
assert self._array.ndim == 1
@classmethod
def from_instance(cls, instance):
return cls(instance._array)
@classmethod
def make_zeros(cls, subtype=None):
assert isinstance(subtype, Number)
return NumpyVector(np.zeros(subtype))
@classmethod
def from_data(cls, data, subtype):
assert isinstance(data, np.ndarray) and data.ndim == 1
assert len(data) == subtype
return cls(data)
@property
def data(self):
return self._array
@property
def dim(self):
return len(self._array)
@property
def subtype(self):
return len(self._array)
def _copy_data(self):
self._array = self._array.copy()
def _scal(self, alpha):
self._array *= alpha
def _axpy(self, alpha, x):
assert self.dim == x.dim
if alpha == 0:
return
if alpha == 1:
self._array += x._array
elif alpha == -1:
self._array -= x._array
else:
self._array += x._array * alpha
def dot(self, other):
assert self.dim == other.dim
return np.sum(self._array * other._array)
def l1_norm(self):
return np.sum(np.abs(self._array))
def l2_norm(self):
return np.linalg.norm(self._array)
def l2_norm2(self):
return np.sum((self._array * self._array.conj()).real)
def components(self, component_indices):
return self._array[component_indices]
def amax(self):
A = np.abs(self._array)
max_ind = np.argmax(A)
max_val = A[max_ind]
return max_ind, max_val
class ListVectorArray(VectorArrayInterface):
"""|VectorArray| implementation via a Python list of vectors.
The :attr:`subtypes <pymor.vectorarrays.interfaces.VectorArrayInterface.subtype>`
a |ListVectorArray| can have are tuples `(vector_type, vector_subtype)`
where `vector_type` is a subclass of :class:`VectorInterface` and
`vector_subtype` is a valid subtype for `vector_type`.
Parameters
----------
vectors
List of :class:`vectors <VectorInterface>` contained in
the array.
subtype
If `vectors` is empty, the array's
:attr:`~pymor.vectorarrays.interfaces.VectorArrayInterface.subtype`
must be provided, as the subtype cannot be derived from `vectors`
in this case.
copy
If `True`, make copies of the vectors in `vectors`.
"""
_NONE = ()
def __init__(self, vectors, subtype=_NONE, copy=True):
vectors = list(vectors)
if subtype is self._NONE:
assert len(vectors) > 0
subtype = (type(vectors[0]), vectors[0].subtype)
if not copy:
self._list = vectors
else:
self._list = [v.copy() for v in vectors]
self.vector_type, self.vector_subtype = vector_type, vector_subtype = subtype
assert all(v.subtype == vector_subtype for v in self._list)
@classmethod
def make_array(cls, subtype=None, count=0, reserve=0):
assert count >= 0
assert reserve >= 0
vector_type, vector_subtype = subtype
return cls([vector_type.make_zeros(vector_subtype) for _ in range(count)], subtype=subtype, copy=False)
@classmethod
def from_data(cls, data, subtype):
vector_type, vector_subtype = subtype
return cls([vector_type.from_data(v, vector_subtype) for v in data], subtype=subtype)
def __len__(self):
return len(self._list)
@property
def data(self):
if not hasattr(self.space.type, 'data'):
raise TypeError('{} does not have a data attribute'.format(self.space.type))
if len(self._list) > 0:
return np.array([v.data for v in self._list])
else:
return np.empty((0, self.dim))
@property
def dim(self):
if len(self._list) > 0:
return self._list[0].dim
else:
return self.vector_type.make_zeros(self.vector_subtype).dim
@property
def subtype(self):
return (self.vector_type, self.vector_subtype)
def copy(self, ind=None, deep=False):
assert self.check_ind(ind)
if ind is None:
vecs = [v.copy(deep=deep) for v in self._list]
elif isinstance(ind, Number):
vecs = [self._list[ind].copy(deep=deep)]
else:
vecs = [self._list[i].copy(deep=deep) for i in ind]
return type(self)(vecs, subtype=self.subtype, copy=False)
def append(self, other, o_ind=None, remove_from_other=False):
assert other.check_ind(o_ind)
assert other.space == self.space
assert other is not self or not remove_from_other
other_list = other._list
if not remove_from_other:
if o_ind is None:
self._list.extend([v.copy() for v in other_list])
elif isinstance(o_ind, Number):
self._list.append(other_list[o_ind].copy())
else:
self._list.extend([other_list[i].copy() for i in o_ind])
else:
if o_ind is None:
self._list.extend(other_list)
other._list = []
elif isinstance(o_ind, Number):
self._list.append(other_list.pop(o_ind))
else:
self._list.extend([other_list[i] for i in o_ind])
remaining = sorted(set(range(len(other_list))) - set(o_ind))
other._list = [other_list[i] for i in remaining]
def remove(self, ind=None):
assert self.check_ind(ind)
if ind is None:
self._list = []
elif isinstance(ind, Number):
del self._list[ind]
else:
thelist = self._list
remaining = sorted(set(range(len(self))) - set(ind))
self._list = [thelist[i] for i in remaining]
def scal(self, alpha, ind=None):
assert self.check_ind_unique(ind)
assert isinstance(alpha, Number) \
or isinstance(alpha, np.ndarray) and alpha.shape == (self.len_ind(ind),)
if ind is None:
if isinstance(alpha, np.ndarray):
for a, v in zip(alpha, self._list):
v.scal(a)
else:
for v in self._list:
v.scal(alpha)
elif isinstance(ind, Number):
if isinstance(alpha, np.ndarray):
alpha = alpha[0]
self._list[ind].scal(alpha)
else:
l = self._list
if isinstance(alpha, np.ndarray):
for a, i in zip(alpha, ind):
l[i].scal(a)
else:
for i in ind:
l[i].scal(alpha)
def axpy(self, alpha, x, ind=None, x_ind=None):
assert self.check_ind_unique(ind)
assert x.check_ind(x_ind)
assert self.space == x.space
assert self.len_ind(ind) == x.len_ind(x_ind) or x.len_ind(x_ind) == 1
assert isinstance(alpha, _INDEXTYPES) \
or isinstance(alpha, np.ndarray) and alpha.shape == (self.len_ind(ind),)
if self is x:
if ind is None or x_ind is None:
self.axpy(alpha, x.copy(), ind, x_ind)
return
ind_set = {ind} if isinstance(ind, _INDEXTYPES) else set(ind)
x_ind_set = {x_ind} if isinstance(x_ind, _INDEXTYPES) else set(x_ind)
if ind_set.intersection(x_ind_set):
self.axpy(alpha, x.copy(x_ind), ind)
return
if ind is None:
Y = iter(self._list)
len_Y = len(self._list)
elif isinstance(ind, _INDEXTYPES):
Y = iter([self._list[ind]])
len_Y = 1
else:
Y = (self._list[i] for i in ind)
len_Y = len(ind)
if x_ind is None:
X = iter(x._list)
len_X = len(x._list)
elif isinstance(x_ind, _INDEXTYPES):
X = iter([x._list[x_ind]])
len_X = 1
else:
X = (x._list[i] for i in x_ind)
len_X = len(x_ind)
if | np.all(alpha == 0) | numpy.all |
import numpy as np
import pandas as pd
import sys
import torch
import torch.nn
import torch.autograd as autograd
import torch.utils.data
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib as mpl
mpl.use('agg')
import matplotlib.pyplot as plt
from tqdm import tqdm_notebook, tqdm
import torch
import torch.nn as nn
from icecream import ic
import warnings
warnings.filterwarnings('ignore')
dtype = torch.FloatTensor
long_dtype = torch.LongTensor
torch.set_default_tensor_type('torch.FloatTensor')
import torch.nn.functional as F
from icecream import ic
import sys
from filenames import cdataset as data_directories
from tqdm import tqdm
NUMCHAN=8
perturb_y_data = False
TOP = 9
def gen_dens(y, bins=int(5.0/0.5*10)):
dens, bins = np.histogram(y[:, 0].ravel(), bins=bins, density=True, range=[4, TOP])
dens[dens == 0.] = np.min(dens[dens > 0.])
plt.clf()
inv_dens = 1.0/dens
inv_dens /= np.average(inv_dens)
bins = bins
return inv_dens, bins
def load_data_normalized(debug=False, downsample=10,
dataset='resonant'):
base = './data/summary_features/'
labels = []
mass_ratios = []
time_series = []
# features = []
if dataset == 'resonant':
from filenames import cdataset as data_directories
elif dataset == 'random':
from filenames import cdataset_rand as data_directories
elif dataset == 'combined':
from filenames import cdataset_rand, cdataset
data_directories = cdataset + cdataset_rand
else:
raise NotImplementedError
from icecream import ic
total_num = []
for dataset in tqdm(data_directories):
dataset_base = base + dataset + '/get_extended_tseriesNorbits10000.0Nout1000trio/'
# features_base = base + dataset + '/resparamsv5Norbits10000.0Nout1000window10/'
try:
time_series_tmp = np.load(dataset_base + 'trainingdata.npy', allow_pickle=True)[:, ::downsample]
assert time_series_tmp.shape[1] == 100
labels_tmp = pd.read_csv(dataset_base + 'labels.csv')
mass_ratios_tmp = pd.read_csv(dataset_base + 'massratios.csv')
# features_tmp = pd.read_csv(features_base + 'trainingdata.csv')
except (FileNotFoundError, IndexError):
print('Skipping', dataset)
continue
time_series.append(time_series_tmp)
labels.append(labels_tmp)
mass_ratios.append(mass_ratios_tmp)
# features.append(features_tmp)
total_num.append(len(labels_tmp))
ic(total_num[-1])
if dataset[:4] == 'only':
labels[-1]['instability_time'] = 1e9
labels[-1]['shadow_instability_time'] = 1e9
if debug:
break
time_series = np.concatenate(time_series)
mass_ratios = pd.concat(mass_ratios)
labels = pd.concat(labels)
ic(len(labels))
last_dataset = (np.arange(len(labels)) >= np.cumsum(total_num)[-2])
ic(last_dataset.sum())
mass_array = np.transpose(np.tile(np.array(mass_ratios[['m1', 'm2', 'm3']]), (1000//downsample, 1, 1)), [1, 0, 2])
old_axis_labels = ['time', 'e+_near', 'e-_near', 'max_strength_mmr_near', 'e+_far', 'e-_far', 'max_strength_mmr_far', 'megno', 'a1', 'e1', 'i1', 'Omega1', 'pomega1', 'theta1', 'a2', 'e2', 'i2', 'Omega2', 'pomega2', 'theta2', 'a3', 'e3', 'i3', 'Omega3', 'pomega3', 'theta3']
old_X = np.concatenate((time_series, mass_array), axis=2)
old_axis_labels.extend(['m1', 'm2', 'm3'])
y = np.array(np.log10(labels[['instability_time', 'shadow_instability_time']])).astype(np.float32)
ic('Removing rows with time as NaN')
tmp_good_rows = ~np.any(~ | np.isfinite(old_X) | numpy.isfinite |
from __future__ import division
__all__ = ['get_resource_path',
'discrete_inverse_logit',
'_sig_stars',
'_robust_estimator',
'_chunk_boot_ols_coefs',
'_chunk_perm_ols',
'_ols',
'_perm_find',
'isPSD',
'nearestPSD']
__author__ = ['<NAME>']
__license__ = "MIT"
from os.path import dirname, join, sep
import numpy as np
import pandas as pd
from patsy import dmatrices
from scipy.special import expit
from scipy.stats import chi2
from itertools import product
from rpy2.robjects.packages import importr
from rpy2.robjects import pandas2ri
base = importr('base')
def get_resource_path():
""" Get path sample data directory. """
return join(dirname(__file__), 'resources') + sep
def discrete_inverse_logit(arr):
""" Apply a discretized inverse logit transform to an array of values. Useful for converting normally distributed values to binomial classes"""
probabilities = expit(arr)
out = np.random.binomial(1, probabilities)
return out
def _sig_stars(val):
"""Adds sig stars to coef table prettier output."""
star = ''
if 0 <= val < .001:
star = '***'
elif .001 <= val < 0.01:
star = '**'
elif .01 <= val < .05:
star = '*'
elif .05 <= val < .1:
star = '.'
return star
def _robust_estimator(vals, X, robust_estimator='hc0', n_lags=1, cluster=None):
"""
Computes robust sandwich estimators for standard errors used in OLS computation. Types include:
'hc0': Huber (1980) sandwich estimator to return robust standard error estimates.
'hc3': MacKinnon and White (1985) HC3 sandwich estimator. Provides more robustness in smaller samples than HC0 Long & Ervin (2000)
'hac': Newey-West (1987) estimator for robustness to heteroscedasticity as well as serial auto-correlation at given lags.
Args:
vals (np.ndarray): 1d array of residuals
X (np.ndarray): design matrix used in OLS
robust_estimator (str): estimator type, 'hc0' (default), 'hc3', 'hac', or 'cluster'
n_lags (int): number of lags, only used with 'hac' estimator, default is 1
cluster (np.ndarry): array of cluster ids
Returns:
stderr (np.ndarray): 1d array of standard errors with length == X.shape[1]
"""
assert robust_estimator in [
'hc0', 'hc3', 'hac', 'cluster'], "robust_estimator must be one of hc0, hc3, hac, or cluster"
# Make a sandwich!
# First we need bread
bread = np.linalg.pinv(np.dot(X.T, X))
# Then we need meat
if robust_estimator == 'hc0':
V = np.diag(vals**2)
meat = np.dot(np.dot(X.T, V), X)
if robust_estimator == 'cluster':
# Good ref: http://projects.iq.harvard.edu/files/gov2001/files/sesection_5.pdf
if cluster is None:
raise ValueError(
"data column identifying clusters must be provided")
else:
u = vals[:, np.newaxis] * X
u = pd.DataFrame(u)
# Use pandas groupby to get cluster-specific residuals
u['Group'] = cluster
u_clust = u.groupby('Group').sum()
num_grps = u['Group'].nunique()
meat = (num_grps / (num_grps - 1)) * \
(X.shape[0] / (X.shape[0] - X.shape[1])) * \
u_clust.T.dot(u_clust)
elif robust_estimator == 'hc3':
V = np.diag(vals**2) / (1 - np.diag(np.dot(X, np.dot(bread, X.T))))**2
meat = np.dot(np.dot(X.T, V), X)
elif robust_estimator == 'hac':
weights = 1 - np.arange(n_lags + 1.) / (n_lags + 1.)
# First compute lag 0
V = np.diag(vals**2)
meat = weights[0] * np.dot(np.dot(X.T, V), X)
# Now loop over additional lags
for l in range(1, n_lags + 1):
V = np.diag(vals[l:] * vals[:-l])
meat_1 = np.dot(np.dot(X[l:].T, V), X[:-l])
meat_2 = np.dot(np.dot(X[:-l].T, V), X[l:])
meat += weights[l] * (meat_1 + meat_2)
# Then we make a sandwich
vcv = np.dot(np.dot(bread, meat), bread)
return np.sqrt(np.diag(vcv))
def _ols(x, y, robust, n_lags, cluster, all_stats=True):
"""
Compute OLS on data given formula. Useful for single computation and within permutation schemes.
"""
# Expects as input pandas series and dataframe
Y, X = y.values.squeeze(), x.values
# The good stuff
b = np.dot(np.linalg.pinv(X), Y)
if all_stats:
res = Y - np.dot(X, b)
if robust:
se = _robust_estimator(
res, X, robust_estimator=robust, n_lags=n_lags, cluster=cluster)
else:
sigma = np.std(res, axis=0, ddof=X.shape[1])
se = np.sqrt(np.diag(np.linalg.pinv(np.dot(X.T, X)))) * sigma
t = b / se
return b, se, t, res
else:
return b
def _chunk_perm_ols(x, y, robust, n_lags, cluster, seed):
"""
Permuted OLS chunk.
"""
# Shuffle y labels
y = y.sample(frac=1, replace=False, random_state=seed)
b, s, t, res = _ols(x, y, robust, n_lags, cluster, all_stats=True)
return list(t)
def _chunk_boot_ols_coefs(dat, formula, seed):
"""
OLS computation of coefficients to be used in a parallelization context.
"""
# Random sample with replacement from all data
dat = dat.sample(frac=1, replace=True, random_state=seed)
y, x = dmatrices(formula, dat, 1, return_type='dataframe')
b = _ols(x, y, robust=None, n_lags=1, cluster=None, all_stats=False)
return list(b)
def _perm_find(arr, x):
"""
Find permutation cutoff in array.
"""
return np.sum(np.abs(arr) >= np.abs(x)) / float(len(arr))
def isPSD(mat, tol=1e-8):
"""
Check if matrix is positive-semi-definite by virtue of all its eigenvalues being >= 0. The cholesky decomposition does not work for edge cases because np.linalg.cholesky fails on matrices with exactly 0 valued eigenvalues, whereas in Matlab this is not true, so that method appropriate. Ref: https://goo.gl/qKWWzJ
"""
# We dont assume matrix is Hermitian, i.e. real-valued and symmetric
# Could swap this out with np.linalg.eigvalsh(), which is faster but less general
e = np.linalg.eigvals(mat)
return np.all(e > -tol)
def nearestPSD(A, nit=100):
"""
Higham (2000) algorithm to find the nearest positive semi-definite matrix that minimizes the Frobenius distance/norm. Sstatsmodels using something very similar in corr_nearest(), but with spectral SGD to search for a local minima. Reference: https://goo.gl/Eut7UU
Args:
nit (int): number of iterations to run algorithm; more iterations improves accuracy but increases computation time.
"""
n = A.shape[0]
W = np.identity(n)
def _getAplus(A):
eigval, eigvec = np.linalg.eig(A)
Q = np.matrix(eigvec)
xdiag = np.matrix(np.diag(np.maximum(eigval, 0)))
return Q * xdiag * Q.T
def _getPs(A, W=None):
W05 = np.matrix(W**.5)
return W05.I * _getAplus(W05 * A * W05) * W05.I
def _getPu(A, W=None):
Aret = np.array(A.copy())
Aret[W > 0] = np.array(W)[W > 0]
return np.matrix(Aret)
# W is the matrix used for the norm (assumed to be Identity matrix here)
# the algorithm should work for any diagonal W
deltaS = 0
Yk = A.copy()
for k in range(nit):
Rk = Yk - deltaS
Xk = _getPs(Rk, W=W)
deltaS = Xk - Rk
Yk = _getPu(Xk, W=W)
# Double check returned matrix is PSD
if isPSD(Yk):
return Yk
else:
nearestPSD(Yk)
def upper(mat):
'''Return upper triangle of matrix'''
idx = np.triu_indices_from(mat, k=1)
return mat[idx]
def _return_t(model):
'''Return t or z stat from R model summary.'''
summary = base.summary(model)
unsum = base.unclass(summary)
return pandas2ri.ri2py(unsum.rx2('coefficients'))[:, -1]
def _get_params(model):
'''Get number of params in a model.'''
return model.coefs.shape[0]
def _lrt(tup):
'''Likelihood ratio test between 2 models.'''
d = np.abs(2 * (tup[0].logLike - tup[1].logLike))
return chi2.sf(d, | np.abs(tup[0].coefs.shape[0] - tup[1].coefs.shape[0]) | numpy.abs |
# coding=utf-8
# Copyright 2019 The Meta-Dataset Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for `sampling` module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import unittest
from absl.testing import parameterized
import gin
from meta_dataset.data import sampling
from meta_dataset.data.dataset_spec import DatasetSpecification
from meta_dataset.data.learning_spec import Split
from meta_dataset.utils.argparse import argparse
import numpy as np
argparse.parser.parse_args()
# DatasetSpecification to use in tests
DATASET_SPEC = DatasetSpecification(
name=None,
classes_per_split={
Split.TRAIN: 15,
Split.VALID: 5,
Split.TEST: 10
},
images_per_class=dict(enumerate([10, 20, 30] * 10)),
class_names=None,
path=None,
file_pattern='{}.tfrecords')
def assert_contains_subset(a, b):
set_a = set(a)
set_b = set(b)
assert(len(set_a) == len(set_a.intersection(set_b)))
# Define defaults and set Gin configuration for EpisodeDescriptionSampler
MIN_WAYS = 5
MAX_WAYS_UPPER_BOUND = 50
MAX_NUM_QUERY = 10
MAX_SUPPORT_SET_SIZE = 500
MAX_SUPPORT_SIZE_CONTRIB_PER_CLASS = 100
MIN_LOG_WEIGHT = np.log(0.5)
MAX_LOG_WEIGHT = np.log(2)
gin.bind_parameter('EpisodeDescriptionSampler.min_ways', MIN_WAYS)
gin.bind_parameter('EpisodeDescriptionSampler.max_ways_upper_bound',
MAX_WAYS_UPPER_BOUND)
gin.bind_parameter('EpisodeDescriptionSampler.max_num_query', MAX_NUM_QUERY)
gin.bind_parameter('EpisodeDescriptionSampler.max_support_set_size',
MAX_SUPPORT_SET_SIZE)
gin.bind_parameter(
'EpisodeDescriptionSampler.max_support_size_contrib_per_class',
MAX_SUPPORT_SIZE_CONTRIB_PER_CLASS)
gin.bind_parameter('EpisodeDescriptionSampler.min_log_weight', MIN_LOG_WEIGHT)
gin.bind_parameter('EpisodeDescriptionSampler.max_log_weight', MAX_LOG_WEIGHT)
# Following is set in a different scope.
gin.bind_parameter('none/EpisodeDescriptionSampler.min_ways', None)
gin.bind_parameter('none/EpisodeDescriptionSampler.max_ways_upper_bound', None)
gin.bind_parameter('none/EpisodeDescriptionSampler.max_num_query', None)
gin.bind_parameter('none/EpisodeDescriptionSampler.max_support_set_size', None)
gin.bind_parameter(
'none/EpisodeDescriptionSampler.max_support_size_contrib_per_class', None)
gin.bind_parameter('none/EpisodeDescriptionSampler.min_log_weight', None)
gin.bind_parameter('none/EpisodeDescriptionSampler.max_log_weight', None)
class SampleNumWaysUniformlyTest(unittest.TestCase):
"""Tests for the `sample_num_ways_uniformly` function."""
def test_min_ways_respected(self):
for _ in range(10):
num_ways = sampling.sample_num_ways_uniformly(
10, min_ways=MIN_WAYS, max_ways=MAX_WAYS_UPPER_BOUND)
self.assertGreaterEqual(num_ways, MIN_WAYS)
def test_num_classes_respected(self):
num_classes = 10
for _ in range(10):
num_ways = sampling.sample_num_ways_uniformly(
num_classes, min_ways=MIN_WAYS, max_ways=MAX_WAYS_UPPER_BOUND)
self.assertLessEqual(num_ways, num_classes)
def test_max_ways_upper_bound_respected(self):
num_classes = 2 * MAX_WAYS_UPPER_BOUND
for _ in range(10):
num_ways = sampling.sample_num_ways_uniformly(
num_classes, min_ways=MIN_WAYS, max_ways=MAX_WAYS_UPPER_BOUND)
self.assertLessEqual(num_ways, MAX_WAYS_UPPER_BOUND)
class SampleClassIDsUniformlyTest(unittest.TestCase):
"""Tests for the `sample_class_ids_uniformly` function."""
def test_num_ways_respected(self):
num_classes = MAX_WAYS_UPPER_BOUND
num_ways = MIN_WAYS
for _ in range(10):
class_ids = sampling.sample_class_ids_uniformly(num_ways, num_classes)
self.assertEqual(len(set(class_ids)), num_ways)
self.assertEqual(len(class_ids), num_ways)
def test_num_classes_respected(self):
num_classes = MAX_WAYS_UPPER_BOUND
num_ways = MIN_WAYS
for _ in range(10):
class_ids = sampling.sample_class_ids_uniformly(num_ways, num_classes)
assert_contains_subset(class_ids, list(range(num_classes)))
def test_unique_class_ids(self):
num_classes = MAX_WAYS_UPPER_BOUND
num_ways = MIN_WAYS
for _ in range(10):
class_ids = sampling.sample_class_ids_uniformly(num_ways, num_classes)
self.assertCountEqual(class_ids, set(class_ids))
class ComputeNumQueryTest(unittest.TestCase):
"""Tests for the `compute_num_query` function."""
def test_max_num_query_respected(self):
images_per_class = np.array([30, 45, 35, 50])
num_query = sampling.compute_num_query(
images_per_class, max_num_query=MAX_NUM_QUERY)
self.assertEqual(num_query, MAX_NUM_QUERY)
def test_at_most_half(self):
images_per_class = np.array([10, 9, 20, 21])
num_query = sampling.compute_num_query(
images_per_class, max_num_query=MAX_NUM_QUERY)
self.assertEqual(num_query, 4)
def test_raises_error_on_one_image_per_class(self):
images_per_class = np.array([1, 3, 8, 8])
with self.assertRaises(ValueError):
sampling.compute_num_query(images_per_class, max_num_query=MAX_NUM_QUERY)
class SampleSupportSetSizeTest(unittest.TestCase):
"""Tests for the `sample_support_set_size` function."""
def test_max_support_set_size_respected(self):
num_remaining_per_class = np.array([MAX_SUPPORT_SET_SIZE] * 10)
for _ in range(10):
support_set_size = sampling.sample_support_set_size(
num_remaining_per_class,
max_support_size_contrib_per_class=MAX_SUPPORT_SIZE_CONTRIB_PER_CLASS,
max_support_set_size=MAX_SUPPORT_SET_SIZE)
self.assertLessEqual(support_set_size, MAX_SUPPORT_SET_SIZE)
def test_raises_error_max_support_too_small(self):
num_remaining_per_class = np.array([5] * 10)
with self.assertRaises(ValueError):
sampling.sample_support_set_size(
num_remaining_per_class,
max_support_size_contrib_per_class=MAX_SUPPORT_SIZE_CONTRIB_PER_CLASS,
max_support_set_size=len(num_remaining_per_class) - 1)
class SampleNumSupportPerClassTest(unittest.TestCase):
"""Tests for the `sample_num_support_per_class` function."""
def test_support_set_size_respected(self):
num_images_per_class = | np.array([50, 40, 30, 20]) | numpy.array |
# KNN으로 기술적분석 지표들과 변동성을 Feature로 향후 20일 동안
# 목표 수익률을 달성할 가능성이 있는지를 추정한다.
#
# 2018.08.20, 아마추어퀀트 (조성현)
# --------------------------------------------------------
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from MyUtil import YahooData, TaFeatureSet
stocks = {'005380':'현대차', '000660':'SK하이닉스', '015760':'한국전력', '034220':'LG디스플레이',
'005490':'POSCO', '035420':'NAVER', '017670':'SK텔레콤', '012330':'현대모비스',
'055550':'신한지주', '000270':'기아차', '105560':'KB금융', '051910':'LG화학'}
# Yahoo site로부터 위에 정의된 주가 데이터를 수집하여 ./stockData 폴더에 저장해 둔다.
def getData(stockList=stocks, start='2007-01-01'):
YahooData.getStockDataList(stockList, start=start)
# 데이터 세트를 생성하고, ./dataset/3-6.TaDataset.csv 에 저장해 둔다.
# 시간이 오래 걸린다.
def createDataSet(stockList=stocks, u=0.5, d=-0.5, nFuture=20, binary=True):
n = 1
for code in stockList.keys():
# 저장된 파일을 읽어온다
data = pd.read_csv('stockData/' + code + '.csv', index_col=0, parse_dates=True)
# 과거 20일의 종가 패턴과 변동성이 어느 수준일 때 매수하면 손실인지 아닌지를 class로 부여하여
# 목표 수익률 달성 여부를 학습한다. 목표 수익률을 달성한다는 것은 향후 주가가 상승하는 것을 의미함.
# Binary classification을 위해 class = 0, 1로 구분하였음.
# u = 0.5 : 수익률 표준편차의 0.5 배 이상이면 수익 (class = 1)
# d = -0.5 : 수익률 표준편차의 -0.5배 이하이면 손실 (class = 0)
# 중간이면 주가 횡보 (classs = 0)
if n == 1:
ft = TaFeatureSet.getTaFeatureSet(data, u, d, nFuture, binary)
else:
ft = ft.append(TaFeatureSet.getTaFeatureSet(data, u, d, nFuture, binary))
print("%d) %s (%s)를 처리하였습니다." % (n, stockList[code], code))
n += 1
ft.to_csv('dataset/3-6.TaDataset.csv')
# 데이터 세트를 읽어온다
ds = pd.read_csv('dataset/3-6.TaDataset.csv')
ds = ds.drop(ds.columns[0], 1)
# data set을 행을 기준으로 랜덤하게 섞는다 (shuffling)
ds = ds.sample(frac=1).reset_index(drop=True)
# 학습용 데이터와 시험용 데이터로 나눈다. (8 : 2)
trainRate = 0.8
trainLen = int(len(ds) * trainRate)
trainX = np.array(ds.iloc[0:trainLen, 0:6])
trainY = np.array(ds.iloc[0:trainLen, -1])
trainY = trainY.reshape(trainLen, 1)
testX = np.array(ds.iloc[trainLen:, 0:6])
testY = np.array(ds.iloc[trainLen:, -1])
testY = testY.reshape(len(testY), 1)
# 그래프 모델을 생성한다
tf.reset_default_graph()
x = tf.placeholder(tf.float32, shape=[None, 6], name="X")
y = tf.placeholder(tf.float32, shape=[None, 1], name="Y")
tx = tf.placeholder(tf.float32, shape=[None, 6], name="X")
parK = tf.placeholder(tf.int32, shape=[], name="K")
# test point와 모든 x와의 거리를 측정한다 (Euclidean distance)
distance = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(x, tx)), 1))
# test point와 모든 x와의 거리중 거리가 짧은 K개의 class (trainY)를 찾는다.
# 이 classes에서 다수결로 test point의 class를 판정한다.
# ex : tf.gather(trainY, indices) = [1, 1, 0, 1, 0, 1, 1] --> class = 1로 판정한다.
# class 들의 평균 = 5/7 = 0.714 --> 0.5 보다 크므로 class = 1로 판정함.
values, indices = tf.nn.top_k(tf.negative(distance), k=parK, sorted=False)
classMean = tf.reduce_mean(tf.cast(tf.gather(trainY, indices), tf.float32))
# 그래프를 실행한다.
sess = tf.Session()
accuracy = [] # K = [1,2,3..]에 따른 정확도를 기록할 list
yHatK = [] # 최적 K일 때 testX의 class를 추정한 list
optK = 0 # 최적 K
optAccuracy = 0.0 # 최적 K일 때의 정확도
minK = 50
maxK = 100 # K = minK ~ maxK 까지 변화시키면서 정확도를 측정한다
for k in range(minK, maxK+1):
yHat = []
for dx in testX:
# testX를 하나씩 읽어가면서 k-개의 가까운 거리를 찾는다
dx = dx.reshape(1, 6)
yHat.append(sess.run(classMean, feed_dict = {x: trainX, tx: dx, parK: k}))
# test data의 class를 추정한다.
yHat = np.array(yHat)
yHat = yHat.reshape(len(yHat), 1)
testYhat = np.where(yHat > 0.5, 1, 0)
# test data의 실제 class와 추정 class를 비교하여 정확도를 측정한다.
accK = 100 * (testY == testYhat).sum() / len(testY)
# 정확도가 가장 높은 최적 K, yHatK, optAccuracy를 기록해 둔다
if accK > optAccuracy:
yHatK = yHat.copy()
optK = k
optAccuracy = accK
# K에 따라 달라지는 정확도를 추적하기위해 history를 기록해 둔다
accuracy.append(accK)
print("k = %d done" % k)
sess.close()
# 결과를 확인한다
fig = plt.figure(figsize=(10, 4))
p1 = fig.add_subplot(1,2,1)
p2 = fig.add_subplot(1,2,2)
xK = | np.arange(minK, maxK+1) | numpy.arange |
import time
import numpy as np
from rex_gym.model.kinematics import Kinematics
class GaitPlanner:
def __init__(self, mode):
self._frame = np.zeros([4, 3])
self._phi = 0.
self._phi_stance = 0.
self._last_time = 0.
self._alpha = 0.
self._s = False
if mode == "walk":
self._offset = np.array([0., 0.5, 0.5, 0.])
self.step_offset = 0.5
else:
self._offset = np.array([0.3, 0.3, 0., 0.])
self.step_offset = 0.5
@staticmethod
def solve_bin_factor(n, k):
return np.math.factorial(n) / (np.math.factorial(k) * np.math.factorial(n - k))
def bezier_curve(self, t, k, point):
n = 9
return point * self.solve_bin_factor(n, k) * np.power(t, k) * np.power(1 - t, n - k)
@staticmethod
def calculate_stance(phi_st, v, angle):
c = np.cos(np.deg2rad(angle))
s = np.sin(np.deg2rad(angle))
A = 0.001
half_l = 0.05
p_stance = half_l * (1 - 2 * phi_st)
stance_x = c * p_stance * np.abs(v)
stance_y = -s * p_stance * np.abs(v)
stance_z = -A * np.cos(np.pi / (2 * half_l) * p_stance)
return stance_x, stance_y, stance_z
def calculate_bezier_swing(self, phi_sw, v, angle):
c = np.cos(np.deg2rad(angle))
s = np.sin(np.deg2rad(angle))
X = np.abs(v) * c * np.array([-0.05, -0.06, -0.07, -0.07, 0.,
0., 0.07, 0.07, 0.06, 0.05])
Y = np.abs(v) * s * (-X)
Z = np.abs(v) * np.array([0., 0., 0.05, 0.05, 0.05,
0.06, 0.06, 0.06, 0., 0.])
swing_x = 0.
swing_y = 0.
swing_z = 0.
for i in range(10):
swing_x = swing_x + self.bezier_curve(phi_sw, i, X[i])
swing_y = swing_y + self.bezier_curve(phi_sw, i, Y[i])
swing_z = swing_z + self.bezier_curve(phi_sw, i, Z[i])
return swing_x, swing_y, swing_z
def step_trajectory(self, phi, v, angle, w_rot, center_to_foot):
if phi >= 1:
phi = phi - 1.
r = np.sqrt(center_to_foot[0] ** 2 + center_to_foot[1] ** 2)
foot_angle = np.arctan2(center_to_foot[1], center_to_foot[0])
if w_rot >= 0.:
circle_trajectory = 90. - np.rad2deg(foot_angle - self._alpha)
else:
circle_trajectory = 270. - np.rad2deg(foot_angle - self._alpha)
if phi <= self.step_offset:
# stance phase
phi_stance = phi / self.step_offset
stepX_long, stepY_long, stepZ_long = self.calculate_stance(phi_stance, v, angle)
stepX_rot, stepY_rot, stepZ_rot = self.calculate_stance(phi_stance, w_rot, circle_trajectory)
else:
# swing phase
phiSwing = (phi - self.step_offset) / (1 - self.step_offset)
stepX_long, stepY_long, stepZ_long = self.calculate_bezier_swing(phiSwing, v, angle)
stepX_rot, stepY_rot, stepZ_rot = self.calculate_bezier_swing(phiSwing, w_rot, circle_trajectory)
if center_to_foot[1] > 0:
if stepX_rot < 0:
self._alpha = -np.arctan2(np.sqrt(stepX_rot ** 2 + stepY_rot ** 2), r)
else:
self._alpha = np.arctan2(np.sqrt(stepX_rot ** 2 + stepY_rot ** 2), r)
else:
if stepX_rot < 0:
self._alpha = np.arctan2(np.sqrt(stepX_rot ** 2 + stepY_rot ** 2), r)
else:
self._alpha = -np.arctan2(np.sqrt(stepX_rot ** 2 + stepY_rot ** 2), r)
coord = np.empty(3)
coord[0] = stepX_long + stepX_rot
coord[1] = stepY_long + stepY_rot
coord[2] = stepZ_long + stepZ_rot
return coord
def loop(self, v, angle, w_rot, t, frames=None):
if frames is None:
k_obj = Kinematics()
x_dist = k_obj.x_dist
y_dist = k_obj.y_dist
height = k_obj.height
frames = np.asmatrix([[x_dist / 2, -y_dist / 2, -height],
[x_dist / 2, y_dist / 2, -height],
[-x_dist / 2, -y_dist / 2, -height],
[-x_dist / 2, y_dist / 2, -height]])
if t <= 0.01:
t = 0.01
if self._phi >= 0.99:
self._last_time = time.time()
self._phi = (time.time() - self._last_time) / t
step_coord = self.step_trajectory(self._phi + self._offset[0], v, angle, w_rot,
np.squeeze(np.asarray(frames[0, :]))) # FR
self._frame[0, 0] = frames[0, 0] + step_coord[0]
self._frame[0, 1] = frames[0, 1] + step_coord[1]
self._frame[0, 2] = frames[0, 2] + step_coord[2]
step_coord = self.step_trajectory(self._phi + self._offset[1], v, angle, w_rot,
np.squeeze(np.asarray(frames[1, :]))) # FL
self._frame[1, 0] = frames[1, 0] + step_coord[0]
self._frame[1, 1] = frames[1, 1] + step_coord[1]
self._frame[1, 2] = frames[1, 2] + step_coord[2]
step_coord = self.step_trajectory(self._phi + self._offset[2], v, angle, w_rot,
np.squeeze( | np.asarray(frames[2, :]) | numpy.asarray |
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
if __name__ == "__main__":
# # Problem 1 - Gaussian Process Modelling
# ## Data I/O
X_train = np.genfromtxt('hw3-data/gaussian_process/X_train.csv', delimiter=',')
X_test = np.genfromtxt('hw3-data/gaussian_process/X_test.csv', delimiter=',')
y_train = np.genfromtxt('hw3-data/gaussian_process/y_train.csv', delimiter=',')
y_test = np.genfromtxt('hw3-data/gaussian_process/y_test.csv', delimiter=',')
# ## Helper Functions
def calculateRMSE(y_pred, y_test):
n = y_pred.shape[0]
return np.linalg.norm(y_pred - y_test)/(n**0.5)
# ## Gaussian Process Regression
class GaussianProcessRegression():
def __init__(self):
pass
def standardize(self, y):
mean = np.mean(y)
std = np.std(y)
y = (y - mean)/std
self.mean = mean
self.std = std
return y
def calcKernel(self):
X = self.X
(n, d) = X.shape
K = np.zeros((n, n))
for i in range(n):
for j in range(i, n):
xi, xj = X[i, :].flatten(), X[j, :].flatten()
k = self.calcRadialDistance(xi, xj)
K[i, j] = k
K[j, i] = k
self.K = K
def transformOutput(self, y):
y = y*self.std + self.mean
return y
def calcRadialDistance(self, x1, x2):
return np.exp(-1*(np.linalg.norm(x1-x2)**2)/self.b)
def train(self, X, y):
self.X = X
self.y = self.standardize(y)
def setb(self, b):
self.b = b
self.calcKernel()
def predict(self, X_t, sig):
X = self.X
y = self.y
(n, d) = X.shape
(m, d) = X_t.shape
Kn = np.zeros((m, n))
for i in range(m):
for j in range(n):
Kn[i, j] = self.calcRadialDistance(X_t[i, :].flatten(), X[j, :].flatten())
Kn = Kn.reshape((m, n))
K = self.K
mu = Kn.dot(np.linalg.inv((sig)*np.identity(n) + K)).dot(y)
#cov = (sig**2) + 1 - Kn.dot(np.linalg.inv((sig**2)*np.identity(n) + K)).dot(Kn.T)
return self.transformOutput(mu)
GPR = GaussianProcessRegression()
GPR.train(X_train, y_train)
# ## RMSE vs. (b, $\sigma^2$)
b_tests = [5, 7, 9, 11, 13, 15]
sig_tests = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
results = np.zeros((len(b_tests), len(sig_tests)))
for i in range(len(b_tests)):
GPR.setb(b_tests[i])
for j in range(len(sig_tests)):
y_pred = GPR.predict(X_test, sig_tests[j])
results[i, j] = calculateRMSE(y_pred, y_test)
plt.figure(figsize=(20, 10))
sns.set_style('whitegrid')
sns.heatmap(results, annot=True, annot_kws={"size": 15}, fmt='.3f', xticklabels=sig_tests, yticklabels=b_tests)
plt.xlabel('sig_squared', fontsize=20)
plt.ylabel('b', fontsize=20)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.title('RMSE', fontsize=20)
plt.savefig('1b.png')
#plt.show()
# ## Prediction using only a single dimension - (car weight)
(n, d) = X_train.shape
X_test_f4 = X_train[:, 3].reshape(n, 1)
for i in range(d-1):
X_test_f4 = np.column_stack((X_test_f4, X_train[:, 3].reshape((n, 1))))
GPR.setb(5)
y_test_f4 = GPR.predict(X_test_f4, 2)
plt.figure(figsize=(20, 10))
plt.scatter(X_train[:, 3], y_test_f4, label="Predictions")
plt.scatter(X_train[:, 3], y_train, label="Training Data")
plt.xlabel("car_weight", fontsize=20)
plt.ylabel("Mileage", fontsize=20)
plt.legend(fontsize=20)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
#plt.show()
GPR_x4 = GaussianProcessRegression()
GPR_x4.train(X_train[:, 3].reshape(X_train.shape[0], 1), y_train)
GPR_x4.setb(5)
y_train_f4 = GPR_x4.predict(X_train[:, 3].reshape(X_train.shape[0], 1), 2)
plt.figure(figsize=(20, 10))
plt.scatter(X_train[:, 3], y_train_f4, label="Predictions")
plt.scatter(X_train[:, 3], y_train, label="Training Data")
plt.xlabel("car_weight", fontsize=20)
plt.ylabel("Mileage", fontsize=20)
plt.legend(fontsize=20)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.savefig('1d_new.png')
#plt.show()
# # Problem 2 - Boosting
# ## Data I/O
X_train = np.genfromtxt('hw3-data/boosting/X_train.csv', delimiter=',')
X_test = np.genfromtxt('hw3-data/boosting/X_test.csv', delimiter=',')
y_train = np.genfromtxt('hw3-data/boosting/y_train.csv', delimiter=',')
y_test = np.genfromtxt('hw3-data/boosting/y_test.csv', delimiter=',')
X_train_w_ones = np.column_stack((X_train, np.ones(X_train.shape[0])))
X_test_w_ones = np.column_stack((X_test, np.ones(X_test.shape[0])))
# ## Helper Functions
def calculateAccuracy(predictions, ground_truth):
n = predictions.shape[0]
assert n == ground_truth.shape[0]
return y_pred[y_pred==ground_truth].shape[0]/n
def calculateErrorRate(predictions, ground_truth):
n = predictions.shape[0]
assert n == ground_truth.shape[0]
return np.sum(y_pred!=ground_truth)/n
# ## Least Square Classifier
class LeastSquareClassifier():
def __init__(self):
self.weights = None
def train(self, X, y):
(n, d) = X.shape
XTX = X.T.dot(X)
w = np.linalg.inv(XTX).dot(X.T).dot(y)
assert w.shape[0] == d
self.weights = w
def test(self, X):
w = self.weights
(n, d) = X.shape
y_int = X.dot(w)
return y_int/np.abs(y_int)
LSClassifier = LeastSquareClassifier()
LSClassifier.train(X_train_w_ones, y_train)
y_pred = LSClassifier.test(X_test_w_ones)
print("Basic Least Square Classifier Accuracy: {}".format(calculateAccuracy(y_pred, y_test)))
# ## Boosted Least Square Classifier
class BoostedLeastSquareClassifier():
def __init__(self, classifier):
self.classifier = classifier
self.classifiers = []
self.alphas = None
self.eps = None
self.training_errors = None
self.testing_errors = None
self.weights = None
self.sample_tracker = []
def train(self, X, y, num_of_classifiers):
np.random.seed(0)
self.training_errors = []
eps = np.zeros(num_of_classifiers)
self.alphas = | np.zeros(num_of_classifiers) | numpy.zeros |
import numpy as np
import scipy.stats as stat
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
parcellation = ['shen', 'gordon']
nets = [9, 13]
labels_dict_shen = {'n0': ['All, 268', 'Whole-brain'],
'n1': ['MF, 29', 'Medial frontal'],
'n2': ['FP, 34', 'Frontoparietal'],
'n3': ['DMN, 20', 'Default mode'],
'n4': ['SC, 90', 'Subcortical-cerebellum'],
'n5': ['M, 50', 'Motor'],
'n6': ['VI, 18', 'Visual I'],
'n7': ['VII, 9', 'Visual II'],
'n8': ['VA, 18', 'Visual association']}
nodes_shen = [268, 29, 34, 20, 90, 50, 18, 9, 18]
labels_dict_gordon = {'n0': ['All, 333', 'Whole-brain'],
'n1': ['DMN, 41', 'Default mode'],
'n2': ['SMh, 38', 'Somato-sensory hand'],
'n3': ['SMm, 8', 'Somato-sensory mouth'],
'n4': ['V, 39', 'Visual'],
'n5': ['FP, 24', 'Frontoparietal'],
'n6': ['Au, 24', 'Auditory'],
'n7': ['CP, 5', 'Cingulo Parietal'],
'n8': ['RT, 8', 'Retrosplenial Temporal'],
'n9': ['CO, 40', 'Cingulo Opercular'],
'n10': ['VAN, 23', 'Ventral Attention'],
'n11': ['S, 4', 'Salience'],
'n12': ['DAN, 32', 'Dorsal Attention'],
}
nodes_gordon = [333, 41, 38, 8, 39, 24, 24, 5, 8, 40, 23, 4, 32]
ACE_h2_shen = np.load('./../multivariate_mean_shen.npz')['list']
ACE_h2_gordon = np.load('./../multivariate_mean_gordon.npz')['list']
for j in range(len(parcellation)):
accuracies_ind = \
np.load('./../outputs/accuracies_ind_id_' + parcellation[j] + '.npz')[
'dict']
accuracies_twin = \
| np.load('./../outputs/accuracies_twin_id_' + parcellation[j] + '.npz') | numpy.load |
from __future__ import division
from __future__ import print_function
from builtins import str
from past.utils import old_div
import numpy as np
from pandas import DataFrame, crosstab
def STDO(obs, mod, axis=None):
""" Standard deviation of Observations """
return np.ma.std(obs, axis=axis)
def STDP(obs, mod, axis=None):
""" Standard deviation of Predictions """
return np.ma.std(mod, axis=axis)
def MNB(obs, mod, axis=None):
""" Mean Normalized Bias (%)"""
return np.ma.masked_invalid(old_div((mod - obs), obs)).mean(axis=axis) * 100.
def MNE(obs, mod, axis=None):
""" Mean Normalized Gross Error (%)"""
return np.ma.masked_invalid(old_div(np.ma.abs(mod - obs), obs)).mean(axis=axis) * 100.
def MdnNB(obs, mod, axis=None):
""" Median Normalized Bias (%)"""
return np.ma.median(np.ma.masked_invalid(old_div((mod - obs), obs)), axis=axis) * 100.
def MdnNE(obs, mod, axis=None):
""" Median Normalized Gross Error (%)"""
return np.ma.median(np.ma.masked_invalid(old_div(np.ma.abs(mod - obs), obs)), axis=axis) * 100.
def NMdnE(obs, mod, axis=None):
""" Normalized Median Gross Error (%)"""
return np.ma.masked_invalid(old_div(np.ma.abs(mod - obs).mean(axis=axis), obs.mean(axis=axis))) * 100.
def NO(obs, mod, axis=None):
""" N Observations (#)"""
return ( | np.ma.getmaskarray(obs) | numpy.ma.getmaskarray |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
import numpy as np
import pytest
import mindspore.context as context
import mindspore.nn as nn
from mindspore import Tensor
from mindspore import Parameter
from mindspore.common import dtype as mstype
from mindspore.ops import operations as P
context.set_context(mode=context.GRAPH_MODE, device_target='CPU', save_graphs=False)
class ScatterNdUpdate1(nn.Cell):
def __init__(self):
super(ScatterNdUpdate1, self).__init__()
self.scatter_nd_update = P.ScatterNdUpdate()
self.x = Parameter(Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mstype.float32), name="x")
def construct(self, indices, update):
return self.scatter_nd_update(self.x, indices, update)
class ScatterNdUpdate2(nn.Cell):
def __init__(self):
super(ScatterNdUpdate2, self).__init__()
self.scatter_nd_update = P.ScatterNdUpdate()
self.x = Parameter(Tensor(np.array([1, 2, 3, 4, 5, 6, 7, 8]), mstype.float32), name="x")
def construct(self, indices, update):
return self.scatter_nd_update(self.x, indices, update)
class ScatterNdUpdate3(nn.Cell):
def __init__(self):
super(ScatterNdUpdate3, self).__init__()
self.scatter_nd_update = P.ScatterNdUpdate()
self.x = Parameter(Tensor( | np.zeros((4, 4, 4)) | numpy.zeros |
#! /usr/bin/env python
import time
import itertools
import numpy as np
import baldor as br
import criutils as cu
import raveutils as ru
import openravepy as orpy
class EnvironmentManager(object):
COLORS = {
"RED": [0.8, 0., 0., 1.],
"BLUE": [0., 0., 0.8, 1.],
"GREEN": [0., 0.8, 0., 1.],
}
def __init__(self, env, num_cubes=6, seed=111):
# Working entities
self.env = env
self.bins = self._add_bins() # keys: bin_type, values: bin_name
self.cubes = self._add_cubes(seed) # keys: cube_name, values: cube_type
print("Environment manager successfully initialized")
def _add_cubes(self, seed):
table = self.env.GetKinBody("cubes_table")
aabb = table.ComputeAABB()
xdim, _, zdim = 2 * aabb.extents()
Tabove_table = table.GetTransform()
Tabove_table[:3, 3] += [0, 0, zdim + br._EPS]
zcube = Tabove_table[2, 3] + 1e-5 # Small delta to avoid colliding with the table
xx = np.linspace(0.35, 0.7, num=3)
yy = np.linspace(-0.3, 0.3, num=5) - Tabove_table[1,3]
num_cubes = 14
| np.random.seed(seed) | numpy.random.seed |
import numpy as np
from torchvision import datasets, transforms
import warnings
warnings.filterwarnings("ignore")
def mnist_iid(dataset, num_users):
"""
Sample I.I.D. client data from MNIST dataset
:param dataset:
:param num_users:
:return: dict of image index
"""
num_items = int(len(dataset) / num_users)
dict_users, all_idxs = {}, [i for i in range(len(dataset))]
for i in range(num_users):
dict_users[i] = set(np.random.choice(all_idxs, num_items, replace=False))
all_idxs = list(set(all_idxs) - dict_users[i])
return dict_users
def mnist_noniid(dataset, num_users):
"""
Sample non-I.I.D client data from MNIST dataset
:param dataset:
:param num_users:
:return:
"""
# 60,000 training imgs --> 200 imgs/shard X 300 shards
num_shards, num_imgs = 200, 300
idx_shard = [i for i in range(num_shards)]
dict_users = {i: np.array([]) for i in range(num_users)}
idxs = np.arange(num_shards * num_imgs)
labels = dataset.train_labels.numpy()
# sort labels
idxs_labels = np.vstack((idxs, labels))
idxs_labels = idxs_labels[:, idxs_labels[1, :].argsort()]
idxs = idxs_labels[0, :]
# divide and assign 2 shards/client
for i in range(num_users):
rand_set = set(np.random.choice(idx_shard, 2, replace=False))
idx_shard = list(set(idx_shard) - rand_set)
for rand in rand_set:
dict_users[i] = np.concatenate((dict_users[i], idxs[rand * num_imgs:(rand + 1) * num_imgs]), axis=0)
return dict_users
def mnist_noniid_unequal(dataset, num_users):
"""
Sample non-I.I.D client data from MNIST dataset s.t clients
have unequal amount of data
:param dataset:
:param num_users:
:returns a dict of clients with each clients assigned certain
number of training imgs
"""
# 60,000 training imgs --> 50 imgs/shard X 1200 shards
num_shards, num_imgs = 1200, 50
idx_shard = [i for i in range(num_shards)]
dict_users = {i: | np.array([]) | numpy.array |
# MIT License
#
# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 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.
"""
This module implements the HopSkipJump attack `HopSkipJump`. This is a black-box attack that only requires class
predictions. It is an advanced version of the Boundary attack.
| Paper link: https://arxiv.org/abs/1904.02144
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from typing import Optional, Tuple, Union, TYPE_CHECKING
import numpy as np
from tqdm.auto import tqdm
from art.config import ART_NUMPY_DTYPE
from art.attacks.attack import EvasionAttack
from art.estimators.estimator import BaseEstimator
from art.estimators.classification import ClassifierMixin
from art.utils import compute_success, to_categorical, check_and_transform_label_format
if TYPE_CHECKING:
from art.utils import CLASSIFIER_TYPE
logger = logging.getLogger(__name__)
class HopSkipJump(EvasionAttack):
"""
Implementation of the HopSkipJump attack from Jianbo et al. (2019). This is a powerful black-box attack that
only requires final class prediction, and is an advanced version of the boundary attack.
| Paper link: https://arxiv.org/abs/1904.02144
"""
attack_params = EvasionAttack.attack_params + [
"targeted",
"norm",
"max_iter",
"max_eval",
"init_eval",
"init_size",
"curr_iter",
"batch_size",
"verbose",
]
_estimator_requirements = (BaseEstimator, ClassifierMixin)
def __init__(
self,
classifier: "CLASSIFIER_TYPE",
batch_size: int = 64,
targeted: bool = False,
norm: Union[int, float, str] = 2,
max_iter: int = 50,
max_eval: int = 10000,
init_eval: int = 100,
init_size: int = 100,
verbose: bool = True,
) -> None:
"""
Create a HopSkipJump attack instance.
:param classifier: A trained classifier.
:param batch_size: The size of the batch used by the estimator during inference.
:param targeted: Should the attack target one specific class.
:param norm: Order of the norm. Possible values: "inf", np.inf or 2.
:param max_iter: Maximum number of iterations.
:param max_eval: Maximum number of evaluations for estimating gradient.
:param init_eval: Initial number of evaluations for estimating gradient.
:param init_size: Maximum number of trials for initial generation of adversarial examples.
:param verbose: Show progress bars.
"""
super().__init__(estimator=classifier)
self._targeted = targeted
self.norm = norm
self.max_iter = max_iter
self.max_eval = max_eval
self.init_eval = init_eval
self.init_size = init_size
self.curr_iter = 0
self.batch_size = batch_size
self.verbose = verbose
self._check_params()
self.curr_iter = 0
# Set binary search threshold
if norm == 2:
self.theta = 0.01 / np.sqrt(np.prod(self.estimator.input_shape))
else:
self.theta = 0.01 / np.prod(self.estimator.input_shape)
def generate(self, x: np.ndarray, y: Optional[np.ndarray] = None, **kwargs) -> np.ndarray:
"""
Generate adversarial samples and return them in an array.
:param x: An array with the original inputs to be attacked.
:param y: Target values (class labels) one-hot-encoded of shape `(nb_samples, nb_classes)` or indices of shape
(nb_samples,).
:param mask: An array with a mask broadcastable to input `x` defining where to apply adversarial perturbations.
Shape needs to be broadcastable to the shape of x and can also be of the same shape as `x`. Any
features for which the mask is zero will not be adversarially perturbed.
:type mask: `np.ndarray`
:param x_adv_init: Initial array to act as initial adversarial examples. Same shape as `x`.
:type x_adv_init: `np.ndarray`
:param resume: Allow users to continue their previous attack.
:type resume: `bool`
:return: An array holding the adversarial examples.
"""
mask = kwargs.get("mask")
y = check_and_transform_label_format(y, self.estimator.nb_classes)
if y is not None and self.estimator.nb_classes == 2 and y.shape[1] == 1: # pragma: no cover
raise ValueError(
"This attack has not yet been tested for binary classification with a single output classifier."
)
# Check whether users need a stateful attack
resume = kwargs.get("resume")
if resume is not None and resume:
start = self.curr_iter
else:
start = 0
# Check the mask
if mask is not None:
if len(mask.shape) == len(x.shape):
mask = mask.astype(ART_NUMPY_DTYPE)
else:
mask = np.array([mask.astype(ART_NUMPY_DTYPE)] * x.shape[0])
else:
mask = np.array([None] * x.shape[0])
# Get clip_min and clip_max from the classifier or infer them from data
if self.estimator.clip_values is not None:
clip_min, clip_max = self.estimator.clip_values
else:
clip_min, clip_max = np.min(x), np.max(x)
# Prediction from the original images
preds = np.argmax(self.estimator.predict(x, batch_size=self.batch_size), axis=1)
# Prediction from the initial adversarial examples if not None
x_adv_init = kwargs.get("x_adv_init")
if x_adv_init is not None:
# Add mask param to the x_adv_init
for i in range(x.shape[0]):
if mask[i] is not None:
x_adv_init[i] = x_adv_init[i] * mask[i] + x[i] * (1 - mask[i])
# Do prediction on the init
init_preds = np.argmax(self.estimator.predict(x_adv_init, batch_size=self.batch_size), axis=1)
else:
init_preds = [None] * len(x)
x_adv_init = [None] * len(x)
# Assert that, if attack is targeted, y is provided
if self.targeted and y is None: # pragma: no cover
raise ValueError("Target labels `y` need to be provided for a targeted attack.")
# Some initial setups
x_adv = x.astype(ART_NUMPY_DTYPE)
if y is not None:
y = np.argmax(y, axis=1)
# Generate the adversarial samples
for ind, val in enumerate(tqdm(x_adv, desc="HopSkipJump", disable=not self.verbose)):
self.curr_iter = start
if self.targeted:
x_adv[ind] = self._perturb(
x=val,
y=y[ind],
y_p=preds[ind],
init_pred=init_preds[ind],
adv_init=x_adv_init[ind],
mask=mask[ind],
clip_min=clip_min,
clip_max=clip_max,
)
else:
x_adv[ind] = self._perturb(
x=val,
y=-1,
y_p=preds[ind],
init_pred=init_preds[ind],
adv_init=x_adv_init[ind],
mask=mask[ind],
clip_min=clip_min,
clip_max=clip_max,
)
if y is not None:
y = to_categorical(y, self.estimator.nb_classes)
logger.info(
"Success rate of HopSkipJump attack: %.2f%%",
100 * compute_success(self.estimator, x, y, x_adv, self.targeted, batch_size=self.batch_size),
)
return x_adv
def _perturb(
self,
x: np.ndarray,
y: int,
y_p: int,
init_pred: int,
adv_init: np.ndarray,
mask: Optional[np.ndarray],
clip_min: float,
clip_max: float,
) -> np.ndarray:
"""
Internal attack function for one example.
:param x: An array with one original input to be attacked.
:param y: If `self.targeted` is true, then `y` represents the target label.
:param y_p: The predicted label of x.
:param init_pred: The predicted label of the initial image.
:param adv_init: Initial array to act as an initial adversarial example.
:param mask: An array with a mask to be applied to the adversarial perturbations. Shape needs to be
broadcastable to the shape of x. Any features for which the mask is zero will not be adversarially
perturbed.
:param clip_min: Minimum value of an example.
:param clip_max: Maximum value of an example.
:return: An adversarial example.
"""
# First, create an initial adversarial sample
initial_sample = self._init_sample(x, y, y_p, init_pred, adv_init, mask, clip_min, clip_max)
# If an initial adversarial example is not found, then return the original image
if initial_sample is None:
return x
# If an initial adversarial example found, then go with HopSkipJump attack
x_adv = self._attack(initial_sample[0], x, initial_sample[1], mask, clip_min, clip_max)
return x_adv
def _init_sample(
self,
x: np.ndarray,
y: int,
y_p: int,
init_pred: int,
adv_init: np.ndarray,
mask: Optional[np.ndarray],
clip_min: float,
clip_max: float,
) -> Optional[Union[np.ndarray, Tuple[np.ndarray, int]]]:
"""
Find initial adversarial example for the attack.
:param x: An array with 1 original input to be attacked.
:param y: If `self.targeted` is true, then `y` represents the target label.
:param y_p: The predicted label of x.
:param init_pred: The predicted label of the initial image.
:param adv_init: Initial array to act as an initial adversarial example.
:param mask: An array with a mask to be applied to the adversarial perturbations. Shape needs to be
broadcastable to the shape of x. Any features for which the mask is zero will not be adversarially
perturbed.
:param clip_min: Minimum value of an example.
:param clip_max: Maximum value of an example.
:return: An adversarial example.
"""
nprd = np.random.RandomState()
initial_sample = None
if self.targeted:
# Attack satisfied
if y == y_p:
return None
# Attack unsatisfied yet and the initial image satisfied
if adv_init is not None and init_pred == y:
return adv_init.astype(ART_NUMPY_DTYPE), init_pred
# Attack unsatisfied yet and the initial image unsatisfied
for _ in range(self.init_size):
random_img = nprd.uniform(clip_min, clip_max, size=x.shape).astype(x.dtype)
if mask is not None:
random_img = random_img * mask + x * (1 - mask)
random_class = np.argmax(
self.estimator.predict(np.array([random_img]), batch_size=self.batch_size),
axis=1,
)[0]
if random_class == y:
# Binary search to reduce the l2 distance to the original image
random_img = self._binary_search(
current_sample=random_img,
original_sample=x,
target=y,
norm=2,
clip_min=clip_min,
clip_max=clip_max,
threshold=0.001,
)
initial_sample = random_img, random_class
logger.info("Found initial adversarial image for targeted attack.")
break
else:
logger.warning("Failed to draw a random image that is adversarial, attack failed.")
else:
# The initial image satisfied
if adv_init is not None and init_pred != y_p:
return adv_init.astype(ART_NUMPY_DTYPE), y_p
# The initial image unsatisfied
for _ in range(self.init_size):
random_img = nprd.uniform(clip_min, clip_max, size=x.shape).astype(x.dtype)
if mask is not None:
random_img = random_img * mask + x * (1 - mask)
random_class = np.argmax(
self.estimator.predict(np.array([random_img]), batch_size=self.batch_size),
axis=1,
)[0]
if random_class != y_p:
# Binary search to reduce the l2 distance to the original image
random_img = self._binary_search(
current_sample=random_img,
original_sample=x,
target=y_p,
norm=2,
clip_min=clip_min,
clip_max=clip_max,
threshold=0.001,
)
initial_sample = random_img, y_p
logger.info("Found initial adversarial image for untargeted attack.")
break
else:
logger.warning("Failed to draw a random image that is adversarial, attack failed.")
return initial_sample
def _attack(
self,
initial_sample: np.ndarray,
original_sample: np.ndarray,
target: int,
mask: Optional[np.ndarray],
clip_min: float,
clip_max: float,
) -> np.ndarray:
"""
Main function for the boundary attack.
:param initial_sample: An initial adversarial example.
:param original_sample: The original input.
:param target: The target label.
:param mask: An array with a mask to be applied to the adversarial perturbations. Shape needs to be
broadcastable to the shape of x. Any features for which the mask is zero will not be adversarially
perturbed.
:param clip_min: Minimum value of an example.
:param clip_max: Maximum value of an example.
:return: an adversarial example.
"""
# Set current perturbed image to the initial image
current_sample = initial_sample
# Main loop to wander around the boundary
for _ in range(self.max_iter):
# First compute delta
delta = self._compute_delta(
current_sample=current_sample,
original_sample=original_sample,
clip_min=clip_min,
clip_max=clip_max,
)
# Then run binary search
current_sample = self._binary_search(
current_sample=current_sample,
original_sample=original_sample,
norm=self.norm,
target=target,
clip_min=clip_min,
clip_max=clip_max,
)
# Next compute the number of evaluations and compute the update
num_eval = min(int(self.init_eval * np.sqrt(self.curr_iter + 1)), self.max_eval)
update = self._compute_update(
current_sample=current_sample,
num_eval=num_eval,
delta=delta,
target=target,
mask=mask,
clip_min=clip_min,
clip_max=clip_max,
)
# Finally run step size search by first computing epsilon
if self.norm == 2:
dist = np.linalg.norm(original_sample - current_sample)
else:
dist = np.max(abs(original_sample - current_sample))
epsilon = 2.0 * dist / np.sqrt(self.curr_iter + 1)
success = False
while not success:
epsilon /= 2.0
potential_sample = current_sample + epsilon * update
success = self._adversarial_satisfactory(
samples=potential_sample[None],
target=target,
clip_min=clip_min,
clip_max=clip_max,
)
# Update current sample
current_sample = np.clip(potential_sample, clip_min, clip_max)
# Update current iteration
self.curr_iter += 1
# If attack failed. return original sample
if np.isnan(current_sample).any(): # pragma: no cover
logger.debug("NaN detected in sample, returning original sample.")
return original_sample
return current_sample
def _binary_search(
self,
current_sample: np.ndarray,
original_sample: np.ndarray,
target: int,
norm: Union[int, float, str],
clip_min: float,
clip_max: float,
threshold: Optional[float] = None,
) -> np.ndarray:
"""
Binary search to approach the boundary.
:param current_sample: Current adversarial example.
:param original_sample: The original input.
:param target: The target label.
:param norm: Order of the norm. Possible values: "inf", np.inf or 2.
:param clip_min: Minimum value of an example.
:param clip_max: Maximum value of an example.
:param threshold: The upper threshold in binary search.
:return: an adversarial example.
"""
# First set upper and lower bounds as well as the threshold for the binary search
if norm == 2:
(upper_bound, lower_bound) = (1, 0)
if threshold is None:
threshold = self.theta
else:
(upper_bound, lower_bound) = (
np.max(abs(original_sample - current_sample)),
0,
)
if threshold is None:
threshold = np.minimum(upper_bound * self.theta, self.theta)
# Then start the binary search
while (upper_bound - lower_bound) > threshold:
# Interpolation point
alpha = (upper_bound + lower_bound) / 2.0
interpolated_sample = self._interpolate(
current_sample=current_sample,
original_sample=original_sample,
alpha=alpha,
norm=norm,
)
# Update upper_bound and lower_bound
satisfied = self._adversarial_satisfactory(
samples=interpolated_sample[None],
target=target,
clip_min=clip_min,
clip_max=clip_max,
)[0]
lower_bound = | np.where(satisfied == 0, alpha, lower_bound) | numpy.where |
# -*- coding: utf-8 -*-
#
# Authors: Swolf <<EMAIL>>
# Date: 2021/1/23
# License: MIT License
"""
Riemannian Procrustes Analysis.
Modified from https://github.com/plcrodrigues/RPA
"""
from typing import Union, List, Tuple, Dict, Optional, Callable
from functools import partial
import numpy as np
from numpy import ndarray
from sklearn.base import BaseEstimator, TransformerMixin, ClassifierMixin
from sklearn.utils.extmath import softmax
from joblib import Parallel, delayed
from scipy.linalg import eigvalsh, inv, eigh
import autograd.numpy as anp
try:
from pymanopt.manifolds import Rotations
except:
from pymanopt.manifolds import SpecialOrthogonalGroup as Rotations
from pymanopt import Problem
try:
from pymanopt.solvers import SteepestDescent
except:
from pymanopt.optimizers import SteepestDescent
from ..utils.covariance import (nearestPD, covariances, sqrtm, invsqrtm, logm, expm, powm)
from .riemann import mean_riemann, distance_riemann
def get_recenter(X: ndarray,
cov_method: str = 'cov',
mean_method: str = 'riemann',
n_jobs: Optional[int] = None):
X = np.reshape(X, (-1, *X.shape[-2:]))
X = X - np.mean(X, axis=-1, keepdims=True)
C = covariances(X, estimator=cov_method, n_jobs=n_jobs)
if mean_method == 'riemann':
M = mean_riemann(C, n_jobs=n_jobs)
elif mean_method == 'euclid':
M = | np.mean(C, axis=0) | numpy.mean |
from numpy import genfromtxt, histogram, savetxt, column_stack
from matplotlib import pyplot as plt
file = "./charts_data/timing_prio.dat"
out_file = "hist_data.dat"
data = genfromtxt(file, delimiter='\t', dtype=None, autostrip=True, skip_header=1)
hist_data, bin_edges = histogram(data[:, 1], bins=20, range=(0.0, 1000.0))
out_data = []
out_data.append(bin_edges[0:-1])
for i in range(0, 4):
hist_data, bin_edges = histogram(data[:, i], bins=20, range=(0.0, 1000.0))
out_data.append(hist_data)
with open(out_file, "w") as f:
savetxt(f, | column_stack(out_data) | numpy.column_stack |
import numpy as np
import torch
from gym import spaces
class ReplayBuffer(object):
"""
Replay Buffer for multi-agent RL with parallel rollouts, global state,
local observations, and shared rewards
"""
def __init__(self, max_steps, num_agents, state_space, observation_space, action_space):
"""
Inputs:
max_steps (int): Maximum number of timepoints to store in buffer
num_agents (int): Number of agents in environment
"""
self.max_steps = max_steps
self.num_agents = num_agents
self.state_vect_buff = np.zeros((max_steps, state_space.shape[0]), dtype=np.float32)
self.next_state_vect_buff = np.zeros((max_steps, state_space.shape[0]), dtype=np.float32)
self.rew_buff = np.zeros(max_steps, dtype=np.float32)
self.done_buff = | np.zeros(max_steps, dtype=np.uint8) | numpy.zeros |
# Implemented by <NAME>
import six
import os
import numpy as np
from copy import deepcopy
from itertools import chain
import unittest
import healpy as hp
import warnings
# disable new order warnings in tests
warnings.filterwarnings("ignore")
nside_precomputed = 4
lmax_precomputed = 8
galm = np.array(
[
-0.60749536999999998 + 0j,
0.83559932999999997 + 0j,
-1.0174608599999999 + 0j,
1.0993299999999999 + 0j,
-1.0415247299999999 + 0j,
0.98637741999999995 + 0j,
-1.2327712799999999 + 0j,
-0.65081703999999996 + 0j,
-1.1239971900000001 + 0j,
0.96501168000000004 - 2.3554313900000001j,
-0.40474513000000001 - 0.65564383000000004j,
0.15638859999999999 - 0.23621884000000001j,
0.28043983 - 0.39658116999999998j,
-0.26163387999999999 - 0.077809699999999996j,
0.20287720000000001 - 0.06082216j,
0.052013629999999998 + 0.073047849999999998j,
0.68909047999999995 + 0.65423257999999995j,
0.48747127000000001 + 0.30760153000000001j,
-0.35432469999999999 - 1.0799235300000001j,
0.43819587999999998 - 0.22769086999999999j,
-0.57252002000000002 - 0.13502544j,
0.63900029000000003 - 0.59585710000000003j,
-1.16030893 - 0.25760955000000002j,
0.37504869000000002 + 0.058102309999999997j,
-0.98924601000000001 - 0.46924109000000003j,
0.71031016000000002 - 0.90896836000000003j,
-0.43448922000000001 - 0.12677451000000001j,
-0.77544904000000003 - 0.25176252999999998j,
-0.01721661 - 0.94948701000000002j,
0.85474141000000003 - 0.051103330000000002j,
-0.60520565999999998 + 0.87760647999999997j,
-0.77864944000000003 - 0.79208626999999998j,
-1.08657508 - 0.59487055j,
0.21367211 - 1.5110769900000001j,
-0.16784056999999999 + 0.80020639000000005j,
-1.1339041000000001 - 0.32197503999999999j,
0.19618954 + 1.08100252j,
0.43866369 - 0.47475267999999998j,
0.11857266 - 0.049022839999999998j,
-0.40366523999999998 + 0.85542658000000005j,
0.56154870999999995 - 0.77527478999999999j,
0.48146275999999999 + 0.16245443000000001j,
-0.68355484 - 0.22983015000000001j,
-0.061040659999999997 - 0.13420304999999999j,
0.27255975999999998 - 0.75328077999999998j,
]
)
calm = np.array(
[
1.0718601933803977 + 0j,
-1.5182685950801673 + 0j,
-0.39119975933464429 + 0j,
-0.6620552667513403 + 0j,
0.42674481653281382 + 0j,
1.3799470126677567 + 0j,
-1.4604721504544589 + 0j,
-1.1136471151307403 + 0j,
-1.647392955477013 + 0j,
0.71919252212426499 - 0.39773236587790972j,
1.1884542365155342 - 0.02640806030381616j,
-0.040937417189905477 + 0.41096619318378996j,
0.19575829981467366 - 0.9285256561788201j,
-0.81538492817093389 - 0.35929021939020905j,
0.46870617235542178 - 0.16617809319149193j,
0.23640105395174835 + 0.20199283448907013j,
-0.4326244206185022 - 0.59306323217984414j,
0.70410703555897491 + 1.1105121855564981j,
-0.25795284664102419 - 1.2596368643912992j,
-0.32298608901330822 + 0.28961247423501457j,
0.86075337105780647 + 0.11654277740017273j,
0.61549312276703594 - 0.10703912813862339j,
0.18586512296424443 - 0.19025963131317278j,
-1.0133508690870945 + 0.37723661046981605j,
0.81779407406185822 + 0.079623471577802724j,
-0.36878503033040533 - 0.2898255702618146j,
-0.13864500443953851 + 0.99443154731355876j,
-0.18473645501235322 - 0.27320195658100321j,
-0.59576170002379292 + 0.82900875927708351j,
-0.42589567337148737 - 0.4359073358803493j,
-1.0071527860797036 + 0.94936616398900131j,
0.52681818118587864 - 0.14360294581437408j,
0.92619570387111039 + 0.051664002362596051j,
0.75431992804310644 - 0.25779974392362176j,
-0.89919787406938079 + 0.4989749264182417j,
0.50889483979981087 + 0.80485052548180069j,
1.0832061738848424 - 0.70024088919678606j,
-0.81326057995656997 + 1.0871815291974078j,
0.66115253781072936 - 1.1579428341478799j,
-0.25669790905903495 + 0.031910894413264487j,
-0.055840352620168392 - 0.27126620265309953j,
0.77754873311978667 + 0.1677199540737199j,
-0.2428367232543345 + 0.058222152917874435j,
-0.35655343174399751 + 0.28585938716743436j,
0.44494756551095588 + 0.17931771534010477j,
]
)
maps = {
1: np.array(
[
1.1743580943750218 + 1.0162508812596662j,
-1.7545991014514022 + 3.9632546003544267j,
3.4755301242047865 + 3.6205268666848651j,
3.463772051893852 - 0.16092758895196169j,
1.6137200258556599 + 0.73266613851658846j,
-0.78408695644456827 - 0.017688408927465843j,
-3.2331912918298711 + 1.0423682626399753j,
-2.4967573102249689 + 5.4249205744223872j,
1.9618186881421982 + 4.9309708160236383j,
3.0923993499620077 - 0.4894899405424642j,
3.8802145016214444 - 1.7023962410322717j,
1.6609384663419748 - 1.907262230594307j,
0.48237984905359593 - 1.7832620041462326j,
-0.91903915540372738 - 1.4797023464820716j,
-3.3079615434500242 - 0.87195141293021572j,
-3.2711896733834713 + 0.12177676469629328j,
-1.4919533733781134 - 1.6435471612444656j,
-2.6523233433871019 + 4.2474564187420576j,
0.91780925153179838 + 4.9570523962893001j,
0.42584487195441895 - 1.8426545772598648j,
0.23225332448920533 - 3.4181823103655073j,
1.4984860851219615 - 0.98863554278420129j,
-0.35246834799111726 - 3.3771616282380563j,
-1.5062845496910013 - 3.4935340751923691j,
0.13099914430749093 - 2.0149335831137503j,
-0.99476127813711768 - 1.9875208527665134j,
-1.1508757672399341 - 1.1170925992609697j,
-2.2800860488149857 + 2.5337276570280665j,
-2.0227144551955485 + 4.4062547882406582j,
0.85159759341389984 - 0.25969432494507549j,
0.10617879436802691 - 1.4704556654073533j,
-0.74056700667340003 + 3.9958069996884769j,
1.8376229758120008 + 4.8939057972543516j,
0.56097592637522953 + 1.1962336897882726j,
-1.3522314207704584 - 2.3788885700721187j,
-0.3910200060975908 - 2.0276298492296441j,
1.1696744495267888 + 2.4194144879695001j,
0.61111633566009804 + 1.9810226991014681j,
-1.2570081724109712 - 2.4256572995991448j,
-2.0379607424382673 - 2.3401230961329462j,
-0.11895117415507916 - 0.20168228572033531j,
-1.1721585258230467 - 0.40434726332170645j,
-0.87007913988881902 + 1.0470079216653014j,
1.0632956396927513 + 0.86183414835909822j,
-0.38580133850999232 + 4.9648768523408924j,
-1.1378511659644674 + 3.5600642062343684j,
0.059277285920489975 + 2.2071682852740224j,
0.32981878804494424 + 2.0708756974471436j,
1.5954797850952303 + 3.9506597955061187j,
1.113967802900363 + 3.8105501539801976j,
-0.34187488675854677 + 3.0267213287624557j,
0.18662232048160876 - 1.2571845658067642j,
2.7139610044225382 + 0.69222466212540557j,
1.4373026138501541 + 3.902110493851922j,
2.3082293966444007 + 2.2987716217551775j,
1.3462006391244148 - 0.10182718246119304j,
-1.0329879104957191 - 1.0590332100623074j,
-3.0810859363267094 + 3.1945037345098988j,
0.77362743359084163 + 0.84013578687826662j,
1.0464890345883808 - 0.72771732260634059j,
-0.51744859070890492 - 0.81451970371406568j,
-2.9428700854575434 + 2.762899585992368j,
-0.40115243174986093 + 3.8372871200581486j,
0.96128270685925343 + 0.93840717545663799j,
0.41639434446527768 + 2.5331280325752732j,
-0.519386987039123 + 4.2723375559049348j,
0.52495944959322849 + 0.8116227621810026j,
2.5244086242304857 - 1.89004339281529j,
2.0195410343451292 + 0.21295550110166039j,
-1.8684314756711684 + 2.3019863570099734j,
4.0113534030248825 + 2.4322957453578007j,
2.5067778456719454 + 1.3635087014727825j,
1.8581737323759087 - 1.1755871365622586j,
-3.278606394868425 - 0.74168306105753778j,
-1.6581650987018286 + 3.4206773381711715j,
-0.20328962742120149 - 2.6517323129301227j,
0.11939427685928439 - 3.914762222637826j,
-1.1719762486786653 - 3.6258016903482262j,
-1.9695972814337694 + 4.7844819781500254j,
0.70410051090004111 - 0.63082142973243238j,
0.58203862242748194 + 0.17092305557744025j,
-1.0446335319978968 + 2.2194447533251744j,
0.15655310887242035 + 0.86561734274560376j,
0.31563746550827387 - 2.9298241668860747j,
2.7860378031530235 - 1.0136028592766184j,
-4.3782229028819648 - 0.33971568537612828j,
-3.0909568032763324 + 2.5513031796814909j,
4.6737413708938655 + 2.7302786045020038j,
0.13272621959023939 - 4.1711765732663011j,
-2.2749762169482466 + 0.25421841905327258j,
-0.50489760751634882 - 0.91377903881434097j,
-2.287069616277897 - 1.0631181589973533j,
0.7972895323203042 - 3.4207848305117969j,
-0.23326908605637886 + 1.089382332171946j,
0.0098601007056405704 + 1.4586475390991032j,
1.0365833871785477 - 2.4620420564717742j,
0.36572720828156252 + 1.6541853704371952j,
-0.51430469009147317 - 0.049252228418473765j,
-0.62145289699741391 - 3.375619986564951j,
0.35466808756859192 - 1.3690595024956109j,
-0.25322914773962185 + 0.32316646758647627j,
-7.4892488525844554 + 1.1525104561324868j,
-0.12392585470999483 + 2.4297661937947765j,
4.2905861596881323 + 0.67018882572843463j,
2.3390789232929543 - 2.3191321695784399j,
-0.44619718489570181 - 3.8333096552555777j,
0.51352876521471524 - 1.6804333968219132j,
-1.7025201697344337 - 0.1008347592396226j,
-1.477972480809314 + 4.2322266421353856j,
1.399058406997034 + 0.63203496833525186j,
-0.039998736140595348 + 3.1534667411092578j,
0.001699954715300489 - 1.6894128318777268j,
1.8608282629517956 + 0.54462233467286736j,
0.022347730866276339 + 0.94097808664808924j,
-0.97565390581191991 - 2.0043597662134327j,
-0.85205216583024623 - 2.2679689843892588j,
0.53947735206622338 + 0.92108210028888182j,
-2.5670596443819931 + 0.38871863049383093j,
-2.934869851153608 + 1.2511147622702086j,
2.0825683383127727 + 0.45929928305134715j,
0.37898448820629005 - 2.6841486733486013j,
1.0120152854590612 - 1.6425972444002646j,
0.7776935701538118 - 1.952106003854329j,
-1.2780368759454575 + 4.6651596443819408j,
-0.039206971051687134 + 5.265018964377389j,
-0.54489461163081254 + 2.8671152905341284j,
-1.636083304638287 + 1.8615197052158607j,
1.4325345827348386 - 0.58443769148648628j,
1.8893019352323406 + 0.93513602825308595j,
-2.139093319814994 + 0.49456047669865844j,
0.033273312452318238 - 0.67524051231226145j,
0.0018165800924796471 + 0.24539790830842012j,
-1.830677860003034 - 0.88907276825821402j,
0.23881421516801424 - 0.71660110558242596j,
1.4607757935805321 - 0.20332350008812516j,
0.31479988117869262 - 1.4797543881405799j,
-1.4700646395419654 - 2.3412000314939014j,
1.3630043099840954 + 1.0459288308034624j,
1.0366509002025306 + 1.4017065365354837j,
0.5324643362883491 - 0.19564285336892207j,
0.86203010112261591 + 3.8589883704164376j,
-1.4871335108899939 + 3.2965305219683243j,
-3.506476212648844 + 3.1925528967103802j,
0.15264175448604056 + 0.431490908418659j,
4.2777064175487407 - 1.2512757866202306j,
-1.1870189698038707 + 0.75501344481612265j,
-1.839602146399741 + 1.4963403982128953j,
2.3099273465758903 + 1.2697775493766699j,
-4.3475497187867314 - 0.32036886085994221j,
-3.3064040751562334 - 2.9625087732893531j,
3.6141886575697248 - 0.0099341031074851038j,
0.0048861040277541345 - 0.6295182389123023j,
1.5000073794953357 - 0.88609288760098115j,
2.2323719937100908 + 5.4902541505729845j,
-0.2585807286071018 + 2.5584952206368938j,
1.7769833707262548 - 0.3408851516775957j,
0.37978034270511074 + 2.9026249163611726j,
-4.6921406543266571 + 4.3678134780358526j,
-2.4462636775404958 + 1.4523419567722944j,
5.2941943690732423 - 2.6008774047519228j,
3.4595406699843201 - 0.99129783569826058j,
-3.4841770617209473 + 1.2717869796731138j,
0.13850539692866526 + 0.94282786052434553j,
-2.1789230651774014 + 1.6415064719591206j,
-8.811149558407779 - 0.86858984219214674j,
-0.98048863671795994 + 0.035234022992954195j,
2.3501190627193562 + 2.7317457688466678j,
-1.5421024919985193 - 1.7186736892960668j,
2.139635096504529 - 1.8367715460959313j,
0.41669207038592981 + 3.3753865855933527j,
0.42812877807536154 + 0.88267208286037602j,
-1.6620756081654045 + 5.368686741364268j,
-5.4496694415397027 + 3.4393514966821126j,
3.2274980963579551 - 2.6154731433818244j,
1.2325162367548854 + 0.25900311819665534j,
-4.9927575224429273 - 0.77655205094166613j,
-3.9137002256716968 - 0.87208435187132305j,
-5.8396208197376538 - 0.033400550471304857j,
0.88165596824067283 + 3.3402495465420188j,
-0.77813555128307499 - 0.49824566884112964j,
-1.2569589183195746 - 3.992299237539171j,
-0.55073556348169195 - 0.99367233232065755j,
-3.1361715966867241 + 3.8990411125610152j,
-1.2479889140797951 - 0.86728888508048596j,
-3.438346192247995 + 0.75427470765301274j,
-5.8362598289444767 - 3.7106623335656881j,
-1.6220739622888261 - 0.85412380326550341j,
-2.3618246988425389 + 0.10262957279861007j,
-2.0128151752491599 - 5.2483459258638678j,
-0.28798741542347162 + 0.082139772535972211j,
-4.4336542047160892 - 0.12984758528642848j,
-3.0452434904226706 - 0.34940617145697844j,
]
),
2: np.array(
[
-1.1165046042602529 + 0.74756586618731813j,
2.9563864696268687 + 1.016510598068517j,
-1.7273931284275377 + 1.684970250530498j,
2.1374510755011236 + 1.3953489111135389j,
1.264058043394483 + 1.0656402139582337j,
0.59206130659344847 + 2.8140992156732278j,
0.062093775185857902 + 2.0904994744842891j,
2.9429778836437221 + 1.7128991560692999j,
-2.6110141508418021 + 1.1140285432863466j,
2.326165567157239 + 3.2728054144888676j,
2.6626908823784907 + 0.52728366204875832j,
3.5908021600075641 + 0.96903781804179978j,
0.90571149765085535 + 0.24081124592692693j,
0.72871814828353709 + 1.332418563783788j,
0.60164374752130945 + 0.15445148430884423j,
-2.5529506354313782 - 2.3304064585375239j,
-1.8879418959660019 + 2.682343033625215j,
2.1668168490952775 + 1.4157064593061692j,
-3.1636708644108649 + 0.64742953025658889j,
-1.4210029334653473 + 2.6334896788286049j,
3.6902066347461573 + 0.13892873924238483j,
2.9575090399303945 - 2.6325502244852719j,
0.17878513667675777 - 1.1585078531329858j,
2.1237001808101663 - 1.323323837586023j,
-0.16120044138369383 - 1.2121424743269673j,
0.8624452370473753 - 1.0686957121793859j,
-0.51467053641764826 - 1.1945130365136154j,
-0.18418165278174148 - 0.59116856193750777j,
-2.6169185838042068 - 2.4146314558175046j,
-2.7622714373457917 - 2.3797351683439834j,
0.073910048482292545 + 0.16496145279596552j,
0.80910813851825103 + 0.56242050573198998j,
-1.9584133243280075 + 1.0892351163388432j,
-2.1814162287477559 + 0.61054532617299695j,
-1.5169577705416253 - 1.0235623545618981j,
1.9895718538585976 - 1.8211523939205545j,
2.4118671091811361 - 1.9453281674321252j,
-1.3835825480021706 - 2.94255319882138j,
-3.3831677322689044 - 2.4580709837790149j,
-1.0643850899431524 - 2.7522668625312905j,
-1.9640650365404291 - 0.35711187195874783j,
2.0439239983559903 - 0.31240155157933036j,
-0.22521863704724376 - 3.4584160218021305j,
-0.51534527570261424 + 1.0301056642659554j,
-0.81562474322987222 + 3.7503264056978267j,
-0.060726807609905009 + 1.8031960877879551j,
0.86667213746967398 - 2.9028917378472125j,
-0.15387539712023934 + 0.13908261984620263j,
0.45953137238099684 + 2.2626118142274105j,
0.62744200989512788 + 1.9272207054022881j,
-2.3255110017526608 - 0.53695630414710283j,
-1.5190658716876777 - 0.9208472578106438j,
2.137223495429847 + 0.68320323689351148j,
3.1584401529074442 + 1.7321545691722557j,
-1.1125695286320998 - 3.2076280088399511j,
-3.7060965836044932 - 1.9780143459066473j,
-0.0012842332451774574 + 3.2452953615132838j,
2.2855371052053712 - 1.1752563745986131j,
-1.7649471509112493 - 0.88061905568140997j,
0.75495292840738937 + 3.6278072525475187j,
-0.49646600004863894 + 5.9486839669421894j,
2.9426274856719101 + 1.0146400853383064j,
-1.5434946162364205 - 1.1288427968038663j,
0.1004948003661843 + 2.7446408233087585j,
1.6891184209589296 + 3.1297213004998374j,
-0.05236089581184955 + 1.9379909861717084j,
-2.5137867334898658 + 1.4249473105986246j,
1.649739972413804 - 0.1284157001992281j,
3.8737660306719093 + 4.4058712012072778j,
5.5734334582390925 - 0.01859570677500616j,
0.034418186067761702 - 3.7863468040480583j,
-3.6185785482837716 + 0.87492996512854082j,
-3.523709866409459 + 3.8351231556344709j,
1.9035220821258987 + 3.5762696257910473j,
-1.3355317211315365 - 0.12437729138156417j,
0.27233720824024044 + 0.62568960888382408j,
-0.087131156071871274 - 0.010324624464344678j,
1.4827889367880731 + 2.2703868481775364j,
-0.27368753287508718 - 0.23035237674465425j,
-2.3786689738351767 + 1.4567486754553038j,
1.4386131990647175 + 2.4034598349374283j,
0.066680160631143237 + 2.7232295144266274j,
-1.666407419777012 + 2.9083944127863561j,
1.3023780882542342 + 0.52194039596842601j,
3.3146056296510493 + 0.66745607226026649j,
4.2456604060579677 + 3.8969561221755749j,
4.1998262021248625 - 4.0793461167911262j,
-0.76421358406766027 - 1.2315027885578802j,
-1.5357398471693586 + 3.7748327293868642j,
0.095984948174640872 + 2.2104973139657291j,
-1.4588631998320354 + 1.134201407450617j,
1.6387745345036606 - 3.8466513697644413j,
-0.73057877816794492 - 4.655134203127945j,
1.6085189126683648 - 0.21988000108022218j,
-3.1142178896816564 + 0.091923489293964877j,
0.62820278401392149 + 0.1889975872022136j,
-0.16120633228908154 + 1.9707163592075072j,
-1.235116936758984 + 2.1482450245585314j,
-0.021985008426573249 + 1.1038279261596868j,
3.6413478144793245 - 1.5615567405467394j,
1.836327464800555 + 2.8541227399557041j,
0.93919940461177709 + 0.14620058990910742j,
0.95456236801488359 - 3.2026192357315972j,
-1.7481075885435755 + 1.6730186360367643j,
-0.84626775726936276 + 1.6575377579793631j,
-0.26164286832258099 + 0.76088427278556803j,
-1.2966015229936554 + 0.97676041471092478j,
1.6124370820759013 - 0.58585228456899752j,
-0.21994376085816314 - 6.2532282013448075j,
0.8353593803854652 - 3.6420691105508212j,
-0.03824087822866562 - 0.054729642257138833j,
-1.3319497354973748 - 2.0327095379389153j,
0.75662881948485083 + 0.30541845281794644j,
-0.76757214187579981 + 2.2787455111432591j,
-0.455100077730823 - 0.55830706795474327j,
1.3313718654711193 - 1.5460827721627417j,
2.9912065916181261 + 0.77182516673656876j,
-0.52278090407902422 + 2.7877639036769803j,
-2.3528997632544266 - 1.2308866273244197j,
0.27817666198979296 + 0.059213451422733376j,
0.45875812556331846 - 1.2692467729246268j,
-0.45874375601474504 - 2.3686526493885238j,
0.479232709947924 - 0.3060902759460391j,
1.4895902195529662 - 0.41735115244048793j,
-0.85025677044974457 - 2.3693856367193904j,
2.0718452260590321 - 0.54927604975188671j,
-1.176356516666446 - 1.9392922793319025j,
-0.79423474673281291 - 2.1390403821586896j,
0.25372445079390721 + 3.1629513441654384j,
0.54044572189189222 + 0.18770434833000893j,
-0.32776474396893496 - 2.9986158756129355j,
1.8555964580559503 + 0.64523330354515551j,
2.6163923211891467 + 2.0073816231373094j,
-0.96827837897054836 - 0.20669532105285635j,
-1.6161700297890988 + 0.058760459668895204j,
1.0388341083117685 + 1.0343083372958142j,
0.8171690777526357 - 1.0241901711901955j,
1.161178491272123 - 3.3193021589202116j,
-0.65705952284124769 - 2.909740964518341j,
1.0464027137937968 - 0.28516514967891382j,
0.31407614249026861 + 2.0789914726795806j,
0.89249898217038592 + 0.74504430864132187j,
0.46653627607511738 - 1.2535459455441251j,
-2.8759949933021893 - 3.4253168189020871j,
-0.55004579155281808 + 1.4416964251162601j,
1.3842770119914176 + 3.7499085234789105j,
0.73300538480603206 - 2.3651197461061306j,
1.2610841999098341 - 0.04478569409858002j,
2.2663256193995895 + 2.6893001805232006j,
3.2282105473513854 - 3.089294872359758j,
1.0246687806608903 - 2.1329916398440454j,
-0.79719171443068326 + 1.1114942772440388j,
2.3820851781718693 - 1.9138147704390083j,
1.478151603469551 + 0.15364879065364989j,
-1.5233345516736922 - 1.3099212472909443j,
1.5072515797375459 - 0.57475142166442117j,
2.1228188430644579 + 2.0096979974944369j,
0.16349467160657194 - 0.13019412026157573j,
-2.8501863703427208 - 4.0570052570082602j,
-1.0157135917807159 - 2.6825682466889411j,
2.3253206740804364 + 4.1263405715172157j,
1.5487387410680176 + 2.2318083306172714j,
3.3480777012584348 - 0.30034799964836079j,
2.7011245606581289 + 4.7335734563336729j,
0.57254668180230106 - 1.6139253460404996j,
3.903853955673366 - 6.6991967093618143j,
0.64492682991521111 - 0.31017629667123225j,
-2.1607929176337426 - 0.16857297635682733j,
4.8098868433499913 + 0.41785061609925878j,
1.1564314939094591 + 4.3710892388226963j,
1.8224691599081939 - 0.63910766786442408j,
2.6435565518448572 + 2.9094520705913056j,
-3.7780259549880189 - 2.1074067076770948j,
1.5393672791948894 - 5.2619312349734786j,
4.5356550511622213 + 4.2698512297085127j,
2.3969803974124391 + 1.9571123112588573j,
3.6061144615068086 + 4.3736176949628423j,
-0.39324476338149617 - 1.9082883633012435j,
3.026448300108715 - 1.7428825416966158j,
-1.9045802882682787 + 0.4426906193634812j,
5.0241978704119958 + 1.9445871037916549j,
2.6831636546598459 + 3.0839149450548007j,
-1.4019967581265769 + 5.0027949271902887j,
-0.0031667657498008206 - 5.3402188332400726j,
2.9517714615379806 + 4.0246422636276797j,
1.4785600380549067 + 0.51660087996842741j,
2.7856553478477579 - 0.88532969501753778j,
0.2673738444085586 + 2.2859423305476705j,
2.7550882281445315 + 0.58476661154179221j,
-3.2828096156515181 + 0.45102580026710948j,
-1.8220345108884464 - 0.00054247733982548674j,
3.2007680062608741 + 2.4615774393552337j,
]
),
3: np.array(
[
-0.66999593287202142 + 0.46243708757420809j,
0.82115988275196528 - 1.6643038327885704j,
0.67399713542071471 - 2.3955600817810208j,
2.215439913637927 + 0.72446638537859487j,
0.93108120226407332 + 0.064033670430578393j,
-0.92739574739897401 + 2.2493044552029375j,
4.0678984753394341 + 3.2507085430096483j,
-1.3168389222564625 - 0.80923697224245794j,
2.4067925151982705 + 0.92813675598570766j,
-2.0493109031701429 - 0.49108376461287684j,
1.6349441369388815 + 4.1340925667887625j,
2.5312429669372829 + 0.44393295017157475j,
2.2198800992090253 - 0.20688768772829413j,
-0.053776255855561117 + 2.1684193251401833j,
-0.74507569207418511 + 2.0534600226420934j,
1.0590676473818048 + 3.4665027379637494j,
2.5831500212178433 + 0.10767106535418591j,
-0.81172453742230211 + 1.5135115252098388j,
0.51675313192529826 + 1.7364523664094207j,
0.017777040747489425 + 0.33054862825595765j,
-0.031923375391498365 - 0.03647474837162834j,
0.75627328628012946 + 2.5870613579433228j,
4.0854570875479279 + 2.1694354582233544j,
3.5281541314540927 + 0.20192676958354183j,
1.2898229939329962 - 2.8439309558484345j,
-1.4676716747053 + 1.2550839973056764j,
1.4660283077695149 + 1.250015105410669j,
-0.24960947184476789 - 1.274656996015006j,
-2.105841001070178 - 2.0766118645037839j,
-2.4893754811904127 - 0.40574540171916373j,
1.1819182474823142 + 1.2543311034554072j,
0.66112124774937775 + 0.73421234301293936j,
-1.5435321344721677 + 0.2405604201908027j,
-2.5174124636556181 + 1.1618925572216374j,
0.69011465007947015 - 0.52483143713649749j,
1.5464610264677234 - 2.6451243970838227j,
-0.097592832333731394 - 2.1470448648923481j,
-1.7790027249170768 + 1.4929022997757122j,
2.1060693685955689 + 0.72313993979877744j,
3.1638994698726481 - 2.1269139943415407j,
2.2107279234732862 - 5.0404555730899059j,
-2.5209363703464924 - 3.302312046473193j,
0.12059012761921761 + 1.3587818158227796j,
1.8826126043065536 - 1.5865310833153738j,
-0.57070268838796012 - 1.585154256627491j,
-4.7784601734110614 - 3.8493106222543396j,
-1.4421251579517258 + 0.98946495072189533j,
3.1612898053286718 - 0.44422399561859394j,
-0.27830641044372373 - 0.94412748500393695j,
-2.6942690780226708 + 0.22023121586779437j,
-1.2938276668529529 - 0.06583465169229219j,
-0.18392187376248736 - 3.6374010616991139j,
1.3907294398416794 - 3.5152092057270137j,
-4.2456806268120735 - 2.3371824677843467j,
-4.5174367628342278 + 3.0159027596758059j,
1.4569480295154498 - 0.40481687203522998j,
0.24452064515296237 - 5.5529329980953808j,
-2.1273220239180053 - 0.73593942867713091j,
1.595151423023013 - 1.1401776866728879j,
0.15780690321442792 + 2.2661324101587246j,
-0.74933288055404634 + 1.3749431486856962j,
-3.0816809779382717 + 0.23742643682485964j,
2.8994367119049036 + 0.7396921744800089j,
1.4994335029613002 - 1.2798108792722671j,
-0.16539584890629019 + 0.48010791918853934j,
-0.89194363806978616 + 0.7170467910739301j,
-2.1293682627235322 - 2.5845385071231268j,
-0.63427315935121464 - 2.1595594356167398j,
0.99308347169563682 - 1.8514493405763055j,
-5.4450584092937877 + 0.97902894760670878j,
-1.0604698602513214 + 3.2312043227524949j,
2.3124452902496664 - 1.3950895449462946j,
1.3201823408003734 - 1.6028209931750983j,
-0.87616516312961035 - 2.1465631953543003j,
-0.34056443490530253 - 0.35013249591511048j,
-1.2364508408450898 + 0.13781313196431211j,
0.038609534515580135 + 6.8698762949471899j,
0.12380533905802339 + 2.7921341862952316j,
0.54660167417157157 + 2.7346629269827281j,
1.6952037866074647 - 0.33387389764274045j,
0.94628165540958409 + 1.2037205024287594j,
0.68176721298456666 + 1.3320274860427599j,
-1.497001928100073 + 0.16859140871709216j,
-2.9208164653643847 - 2.013262526262011j,
2.23493624166204 + 0.38888195090814426j,
0.083266882937527834 + 0.042519190431531406j,
-0.81622472526299195 + 1.602983850729655j,
1.9107865697855551 + 1.8860940491210119j,
-0.5161686146069725 + 0.1067286365498733j,
-0.56830015109909349 + 1.5080358150275226j,
-1.9977061163459469 - 1.2634518707513132j,
-2.7762791817204802 + 2.8410553962536476j,
1.5348104323655993 + 3.8209466359027746j,
1.0447821110316866 + 2.8953941140696262j,
-0.16156969418429323 + 2.1568137355441648j,
1.1423882118876016 + 0.80959057152946856j,
1.2184203681166248 + 1.6431143641185439j,
-1.3333936354073923 + 1.3051448172275528j,
-2.2003497621202652 + 0.034485634672569598j,
0.48305931966908489 - 1.0059947680083925j,
2.4240719735430218 + 1.520434513132964j,
0.14152780483805999 + 0.38291838819136248j,
2.6247680254133194 - 0.34273750279620985j,
0.5170632044924367 + 1.5591723010537319j,
-1.964084322524609 + 2.2043273581641452j,
-1.1123693520916111 + 2.9076285022885537j,
-1.0205304639064758 + 1.726462948906172j,
-3.0513199493069254 - 1.3262259566094576j,
-1.1782640915309317 - 0.13290415044827952j,
2.2282976599379309 - 0.72321887567511034j,
-0.60179533239909233 + 3.307433985055094j,
0.16788252783154045 + 1.0362178538533637j,
2.6706953553371453 + 0.77074105928608427j,
-1.8533672105796244 + 0.35596405935487074j,
-2.6147380869392443 + 1.6093046768585832j,
0.37759170296150524 - 1.5083149569782319j,
1.8716643004532001 - 0.35801239552465747j,
-1.1450981234973723 + 3.042261086804297j,
0.44452106639608746 - 0.69350503725695845j,
1.4879090143200902 - 0.64776217405327741j,
-2.8205775502795389 + 2.641687352135917j,
-0.93692044263706187 + 3.0048923877610507j,
-0.426546964943878 + 0.013344667316707221j,
-1.4443525828613666 - 1.7131214807111499j,
-0.14354399201917334 - 4.0206831461274337j,
0.83443104253838163 + 0.29432217858366894j,
-0.93252862665525393 + 2.9364673343460126j,
3.4431983705905731 - 0.3251990454994399j,
0.43806792303059483 - 0.70784096193188306j,
-4.4119004072708137 + 0.24052114921567447j,
-0.98891595175430935 - 0.46079086925838275j,
1.7417334974194558 - 2.9208658301095776j,
-1.5454462711687187 + 2.5296917145427482j,
-3.3282492610480996 + 4.156447539050224j,
0.40902409375307852 - 0.76847358054292236j,
-0.56330685439900319 + 0.69661436668049836j,
-1.8762485869816681 + 0.64778551016479047j,
-2.4393425483279865 + 0.85171074321319784j,
-0.209819964163376 + 0.099157970328755729j,
1.2392961839922023 - 0.64639270138790006j,
-1.1641752459378989 - 1.4971678104463564j,
-0.56703471832581931 - 2.1716088946899359j,
-0.16437097090423169 + 3.1220884585750146j,
1.3539163377460306 + 1.1869107505913261j,
2.9491476787185125 - 1.2808347797003192j,
-3.2908684053012207 - 0.88608324309025921j,
-4.1007674458331485 - 1.4527729940313197j,
0.44035311401335531 - 3.1365712871936395j,
-1.0141686129277752 - 0.63568191152634734j,
-3.4102891864012639 + 4.2247127971259122j,
-1.1836594760112424 + 3.781939963215049j,
0.51422023588565446 + 0.57579154063617177j,
-2.0246664119505891 - 2.237040145119146j,
-2.2053210495403732 - 1.3846005574579319j,
-1.1160865960532751 - 2.5475738207830227j,
0.50275220925239728 - 1.2519481985598606j,
-1.2100185502945444 - 0.16812837098982908j,
-0.59983421887255994 + 1.6027230741262604j,
-0.52478938635633754 + 2.458183305060198j,
1.5028757257080834 - 0.72420113128118369j,
-0.31146843994891138 - 0.27135667939274499j,
-5.1133106827158112 - 1.8113241566448617j,
-1.5548284863229618 - 4.0468311536026844j,
-0.73513228831134692 - 0.50030377688003924j,
-4.1474633033600306 + 0.067247755883021731j,
0.21758777097351378 + 1.278485302383952j,
1.2889426032473679 + 3.3676304645801252j,
-1.6413393543174832 - 0.091092522462874137j,
-0.40598559211980501 - 3.5363616320930467j,
-4.4770433756596688 - 1.0937535548777739j,
-1.2734316477554803 - 5.4194063797821297j,
0.97449379705901817 + 0.49671560815912308j,
-2.4145658013036444 + 1.063978254382109j,
0.99809956584583803 - 2.5020372804114697j,
-0.12266974796697871 + 1.5896940246064126j,
-2.8686854657724843 - 3.1801933594238334j,
-0.082981417033829663 + 1.7518152509849325j,
-5.3524188522498743 - 2.1053297170691661j,
2.5900259839505644 - 0.061488539624564797j,
-3.4408514291718109 - 0.25659858369140398j,
1.1709160532948188 - 1.3230248129652447j,
-2.9408323582582936 - 4.5277551603690283j,
-0.28478178944932209 + 2.5139667584019603j,
0.28384136446055264 - 6.2274346660954141j,
1.0139856934187432 + 3.7690735174469179j,
-0.0078974510283624788 + 1.2194467618092526j,
-2.7712491346368346 - 2.8279715184334919j,
-2.992529715098045 + 0.56058068732562871j,
0.84316411435805716 - 0.86466988408221113j,
-5.5804660954223984 - 2.9335962670233511j,
-2.5482718063619298 + 3.9524532393702518j,
1.0516464424971148 + 1.578274341181523j,
]
),
}
glms = {
1: np.array(
[
0.0,
0.84319998566330767 + 0j,
-1.0248100911568008 + 0j,
1.110961761523819 + 0j,
-1.0626942039579403 + 0j,
0.99145170493860635 + 0j,
-1.2628244164642952 + 0j,
-0.63157305188622881 + 0j,
-1.1573098411259166 + 0j,
0.98774392762746244 - 2.3324463135047853j,
-0.42041547702109927 - 0.6638941892709691j,
0.17949892445575544 - 0.18716973000962853j,
0.26430768591955539 - 0.40505260468553134j,
-0.24063674747596783 - 0.01667629102507856j,
0.20243814807193189 - 0.061501040558063963j,
0.074181600901263869 + 0.13110650173965177j,
0.70925473188372479 + 0.65335194343646219j,
0.4879926917946677 + 0.31352391256853401j,
-0.35809352192298388 - 1.0728322735956963j,
0.4533725297757551 - 0.22559691758977207j,
-0.60038286724379097 - 0.11246033971793468j,
0.66825095356633812 - 0.60076635444258042j,
-1.1946567473464309 - 0.22635664737160516j,
0.40228588081801298 + 0.068430477904664722j,
-0.9882729303598855 - 0.46953404636080764j,
0.71188035470148237 - 0.92234375063488339j,
-0.42665812492162319 - 0.12577894001454354j,
-0.76472165401579706 - 0.26752959905101342j,
-0.0060656639141563051 - 0.93138763769826982j,
0.89415079943278952 - 0.066507100471720232j,
-0.61447982075563323 + 0.87348984596560353j,
-0.78070473872335344 - 0.78753205263021409j,
-1.1191256017366982 - 0.60047283637051052j,
0.2133088567364409 - 1.464647765466137j,
-0.23425203712922088 + 0.80569933612650535j,
-1.1366303557443924 - 0.32263741303024324j,
0.2041593807964231 + 1.0927143488558069j,
0.43611791501355668 - 0.46222719965613662j,
0.13160849960684828 - 0.025453022150853984j,
-0.39955107839159809 + 0.85522030725234566j,
0.55636294499207284 - 0.77063085552936683j,
0.50643037413406744 + 0.15921955235797908j,
-0.67794895826681578 - 0.2302258170581491j,
-0.057766506371200475 - 0.13606392096680481j,
0.2681214210068823 - 0.75888465889983925j,
]
),
2: np.array(
[
0.0,
0.0,
-1.0146369650118083 + 0j,
1.11121557988063 + 0j,
-1.0268187317357511 + 0j,
0.98244234543551479 + 0j,
-1.2007880041682084 + 0j,
-0.69447547017176625 + 0j,
-1.0726374658022424 + 0j,
0.0,
-0.40253474561900393 - 0.65784721719896422j,
0.15199112969379647 - 0.24330956005348325j,
0.28523253658954206 - 0.3981266584575725j,
-0.26845152711149062 - 0.083593980089662734j,
0.19959571779331189 - 0.057385723112071435j,
0.048274474287257146 + 0.05571849108314867j,
0.66612416673860797 + 0.66489298075894143j,
0.47445092525264315 + 0.33233327925496392j,
-0.33978651546110278 - 1.0700406529115529j,
0.42170150945972673 - 0.20638423667056441j,
-0.5630841470957999 - 0.12922848005411802j,
0.61971326220555945 - 0.56144750223866158j,
-1.1423916258591016 - 0.25581299034320437j,
0.34730218633923393 + 0.10618832232762943j,
-0.99822733104115735 - 0.4682367163596412j,
0.70620977727778933 - 0.90938188008554444j,
-0.44219516027124856 - 0.13493822626962626j,
-0.78951918570902713 - 0.23576709704052287j,
-0.014428235772776353 - 0.97751697894267986j,
0.81909761987552843 - 0.032145061525208574j,
-0.59959900791799092 + 0.87660510575181094j,
-0.77968569605966409 - 0.81916479783758211j,
-1.0543271356804378 - 0.59294085416609699j,
0.21451468853321071 - 1.575924063487286j,
-0.097584235980056111 + 0.79606153258991741j,
-1.1425268084073952 - 0.33343881952558124j,
0.20815667516194364 + 1.0864812143836942j,
0.42124636529500581 - 0.49483794628510092j,
0.12538155362131775 - 0.054095442648732069j,
-0.40820405930119319 + 0.85936840188813757j,
0.57774999828224061 - 0.79228000632060525j,
0.45984172555887304 + 0.1760761108040782j,
-0.69197600035251772 - 0.22762901382604028j,
-0.068152714393202821 - 0.13031971412287957j,
0.28004810987754036 - 0.74648931403104868j,
]
),
3: np.array(
[
0.0,
0.0,
0.0,
1.1040780794436231 + 0j,
-1.0554780343915136 + 0j,
1.003760955073254 + 0j,
-1.2565856441338645 + 0j,
-0.62932602562674234 + 0j,
-1.160067204424214 + 0j,
0.0,
0.0,
0.15865387620507715 - 0.23612586328728333j,
0.27391824074536975 - 0.40229821680653666j,
-0.24904217061890843 - 0.066454748333335312j,
0.19465514972961681 - 0.071603817219522803j,
0.07585111789946225 + 0.10671255623789123j,
0.67521859645108184 + 0.63791014584128802j,
0.0,
-0.34816350138864738 - 1.084783542403446j,
0.43615290425078285 - 0.22284828128529358j,
-0.57324320239356563 - 0.14126286640853886j,
0.65304426498325374 - 0.6000904287578529j,
-1.165079833528107 - 0.26540336287320754j,
0.38879888788337164 + 0.049892403597867507j,
-0.95196155755809375 - 0.46240128463150965j,
0.66010872131183373 - 0.89379242001828385j,
-0.38155334031368932 - 0.11319555736108271j,
-0.83737598920187895 - 0.23689666124954797j,
0.036024621196599382 - 0.93058744213774647j,
0.79480395548872762 - 0.042441974598074916j,
-0.61480456309191522 + 0.88772972943182071j,
-0.77889262539414239 - 0.76334259507894808j,
-1.1118023694151189 - 0.59375535579172312j,
0.21015147536095025 - 1.4894366921848528j,
-0.20540486553192566 + 0.80716874886526713j,
-1.1317123907310076 - 0.32257306660406088j,
0.18948788955123907 + 1.0757829951402618j,
0.45816121337749072 - 0.46825028118838685j,
0.094048425004741185 - 0.062988484577269799j,
-0.40021838153849576 + 0.85629510171370782j,
0.54773135746681112 - 0.76849935301866623j,
0.49872929242448694 + 0.14779843610587595j,
-0.67415810187311553 - 0.22910004410769433j,
-0.05652956808223264 - 0.13895923733616072j,
0.26192691834998399 - 0.75985770223080795j,
]
),
}
clms = {
1: np.array(
[
0.0,
-1.5258173689739127 + 0j,
-0.38321729790014736 + 0j,
-0.67468807400536313 + 0j,
0.42460653551185651 + 0j,
1.3828469966900694 + 0j,
-1.4606906476867365 + 0j,
-1.1024802895292889 + 0j,
-1.6258480748456989 + 0j,
0.72184388572247027 - 0.40980679076163978j,
1.155123366597125 - 0.00025652164718847903j,
-0.046798126366738545 + 0.38718565377077507j,
0.14209457945669973 - 0.89695521394655509j,
-0.81580217823771384 - 0.40181448848956358j,
0.41047881458968138 - 0.1152355464248823j,
0.25214366009371275 + 0.13596558218505578j,
-0.48642804026342107 - 0.51921699092205253j,
0.70318282623713557 + 1.1149229917786518j,
-0.2620711198443052 - 1.2608592875108899j,
-0.32886228833465481 + 0.28343506891478615j,
0.87116700915729073 + 0.12201153895105338j,
0.61061947387230175 - 0.13255341818790078j,
0.20682058643208909 - 0.18157727548793343j,
-1.012535222212142 + 0.35770276797463263j,
0.82344404513932368 + 0.081123452026155174j,
-0.36925633394180285 - 0.28239296801331859j,
-0.13701971130554524 + 1.0015322075605051j,
-0.17636539799409506 - 0.23987373576395629j,
-0.61110525471621113 + 0.8387900954265588j,
-0.38131027712597904 - 0.36432117739386211j,
-1.0079042770692939 + 0.9484888310663222j,
0.53963333913487466 - 0.15889892563621916j,
0.90252874051924248 + 0.047882748600954872j,
0.77742302026156063 - 0.28243856974519727j,
-0.9721760087917013 + 0.49058350689687308j,
0.50365618535953161 + 0.8080725210109363j,
1.0815686965383575 - 0.70497162383482825j,
-0.83122125861324603 + 1.0900112211266584j,
0.63134176691035382 - 1.1506771025986287j,
-0.25413053864796836 + 0.029385890444217244j,
-0.056623996602004172 - 0.26225905883112283j,
0.79047827545371763 + 0.14640251150139555j,
-0.24482352824373257 + 0.055856847996116454j,
-0.34090568518036446 + 0.31363733143816142j,
0.4367718299537125 + 0.17676151335880672j,
]
),
2: np.array(
[
0.0,
0.0,
-0.38326814027750383 + 0j,
-0.65418849087307329 + 0j,
0.4365892671577063 + 0j,
1.3803202920785584 + 0j,
-1.4916247379419461 + 0j,
-1.1324277132571721 + 0j,
-1.718185868626174 + 0j,
0.0,
1.1956968215533583 - 0.030205892584907437j,
-0.046100534504420865 + 0.41807122036767436j,
0.20782483037951727 - 0.94246433056743517j,
-0.83529709861832213 - 0.33903347515975163j,
0.48223350794745773 - 0.1926218400020257j,
0.21761499886653402 + 0.23961747977479567j,
-0.41751923193484447 - 0.6353671827291465j,
0.69260449292859827 + 1.130305228894001j,
-0.27954119293120033 - 1.2766279639264633j,
-0.33817969510878398 + 0.30951969744288232j,
0.83742868793014358 + 0.091212369129396176j,
0.58571691217352817 - 0.070712873379824182j,
0.14679306846624376 - 0.21513933832793367j,
-1.0638029100403115 + 0.41792437931719256j,
0.8237611915825912 + 0.077755997607020733j,
-0.37108969890984272 - 0.30238750878485998j,
-0.14723325508395391 + 0.9932281688841047j,
-0.19383569442563495 - 0.29295381202435722j,
-0.60670529686130736 + 0.83380243303561374j,
-0.45917079393130283 - 0.47912168797908361j,
-0.99345730695253176 + 0.94820175796661454j,
0.52649034820916507 - 0.12783909225900825j,
0.95924022156146393 + 0.055538327979596458j,
0.75064860942575096 - 0.21370815773918539j,
-0.84586566942124497 + 0.51342826175108991j,
0.50395723769037315 + 0.813189467153421j,
1.1022997429292671 - 0.71579859067105911j,
-0.81673852639172906 + 1.1007947378391343j,
0.68458074409331271 - 1.1856051362879017j,
-0.25008109729217404 + 0.039905637802000099j,
-0.062189175604629054 - 0.28221196312220687j,
0.78892563532515847 + 0.20103962113750989j,
-0.2427808848517484 + 0.05747362398942496j,
-0.36648874880005772 + 0.26046556342439908j,
0.46087686583398435 + 0.18234525262036616j,
]
),
3: np.array(
[
0.0,
0.0,
0.0,
-0.65872355978145192 + 0j,
0.43111157992422688 + 0j,
1.3933719902449626 + 0j,
-1.4337104872664086 + 0j,
-1.0953871385562564 + 0j,
-1.592919216965424 + 0j,
0.0,
0.0,
-0.037750501706858508 + 0.4056437707216613j,
0.19266431434449349 - 0.92413738054154204j,
-0.80624682077443821 - 0.3750231326847116j,
0.44820402588981811 - 0.14801697141861184j,
0.25229035881318124 + 0.17607723506064732j,
-0.47384685147145073 - 0.54847200740427982j,
0.0,
-0.26403005654710615 - 1.2664841194732137j,
-0.31764611275074489 + 0.29566346120804393j,
0.85876964582432236 + 0.11833464087123241j,
0.62548078652733941 - 0.10502140662441077j,
0.18551399493477491 - 0.18721874018509277j,
-0.9828066043226521 + 0.38082405462307395j,
0.80637975865752387 + 0.038495909743214873j,
-0.37901190842236099 - 0.24290178119622488j,
-0.15681111690711577 + 0.93523746819782994j,
-0.19823080090222214 - 0.21435654151321781j,
-0.61995793538329469 + 0.75489242177728544j,
-0.4291786442205881 - 0.3647575706316637j,
-1.036373422481776 + 0.9498490485674238j,
0.52091939787694486 - 0.16079466106792323j,
0.90447971944064343 + 0.049384983566628349j,
0.76161216915691299 - 0.28843184314201131j,
-0.921447188295894 + 0.49222438394413293j,
0.50972830882201325 + 0.80496870972031798j,
1.0799130050305059 - 0.69042579996889542j,
-0.80230481303668388 + 1.0710316308031511j,
0.65228711481346291 - 1.1285250709486818j,
-0.25636616152524505 + 0.027205860798986677j,
-0.052885291187932219 - 0.26226354597662616j,
0.76408397668509698 + 0.13719891764968475j,
-0.24129807401981906 + 0.059572855113709577j,
-0.35702076334353117 + 0.30851416270921495j,
0.42377772250897539 + 0.17587202874134827j,
]
),
}
class TestSpinFunc(unittest.TestCase):
def setUp(self):
self.nside = 64
self.lmax = self.nside
seed = 12345
np.random.seed(seed)
self.mapr = hp.synfast(
np.ones(self.lmax + 1), self.nside, pixwin=False, fwhm=0.0, sigma=None
)
self.mapi = hp.synfast(
np.ones(self.lmax + 1), self.nside, pixwin=False, fwhm=0.0, sigma=None
)
self.almg = hp.synalm(np.ones(self.lmax + 1), self.lmax)
self.almc = hp.synalm(np.ones(self.lmax + 1), self.lmax)
def test_der1(self):
""" compare output of alm2map_der1 with the equivalent spin-1 transform using alm2map_spin """
m, dt_der1, dp_der1 = hp.alm2map_der1(self.almg, self.nside)
alm_spin = hp.almxfl(
self.almg,
np.array(
[np.sqrt(l * (l + 1.0)) for l in six.moves.xrange(0, self.lmax + 1)]
),
inplace=False,
)
dt_spin, dp_spin = hp.alm2map_spin(
[alm_spin, alm_spin * 0.0], self.nside, 1, self.lmax
)
np.testing.assert_array_almost_equal(dt_der1, dt_spin, decimal=8)
np.testing.assert_array_almost_equal(dp_der1, dp_spin, decimal=8)
def test_spin0(self):
m1 = hp.alm2map(self.almg, self.nside, self.lmax)
m2_r, m2_i = hp.alm2map_spin(
[self.almg, 0.0 * self.almg], self.nside, 0, self.lmax
)
np.testing.assert_array_almost_equal(m1, m2_r, decimal=8)
| np.testing.assert_array_almost_equal(m1 * 0.0, m2_i, decimal=8) | numpy.testing.assert_array_almost_equal |
import copy
import numpy as np
import pandas as pd
import seaborn as sns
class GreedyBanditAgent(object):
def __init__(self, epsilon=0.1, learning_rate=0.5, action_space=10, q0=0):
self.action_space = action_space
self.epsilon = epsilon
self.learning_rate = learning_rate
self.action_values = np.array([q0] * self.action_space).astype('float')
self.naction_values = np.array([1] * self.action_space).astype('float')
self.rewards = []
def choose(self):
if np.random.rand() > self.epsilon:
arr = np.argwhere(
self.action_values == np.max(self.action_values)).flatten()
action = | np.random.choice(arr) | numpy.random.choice |
"""
A FEED-FORWARD DEEP NEURAL NETWORK
"""
import pickle
import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import numpy.linalg as la
import seaborn as sns
np.set_printoptions(formatter={'float': '{: 0.1f}'.format})
# Batch Normalization
def batch_norm_ff(modes, v, gamma_bn, beta_bn, i, bnorm):
if bnorm:
eps = 1.0e-1
momenti = 0.9
global running_mean, running_variance
gamma = gamma_bn + 0
beta = beta_bn + 0
v_in = v + 0
m_dim, n_dim = np.shape(v_in)
if modes == 'train':
means = np.mean(v_in, axis=0)
variances = np.var(v_in, axis=0)
va = v_in - means
vx = np.sqrt((variances) + eps) + eps
v_norm = (v_in - means) / (np.sqrt(variances + eps) + eps)
v_out_bn = (gamma * v_norm) + beta
# estimate running averages for test and validation
running_mean[i] = (momenti * running_mean[i]) + (1 - momenti) * means
running_variance[i] = (momenti * running_variance[i]) + (1 - momenti) * variances
cache = [v_norm, v_in, means, variances, m_dim, gamma, beta]
return [v_out_bn, cache]
if modes == 'test' or modes == 'validate':
v_norm = (v_in - running_mean[i]) / (np.sqrt(running_variance[i]) + eps)
v_out_bn = (gamma_bn * v_norm) + beta_bn
return v_out_bn
if not bnorm and modes == 'test':
return v
return [v, 0]
def batch_norm_bp(delta, store, bnorm):
if bnorm:
v_norm, v_in, means, variance, m_dim, gamma, beta = store
eps = 1.0e-8
delta_in = delta + 0
dgamma = np.sum((delta_in * v_norm), axis=0)
dbeta = np.sum(delta_in, axis=0)
inv_std = 1. / (np.sqrt(variance) + eps)
dv_norm = delta_in * gamma
dvar = -0.5 * (inv_std ** 3) * np.sum(dv_norm *(v_in - means), axis = 0)
dmean = -1 * inv_std * np.sum(dv_norm, axis=0) + dvar * -2.0 * np.mean((v_in - means), axis=0)
ddelta = (inv_std * dv_norm) + (2.0 / m_dim * (v_in - means) * dvar) + (dmean / m_dim)
# dx1 = gamma * t / m_dim
# dx2 = (m_dim * delta_in) - np.sum(delta_in, axis=0)
# dx3 = np.square(t) * (v_in - means)
# dx4 = np.sum(delta_in * (v_in - means), axis=0)
#
# ddelta = dx1 * (dx2 - (dx3 * dx4))
return ddelta, dgamma, dbeta
return [delta, 0, 0]
def bn_term_update(g, b, dg, db, momentsg, momentsb):
eps = 1.0e-8
dwg = alpha * dg
dwb = alpha * db
beta = 0.9
momentsg = (beta * momentsg) + ((1 - beta) * np.square(dg))
momentsb = (beta * momentsb) + ((1 - beta) * np.square(db))
rms_momentg= np.sqrt(momentsg) + eps
rms_momentb = np.sqrt(momentsb) + eps
g += dwg / rms_momentg
b += dwb / rms_momentb
return g, b
# Weighted sum of input nodes and weights
def weight_sum(x_data, weights):
v = x_data.dot(weights)
return v
# Activation functions
def activation(v, mode):
y_io = 0
if mode == 'reLU':
y_io = v + 0
np.putmask(y_io, y_io < 0, [0])
# y = y * (y > 0)np.maximum(y, 0, y)
if mode == 'leaky_reLU':
y_io = v + 0
np.putmask(y_io, y_io < 0, y_io * 0.01)
if mode == 'sigmoid':
y_io = 1 / (1 + np.exp(-v))
if mode == 'softmax':
ex = np.exp(v)
sum_exp = ex.sum(axis=1)[:, np.newaxis]
# out2 = (ex.T / sum_exp).T
# out3 = (np.exp(v).T / np.sum(np.exp(v), axis=1)).T
# ex / sum_exp[:, np.newaxis] # or [:,None]
# y = np.exp(v) / (np.sum(np.exp(v), axis=1)[:, np.newaxis]))
y_io = ex / sum_exp
return y_io
# Delta GRADIENT Rule
def delta_grad(y_in, e, mode):
d_in = 0
if mode == 'sigmoid':
d_in = (y_in * (1 - y_in))
if mode == 'reLU':
d_in = y_in + 0
# d = 1 * (d > 0)
np.putmask(d_in, d_in > 0, [1])
np.putmask(d_in, d_in < 0, [0])
if mode == 'leaky_reLU':
d_in = y_in + 0
np.putmask(d_in, d_in > 0, [1])
np.putmask(d_in, d_in < 0, [0.01])
return d_in * e
# Backward Error calculation for Hidden layers
def error_h(delta, w):
e_h = delta.dot(w.T)
return e_h
def regularization(weights, opt=1):
if opt != 0:
lda = 0.001
return lda * weights # regularization improves learning accuracy
else:
return 0
# Weight Update Optimization Techniques against Vanishing Gradients -
# Advanced Gradient Descents for stability and better performance
def weight_update(x_data, weights_in, it, delta, momentums, moments, mode="SGD"):
beta = 0.9
g = x_data.T.dot(delta)
dw = alpha * (g + regularization(weights_in))
dW = dw
if mode == 'Momentum':
momentums = dw + (momentums * beta)
dW = momentums
if mode == 'NAG': # Nesterov Accelerated Gradient
momentums_old = momentums
momentums = (momentums * beta) + dw
dW = (momentums_old * beta) + ((1 + beta) * momentums)
if mode == 'AdaGrad':
eps = 1.0e-8
dw = alpha * g
moments += np.square(g)
rms_moment = np.sqrt(moments) + eps
dW = dw / rms_moment
if mode == 'AdaDelta':
eps = 1.0e-8
moments = (beta * moments) + ((1 - beta) * np.square(g))
rms_moment = np.sqrt(moments) + eps
momentums = (beta * momentums) + ((1 - beta) * np.square(dw))
rms_momentum = np.sqrt(momentums) + eps
dW = rms_momentum * g / rms_moment
if mode == 'RMSProp':
eps = 1.0e-8
dw = alpha * g
beta = 0.9
moments = (beta * moments) + ((1 - beta) * np.square(g))
rms_moment = np.sqrt(moments) + eps
dW = dw / rms_moment
if mode == 'Adam':
eps = 1.0e-8
beta_1 = 0.9
beta_2 = 0.99
ts = it + 1
momentums = (beta_1 * momentums) + (1 - beta_1) * g
moments = (beta_2 * moments) + (1 - beta_2) * np.square(g)
momentums_norm = momentums / (1 - np.power(beta_1, ts))
moments_norm = moments / (1 - np.power(beta_2, ts))
rms_moment = np.sqrt(moments_norm) + eps
dW = (alpha * momentums_norm) / rms_moment
if mode == 'AdaMax':
eps = 1.0e-8
beta_1 = 0.9
beta_2 = 0.99
ts = it + 1
momentums = (beta_1 * momentums) + (1 - beta_1) * g
m_norm = (beta_2 * moments) + eps
moments = np.maximum(m_norm, np.abs(g))
momentums_norm = momentums / (1 - np.power(beta_1, ts))
dW = (alpha / (moments + eps)) * momentums_norm
if mode == 'NAdam':
eps = 1.0e-8
beta_1 = 0.9
beta_2 = 0.99
ts = it + 1
momentums = (beta_1 * momentums) + (1 - beta_1) * g
moments = (beta_2 * moments) + (1 - beta_2) * np.square(g)
momentums_norm = momentums / (1 - np.power(beta_1, ts))
moments_norm = moments / (1 - np.power(beta_2, ts))
rms_moment = np.sqrt(moments_norm) + eps
nestrov_param = ((beta_1 * momentums_norm) + (1 - beta_1) * g) / (1 - np.power(beta_1, ts))
dW = (alpha * nestrov_param) / rms_moment
if mode == 'NAdaMax':
eps = 1.0e-8
beta_1 = 0.9
beta_2 = 0.99
ts = it + 1
momentums = (beta_1 * momentums) + (1 - beta_1) * g
m_norm = (beta_2 * moments) + eps
moments = np.maximum(m_norm, np.abs(g))
momentums_norm = momentums / (1 - np.power(beta_1, ts))
nestrov_param = ((beta_1 * momentums_norm) + (1 - beta_1) * g) / (1 - np.power(beta_1, ts))
dW = (alpha * nestrov_param) / (moments + eps)
if mode == 'AdaDeltaMax':
a = 0 # do nothing
return weights_in + dW
# Drop-out : To prevent Over-fitting # TODO: Dropout causes an unstable learning model in nature
def drop_out(y_in, drops, drop_ratio=0.2):
# drop-ratio or drop-percent: drops out this percentage from the hidden nodes,
# by setting its output to zero
v_in = 1
if drops:
# drop_ratio = 1 - drop_ratio
# size = y_in.shape
# v_in = np.random.binomial(1, drop_ratio, size=y_in.shape) / drop_ratio
p = drop_ratio / (1 - drop_ratio)
p = np.sqrt(p)
# elements = np.size(y)
my, ny = np.shape(y_in)
v_in = np.zeros([my, ny])
num_of_elem_nodrop = np.round(ny * (1 - drop_ratio))
elem_index = np.random.choice(ny, int(num_of_elem_nodrop), replace=False)
for i in range(my):
# elem_index = np.random.choice(ny, int(num_of_elem_nodrop), replace=False)
np.put(v_in[i, :], elem_index, [p], mode='raise')
return v_in
# Back propagation, cross-entropy driven learning algorithm
def back_prop_ce_multi_class(modus, x, d=None, weights=None, ls=None, it=0, bn_terms=None):
set_activation_modes()
global bnorm
if ls is None:
ls = layer_space
h = ls - 1
# n = len(x)
# output
u = x
y = np.zeros(ls, dtype=object) # or np.array or np.asarray([None] * ls)
cache = np.zeros(ls, object)
drop_cache = np.zeros(h, object)
loss = 0
# TEST MODE
if modus == 'test':
global bn_term
gamma_bn, beta_bn = bn_term
global running_weight
print('...TEST MODE...\n')
for i in range(ls):
# v = weight_sum(u, weights[i])
# y = sigmoid(v)
if i == h:
v = weight_sum(u, running_weight[i])
y = activation(v, acto_mode)
else:
v = weight_sum(u, running_weight[i])
v = batch_norm_ff('test', v, gamma_bn[i], beta_bn[i], i, bnorm)
y = activation(v, acth_mode)
u = y
return y
gamma_bn, beta_bn = bn_terms
# TRAIN MODE
for i in range(ls):
# v = weight_sum(u, weights[i])
# y = sigmoid(v)
if i == h:
v = weight_sum(u, weights[i])
y[i] = activation(v, acto_mode)
else:
v = weight_sum(u, weights[i])
v, cache[i] = batch_norm_ff('train', v, gamma_bn[i], beta_bn[i], i, bnorm)
y[i] = activation(v, acth_mode)
# drop_cache[i] = drop_out(y[i], drop, 0.2)
y[i] *= drop_out(y[i], drop, 0.2) # drop_cache[i]
u = y[i]
e = d - y[h] # output error
# drop_cache = drop_cache[::-1]
ex, ey = np.shape(e)
# loss = np.square(e)
# avg_loss = np.sum(loss, axis=1) / ey
# total_avg_loss = np.sum(avg_loss, axis=0) / ex
# QUICK CALCULATION OF AVERAGE TRAINING ACCURACY AND LOSS
ya = y[h] + 0
dmax = np.argmax(d, axis=1)
loss = np.asarray([np.square(d[i, dmax[i]] - ya[i, dmax[i]]) for i in range(ex)])
total_avg_loss = np.sum(loss, axis=0) / ex
accuracy = np.asarray([ya[i, dmax[i]] / d[i, dmax[i]] * 100 for i in range(ex)])
total_avg_accuracy = np.sum(accuracy, axis=0) / ex
# VALIDATION MODE
if modus == 'validate':
return [y[h], total_avg_loss, total_avg_accuracy]
# TRAIN MODE: BACK-PROPAGATION
deltas_r = np.zeros(ls, object)
errors_r = | np.zeros(ls, object) | numpy.zeros |
# -*- coding: utf-8 -*-
import unittest
import platform
import pandas as pd
import numpy as np
import pyarrow.parquet as pq
import hpat
from hpat.tests.test_utils import (
count_array_REPs, count_parfor_REPs, count_array_OneDs, get_start_end)
from hpat.tests.gen_test_data import ParquetGenerator
from numba import types
from numba.config import IS_32BITS
from numba.errors import TypingError
_cov_corr_series = [(pd.Series(x), pd.Series(y)) for x, y in [
(
[np.nan, -2., 3., 9.1],
[np.nan, -2., 3., 5.0],
),
# TODO(quasilyte): more intricate data for complex-typed series.
# Some arguments make assert_almost_equal fail.
# Functions that yield mismaching results:
# _column_corr_impl and _column_cov_impl.
(
[complex(-2., 1.0), complex(3.0, 1.0)],
[complex(-3., 1.0), complex(2.0, 1.0)],
),
(
[complex(-2.0, 1.0), complex(3.0, 1.0)],
[1.0, -2.0],
),
(
[1.0, -4.5],
[complex(-4.5, 1.0), complex(3.0, 1.0)],
),
]]
min_float64 = np.finfo('float64').min
max_float64 = np.finfo('float64').max
test_global_input_data_float64 = [
[1., np.nan, -1., 0., min_float64, max_float64],
[np.nan, np.inf, np.NINF, np.NZERO]
]
min_int64 = np.iinfo('int64').min
max_int64 = np.iinfo('int64').max
max_uint64 = np.iinfo('uint64').max
test_global_input_data_integer64 = [
[1, -1, 0],
[min_int64, max_int64],
[max_uint64]
]
test_global_input_data_numeric = test_global_input_data_integer64 + test_global_input_data_float64
test_global_input_data_unicode_kind4 = [
'ascii',
'12345',
'1234567890',
'¡Y tú quién te crees?',
'🐍⚡',
'大处着眼,小处着手。',
]
test_global_input_data_unicode_kind1 = [
'ascii',
'12345',
'1234567890',
]
def _make_func_from_text(func_text, func_name='test_impl'):
loc_vars = {}
exec(func_text, {}, loc_vars)
test_impl = loc_vars[func_name]
return test_impl
def _make_func_use_binop1(operator):
func_text = "def test_impl(A, B):\n"
func_text += " return A {} B\n".format(operator)
return _make_func_from_text(func_text)
def _make_func_use_binop2(operator):
func_text = "def test_impl(A, B):\n"
func_text += " A {} B\n".format(operator)
func_text += " return A\n"
return _make_func_from_text(func_text)
def _make_func_use_method_arg1(method):
func_text = "def test_impl(A, B):\n"
func_text += " return A.{}(B)\n".format(method)
return _make_func_from_text(func_text)
GLOBAL_VAL = 2
class TestSeries(unittest.TestCase):
def test_create1(self):
def test_impl():
df = pd.DataFrame({'A': [1, 2, 3]})
return (df.A == 1).sum()
hpat_func = hpat.jit(test_impl)
self.assertEqual(hpat_func(), test_impl())
@unittest.skip('Feature request: implement Series::ctor with list(list(type))')
def test_create_list_list_unicode(self):
def test_impl():
S = pd.Series([
['abc', 'defg', 'ijk'],
['lmn', 'opq', 'rstuvwxyz']
])
return S
hpat_func = hpat.jit(test_impl)
result_ref = test_impl()
result = hpat_func()
pd.testing.assert_series_equal(result, result_ref)
@unittest.skip('Feature request: implement Series::ctor with list(list(type))')
def test_create_list_list_integer(self):
def test_impl():
S = pd.Series([
[123, 456, -789],
[-112233, 445566, 778899]
])
return S
hpat_func = hpat.jit(test_impl)
result_ref = test_impl()
result = hpat_func()
pd.testing.assert_series_equal(result, result_ref)
@unittest.skip('Feature request: implement Series::ctor with list(list(type))')
def test_create_list_list_float(self):
def test_impl():
S = pd.Series([
[1.23, -4.56, 7.89],
[11.2233, 44.5566, -778.899]
])
return S
hpat_func = hpat.jit(test_impl)
result_ref = test_impl()
result = hpat_func()
pd.testing.assert_series_equal(result, result_ref)
def test_create2(self):
def test_impl(n):
df = pd.DataFrame({'A': np.arange(n)})
return (df.A == 2).sum()
hpat_func = hpat.jit(test_impl)
n = 11
self.assertEqual(hpat_func(n), test_impl(n))
def test_create_series1(self):
def test_impl():
A = pd.Series([1, 2, 3])
return A
hpat_func = hpat.jit(test_impl)
pd.testing.assert_series_equal(hpat_func(), test_impl())
def test_create_series_index1(self):
# create and box an indexed Series
def test_impl():
A = pd.Series([1, 2, 3], ['A', 'C', 'B'])
return A
hpat_func = hpat.jit(test_impl)
pd.testing.assert_series_equal(hpat_func(), test_impl())
def test_create_series_index2(self):
def test_impl():
A = pd.Series([1, 2, 3], index=['A', 'C', 'B'])
return A
hpat_func = hpat.jit(test_impl)
pd.testing.assert_series_equal(hpat_func(), test_impl())
def test_create_series_index3(self):
def test_impl():
A = pd.Series([1, 2, 3], index=['A', 'C', 'B'], name='A')
return A
hpat_func = hpat.jit(test_impl)
pd.testing.assert_series_equal(hpat_func(), test_impl())
def test_create_series_index4(self):
def test_impl(name):
A = pd.Series([1, 2, 3], index=['A', 'C', 'B'], name=name)
return A
hpat_func = hpat.jit(test_impl)
pd.testing.assert_series_equal(hpat_func('A'), test_impl('A'))
def test_create_str(self):
def test_impl():
df = pd.DataFrame({'A': ['a', 'b', 'c']})
return (df.A == 'a').sum()
hpat_func = hpat.jit(test_impl)
self.assertEqual(hpat_func(), test_impl())
def test_pass_df1(self):
def test_impl(df):
return (df.A == 2).sum()
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n)})
self.assertEqual(hpat_func(df), test_impl(df))
def test_pass_df_str(self):
def test_impl(df):
return (df.A == 'a').sum()
hpat_func = hpat.jit(test_impl)
df = pd.DataFrame({'A': ['a', 'b', 'c']})
self.assertEqual(hpat_func(df), test_impl(df))
def test_pass_series1(self):
# TODO: check to make sure it is series type
def test_impl(A):
return (A == 2).sum()
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n)})
self.assertEqual(hpat_func(df.A), test_impl(df.A))
def test_pass_series2(self):
# test creating dataframe from passed series
def test_impl(A):
df = pd.DataFrame({'A': A})
return (df.A == 2).sum()
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n)})
self.assertEqual(hpat_func(df.A), test_impl(df.A))
def test_pass_series_str(self):
def test_impl(A):
return (A == 'a').sum()
hpat_func = hpat.jit(test_impl)
df = pd.DataFrame({'A': ['a', 'b', 'c']})
self.assertEqual(hpat_func(df.A), test_impl(df.A))
def test_pass_series_index1(self):
def test_impl(A):
return A
hpat_func = hpat.jit(test_impl)
S = pd.Series([3, 5, 6], ['a', 'b', 'c'], name='A')
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
def test_series_size(self):
def test_impl(S):
return S.size
hpat_func = hpat.jit(test_impl)
n = 11
for S, expected in [
(pd.Series(), 0),
(pd.Series([]), 0),
(pd.Series(np.arange(n)), n),
(pd.Series([np.nan, 1, 2]), 3),
(pd.Series(['1', '2', '3']), 3),
]:
with self.subTest(S=S, expected=expected):
self.assertEqual(hpat_func(S), expected)
self.assertEqual(hpat_func(S), test_impl(S))
def test_series_attr2(self):
def test_impl(A):
return A.copy().values
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n)})
np.testing.assert_array_equal(hpat_func(df.A), test_impl(df.A))
def test_series_attr3(self):
def test_impl(A):
return A.min()
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n)})
self.assertEqual(hpat_func(df.A), test_impl(df.A))
def test_series_attr4(self):
def test_impl(A):
return A.cumsum().values
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n)})
np.testing.assert_array_equal(hpat_func(df.A), test_impl(df.A))
def test_series_argsort1(self):
def test_impl(A):
return A.argsort()
hpat_func = hpat.jit(test_impl)
n = 11
A = pd.Series(np.random.ranf(n))
pd.testing.assert_series_equal(hpat_func(A), test_impl(A))
def test_series_attr6(self):
def test_impl(A):
return A.take([2, 3]).values
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n)})
np.testing.assert_array_equal(hpat_func(df.A), test_impl(df.A))
def test_series_attr7(self):
def test_impl(A):
return A.astype(np.float64)
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n)})
np.testing.assert_array_equal(hpat_func(df.A), test_impl(df.A))
def test_series_getattr_ndim(self):
'''Verifies getting Series attribute ndim is supported'''
def test_impl(S):
return S.ndim
hpat_func = hpat.jit(test_impl)
n = 11
S = pd.Series(np.arange(n))
self.assertEqual(hpat_func(S), test_impl(S))
def test_series_getattr_T(self):
'''Verifies getting Series attribute T is supported'''
def test_impl(S):
return S.T
hpat_func = hpat.jit(test_impl)
n = 11
S = pd.Series(np.arange(n))
np.testing.assert_array_equal(hpat_func(S), test_impl(S))
def test_series_copy_str1(self):
def test_impl(A):
return A.copy()
hpat_func = hpat.jit(test_impl)
S = pd.Series(['aa', 'bb', 'cc'])
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
def test_series_copy_int1(self):
def test_impl(A):
return A.copy()
hpat_func = hpat.jit(test_impl)
S = pd.Series([1, 2, 3])
np.testing.assert_array_equal(hpat_func(S), test_impl(S))
def test_series_copy_deep(self):
def test_impl(A, deep):
return A.copy(deep=deep)
hpat_func = hpat.jit(test_impl)
for S in [
pd.Series([1, 2]),
pd.Series([1, 2], index=["a", "b"]),
]:
with self.subTest(S=S):
for deep in (True, False):
with self.subTest(deep=deep):
actual = hpat_func(S, deep)
expected = test_impl(S, deep)
pd.testing.assert_series_equal(actual, expected)
self.assertEqual(actual.values is S.values, expected.values is S.values)
self.assertEqual(actual.values is S.values, not deep)
# Shallow copy of index is not supported yet
if deep:
self.assertEqual(actual.index is S.index, expected.index is S.index)
self.assertEqual(actual.index is S.index, not deep)
def test_series_astype_int_to_str1(self):
'''Verifies Series.astype implementation with function 'str' as argument
converts integer series to series of strings
'''
def test_impl(S):
return S.astype(str)
hpat_func = hpat.jit(test_impl)
n = 11
S = pd.Series(np.arange(n))
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
def test_series_astype_int_to_str2(self):
'''Verifies Series.astype implementation with a string literal dtype argument
converts integer series to series of strings
'''
def test_impl(S):
return S.astype('str')
hpat_func = hpat.jit(test_impl)
n = 11
S = pd.Series(np.arange(n))
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
def test_series_astype_str_to_str1(self):
'''Verifies Series.astype implementation with function 'str' as argument
handles string series not changing it
'''
def test_impl(S):
return S.astype(str)
hpat_func = hpat.jit(test_impl)
S = pd.Series(['aa', 'bb', 'cc'])
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
def test_series_astype_str_to_str2(self):
'''Verifies Series.astype implementation with a string literal dtype argument
handles string series not changing it
'''
def test_impl(S):
return S.astype('str')
hpat_func = hpat.jit(test_impl)
S = pd.Series(['aa', 'bb', 'cc'])
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
def test_series_astype_str_to_str_index_str(self):
'''Verifies Series.astype implementation with function 'str' as argument
handles string series not changing it
'''
def test_impl(S):
return S.astype(str)
hpat_func = hpat.jit(test_impl)
S = pd.Series(['aa', 'bb', 'cc'], index=['d', 'e', 'f'])
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
def test_series_astype_str_to_str_index_int(self):
'''Verifies Series.astype implementation with function 'str' as argument
handles string series not changing it
'''
def test_impl(S):
return S.astype(str)
hpat_func = hpat.jit(test_impl)
S = pd.Series(['aa', 'bb', 'cc'], index=[1, 2, 3])
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
@unittest.skip('TODO: requires str(datetime64) support in Numba')
def test_series_astype_dt_to_str1(self):
'''Verifies Series.astype implementation with function 'str' as argument
converts datetime series to series of strings
'''
def test_impl(A):
return A.astype(str)
hpat_func = hpat.jit(test_impl)
S = pd.Series([pd.Timestamp('20130101 09:00:00'),
pd.Timestamp('20130101 09:00:02'),
pd.Timestamp('20130101 09:00:03')
])
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
@unittest.skip('AssertionError: Series are different'
'[left]: [0.000000, 1.000000, 2.000000, 3.000000, ...'
'[right]: [0.0, 1.0, 2.0, 3.0, ...'
'TODO: needs alignment to NumPy on Numba side')
def test_series_astype_float_to_str1(self):
'''Verifies Series.astype implementation with function 'str' as argument
converts float series to series of strings
'''
def test_impl(A):
return A.astype(str)
hpat_func = hpat.jit(test_impl)
n = 11.0
S = pd.Series(np.arange(n))
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
def test_series_astype_int32_to_int64(self):
'''Verifies Series.astype implementation with NumPy dtype argument
converts series with dtype=int32 to series with dtype=int64
'''
def test_impl(A):
return A.astype(np.int64)
hpat_func = hpat.jit(test_impl)
n = 11
S = pd.Series(np.arange(n), dtype=np.int32)
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
def test_series_astype_int_to_float64(self):
'''Verifies Series.astype implementation with NumPy dtype argument
converts integer series to series of float
'''
def test_impl(A):
return A.astype(np.float64)
hpat_func = hpat.jit(test_impl)
n = 11
S = pd.Series(np.arange(n))
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
def test_series_astype_float_to_int32(self):
'''Verifies Series.astype implementation with NumPy dtype argument
converts float series to series of integers
'''
def test_impl(A):
return A.astype(np.int32)
hpat_func = hpat.jit(test_impl)
n = 11.0
S = pd.Series(np.arange(n))
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
@unittest.skip('TODO: needs Numba astype impl support string literal as dtype arg')
def test_series_astype_literal_dtype1(self):
'''Verifies Series.astype implementation with a string literal dtype argument
converts float series to series of integers
'''
def test_impl(A):
return A.astype('int32')
hpat_func = hpat.jit(test_impl)
n = 11.0
S = pd.Series(np.arange(n))
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
@unittest.skip('TODO: needs Numba astype impl support converting unicode_type to int')
def test_series_astype_str_to_int32(self):
'''Verifies Series.astype implementation with NumPy dtype argument
converts series of strings to series of integers
'''
import numba
def test_impl(A):
return A.astype(np.int32)
hpat_func = hpat.jit(test_impl)
n = 11
S = pd.Series([str(x) for x in np.arange(n) - n // 2])
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
@unittest.skip('TODO: needs Numba astype impl support converting unicode_type to float')
def test_series_astype_str_to_float64(self):
'''Verifies Series.astype implementation with NumPy dtype argument
converts series of strings to series of float
'''
def test_impl(A):
return A.astype(np.float64)
hpat_func = hpat.jit(test_impl)
S = pd.Series(['3.24', '1E+05', '-1', '-1.3E-01', 'nan', 'inf'])
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
def test_series_astype_str_index_str(self):
'''Verifies Series.astype implementation with function 'str' as argument
handles string series not changing it
'''
def test_impl(S):
return S.astype(str)
hpat_func = hpat.jit(test_impl)
S = pd.Series(['aa', 'bb', 'cc'], index=['a', 'b', 'c'])
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
def test_series_astype_str_index_int(self):
'''Verifies Series.astype implementation with function 'str' as argument
handles string series not changing it
'''
def test_impl(S):
return S.astype(str)
hpat_func = hpat.jit(test_impl)
S = pd.Series(['aa', 'bb', 'cc'], index=[2, 3, 5])
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
def test_np_call_on_series1(self):
def test_impl(A):
return np.min(A)
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n)})
np.testing.assert_array_equal(hpat_func(df.A), test_impl(df.A))
def test_series_values(self):
def test_impl(A):
return A.values
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n)})
np.testing.assert_array_equal(hpat_func(df.A), test_impl(df.A))
def test_series_values1(self):
def test_impl(A):
return (A == 2).values
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n)})
np.testing.assert_array_equal(hpat_func(df.A), test_impl(df.A))
def test_series_shape1(self):
def test_impl(A):
return A.shape
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n)})
self.assertEqual(hpat_func(df.A), test_impl(df.A))
def test_static_setitem_series1(self):
def test_impl(A):
A[0] = 2
return (A == 2).sum()
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n)})
self.assertEqual(hpat_func(df.A), test_impl(df.A))
def test_setitem_series1(self):
def test_impl(A, i):
A[i] = 2
return (A == 2).sum()
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n)})
self.assertEqual(hpat_func(df.A.copy(), 0), test_impl(df.A.copy(), 0))
def test_setitem_series2(self):
def test_impl(A, i):
A[i] = 100
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n)})
A1 = df.A.copy()
A2 = df.A
hpat_func(A1, 0)
test_impl(A2, 0)
pd.testing.assert_series_equal(A1, A2)
@unittest.skip("enable after remove dead in hiframes is removed")
def test_setitem_series3(self):
def test_impl(A, i):
S = pd.Series(A)
S[i] = 100
hpat_func = hpat.jit(test_impl)
n = 11
A = np.arange(n)
A1 = A.copy()
A2 = A
hpat_func(A1, 0)
test_impl(A2, 0)
np.testing.assert_array_equal(A1, A2)
def test_setitem_series_bool1(self):
def test_impl(A):
A[A > 3] = 100
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n)})
A1 = df.A.copy()
A2 = df.A
hpat_func(A1)
test_impl(A2)
pd.testing.assert_series_equal(A1, A2)
def test_setitem_series_bool2(self):
def test_impl(A, B):
A[A > 3] = B[A > 3]
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n), 'B': np.arange(n)**2})
A1 = df.A.copy()
A2 = df.A
hpat_func(A1, df.B)
test_impl(A2, df.B)
pd.testing.assert_series_equal(A1, A2)
def test_static_getitem_series1(self):
def test_impl(A):
return A[0]
hpat_func = hpat.jit(test_impl)
n = 11
A = pd.Series(np.arange(n))
self.assertEqual(hpat_func(A), test_impl(A))
def test_getitem_series1(self):
def test_impl(A, i):
return A[i]
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n)})
self.assertEqual(hpat_func(df.A, 0), test_impl(df.A, 0))
def test_getitem_series_str1(self):
def test_impl(A, i):
return A[i]
hpat_func = hpat.jit(test_impl)
df = pd.DataFrame({'A': ['aa', 'bb', 'cc']})
self.assertEqual(hpat_func(df.A, 0), test_impl(df.A, 0))
def test_series_iat1(self):
def test_impl(A):
return A.iat[3]
hpat_func = hpat.jit(test_impl)
n = 11
S = pd.Series(np.arange(n)**2)
self.assertEqual(hpat_func(S), test_impl(S))
def test_series_iat2(self):
def test_impl(A):
A.iat[3] = 1
return A
hpat_func = hpat.jit(test_impl)
n = 11
S = pd.Series(np.arange(n)**2)
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
def test_series_iloc1(self):
def test_impl(A):
return A.iloc[3]
hpat_func = hpat.jit(test_impl)
n = 11
S = pd.Series(np.arange(n)**2)
self.assertEqual(hpat_func(S), test_impl(S))
def test_series_iloc2(self):
def test_impl(A):
return A.iloc[3:8]
hpat_func = hpat.jit(test_impl)
n = 11
S = pd.Series(np.arange(n)**2)
pd.testing.assert_series_equal(
hpat_func(S), test_impl(S).reset_index(drop=True))
def test_series_op1(self):
arithmetic_binops = ('+', '-', '*', '/', '//', '%', '**')
for operator in arithmetic_binops:
test_impl = _make_func_use_binop1(operator)
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(1, n), 'B': np.ones(n - 1)})
pd.testing.assert_series_equal(hpat_func(df.A, df.B), test_impl(df.A, df.B), check_names=False)
def test_series_op2(self):
arithmetic_binops = ('+', '-', '*', '/', '//', '%', '**')
for operator in arithmetic_binops:
test_impl = _make_func_use_binop1(operator)
hpat_func = hpat.jit(test_impl)
n = 11
if platform.system() == 'Windows' and not IS_32BITS:
df = pd.DataFrame({'A': np.arange(1, n, dtype=np.int64)})
else:
df = pd.DataFrame({'A': np.arange(1, n)})
pd.testing.assert_series_equal(hpat_func(df.A, 1), test_impl(df.A, 1), check_names=False)
def test_series_op3(self):
arithmetic_binops = ('+', '-', '*', '/', '//', '%', '**')
for operator in arithmetic_binops:
test_impl = _make_func_use_binop2(operator)
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(1, n), 'B': np.ones(n - 1)})
pd.testing.assert_series_equal(hpat_func(df.A, df.B), test_impl(df.A, df.B), check_names=False)
def test_series_op4(self):
arithmetic_binops = ('+', '-', '*', '/', '//', '%', '**')
for operator in arithmetic_binops:
test_impl = _make_func_use_binop2(operator)
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(1, n)})
pd.testing.assert_series_equal(hpat_func(df.A, 1), test_impl(df.A, 1), check_names=False)
def test_series_op5(self):
arithmetic_methods = ('add', 'sub', 'mul', 'div', 'truediv', 'floordiv', 'mod', 'pow')
for method in arithmetic_methods:
test_impl = _make_func_use_method_arg1(method)
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(1, n), 'B': np.ones(n - 1)})
pd.testing.assert_series_equal(hpat_func(df.A, df.B), test_impl(df.A, df.B), check_names=False)
@unittest.skipIf(platform.system() == 'Windows', 'Series values are different (20.0 %)'
'[left]: [1, 1024, 59049, 1048576, 9765625, 60466176, 282475249, 1073741824, 3486784401, 10000000000]'
'[right]: [1, 1024, 59049, 1048576, 9765625, 60466176, 282475249, 1073741824, -808182895, 1410065408]')
def test_series_op5_integer_scalar(self):
arithmetic_methods = ('add', 'sub', 'mul', 'div', 'truediv', 'floordiv', 'mod', 'pow')
for method in arithmetic_methods:
test_impl = _make_func_use_method_arg1(method)
hpat_func = hpat.jit(test_impl)
n = 11
if platform.system() == 'Windows' and not IS_32BITS:
operand_series = pd.Series(np.arange(1, n, dtype=np.int64))
else:
operand_series = pd.Series(np.arange(1, n))
operand_scalar = 10
pd.testing.assert_series_equal(
hpat_func(operand_series, operand_scalar),
test_impl(operand_series, operand_scalar),
check_names=False)
def test_series_op5_float_scalar(self):
arithmetic_methods = ('add', 'sub', 'mul', 'div', 'truediv', 'floordiv', 'mod', 'pow')
for method in arithmetic_methods:
test_impl = _make_func_use_method_arg1(method)
hpat_func = hpat.jit(test_impl)
n = 11
operand_series = pd.Series(np.arange(1, n))
operand_scalar = .5
pd.testing.assert_series_equal(
hpat_func(operand_series, operand_scalar),
test_impl(operand_series, operand_scalar),
check_names=False)
def test_series_op6(self):
def test_impl(A):
return -A
hpat_func = hpat.jit(test_impl)
n = 11
A = pd.Series(np.arange(n))
pd.testing.assert_series_equal(hpat_func(A), test_impl(A))
def test_series_op7(self):
comparison_binops = ('<', '>', '<=', '>=', '!=', '==')
for operator in comparison_binops:
test_impl = _make_func_use_binop1(operator)
hpat_func = hpat.jit(test_impl)
n = 11
A = pd.Series(np.arange(n))
B = pd.Series(np.arange(n)**2)
pd.testing.assert_series_equal(hpat_func(A, B), test_impl(A, B), check_names=False)
def test_series_op8(self):
comparison_methods = ('lt', 'gt', 'le', 'ge', 'ne', 'eq')
for method in comparison_methods:
test_impl = _make_func_use_method_arg1(method)
hpat_func = hpat.jit(test_impl)
n = 11
A = pd.Series(np.arange(n))
B = pd.Series(np.arange(n)**2)
pd.testing.assert_series_equal(hpat_func(A, B), test_impl(A, B), check_names=False)
@unittest.skipIf(platform.system() == 'Windows', "Attribute dtype are different: int64, int32")
def test_series_op8_integer_scalar(self):
comparison_methods = ('lt', 'gt', 'le', 'ge', 'eq', 'ne')
for method in comparison_methods:
test_impl = _make_func_use_method_arg1(method)
hpat_func = hpat.jit(test_impl)
n = 11
operand_series = pd.Series(np.arange(1, n))
operand_scalar = 10
pd.testing.assert_series_equal(
hpat_func(operand_series, operand_scalar),
test_impl(operand_series, operand_scalar),
check_names=False)
def test_series_op8_float_scalar(self):
comparison_methods = ('lt', 'gt', 'le', 'ge', 'eq', 'ne')
for method in comparison_methods:
test_impl = _make_func_use_method_arg1(method)
hpat_func = hpat.jit(test_impl)
n = 11
operand_series = pd.Series(np.arange(1, n))
operand_scalar = .5
pd.testing.assert_series_equal(
hpat_func(operand_series, operand_scalar),
test_impl(operand_series, operand_scalar),
check_names=False)
def test_series_inplace_binop_array(self):
def test_impl(A, B):
A += B
return A
hpat_func = hpat.jit(test_impl)
n = 11
A = np.arange(n)**2.0 # TODO: use 2 for test int casting
B = pd.Series(np.ones(n))
np.testing.assert_array_equal(hpat_func(A.copy(), B), test_impl(A, B))
def test_series_fusion1(self):
def test_impl(A, B):
return A + B + 1
hpat_func = hpat.jit(test_impl)
n = 11
if platform.system() == 'Windows' and not IS_32BITS:
A = pd.Series(np.arange(n), dtype=np.int64)
B = pd.Series(np.arange(n)**2, dtype=np.int64)
else:
A = pd.Series(np.arange(n))
B = pd.Series(np.arange(n)**2)
pd.testing.assert_series_equal(hpat_func(A, B), test_impl(A, B))
self.assertEqual(count_parfor_REPs(), 1)
def test_series_fusion2(self):
# make sure getting data var avoids incorrect single def assumption
def test_impl(A, B):
S = B + 2
if A[0] == 0:
S = A + 1
return S + B
hpat_func = hpat.jit(test_impl)
n = 11
if platform.system() == 'Windows' and not IS_32BITS:
A = pd.Series(np.arange(n), dtype=np.int64)
B = pd.Series(np.arange(n)**2, dtype=np.int64)
else:
A = pd.Series(np.arange(n))
B = pd.Series(np.arange(n)**2)
pd.testing.assert_series_equal(hpat_func(A, B), test_impl(A, B))
self.assertEqual(count_parfor_REPs(), 3)
def test_series_len(self):
def test_impl(A, i):
return len(A)
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n)})
self.assertEqual(hpat_func(df.A, 0), test_impl(df.A, 0))
def test_series_box(self):
def test_impl():
A = pd.Series([1, 2, 3])
return A
hpat_func = hpat.jit(test_impl)
pd.testing.assert_series_equal(hpat_func(), test_impl())
def test_series_box2(self):
def test_impl():
A = pd.Series(['1', '2', '3'])
return A
hpat_func = hpat.jit(test_impl)
pd.testing.assert_series_equal(hpat_func(), test_impl())
def test_series_list_str_unbox1(self):
def test_impl(A):
return A.iloc[0]
hpat_func = hpat.jit(test_impl)
S = pd.Series([['aa', 'b'], ['ccc'], []])
np.testing.assert_array_equal(hpat_func(S), test_impl(S))
# call twice to test potential refcount errors
np.testing.assert_array_equal(hpat_func(S), test_impl(S))
def test_np_typ_call_replace(self):
# calltype replacement is tricky for np.typ() calls since variable
# type can't provide calltype
def test_impl(i):
return np.int32(i)
hpat_func = hpat.jit(test_impl)
self.assertEqual(hpat_func(1), test_impl(1))
def test_series_ufunc1(self):
def test_impl(A, i):
return np.isinf(A).values
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n)})
np.testing.assert_array_equal(hpat_func(df.A, 1), test_impl(df.A, 1))
def test_list_convert(self):
def test_impl():
df = pd.DataFrame({'one': np.array([-1, np.nan, 2.5]),
'two': ['foo', 'bar', 'baz'],
'three': [True, False, True]})
return df.one.values, df.two.values, df.three.values
hpat_func = hpat.jit(test_impl)
one, two, three = hpat_func()
self.assertTrue(isinstance(one, np.ndarray))
self.assertTrue(isinstance(two, np.ndarray))
self.assertTrue(isinstance(three, np.ndarray))
@unittest.skip("needs empty_like typing fix in npydecl.py")
def test_series_empty_like(self):
def test_impl(A):
return np.empty_like(A)
hpat_func = hpat.jit(test_impl)
n = 11
df = pd.DataFrame({'A': np.arange(n)})
self.assertTrue(isinstance(hpat_func(df.A), np.ndarray))
def test_series_fillna1(self):
def test_impl(A):
return A.fillna(5.0)
hpat_func = hpat.jit(test_impl)
df = pd.DataFrame({'A': [1.0, 2.0, np.nan, 1.0]})
pd.testing.assert_series_equal(hpat_func(df.A),
test_impl(df.A), check_names=False)
# test inplace fillna for named numeric series (obtained from DataFrame)
def test_series_fillna_inplace1(self):
def test_impl(A):
A.fillna(5.0, inplace=True)
return A
hpat_func = hpat.jit(test_impl)
df = pd.DataFrame({'A': [1.0, 2.0, np.nan, 1.0]})
pd.testing.assert_series_equal(hpat_func(df.A),
test_impl(df.A), check_names=False)
def test_series_fillna_str1(self):
def test_impl(A):
return A.fillna("dd")
hpat_func = hpat.jit(test_impl)
df = pd.DataFrame({'A': ['aa', 'b', None, 'ccc']})
pd.testing.assert_series_equal(hpat_func(df.A),
test_impl(df.A), check_names=False)
def test_series_fillna_str_inplace1(self):
def test_impl(A):
A.fillna("dd", inplace=True)
return A
hpat_func = hpat.jit(test_impl)
S1 = pd.Series(['aa', 'b', None, 'ccc'])
S2 = S1.copy()
pd.testing.assert_series_equal(hpat_func(S1), test_impl(S2))
# TODO: handle string array reflection
# hpat_func(S1)
# test_impl(S2)
# np.testing.assert_array_equal(S1, S2)
def test_series_fillna_str_inplace_empty1(self):
def test_impl(A):
A.fillna("", inplace=True)
return A
hpat_func = hpat.jit(test_impl)
S1 = pd.Series(['aa', 'b', None, 'ccc'])
S2 = S1.copy()
pd.testing.assert_series_equal(hpat_func(S1), test_impl(S2))
@unittest.skip('Unsupported functionality: failed to handle index')
def test_series_fillna_index_str(self):
def test_impl(S):
return S.fillna(5.0)
hpat_func = hpat.jit(test_impl)
S = pd.Series([1.0, 2.0, np.nan, 1.0], index=['a', 'b', 'c', 'd'])
pd.testing.assert_series_equal(hpat_func(S),
test_impl(S), check_names=False)
@unittest.skip('Unsupported functionality: failed to handle index')
def test_series_fillna_index_int(self):
def test_impl(S):
return S.fillna(5.0)
hpat_func = hpat.jit(test_impl)
S = pd.Series([1.0, 2.0, np.nan, 1.0], index=[2, 3, 4, 5])
pd.testing.assert_series_equal(hpat_func(S),
test_impl(S), check_names=False)
@unittest.skipIf(hpat.config.config_pipeline_hpat_default,
'No support of axis argument in old-style Series.dropna() impl')
def test_series_dropna_axis1(self):
'''Verifies Series.dropna() implementation handles 'index' as axis argument'''
def test_impl(S):
return S.dropna(axis='index')
hpat_func = hpat.jit(test_impl)
S1 = pd.Series([1.0, 2.0, np.nan, 1.0, np.inf])
S2 = S1.copy()
pd.testing.assert_series_equal(hpat_func(S1), test_impl(S2))
@unittest.skipIf(hpat.config.config_pipeline_hpat_default,
'No support of axis argument in old-style Series.dropna() impl')
def test_series_dropna_axis2(self):
'''Verifies Series.dropna() implementation handles 0 as axis argument'''
def test_impl(S):
return S.dropna(axis=0)
hpat_func = hpat.jit(test_impl)
S1 = pd.Series([1.0, 2.0, np.nan, 1.0, np.inf])
S2 = S1.copy()
pd.testing.assert_series_equal(hpat_func(S1), test_impl(S2))
@unittest.skipIf(hpat.config.config_pipeline_hpat_default,
'No support of axis argument in old-style Series.dropna() impl')
def test_series_dropna_axis3(self):
'''Verifies Series.dropna() implementation handles correct non-literal axis argument'''
def test_impl(S, axis):
return S.dropna(axis=axis)
hpat_func = hpat.jit(test_impl)
S1 = pd.Series([1.0, 2.0, np.nan, 1.0, np.inf])
S2 = S1.copy()
axis_values = [0, 'index']
for value in axis_values:
pd.testing.assert_series_equal(hpat_func(S1, value), test_impl(S2, value))
@unittest.skipIf(hpat.config.config_pipeline_hpat_default,
'BUG: old-style dropna impl returns series without index')
def test_series_dropna_float_index1(self):
'''Verifies Series.dropna() implementation for float series with default index'''
def test_impl(S):
return S.dropna()
hpat_func = hpat.jit(test_impl)
for data in test_global_input_data_float64:
S1 = pd.Series(data)
S2 = S1.copy()
pd.testing.assert_series_equal(hpat_func(S1), test_impl(S2))
@unittest.skipIf(hpat.config.config_pipeline_hpat_default,
'BUG: old-style dropna impl returns series without index')
def test_series_dropna_float_index2(self):
'''Verifies Series.dropna() implementation for float series with string index'''
def test_impl(S):
return S.dropna()
hpat_func = hpat.jit(test_impl)
S1 = pd.Series([1.0, 2.0, np.nan, 1.0, np.inf], ['a', 'b', 'c', 'd', 'e'])
S2 = S1.copy()
pd.testing.assert_series_equal(hpat_func(S1), test_impl(S2))
@unittest.skipIf(hpat.config.config_pipeline_hpat_default,
'BUG: old-style dropna impl returns series without index')
def test_series_dropna_str_index1(self):
'''Verifies Series.dropna() implementation for series of strings with default index'''
def test_impl(S):
return S.dropna()
hpat_func = hpat.jit(test_impl)
S1 = pd.Series(['aa', 'b', None, 'cccd', ''])
S2 = S1.copy()
pd.testing.assert_series_equal(hpat_func(S1), test_impl(S2))
@unittest.skipIf(hpat.config.config_pipeline_hpat_default,
'BUG: old-style dropna impl returns series without index')
def test_series_dropna_str_index2(self):
'''Verifies Series.dropna() implementation for series of strings with string index'''
def test_impl(S):
return S.dropna()
hpat_func = hpat.jit(test_impl)
S1 = pd.Series(['aa', 'b', None, 'cccd', ''], ['a', 'b', 'c', 'd', 'e'])
S2 = S1.copy()
pd.testing.assert_series_equal(hpat_func(S1), test_impl(S2))
@unittest.skipIf(hpat.config.config_pipeline_hpat_default,
'BUG: old-style dropna impl returns series without index')
def test_series_dropna_str_index3(self):
def test_impl(S):
return S.dropna()
hpat_func = hpat.jit(test_impl)
S1 = pd.Series(['aa', 'b', None, 'cccd', ''], index=[1, 2, 5, 7, 10])
S2 = S1.copy()
pd.testing.assert_series_equal(hpat_func(S1), test_impl(S2))
@unittest.skip('BUG: old-style dropna impl returns series without index, in new-style inplace is unsupported')
def test_series_dropna_float_inplace_no_index1(self):
'''Verifies Series.dropna() implementation for float series with default index and inplace argument True'''
def test_impl(S):
S.dropna(inplace=True)
return S
hpat_func = hpat.jit(test_impl)
S1 = pd.Series([1.0, 2.0, np.nan, 1.0, np.inf])
S2 = S1.copy()
pd.testing.assert_series_equal(hpat_func(S1), test_impl(S2))
@unittest.skip('TODO: add reflection support and check method return value')
def test_series_dropna_float_inplace_no_index2(self):
'''Verifies Series.dropna(inplace=True) results are reflected back in the original float series'''
def test_impl(S):
return S.dropna(inplace=True)
hpat_func = hpat.jit(test_impl)
S1 = pd.Series([1.0, 2.0, np.nan, 1.0, np.inf])
S2 = S1.copy()
self.assertIsNone(hpat_func(S1))
self.assertIsNone(test_impl(S2))
pd.testing.assert_series_equal(S1, S2)
@unittest.skip('BUG: old-style dropna impl returns series without index, in new-style inplace is unsupported')
def test_series_dropna_str_inplace_no_index1(self):
'''Verifies Series.dropna() implementation for series of strings
with default index and inplace argument True
'''
def test_impl(S):
S.dropna(inplace=True)
return S
hpat_func = hpat.jit(test_impl)
S1 = pd.Series(['aa', 'b', None, 'cccd', ''])
S2 = S1.copy()
pd.testing.assert_series_equal(hpat_func(S1), test_impl(S2))
@unittest.skip('TODO: add reflection support and check method return value')
def test_series_dropna_str_inplace_no_index2(self):
'''Verifies Series.dropna(inplace=True) results are reflected back in the original string series'''
def test_impl(S):
return S.dropna(inplace=True)
hpat_func = hpat.jit(test_impl)
S1 = pd.Series(['aa', 'b', None, 'cccd', ''])
S2 = S1.copy()
self.assertIsNone(hpat_func(S1))
self.assertIsNone(test_impl(S2))
pd.testing.assert_series_equal(S1, S2)
def test_series_dropna_str_parallel1(self):
'''Verifies Series.dropna() distributed work for series of strings with default index'''
def test_impl(A):
B = A.dropna()
return (B == 'gg').sum()
hpat_func = hpat.jit(distributed=['A'])(test_impl)
S1 = pd.Series(['aa', 'b', None, 'ccc', 'dd', 'gg'])
start, end = get_start_end(len(S1))
# TODO: gatherv
self.assertEqual(hpat_func(S1[start:end]), test_impl(S1))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
self.assertTrue(count_array_OneDs() > 0)
@unittest.skip('AssertionError: Series are different\n'
'Series length are different\n'
'[left]: 3, Int64Index([0, 1, 2], dtype=\'int64\')\n'
'[right]: 2, Int64Index([1, 2], dtype=\'int64\')')
def test_series_dropna_dt_no_index1(self):
'''Verifies Series.dropna() implementation for datetime series with default index'''
def test_impl(S):
return S.dropna()
hpat_func = hpat.jit(test_impl)
S1 = pd.Series([pd.NaT, pd.Timestamp('1970-12-01'), pd.Timestamp('2012-07-25')])
S2 = S1.copy()
pd.testing.assert_series_equal(hpat_func(S1), test_impl(S2))
def test_series_dropna_bool_no_index1(self):
'''Verifies Series.dropna() implementation for bool series with default index'''
def test_impl(S):
return S.dropna()
hpat_func = hpat.jit(test_impl)
S1 = pd.Series([True, False, False, True])
S2 = S1.copy()
pd.testing.assert_series_equal(hpat_func(S1), test_impl(S2))
@unittest.skipIf(hpat.config.config_pipeline_hpat_default,
'BUG: old-style dropna impl returns series without index')
def test_series_dropna_int_no_index1(self):
'''Verifies Series.dropna() implementation for integer series with default index'''
def test_impl(S):
return S.dropna()
hpat_func = hpat.jit(test_impl)
n = 11
S1 = pd.Series(np.arange(n, dtype=np.int64))
S2 = S1.copy()
pd.testing.assert_series_equal(hpat_func(S1), test_impl(S2))
@unittest.skip('numba.errors.TypingError - fix needed\n'
'Failed in hpat mode pipeline'
'(step: convert to distributed)\n'
'Invalid use of Function(<built-in function len>)'
'with argument(s) of type(s): (none)\n')
def test_series_rename1(self):
def test_impl(A):
return A.rename('B')
hpat_func = hpat.jit(test_impl)
df = pd.DataFrame({'A': [1.0, 2.0, np.nan, 1.0]})
pd.testing.assert_series_equal(hpat_func(df.A), test_impl(df.A))
def test_series_sum_default(self):
def test_impl(S):
return S.sum()
hpat_func = hpat.jit(test_impl)
S = pd.Series([1., 2., 3.])
self.assertEqual(hpat_func(S), test_impl(S))
def test_series_sum_nan(self):
def test_impl(S):
return S.sum()
hpat_func = hpat.jit(test_impl)
# column with NA
S = pd.Series([np.nan, 2., 3.])
self.assertEqual(hpat_func(S), test_impl(S))
# all NA case should produce 0
S = pd.Series([np.nan, np.nan])
self.assertEqual(hpat_func(S), test_impl(S))
@unittest.skipIf(hpat.config.config_pipeline_hpat_default, "Old style Series.sum() does not support parameters")
def test_series_sum_skipna_false(self):
def test_impl(S):
return S.sum(skipna=False)
hpat_func = hpat.jit(test_impl)
S = pd.Series([np.nan, 2., 3.])
self.assertEqual(np.isnan(hpat_func(S)), np.isnan(test_impl(S)))
@unittest.skipIf(not hpat.config.config_pipeline_hpat_default,
"Series.sum() operator + is not implemented yet for Numba")
def test_series_sum2(self):
def test_impl(S):
return (S + S).sum()
hpat_func = hpat.jit(test_impl)
S = pd.Series([np.nan, 2., 3.])
self.assertEqual(hpat_func(S), test_impl(S))
S = pd.Series([np.nan, np.nan])
self.assertEqual(hpat_func(S), test_impl(S))
def test_series_prod(self):
def test_impl(S, skipna):
return S.prod(skipna=skipna)
hpat_func = hpat.jit(test_impl)
data_samples = [
[6, 6, 2, 1, 3, 3, 2, 1, 2],
[1.1, 0.3, 2.1, 1, 3, 0.3, 2.1, 1.1, 2.2],
[6, 6.1, 2.2, 1, 3, 3, 2.2, 1, 2],
[6, 6, np.nan, 2, np.nan, 1, 3, 3, np.inf, 2, 1, 2, np.inf],
[1.1, 0.3, np.nan, 1.0, np.inf, 0.3, 2.1, np.nan, 2.2, np.inf],
[1.1, 0.3, np.nan, 1, np.inf, 0, 1.1, np.nan, 2.2, np.inf, 2, 2],
[np.nan, np.nan, np.nan],
[np.nan, np.nan, np.inf],
]
for data in data_samples:
S = pd.Series(data)
for skipna_var in [True, False]:
actual = hpat_func(S, skipna=skipna_var)
expected = test_impl(S, skipna=skipna_var)
if np.isnan(actual) or np.isnan(expected):
# con not compare Nan != Nan directly
self.assertEqual(np.isnan(actual), np.isnan(expected))
else:
self.assertEqual(actual, expected)
def test_series_prod_skipna_default(self):
def test_impl(S):
return S.prod()
hpat_func = hpat.jit(test_impl)
S = pd.Series([np.nan, 2, 3.])
self.assertEqual(hpat_func(S), test_impl(S))
def test_series_count1(self):
def test_impl(S):
return S.count()
hpat_func = hpat.jit(test_impl)
S = pd.Series([np.nan, 2., 3.])
self.assertEqual(hpat_func(S), test_impl(S))
S = pd.Series([np.nan, np.nan])
self.assertEqual(hpat_func(S), test_impl(S))
S = pd.Series(['aa', 'bb', np.nan])
self.assertEqual(hpat_func(S), test_impl(S))
def test_series_mean(self):
def test_impl(S):
return S.mean()
hpat_func = hpat.jit(test_impl)
data_samples = [
[6, 6, 2, 1, 3, 3, 2, 1, 2],
[1.1, 0.3, 2.1, 1, 3, 0.3, 2.1, 1.1, 2.2],
[6, 6.1, 2.2, 1, 3, 3, 2.2, 1, 2],
[6, 6, np.nan, 2, np.nan, 1, 3, 3, np.inf, 2, 1, 2, np.inf],
[1.1, 0.3, np.nan, 1.0, np.inf, 0.3, 2.1, np.nan, 2.2, np.inf],
[1.1, 0.3, np.nan, 1, np.inf, 0, 1.1, np.nan, 2.2, np.inf, 2, 2],
[np.nan, np.nan, np.nan],
[np.nan, np.nan, np.inf],
]
for data in data_samples:
with self.subTest(data=data):
S = pd.Series(data)
actual = hpat_func(S)
expected = test_impl(S)
if np.isnan(actual) or np.isnan(expected):
self.assertEqual(np.isnan(actual), np.isnan(expected))
else:
self.assertEqual(actual, expected)
@unittest.skipIf(hpat.config.config_pipeline_hpat_default, "Series.mean() any parameters unsupported")
def test_series_mean_skipna(self):
def test_impl(S, skipna):
return S.mean(skipna=skipna)
hpat_func = hpat.jit(test_impl)
data_samples = [
[6, 6, 2, 1, 3, 3, 2, 1, 2],
[1.1, 0.3, 2.1, 1, 3, 0.3, 2.1, 1.1, 2.2],
[6, 6.1, 2.2, 1, 3, 3, 2.2, 1, 2],
[6, 6, np.nan, 2, np.nan, 1, 3, 3, np.inf, 2, 1, 2, np.inf],
[1.1, 0.3, np.nan, 1.0, np.inf, 0.3, 2.1, np.nan, 2.2, np.inf],
[1.1, 0.3, np.nan, 1, np.inf, 0, 1.1, np.nan, 2.2, np.inf, 2, 2],
[np.nan, np.nan, np.nan],
[np.nan, np.nan, np.inf],
]
for skipna in [True, False]:
for data in data_samples:
S = pd.Series(data)
actual = hpat_func(S, skipna)
expected = test_impl(S, skipna)
if np.isnan(actual) or np.isnan(expected):
self.assertEqual(np.isnan(actual), np.isnan(expected))
else:
self.assertEqual(actual, expected)
def test_series_var1(self):
def test_impl(S):
return S.var()
hpat_func = hpat.jit(test_impl)
S = pd.Series([np.nan, 2., 3.])
self.assertEqual(hpat_func(S), test_impl(S))
def test_series_min(self):
def test_impl(S):
return S.min()
hpat_func = hpat.jit(test_impl)
# TODO type_min/type_max
for input_data in [[np.nan, 2., np.nan, 3., np.inf, 1, -1000],
[8, 31, 1123, -1024],
[2., 3., 1, -1000, np.inf]]:
S = pd.Series(input_data)
result_ref = test_impl(S)
result = hpat_func(S)
self.assertEqual(result, result_ref)
@unittest.skipIf(hpat.config.config_pipeline_hpat_default, "Series.min() any parameters unsupported")
def test_series_min_param(self):
def test_impl(S, param_skipna):
return S.min(skipna=param_skipna)
hpat_func = hpat.jit(test_impl)
for input_data, param_skipna in [([np.nan, 2., np.nan, 3., 1, -1000, np.inf], True),
([2., 3., 1, np.inf, -1000], False)]:
S = pd.Series(input_data)
result_ref = test_impl(S, param_skipna)
result = hpat_func(S, param_skipna)
self.assertEqual(result, result_ref)
def test_series_max(self):
def test_impl(S):
return S.max()
hpat_func = hpat.jit(test_impl)
# TODO type_min/type_max
for input_data in [[np.nan, 2., np.nan, 3., np.inf, 1, -1000],
[8, 31, 1123, -1024],
[2., 3., 1, -1000, np.inf]]:
S = pd.Series(input_data)
result_ref = test_impl(S)
result = hpat_func(S)
self.assertEqual(result, result_ref)
@unittest.skipIf(hpat.config.config_pipeline_hpat_default, "Series.max() any parameters unsupported")
def test_series_max_param(self):
def test_impl(S, param_skipna):
return S.max(skipna=param_skipna)
hpat_func = hpat.jit(test_impl)
for input_data, param_skipna in [([np.nan, 2., np.nan, 3., 1, -1000, np.inf], True),
([2., 3., 1, np.inf, -1000], False)]:
S = pd.Series(input_data)
result_ref = test_impl(S, param_skipna)
result = hpat_func(S, param_skipna)
self.assertEqual(result, result_ref)
def test_series_value_counts(self):
def test_impl(S):
return S.value_counts()
hpat_func = hpat.jit(test_impl)
S = pd.Series(['AA', 'BB', 'C', 'AA', 'C', 'AA'])
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
def test_series_dist_input1(self):
'''Verify distribution of a Series without index'''
def test_impl(S):
return S.max()
hpat_func = hpat.jit(distributed={'S'})(test_impl)
n = 111
S = pd.Series(np.arange(n))
start, end = get_start_end(n)
self.assertEqual(hpat_func(S[start:end]), test_impl(S))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
def test_series_dist_input2(self):
'''Verify distribution of a Series with integer index'''
def test_impl(S):
return S.max()
hpat_func = hpat.jit(distributed={'S'})(test_impl)
n = 111
S = pd.Series(np.arange(n), 1 + np.arange(n))
start, end = get_start_end(n)
self.assertEqual(hpat_func(S[start:end]), test_impl(S))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
@unittest.skip("Passed if run single")
def test_series_dist_input3(self):
'''Verify distribution of a Series with string index'''
def test_impl(S):
return S.max()
hpat_func = hpat.jit(distributed={'S'})(test_impl)
n = 111
S = pd.Series(np.arange(n), ['abc{}'.format(id) for id in range(n)])
start, end = get_start_end(n)
self.assertEqual(hpat_func(S[start:end]), test_impl(S))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
def test_series_tuple_input1(self):
def test_impl(s_tup):
return s_tup[0].max()
hpat_func = hpat.jit(test_impl)
n = 111
S = pd.Series(np.arange(n))
S2 = pd.Series(np.arange(n) + 1.0)
s_tup = (S, 1, S2)
self.assertEqual(hpat_func(s_tup), test_impl(s_tup))
@unittest.skip("pending handling of build_tuple in dist pass")
def test_series_tuple_input_dist1(self):
def test_impl(s_tup):
return s_tup[0].max()
hpat_func = hpat.jit(locals={'s_tup:input': 'distributed'})(test_impl)
n = 111
S = pd.Series(np.arange(n))
S2 = pd.Series(np.arange(n) + 1.0)
start, end = get_start_end(n)
s_tup = (S, 1, S2)
h_s_tup = (S[start:end], 1, S2[start:end])
self.assertEqual(hpat_func(h_s_tup), test_impl(s_tup))
def test_series_rolling1(self):
def test_impl(S):
return S.rolling(3).sum()
hpat_func = hpat.jit(test_impl)
S = pd.Series([1.0, 2., 3., 4., 5.])
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
def test_series_concat1(self):
def test_impl(S1, S2):
return pd.concat([S1, S2]).values
hpat_func = hpat.jit(test_impl)
S1 = pd.Series([1.0, 2., 3., 4., 5.])
S2 = pd.Series([6., 7.])
np.testing.assert_array_equal(hpat_func(S1, S2), test_impl(S1, S2))
def test_series_map1(self):
def test_impl(S):
return S.map(lambda a: 2 * a)
hpat_func = hpat.jit(test_impl)
S = pd.Series([1.0, 2., 3., 4., 5.])
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
def test_series_map_global1(self):
def test_impl(S):
return S.map(lambda a: a + GLOBAL_VAL)
hpat_func = hpat.jit(test_impl)
S = pd.Series([1.0, 2., 3., 4., 5.])
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
def test_series_map_tup1(self):
def test_impl(S):
return S.map(lambda a: (a, 2 * a))
hpat_func = hpat.jit(test_impl)
S = pd.Series([1.0, 2., 3., 4., 5.])
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
def test_series_map_tup_map1(self):
def test_impl(S):
A = S.map(lambda a: (a, 2 * a))
return A.map(lambda a: a[1])
hpat_func = hpat.jit(test_impl)
S = pd.Series([1.0, 2., 3., 4., 5.])
pd.testing.assert_series_equal(hpat_func(S), test_impl(S))
def test_series_combine(self):
def test_impl(S1, S2):
return S1.combine(S2, lambda a, b: 2 * a + b)
hpat_func = hpat.jit(test_impl)
S1 = pd.Series([1.0, 2., 3., 4., 5.])
S2 = pd.Series([6.0, 21., 3.6, 5.])
pd.testing.assert_series_equal(hpat_func(S1, S2), test_impl(S1, S2))
def test_series_combine_float3264(self):
def test_impl(S1, S2):
return S1.combine(S2, lambda a, b: 2 * a + b)
hpat_func = hpat.jit(test_impl)
S1 = pd.Series([np.float64(1), np.float64(2),
np.float64(3), | np.float64(4) | numpy.float64 |
#######################################################################################################################################################
#######################################################################Imports#########################################################################
#######################################################################################################################################################
#from itertools import product # forms cartesian products
from tqdm import tqdm_notebook as tqdm
#import pickle
import numpy as np
from numpy import linspace
import pandas as pd
import scipy as sp
from functools import reduce
from more_itertools import random_product
import operator
import math
from joblib import Parallel, delayed
from collections.abc import Iterable
#from scipy.integrate import quad
import matplotlib.pyplot as plt
#from sklearn.model_selection import cross_val_score, train_test_split, StratifiedKFold, KFold
from sklearn.metrics import accuracy_score, log_loss, roc_auc_score, f1_score, mean_absolute_error, r2_score
from similaritymeasures import frechet_dist, area_between_two_curves, dtw
import time
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.utils import plot_model
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
from IPython.display import display, Math, Latex, clear_output
import os
import shutil
import pickle
import traceback
#udf import
from utilities.LambdaNet import *
from utilities.metrics import *
#from utilities.utility_functions import *
from scipy.optimize import minimize
from scipy import optimize
import sympy as sym
from sympy import Symbol, sympify, lambdify, abc, SympifyError
# Function Generation 0 1 import
from sympy.sets.sets import Union
from sympy import Number
import math
from numba import jit, njit
import itertools
from interruptingcow import timeout
import time
from sklearn.linear_model import Lasso
from sklearn.preprocessing import PolynomialFeatures
#######################################################################################################################################################
#############################################################Setting relevant parameters from current config###########################################
#######################################################################################################################################################
def initialize_utility_functions_config_from_curent_notebook(config):
try:
globals().update(config['data'])
except KeyError:
print(KeyError)
try:
globals().update(config['lambda_net'])
except KeyError:
print(KeyError)
try:
globals().update(config['i_net'])
except KeyError:
print(KeyError)
try:
globals().update(config['evaluation'])
except KeyError:
print(KeyError)
try:
globals().update(config['computation'])
except KeyError:
print(KeyError)
random.seed(RANDOM_SEED)
np.random.seed(RANDOM_SEED)
if int(tf.__version__[0]) >= 2:
tf.random.set_seed(RANDOM_SEED)
else:
tf.set_random_seed(RANDOM_SEED)
global list_of_monomial_identifiers
from utilities.utility_functions import flatten, rec_gen, gen_monomial_identifier_list
list_of_monomial_identifiers_extended = []
if laurent:
variable_sets = [list(flatten([[_d for _d in range(d+1)], [-_d for _d in range(1, neg_d+1)]])) for _ in range(n)]
list_of_monomial_identifiers_extended = rec_gen(variable_sets)
if len(list_of_monomial_identifiers_extended) < 500:
print(list_of_monomial_identifiers_extended)
list_of_monomial_identifiers = []
for monomial_identifier in tqdm(list_of_monomial_identifiers_extended):
if np.sum(monomial_identifier) <= d:
if monomial_vars == None or len(list(filter(lambda x: x != 0, monomial_identifier))) <= monomial_vars:
list_of_monomial_identifiers.append(monomial_identifier)
else:
variable_list = ['x'+ str(i) for i in range(n)]
list_of_monomial_identifiers = gen_monomial_identifier_list(variable_list, d, n)
#######################################################################################################################################################
#############################################################General Utility Functions#################################################################
#######################################################################################################################################################
def round_expr(expr, num_digits):
return expr.xreplace({n : round(n, num_digits) for n in expr.atoms(Number)})
def nCr(n,r):
f = math.factorial
return f(n) // f(r) // f(n-r)
def rec_gen(x):
if len(x) == 1:
return [[item] for item in x[0]]
appended = []
for s_el in x[0]:
for next_s in rec_gen(x[1:]):
appended.append([s_el] + next_s)
return appended
def gen_monomial_identifier_list(variable_list, degree, number_of_variables):
def get_polynomial(vars, power):
if "c" in vars:
raise Exception("\"c\" cannot be a variable")
vars.append("c") # add dummy variable
# compute all combinations of variables
terms = []
for x in itertools.combinations_with_replacement(vars, power):
terms.append(x)
# get rid of "c" terms
terms = list(map(list, terms))
for i in range(len(terms)):
while "c" in terms[i]:
terms[i].remove("c")
return terms
terms = get_polynomial(variable_list, degree)
monomial_identifier_list = []
for term in terms:
monomial = [0 for i in range(number_of_variables)]
for value in term:
index = int(value[1:])
monomial[index] = monomial[index] + 1
monomial_identifier_list.append(monomial)
return monomial_identifier_list
def pairwise(iterable):
"s -> (s0, s1), (s2, s3), (s4, s5), ..."
a = iter(iterable)
return zip(a, a)
def chunks(lst, chunksize):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), chunksize):
yield lst[i:i + chunksize]
def prod(iterable):
return reduce(operator.mul, iterable, 1)
def return_float_tensor_representation(some_representation, dtype=tf.float32):
if tf.is_tensor(some_representation):
some_representation = tf.dtypes.cast(some_representation, dtype)
else:
some_representation = tf.convert_to_tensor(some_representation)
some_representation = tf.dtypes.cast(some_representation, dtype)
if not tf.is_tensor(some_representation):
raise SystemExit('Given variable is no instance of ' + str(dtype) + ':' + str(some_representation))
return some_representation
def return_numpy_representation(some_representation):
if isinstance(some_representation, pd.DataFrame):
some_representation = some_representation.values
some_representation = np.float32(some_representation)
if isinstance(some_representation, list):
some_representation = np.array(some_representation, dtype=np.float32)
if isinstance(some_representation, np.ndarray):
#print(some_representation)
#print(type(some_representation))
#print(some_representation.dtype)
#print(some_representation[0])
#print(some_representation[0].dtype)
some_representation = np.float32(some_representation)
else:
raise SystemExit('Given variable is no instance of ' + str(np.ndarray) + ':' + str(some_representation))
return some_representation
def mergeDict(dict1, dict2):
#Merge dictionaries and keep values of common keys in list
newDict = {**dict1, **dict2}
for key, value in newDict.items():
if key in dict1 and key in dict2:
if isinstance(dict1[key], list) and isinstance(value, list):
newDict[key] = dict1[key]
newDict[key].extend(value)
elif isinstance(dict1[key], list) and not isinstance(value, list):
newDict[key] = dict1[key]
newDict[key].extend([value])
elif not isinstance(dict1[key], list) and isinstance(value, list):
newDict[key] = [dict1[key]]
newDict[key].extend(value)
else:
newDict[key] = [dict1[key], value]
return newDict
def return_callbacks_from_string(callback_string_list):
callbacks = [] if len(callback_string_list) > 0 else None
#if 'plot_losses_callback' in callback_string_list:
#callbacks.append(PlotLossesCallback())
if 'reduce_lr_loss' in callback_string_list:
reduce_lr_loss = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=min(50, epochs//10), verbose=0, min_delta=0, mode='min') #epsilon
callbacks.append(reduce_lr_loss)
if 'early_stopping' in callback_string_list:
try:
patience = early_stopping_patience if early_stopping_patience is not None else min(50, epochs//10)
except:
patience = min(50, epochs//10)
earlyStopping = EarlyStopping(monitor='val_loss', patience=patience, min_delta=0, verbose=0, mode='min', restore_best_weights=True)
callbacks.append(earlyStopping)
#if not multi_epoch_analysis and samples_list == None:
#callbacks.append(TQDMNotebookCallback())
return callbacks
def arreq_in_list(myarr, list_arrays):
return next((True for elem in list_arrays if np.array_equal(elem, myarr)), False)
def flatten(l):
for el in l:
if isinstance(el, Iterable) and not isinstance(el, (str, bytes)):
yield from flatten(el)
else:
yield el
def shape_flat_network_parameters(flat_network_parameters, target_network_parameters):
#from utilities.utility_functions import flatten_list
#def recursive_len(item):
# if type(item) == list:
# return sum(recursive_len(subitem) for subitem in item)
# else:
# return 1
shaped_network_parameters =[]
start = 0
for parameters in target_network_parameters:
target_shape = parameters.shape
size = np.prod(target_shape)#recursive_len(el)#len(list(flatten_list(el)))
shaped_parameters = np.reshape(flat_network_parameters[start:start+size], target_shape)
shaped_network_parameters.append(shaped_parameters)
start += size
return shaped_network_parameters
def shaped_network_parameters_to_array(shaped_network_parameters):
network_parameter_list = []
for layer_weights, biases in pairwise(shaped_network_parameters): #clf.get_weights()
for neuron in layer_weights:
for weight in neuron:
network_parameter_list.append(weight)
for bias in biases:
network_parameter_list.append(bias)
return np.array(network_parameter_list)
#################################################################################################################################################################################### Normalization #################################################################################### ################################################################################################################################################################################################################
def get_order_sum(arrays):
arrays = np.array(arrays)
values = [np.sum(arrays[0])]
order = [0]
for i in range(1, len(arrays)):
value = np.sum(arrays[i])
pos = 0
while pos<len(values) and value>=values[pos]:
if value == values[pos]:
print("!!!!!!!!!!!!!!!!KOLLISION!!!!!!!!!!!!!!!!!!")
print(value)
print(arrays[i])
print(arrays[order[pos]])
pos += 1
values.insert(pos, value)
order.insert(pos, i)
return order
## source for sort_array: https://www.geeksforgeeks.org/permute-the-elements-of-an-array-following-given-order/
def sort_array(arr, order):
length = len(order)
#ordered_arr = np.zeros(length)
ordered_arr = [None] * length
for i in range(length):
ordered_arr[i] = arr[order[i]]
arr=ordered_arr
return arr
def normal_neural_net(model_arr):
for i in range(len(lambda_network_layers)):
index = 2*(i)
dense_arr = | np.transpose(model_arr[index]) | numpy.transpose |
import tensorflow as tf
import numpy as np
import sys
def get_angles(pos, i, d_model):
angle_rates = 1 / np.power(10000, (2 * (i//2)) / | np.float32(d_model) | numpy.float32 |
import numpy as np
import torch
from torch import nn
from .base import SeparablePoolNd
from ..utils import NdSpec
def _gaussian_kernel1d(sigma, order, radius):
"""
Computes a 1-D Gaussian convolution kernel.
This function is copied from scipy to avoid
dependency issues when importing from scipy
"""
if order < 0:
raise ValueError('order must be non-negative')
exponent_range = np.arange(order + 1)
sigma2 = sigma * sigma
x = np.arange(-radius, radius+1)
phi_x = | np.exp(-0.5 / sigma2 * x ** 2) | numpy.exp |
import pytest
import numpy as np
from obp.policy.linear import LinEpsilonGreedy
from obp.policy.linear import LinUCB
from obp.policy.linear import LinTS
def test_linear_base_exception():
# invalid dim
with pytest.raises(ValueError):
LinEpsilonGreedy(n_actions=2, dim=-3)
with pytest.raises(ValueError):
LinEpsilonGreedy(n_actions=2, dim=0)
with pytest.raises(ValueError):
LinEpsilonGreedy(n_actions=2, dim="3")
# invalid n_actions
with pytest.raises(ValueError):
LinEpsilonGreedy(n_actions=-3, dim=2)
with pytest.raises(ValueError):
LinEpsilonGreedy(n_actions=1, dim=2)
with pytest.raises(ValueError):
LinEpsilonGreedy(n_actions="2", dim=2)
# invalid len_list
with pytest.raises(ValueError):
LinEpsilonGreedy(n_actions=2, dim=2, len_list=-3)
with pytest.raises(ValueError):
LinEpsilonGreedy(n_actions=2, dim=2, len_list=0)
with pytest.raises(ValueError):
LinEpsilonGreedy(n_actions=2, dim=2, len_list="3")
# invalid batch_size
with pytest.raises(ValueError):
LinEpsilonGreedy(n_actions=2, dim=2, batch_size=-2)
with pytest.raises(ValueError):
LinEpsilonGreedy(n_actions=2, dim=2, batch_size=0)
with pytest.raises(ValueError):
LinEpsilonGreedy(n_actions=2, dim=2, batch_size="10")
# invalid relationship between n_actions and len_list
with pytest.raises(ValueError):
LinEpsilonGreedy(n_actions=5, len_list=10, dim=2)
with pytest.raises(ValueError):
LinEpsilonGreedy(n_actions=2, len_list=3, dim=2)
# invalid alpha and lambda
with pytest.raises(ValueError):
LinEpsilonGreedy(n_actions=2, dim=2, alpha_=0.0, lambda_=-3.0)
with pytest.raises(ValueError):
LinEpsilonGreedy(n_actions=2, dim=2, alpha_=-0.0)
with pytest.raises(ValueError):
LinEpsilonGreedy(n_actions=2, dim=2, lambda_=-1.0)
def test_lin_epsilon_normal_epsilon():
policy1 = LinEpsilonGreedy(n_actions=2, dim=2)
assert 0 <= policy1.epsilon <= 1
policy2 = LinEpsilonGreedy(n_actions=2, dim=2, epsilon=0.3)
assert policy2.epsilon == 0.3
def test_lin_epsilon_abnormal_epsilon():
with pytest.raises(ValueError):
LinEpsilonGreedy(n_actions=2, dim=2, epsilon=1.2)
with pytest.raises(ValueError):
LinEpsilonGreedy(n_actions=2, dim=2, epsilon=-0.2)
def test_lin_epsilon_select_action_exploitation():
trial_num = 50
policy = LinEpsilonGreedy(n_actions=2, dim=2, epsilon=0.0)
context = np.array([1.0, 1.0]).reshape(1, -1)
policy.update_params(action=0, reward=1.0, context=context)
policy.update_params(action=0, reward=1.0, context=context)
policy.update_params(action=1, reward=1.0, context=context)
policy.update_params(action=1, reward=0.0, context=context)
for _ in range(trial_num):
assert policy.select_action(context=context)[0] == 0
def test_lin_epsilon_select_action_exploration():
trial_num = 50
policy = LinEpsilonGreedy(n_actions=2, dim=2, epsilon=1.0)
context = np.array([1.0, 1.0]).reshape(1, -1)
policy.update_params(action=0, reward=1.0, context=context)
policy.update_params(action=0, reward=1.0, context=context)
policy.update_params(action=1, reward=1.0, context=context)
policy.update_params(action=1, reward=0.0, context=context)
selected_action = [policy.select_action(context=context) for _ in range(trial_num)]
assert 0 < sum(selected_action)[0] < trial_num
def test_lin_epsilon_update_params():
# check the consistency with Sherman–Morrison formula
policy = LinEpsilonGreedy(n_actions=2, dim=2, epsilon=1.0)
action = 0
reward = 1.0
context = np.array([1, 0]).reshape(1, -1)
A_inv_temp = np.array([[1 / 2, 0], [0, 1]])
b_temp = np.array([1, 1])
policy.A_inv_temp[action] = np.copy(A_inv_temp)
policy.b_temp[:, action] = np.copy(b_temp)
policy.update_params(action=action, reward=reward, context=context)
next_A_inv = A_inv_temp - np.array([[1 / 4, 0], [0, 0]]) / (1 + 1 / 2)
next_b = b_temp + reward * context
assert np.allclose(policy.A_inv[action], next_A_inv)
assert np.allclose(policy.b[:, action], next_b)
def test_lin_ucb_initialize():
# note that the meaning of epsilon is different from that of LinEpsilonGreedy
with pytest.raises(ValueError):
LinUCB(n_actions=2, dim=2, epsilon=-0.2)
n_actions = 3
dim = 2
policy = LinUCB(n_actions=n_actions, dim=dim, epsilon=2.0)
assert policy.theta_hat.shape == (dim, n_actions)
assert policy.A_inv.shape == (n_actions, dim, dim)
assert policy.b.shape == (dim, n_actions)
assert policy.A_inv_temp.shape == (n_actions, dim, dim)
assert policy.b_temp.shape == (dim, n_actions)
def test_lin_ucb_select_action():
dim = 3
len_list = 2
policy = LinUCB(n_actions=4, dim=dim, len_list=2, epsilon=0.0)
context = np.ones(dim).reshape(1, -1)
action = policy.select_action(context=context)
assert len(action) == len_list
def test_lin_ucb_update_params():
# check the consistency with Sherman–Morrison formula
policy = LinUCB(n_actions=2, dim=2, epsilon=1.0)
action = 0
reward = 1.0
context = np.array([1, 0]).reshape(1, -1)
A_inv_temp = np.array([[1 / 2, 0], [0, 1]])
b_temp = np.array([1, 1])
policy.A_inv_temp[action] = np.copy(A_inv_temp)
policy.b_temp[:, action] = np.copy(b_temp)
policy.update_params(action=action, reward=reward, context=context)
next_A_inv = A_inv_temp - np.array([[1 / 4, 0], [0, 0]]) / (1 + 1 / 2)
next_b = b_temp + reward * context
assert np.allclose(policy.A_inv[action], next_A_inv)
assert np.allclose(policy.b[:, action], next_b)
def test_lin_ts_initialize():
n_actions = 3
dim = 2
policy = LinTS(n_actions=n_actions, dim=dim)
assert policy.A_inv.shape == (n_actions, dim, dim)
assert policy.b.shape == (dim, n_actions)
assert policy.A_inv_temp.shape == (n_actions, dim, dim)
assert policy.b_temp.shape == (dim, n_actions)
def test_lin_ts_select_action():
dim = 3
len_list = 2
policy = LinTS(n_actions=4, dim=dim, len_list=2)
context = np.ones(dim).reshape(1, -1)
action = policy.select_action(context=context)
assert len(action) == len_list
def test_lin_ts_update_params():
# check the consistency with Sherman–Morrison formula
policy = LinTS(n_actions=2, dim=2)
action = 0
reward = 1.0
context = np.array([1, 0]).reshape(1, -1)
A_inv_temp = np.array([[1 / 2, 0], [0, 1]])
b_temp = | np.array([1, 1]) | numpy.array |
import site # so that ai4water directory is in path
import unittest
import os
import sys
ai4_dir = os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0])))
site.addsitedir(ai4_dir)
import numpy as np
import pandas as pd
from ai4water.preprocessing.transformations import Transformation
from ai4water.tf_attributes import tf
from ai4water.datasets import busan_beach
if 230 <= int(''.join(tf.__version__.split('.')[0:2]).ljust(3, '0')) < 250:
from ai4water.functional import Model
print(f"Switching to functional API due to tensorflow version {tf.__version__}")
else:
from ai4water import Model
df = pd.DataFrame(np.concatenate([np.arange(1, 10).reshape(-1, 1), np.arange(1001, 1010).reshape(-1, 1)], axis=1),
columns=['data1', 'data2'])
def build_and_run(x_transformation, y_transformation,
data, inputs, outputs):
model = Model(model="RandomForestRegressor",
input_features=inputs,
output_features=outputs,
x_transformation=x_transformation,
y_transformation=y_transformation,
verbosity=0)
model.fit(data=data)
x, y = model.training_data(key='junk')
#pred, pred = model.inverse_transform(y, y, key='junk')
pred, index = model.dh_.deindexify(y, key='junk')
pred = pd.DataFrame(pred.reshape(len(pred), model.num_outs), columns=outputs, index=index).sort_index()
return pred
def run_method1(method,
cols=None,
data=None,
**kwargs):
normalized_df1, scaler = Transformation(method=method,
features=cols,
**kwargs)(data,
'fit_transform',
return_key=True)
denormalized_df1 = Transformation(features=cols,
)(normalized_df1,
'inverse',
scaler=scaler['scaler'])
return normalized_df1, denormalized_df1
def run_method2(method,
data=None,
index=None,
**kwargs):
if index:
data.index = pd.date_range("20110101", periods=len(data), freq="D")
scaler = Transformation(method=method,
**kwargs)
normalized_df, scaler_dict = scaler.fit_transform(data, return_key=True)
denormalized_df = scaler.inverse_transform(data=normalized_df, key=scaler_dict['key'])
return data, normalized_df, denormalized_df
def run_method3(method,
data=None,
index=None,
**kwargs):
if index:
data.index = pd.date_range("20110101", periods=len(data), freq="D")
scaler = Transformation(method=method,
**kwargs)
normalized_df3, scaler_dict = scaler(data,
return_key=True)
denormalized_df3 = scaler(what='inverse', data=normalized_df3, key=scaler_dict['key'])
return data, normalized_df3, denormalized_df3
def run_method4(method,data=None, **kwargs):
scaler = Transformation(**kwargs)
normalized_df4, scaler_dict = getattr(scaler, "fit_transform_with_" + method)(
data=data,
return_key=True)
denormalized_df4 = getattr(scaler, "inverse_transform_with_" + method)(data=normalized_df4, key=scaler_dict['key'])
return normalized_df4, denormalized_df4
def run_log_methods(method="log", index=None, insert_nans=True, insert_zeros=False, assert_equality=True,
insert_ones=False):
a = np.random.random((10, 4))
a[0, 0] = np.nan
a[0, 1] = 1.
if insert_nans or insert_zeros:
a[2:4, 1] = np.nan
a[3:5, 2:3] = np.nan
if insert_zeros:
a[5:8, 3] = 0.0
if insert_ones:
a[6, 1] = 1.0
a[9, 2:3] = 1.0
cols = ['data1', 'data2', 'data3', 'data4']
if index is not None:
index = pd.date_range("20110101", periods=len(a), freq="D")
df3 = pd.DataFrame(a, columns=cols, index=index)
_, _ = run_method1(method=method, data=df3.copy())
_, _, dfo2 = run_method2(method=method, data=df3.copy())
_, _, dfo3 = run_method3(method=method, data=df3.copy())
_, dfo4 = run_method4(method=method, data=df3.copy())
if assert_equality:
#assert np.allclose(df3, dfo1, equal_nan=True)
assert np.allclose(df3, dfo2, equal_nan=True)
assert np.allclose(df3, dfo3, equal_nan=True)
assert np.allclose(df3, dfo4, equal_nan=True)
return
class test_Scalers(unittest.TestCase):
def run_method(self, method, cols=None, index=None, assert_equality=False, **kwargs):
cols = ['data1', 'data2'] if cols is None else cols
normalized_df1, denormalized_df1 = run_method1(method, cols, data=df.copy())
orig_data2, normalized_df2, denormalized_df2 = run_method2(method,
index=index,
features=cols,
data=df.copy(),
**kwargs
)
orig_data3, normalized_df3, denormalized_df3 = run_method3(method, index=index,
data=df.copy(),
**kwargs)
normalized_df4, denormalized_df4 = run_method4(method, data=df.copy(),
**kwargs)
if assert_equality:
assert np.allclose(orig_data2, denormalized_df2)
#assert np.allclose(orig_data3, normalized_df3) # todo
if len(cols) < 2:
self.check_features(denormalized_df1)
else:
for i,j,k,l in zip(normalized_df1[cols].values, normalized_df2[cols].values, normalized_df3[cols].values, normalized_df4[cols].values):
for x in [0, 1]:
self.assertEqual(int(i[x]), int(j[x]))
self.assertEqual(int(j[x]), int(k[x]))
self.assertEqual(int(k[x]), int(l[x]))
for a,i,j,k,l in zip(df.values, denormalized_df1[cols].values, denormalized_df2[cols].values, denormalized_df3[cols].values, denormalized_df4[cols].values):
for x in [0, 1]:
self.assertEqual(int(round(a[x])), int(round(j[x])))
self.assertEqual(int(round(i[x])), int(round(j[x])))
self.assertEqual(int(round(j[x])), int(round(k[x])))
self.assertEqual(int(round(k[x])), int(round(l[x])))
def check_features(self, denorm):
for idx, v in enumerate(denorm['data2']):
self.assertEqual(v, 1001 + idx)
def test_get_scaler_from_dict_error(self):
normalized_df1, _ = Transformation()(df, 'fit_transform', return_key=True)
self.assertRaises(ValueError, Transformation(), what='inverse', data=normalized_df1)
return
def test_log_scaler_with_feat(self):
self.run_method("log", cols=["data1"])
return
def test_robust_scaler_with_feat(self):
self.run_method("robust", cols=["data1"], assert_equality=True)
return
def test_minmax_scaler_with_feat(self):
self.run_method("minmax", cols=["data1"], assert_equality=True)
return
def test_minmax_scaler_with_feat_and_index(self):
self.run_method("minmax", cols=["data1"], index=True, assert_equality=True)
def test_maxabs_scaler_with_feat(self):
self.run_method("maxabs", cols=["data1"], assert_equality=True)
def test_zscore_scaler_with_feat(self):
self.run_method("minmax", cols=["data1"], assert_equality=True)
def test_power_scaler_with_feat(self):
self.run_method("maxabs", cols=["data1"], assert_equality=True)
def test_quantile_scaler_with_feat(self):
self.run_method("quantile", cols=["data1"], assert_equality=True, n_quantiles=5)
def test_log_scaler(self):
self.run_method("log", assert_equality=True)
def test_log10_scaler(self):
self.run_method("log10", assert_equality=True)
return
def test_log2_scaler(self):
self.run_method("log2", assert_equality=True)
return
def test_robust_scaler(self):
self.run_method("robust", assert_equality=True)
return
def test_minmax_scaler(self):
self.run_method("minmax", assert_equality=True)
return
def test_maxabs_scaler(self):
self.run_method("maxabs", assert_equality=True)
def test_zscore_scaler(self):
self.run_method("minmax", assert_equality=True)
def test_power_scaler(self):
self.run_method("maxabs", assert_equality=True)
def test_quantile_scaler(self):
self.run_method("quantile", assert_equality=True, n_quantiles=5)
return
def test_log_with_nans(self):
run_log_methods(index=None)
return
def test_log_with_index(self):
run_log_methods("log", True)
return
def test_log10_with_nans(self):
run_log_methods(method='log10', index=None)
return
def test_log10_with_index(self):
run_log_methods("log10", True)
return
def test_log2_with_nans(self):
run_log_methods(method='log2', index=None)
return
def test_log2_with_index(self):
run_log_methods("log2", True)
return
def test_tan_with_nans(self):
run_log_methods("tan", index=None, assert_equality=False)
return
def test_tan_with_index(self):
run_log_methods("tan", True, assert_equality=False)
return
def test_cumsum_with_index(self):
run_log_methods("cumsum", True, insert_nans=False, assert_equality=False)
return
def test_cumsum_with_nan(self):
run_log_methods("cumsum", True, insert_nans=True, assert_equality=False)
return
def test_zero_log(self):
run_log_methods("log", True, insert_nans=True, insert_zeros=True)
return
def test_zero_one_log(self):
run_log_methods("log", True, insert_nans=True, insert_zeros=True, insert_ones=True)
return
def test_zero_log10(self):
run_log_methods("log10", True, insert_nans=True, insert_zeros=True)
return
def test_zero_one_log10(self):
run_log_methods("log10", True, insert_nans=True, insert_zeros=True, insert_ones=True)
return
def test_zero_log2(self):
run_log_methods("log2", True, insert_nans=True, insert_zeros=True)
return
def test_zero_one_log2(self):
run_log_methods("log2", True, insert_nans=True, insert_zeros=True, insert_ones=True)
return
def test_multiple_transformations(self):
"""Test when we want to apply multiple transformations on one or more features"""
inputs = ['in1', 'inp1']
outputs = ['out1']
data = pd.DataFrame(np.random.random((100, 3)), columns=inputs+outputs)
x_transformation = "minmax"
y_transformation = ["log", "minmax"]
pred = build_and_run(x_transformation, y_transformation, data, inputs, outputs)
for i in pred.index:
assert np.allclose(data['out1'].loc[i], pred['out1'].loc[i])
return
def test_multiple_same_transformations(self):
"""Test when we want to apply multiple transformations on one or more features"""
inputs = ['in1', 'inp1']
outputs = ['out1']
data = pd.DataFrame(np.random.random((100, 3)), columns=inputs+outputs)
x_transformation = "robust"
y_transformation = ["robust", "robust"]
pred = build_and_run(x_transformation, y_transformation, data, inputs,outputs)
for i in pred.index:
assert np.allclose(data['out1'].loc[i], pred['out1'].loc[i])
return
def test_multiple_same_transformations_mutile_outputs(self):
"""Test when we want to apply multiple transformations on one or more features"""
inputs = ['in1', 'inp1']
outputs = ['out1', 'out2']
data = pd.DataFrame( | np.random.random((100, 4)) | numpy.random.random |
# Copyright 2016 <NAME> (INAC / CEA Grenoble).
#
# This file is subject to the 2-clause BSD license as found at
# http://kwant-project.org/license.
"""Replace symmetries of Kwant builders with momentum parameters to the
system."""
import sys
import collections
import cmath
import numpy as np
import tinyarray as ta
import kwant
from kwant.builder import herm_conj
if sys.version_info >= (3, 0):
def _hashable(obj):
return isinstance(obj, collections.Hashable)
else:
def _hashable(obj):
return (isinstance(obj, collections.Hashable)
and not isinstance(obj, np.ndarray))
def _memoize(f):
"""Decorator to memoize a function that works even with unhashable args.
This decorator will even work with functions whose args are not hashable.
The cache key is made up by the hashable arguments and the ids of the
non-hashable args. It is up to the user to make sure that non-hashable
args do not change during the lifetime of the decorator.
This decorator will keep reevaluating functions that return None.
"""
def lookup(*args):
key = tuple(arg if _hashable(arg) else id(arg) for arg in args)
result = cache.get(key)
if result is None:
cache[key] = result = f(*args)
return result
cache = {}
return lookup
def wraparound(builder, keep=None):
"""Replace translational symmetries by momentum parameters.
A new Builder instance is returned. By default, each symmetry is replaced
by one scalar momentum parameter that is appended to the already existing
arguments of the system. Optionally, one symmetry may be kept by using the
`keep` argument.
"""
@_memoize
def bind_site(val):
assert callable(val)
return lambda a, *args: val(a, *args[:mnp])
@_memoize
def bind_hopping_as_site(elem, val):
def f(a, *args):
phase = cmath.exp(1j * ta.dot(elem, args[mnp:]))
v = val(a, sym.act(elem, a), *args[:mnp]) if callable(val) else val
pv = phase * v
return pv + herm_conj(pv)
return f
@_memoize
def bind_hopping(elem, val):
def f(a, b, *args):
phase = cmath.exp(1j * ta.dot(elem, args[mnp:]))
v = val(a, sym.act(elem, b), *args[:mnp]) if callable(val) else val
return phase * v
return f
@_memoize
def bind_sum(*vals):
return lambda *args: sum((val(*args) if callable(val) else val)
for val in vals)
if keep is None:
ret = kwant.Builder()
sym = builder.symmetry
else:
periods = list(builder.symmetry.periods)
ret = kwant.Builder(kwant.TranslationalSymmetry(periods.pop(keep)))
sym = kwant.TranslationalSymmetry(*periods)
sites = {}
hops = collections.defaultdict(list)
mnp = -len(sym.periods) # Used by the bound functions above.
# Store lists of values, so that multiple values can be assigned to the
# same site or hopping.
for site, val in builder.site_value_pairs():
sites[site] = [bind_site(val) if callable(val) else val]
for hop, val in builder.hopping_value_pairs():
a, b = hop
b_dom = sym.which(b)
b_wa = sym.act(-b_dom, b)
if a == b_wa:
# The hopping gets wrapped-around into an onsite Hamiltonian.
# Since site `a` already exists in the system, we can simply append.
sites[a].append(bind_hopping_as_site(b_dom, val))
else:
# The hopping remains a hopping.
if b != b_wa or callable(val):
# The hopping got wrapped-around or is a function.
val = bind_hopping(b_dom, val)
# Make sure that there is only one entry for each hopping
# (pointing in one direction).
if (b_wa, a) in hops:
assert (a, b_wa) not in hops
if callable(val):
assert not isinstance(val, kwant.builder.HermConjOfFunc)
val = kwant.builder.HermConjOfFunc(val)
else:
val = kwant.builder.herm_conj(val)
hops[b_wa, a].append(val)
else:
hops[a, b_wa].append(val)
# Copy stuff into result builder, converting lists of more than one element
# into summing functions.
for site, vals in sites.items():
ret[site] = vals[0] if len(vals) == 1 else bind_sum(*vals)
for hop, vals in hops.items():
ret[hop] = vals[0] if len(vals) == 1 else bind_sum(*vals)
return ret
def plot_bands_2d(syst, args=(), momenta=(31, 31)):
"""Plot the bands of a system with two wrapped-around symmetries."""
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot
if not isinstance(syst, kwant.system.FiniteSystem):
raise TypeError("Need a system without symmetries.")
fig = pyplot.figure()
ax = fig.gca(projection='3d')
kxs = np.linspace(-np.pi, np.pi, momenta[0])
kys = np.linspace(-np.pi, np.pi, momenta[1])
energies = [[np.sort(np.linalg.eigvalsh(syst.hamiltonian_submatrix(
args + (kx, ky), sparse=False)).real)
for ky in kys] for kx in kxs]
energies = np.array(energies)
mesh_x, mesh_y = np.meshgrid(kxs, kys)
for i in range(energies.shape[-1]):
ax.plot_wireframe(mesh_x, mesh_y, energies[:, :, i],
rstride=1, cstride=1)
pyplot.show()
def _simple_syst(lat, E=0, t=1+1j):
"""Create a builder for a simple infinite system."""
sym = kwant.TranslationalSymmetry(lat.vec((1, 0)), lat.vec((0, 1)))
# Build system with 2d periodic BCs. This system cannot be finalized in
# Kwant <= 1.2.
syst = kwant.Builder(sym)
syst[lat.shape(lambda p: True, (0, 0))] = E
syst[lat.neighbors(1)] = t
return syst
def test_consistence_with_bands(kx=1.9, nkys=31):
kys = | np.linspace(-np.pi, np.pi, nkys) | numpy.linspace |
#!/usr/bin/env python
# coding: utf-8
import sys
import time
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-n","--name", help="if we want re-train")
parser.add_argument("-T","--done", help="if we want load dictionary and data",type=int)
parser.add_argument("-e","--epoch", help="the number of epoch to train by default is 60",type=int)
parser.add_argument("-b","--batch", help="the batch size by default is 64",type=int)
parser.add_argument("-m","--model", help="the model name we want to re-train")
args=parser.parse_args()
def usage():
print("""
This script it's for training model.
you need to run this script with at least one parameter the model_name you want to save the wight with.
exp:
$python train.py model_v1
if you wont re train you should second parameter which is T that mean don't extract data agine just readit from the X_data.npy file
exp:
$python train.py model_v2 T
you can change the strucher of model as you want just open the file and go to the model section line
you can change the hiper parameter by passing as argument to the script
exp:
""")
import numpy as np
import tensorflow.keras as keras
import pickle
import os
def extract_array(path,label_map):
action_names=os.listdir(path)
data=[]
label=[]
for action in action_names:
print(action)
for folder in os.listdir(os.path.join(path,action)):
sequnce=[]
for frame in sorted(os.listdir(os.path.join(path,action,folder)),key=lambda x: int(x[:x.find('.')])):
arr=np.load(os.path.join(path,action,folder,frame))
sequnce.append(arr)
data.append(sequnce)
label.append(label_map[action])
return data,label
def get_run_logdir(model_name):
root_logdir = os.path.join(os.curdir, "my_logs")
run_id = time.strftime("run_%Y_%m_%d")
return os.path.join(root_logdir, run_id,model_name)
print("Reading The action....")
if args.done==1:
print("read label...")
with open("label_map.pkl",'rb') as f:
label_map=pickle.load(f)
print("load data...")
X_data=np.load("X_data.npy")
y_data=np.load("label.npy")
else:
action_names=os.listdir('npy_data')
label_map=dict(zip(action_names,range(len(action_names))))
with open('label_map.pkl', 'wb') as f:
pickle.dump(label_map, f, pickle.HIGHEST_PROTOCOL)
print("start extract array .....")
X_data,y_data=extract_array('npy_data',label_map)
X_data=np.array(X_data)
print("savaing data so you can use it later")
np.save("X_data.npy",X_data)
| np.save("label.npy",y_data) | numpy.save |
from rllab.algos.base import RLAlgorithm
from rllab.misc.overrides import overrides
from rllab.misc import special
from rllab.misc import ext
from rllab.sampler import parallel_sampler
from rllab.plotter import plotter
from functools import partial
import rllab.misc.logger as logger
import theano.tensor as TT
import pickle as pickle
import numpy as np
import pyprind
import lasagne
import math
def parse_update_method(update_method, **kwargs):
if update_method == 'adam':
return partial(lasagne.updates.adam, **ext.compact(kwargs))
elif update_method == 'sgd':
return partial(lasagne.updates.sgd, **ext.compact(kwargs))
else:
raise NotImplementedError
class SimpleReplayPool(object):
def __init__(
self, max_pool_size, observation_dim, action_dim):
self._observation_dim = observation_dim
self._action_dim = action_dim
self._max_pool_size = max_pool_size
self._observations = np.zeros(
(max_pool_size, observation_dim),
)
self._actions = np.zeros(
(max_pool_size, action_dim),
)
self._rewards = np.zeros(max_pool_size)
self._terminals = np.zeros(max_pool_size, dtype='uint8')
self._bottom = 0
self._top = 0
self._size = 0
def add_sample(self, observation, action, reward, terminal):
self._observations[self._top] = observation
self._actions[self._top] = action
self._rewards[self._top] = reward
self._terminals[self._top] = terminal
self._top = (self._top + 1) % self._max_pool_size
if self._size >= self._max_pool_size:
self._bottom = (self._bottom + 1) % self._max_pool_size
else:
self._size += 1
def random_batch(self, batch_size):
assert self._size > batch_size
indices = np.zeros(batch_size, dtype='uint64')
transition_indices = | np.zeros(batch_size, dtype='uint64') | numpy.zeros |
"""
"""
import numpy as np
from astropy.table import Table
from ..prim_galprop_model import PrimGalpropModel
__all__ = ('test_galprop_name1',)
class BaryonicMass(PrimGalpropModel):
def __init__(self, **kwargs):
galprop_name = 'baryonic_mass'
PrimGalpropModel.__init__(self, galprop_name, **kwargs)
def mean_baryonic_mass(self, **kwargs):
try:
table = kwargs['table']
halo_mass = table[self.prim_haloprop_key]
except KeyError:
halo_mass = kwargs['prim_haloprop']
result = halo_mass/100.
if 'table' in kwargs:
table['baryonic_mass'][:] = result
else:
return result
def test_galprop_name1():
model = BaryonicMass()
assert hasattr(model, 'mc_baryonic_mass')
def test_galprop_name2():
model = BaryonicMass()
assert 'mc_baryonic_mass' in model._mock_generation_calling_sequence
def test_galprop_name3():
model = BaryonicMass()
assert 'baryonic_mass' in model._galprop_dtypes_to_allocate.names
def test_mean_galprop_behavior1():
model = BaryonicMass()
halo_mass = np.logspace(10, 15, 100)
baryonic_mass = model.mean_baryonic_mass(prim_haloprop=halo_mass)
def test_mean_galprop_behavior2():
model = BaryonicMass()
halo_mass = np.logspace(10, 15, 100)
baryonic_mass1 = model.mean_baryonic_mass(prim_haloprop=halo_mass)
t = Table({model.prim_haloprop_key: halo_mass})
t['baryonic_mass'] = 0.
model.mean_baryonic_mass(table=t)
assert np.all(t['baryonic_mass'] == baryonic_mass1)
def test_mc_galprop_determinism1():
model = BaryonicMass(redshift=0)
npts = int(1e2)
halo_mass = np.zeros(npts) + 1e10
mc_baryonic_mass1 = model.mc_baryonic_mass(
prim_haloprop=halo_mass, seed=43)
mc_baryonic_mass2 = model.mc_baryonic_mass(
prim_haloprop=halo_mass, seed=43)
assert np.allclose(mc_baryonic_mass1, mc_baryonic_mass2)
mc_baryonic_mass3 = model.mc_baryonic_mass(
prim_haloprop=halo_mass, seed=44)
assert not np.allclose(mc_baryonic_mass1, mc_baryonic_mass3)
def test_mc_galprop_determinism2():
model = BaryonicMass(redshift=0)
npts = int(1e2)
halo_mass = np.zeros(npts) + 1e10
mc_baryonic_mass1 = model.mc_baryonic_mass(
prim_haloprop=halo_mass, seed=43)
mc_baryonic_mass2 = model.mc_baryonic_mass(
prim_haloprop=halo_mass, seed=44)
assert not np.allclose(mc_baryonic_mass1, mc_baryonic_mass2)
def test_mc_galprop_consistency1():
model = BaryonicMass(redshift=0)
npts = int(1e3)
halo_mass = | np.zeros(npts) | numpy.zeros |
# from __future__ import division
#-------------------------------------
#
# Started at 06/08/2018 (YuE)
#
# This script based on the previous script
# threeApproachesComparison_v6.py
#
## Upgraded version of python (python3.4): script was rewritten to take into
# account some differences in the descriptions and using of some functions
# (version cma_v3 and more earlier scripts are written under python2).
#
# 07/24/2018: IT IS NOT FINISHED:
#
# Which are still unsatisfactory:
# 1) the absolute values of frictional forces for all methods of calculation,
# 2) their dependence on the ion velocity.
#
# But nevertheless, the dependences of the transmitted energy on the impact
# parameter are close to the inverse quadratic (as it should be!) at all velocities.
#
# 07/27/2018: IT IS NOT FINISHED:
#
# Which are still unsatisfactory:
# 1) the absolute values of frictional forces for all methods of calculation,
# 2) their dependence on the ion velocity.
# The investigation of that is in progress.
#
# Some features were improved, some figures were corrected.
#
#-------------------------------------
#========================================================
#
# This code compairs two approaches: "classical" (from [1]) and
# "magnus" (from [2]).
#
# For "classical" approach the magnetized interaction between ion
# and electron is considered for ion velocities V_i > rmsTrnsvVe.
#
# References:
#
# [1] <NAME>, <NAME>, <NAME>, <NAME>.
# "Physics guide of BETACOOL code. Version 1.1". C-A/AP/#262, November
# 2006, Brookhaven National Laboratory, Upton, NY 11973.
# [2] <NAME>, <NAME>. "New Algorithm for Dynamical Friction
# of Ions in a Magnetized Electron Beam". AIP Conf. Proc. 1812, 05006 (2017).
#
#========================================================
#########################################################
#
# Main issues of the calculations:
#
# 1) Friction force (FF) is calculated in the (P)article (R)est (F)rame,
# i.e. in the frame moving together with both (cooled and cooling)
# beams at a velocity V0;
# 2) Friction force is calculated for each value of ion velocity
# in the interval from .1*rmsTrnsvVe till 10*rmsTrnsvVe;
# 3) Initially assumped that all electrons have a logitudinal
# velocity rmsLongVe and transversal velocity rmsTrnsvVe;
# 4) For each ion velocity the minimal and maximal values of the
# impact parameter are defined. Radius of the shielding of the
# electric field of the ion equals to the value of the maximal
# impact parameter;
# 5) For each impact parameter in the interval from minimal till
# maximal values the transfered momenta deltap_x,y,z are
# calculated;
# 6) Founded transfered momenta allow to calculate the transfered
# energy delta_E =deltap^2/(2*m_e) and to integrate it over
# impact parameter; then (expressions (3.4), (3.5) from [1]):
# FF =-2*pi*n_e*integral_rhoMin^rhoMax delta_E*rho*drho;
# 7) For taking into account the velocity distribution of the
# electrons it is necessary to repeat these calculations for
# each value of the electron's velocity and then integrate result
# over distribution of the velocities.
#
# 10/26/2018:
#
# 8) Item 6 is wrong and correct expression for transfered
# energy delta_E will be used;
# 9) Method (my own) Least Squares Method - LSM is used to fit the
# dependence of transferred momenta on impact parameter;
#
#
# 11/08/2018:
#
# 10) Two functions ('fitting' and 'errFitAB' are defined to realize
# my LSM to find the parameters of the fitting end error of this
# fitting;
#
# 11) Analys of different dependeces between values; graphical
# presentation of these dependences;
#
#########################################################
import os, sys
import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import LogNorm
from matplotlib import ticker
from matplotlib import markers
import matplotlib as mpl
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D
import scipy.integrate as integrate
from scipy.integrate import quad, nquad, dblquad
from scipy.constants import pi
from scipy import optimize
from statistics import mean
from array import array
#
# All physical constants have its dimension in units in the system CI.
# This code uses units in the system CGS!
#
from scipy.constants import speed_of_light as clight
from scipy.constants import epsilon_0 as eps0
from scipy.constants import mu_0 as mu0
from scipy.constants import elementary_charge as qe
from scipy.constants import electron_mass as me
from scipy.constants import proton_mass as mp
from scipy.constants import Boltzmann as kB
pi=3.14159265358
#
# Physical constants:
#
m_e=9.10938356e-28 # electron mass, g
m_elec=m_e # to keep variable from previous script
m_p=1.672621898e-24 # electron mass, g
M_ion = m_p # to keep variable from previous script
q_e=4.803204673e-10 # electron charge, CGSE unit: sqrt(g*cm^3/sec^2)
q_elec=q_e # to keep variable from previous script
Z_ion = q_e # to keep variable from previous script
cLight=2.99792458e10 # speed of light, cm/sec
eVtoErg=1.6021766208e-12 # 1 eV = 1.6...e-12 erg
CtoPart=2.99792458e9 # 1 C = 1 A*sec = 2.9...e9 particles
m_e_eV = m_e*cLight**2/eVtoErg
#
# Electron beam parameters:
#
Ekin=3.0e4 # kinetic energy, eV
curBeam=0.5 # current density, A/cm^2
dBeam=3.0 # beam diameter, cm
angSpread=3.0 # angular spread, mrad
trnsvT=0.5 # transversal temperature, eV
longT=2.0e-4 # longitudinal temperature, eV (was 2.0e-4)
nField=1 # number ov values of the magnetic field
fieldB=np.zeros(nField) # magnetic field
fieldB[0]=3.e3 # Gs
omega_p=1.0e9 # plasma frequency, 1/sec
n_e=omega_p**2*m_e/(4.*pi*q_e**2) # plasma density, 3.1421e+08 cm-3
n_e1=8.e7 # plasma density, cm-3
omega_p1=np.sqrt(4.*pi*n_e1*q_e**2/m_e) # plasma frequency, 5.0459e+08 1/s
#
# Cooling system parameter:
#
coolLength=150.0 # typical length of the coolong section, cm
#
# HESR:
#
Ekin=90.8e4 # HESR kinetic energy, eV
curBeam=0.5 # HESR current beam, A
dBeam=2.0 # HESR beam diameter, cm
angSpread=0.0 # HESR angular spread, mrad
trnsvT=0.2 # HESR transversal temperature, eV
longT=1.0e-2 # HESR longitudinal temperature, eV (was 2.0e-4)
fieldB[0]=1.e3 # HESR, Gs
coolLength=270.0 # HESR typical length of the coolong section, cm
#
# EIC:
#
angSpread=0.0 # EIC angular spread, mrad
fieldB[0]=5.e4 # EIC, Gs
coolLength=300.0 # EIC typical length of the coolong section, cm
#
# Calculated parameters of the electron beam:
#
V0 = cLight*np.sqrt(Ekin/m_e_eV*(Ekin/m_e_eV+2.))/(Ekin/m_e_eV+1.)
print ('V0 =%e' % V0)
tetaV0=0. # angle between V0 and magnetic field, rad
B_mag=fieldB[0]*np.cos(tetaV0) # magnetic field acting on an electron, Gs
rmsTrnsvVe=np.sqrt(2.*trnsvT*eVtoErg/m_e) # RMS transversal velocity, cm/s
rmsLongVe=np.sqrt(2.*longT*eVtoErg/m_e) # RMS longitudinal velocity, cm/s
# HESR:
dens=curBeam*(CtoPart/q_e)/(pi*(.5*dBeam)**2*V0) # density, 1/cm^3
omega=np.sqrt(4.*pi*dens*q_e**2/m_e) # plasma frequency, 1/s
n_e=dens
omega_p=omega
print ('HESR: dens = %e,omega_p = %e' % (dens,omega_p))
# EIC:
rmsLongVe = 1.0e+7 # cm/s
longT = .5*m_e*rmsLongVe**2/eVtoErg
rmsTrnsvVe = 4.2e+7 # cm/s
trnsvT = .5*m_e*rmsTrnsvVe**2/eVtoErg
print ('EIC: rmsLongVe = %e, longT = %e, rmsTrnsvVe = %e, trnsvT = %e' % \
(rmsLongVe,longT,rmsTrnsvVe,trnsvT))
dens=2.e9 # density, 1/cm^3
omega=np.sqrt(4.*pi*dens*q_e**2/m_e) # plasma frequency, 1/s
n_e=dens
omega_p=omega
print ('EIC: dens = %e,omega_p = %e' % (dens,omega_p))
cyclFreq=q_e*B_mag/(m_e*cLight) # cyclotron frequency, 1/s
rmsRoLarm=rmsTrnsvVe*cyclFreq**(-1) # RMS Larmor radius, cm
dens=omega_p**2*m_e/(4.*pi*q_e**2) # density, 1/cm^3
likeDebyeR=(3./dens)**(1./3.) # "Debye" sphere with 3 electrons, cm
eTempTran=trnsvT # to keep variable from previous script
eTempLong=longT # to keep variable from previous script
coolPassTime=coolLength/V0 # time pass through cooling section, cm
thetaVi=0. # polar angle ion and cooled electron beams, rad
phiVi=0. # azimuth angle ion and cooled electron beams, rad
powV0=round(np.log10(V0))
mantV0=V0/(10**powV0)
pow_n_e=round(np.log10(n_e))
mant_n_e=n_e/(10**pow_n_e)
#
# Formfactor ffForm for friction force:
#
# ffForm = 2*pi*dens*q_e**4/(m_e*V0**2)=
# = 0.5*omega_p**2*q_e**2/V0**2
#
# Dimension of ffForm is force: g*cm/sec**2=erg/cm
#
# 1 MeV/m = 1.e6*eVtoErg/100. g*cm/sec**2 = 1.e4*eVtoErg erg/cm
MeV_mToErg_cm=1.e4*eVtoErg
# ffForm=-.5*omega_p**2*q_e**2/V0**2/MeV_mToErg_cm # MeV/m
eV_mToErg_m=100.*eVtoErg
# ffForm=-.5*omega_p**2*q_e**2/V0**2/eV_mToErg_m # =-6.8226e-12 eV/m
eV_mInErg_cm=100.*eVtoErg
ffForm=-.5*omega_p**2*q_e**2/V0**2/eVtoErg # =-6.8226e-10 eV/cm
ffForm=100.*ffForm # =-6.8226e-08 eV/m
ergToEV = 1./1.60218e-12
#
# Relative velocities of electrons:
#
relVeTrnsv=rmsTrnsvVe/V0
relVeLong=rmsLongVe/V0
print ('V0=%e cm/s, rmsTrnsvVe=%e cm/s (rel = %e), rmsLongVe=%e cm/s (rel = %e)' % \
(V0,rmsTrnsvVe,relVeTrnsv,rmsLongVe,relVeLong))
# Indices:
(Ix, Ipx, Iy, Ipy, Iz, Ipz) = range(6)
stepsNumberOnGyro = 25 # number of the steps on each Larmour period
'''
#
# Opening the input file:
#
inputFile='areaOfImpactParameter_tAC-v6_fig110.data'
print ('Open input file "%s"...' % inputFile)
inpfileFlag=0
try:
inpfile = open(inputFile,'r')
inpfileFlag=1
except:
print ('Problem to open input file "%s"' % inputFile)
if inpfileFlag == 1:
print ('No problem to open input file "%s"' % inputFile)
lines=0 # Number of current line from input file
dataNumber=0 # Number of current value of any types of Data
xAboundary=np.zeros(100)
xBboundary=np.zeros(100)
while True:
lineData=inpfile.readline()
# print ('line=%d: %s' % (lines,lineData))
if not lineData:
break
lines += 1
if lines > 4:
words=lineData.split()
nWords=len(words)
# print ('Data from %d: words=%s, number of entries = %d' % (lines,words,nWords))
xAboundary[dataNumber]=float(words[0])
xBboundary[dataNumber]=float(words[1])
dataNumber += 1
inpfile.close()
print ('Close input file "%s"' % inputFile)
'''
#====================================================================
#
#------------------ Begin of defined functions -----------------------
#
# Larmor frequency electron:
#
def omega_Larmor(mass,B_mag):
return (q_elec)*B_mag/(mass*clight*1.e+2) # rad/sec
#
# Derived quantities:
#
omega_L = omega_Larmor(m_elec,B_mag) # rad/sec
T_larm = 2*pi/omega_L # sec
timeStep = T_larm/stepsNumberOnGyro # time step, sec
print ('omega_Larmor= %e rad/sec, T_larm = %e sec, timeStep = %e sec' % \
(omega_L,T_larm,timeStep))
nLarmorAvrgng=10 # number of averaged Larmor rotations
#
# Data to integrate transferred momemta over the track:
#
timeStep_c=nLarmorAvrgng*stepsNumberOnGyro*timeStep # sec
print ('timeStep_c = %e s' % timeStep_c)
eVrmsTran = np.sqrt(2.*eTempTran*eVtoErg/m_elec) # cm/sec
eVrmsLong = np.sqrt(2.*eTempLong*eVtoErg/m_elec) # cm/sec
kinEnergy = m_elec*(eVrmsTran**2+eVrmsLong**2)/2. # kinetic energy; erg
print ('eVrmsTran = %e cm/sec, eVrmsLong = %e cm/sec, kinEnergy = %e eV' % \
(eVrmsTran,eVrmsLong,ergToEV*kinEnergy))
ro_larmRMS = eVrmsTran/omega_L # cm
print ('ro_larmRMS =%e mkm' % (1.e4*ro_larmRMS))
#
# Electrons are magnetized for impact parameter >> rhoCrit:
#
rhoCrit=math.pow(q_elec**2/(m_elec*omega_L**2),1./3) # cm
print ('rhoCrit (mkm) = ' , 1.e+4*rhoCrit)
#
# Convertion from 6-vector of relectron's "coordinates" to 6-vector
# of guiding-center coordinates:
# z_e=(x_e,px_e,y_e,py_e,z_e,pz_e) --> zgc_e=(phi,p_phi,y_gc,p_gc,z_e,pz_e);
#
def toGuidingCenter(z_e):
mOmega=m_elec*omega_L # g/sec
zgc_e=z_e.copy() # 6-vector
zgc_e[Ix] = np.arctan2(z_e[Ipx]+mOmega*z_e[Iy],z_e[Ipy]) # radians
zgc_e[Ipx]= (((z_e[Ipx]+mOmega*z_e[Iy])**2+z_e[Ipy]**2)/(2.*mOmega)) # g*cm**2/sec
zgc_e[Iy] =-z_e[Ipx]/mOmega # cm
zgc_e[Ipy]= z_e[Ipy]+mOmega*z_e[Ix] # g/sec
return zgc_e
#
# Convertion from 6-vector of guiding-center coordinates to 6-vector
# of electron's "coordinates":
# zgc_e=(phi,p_phi,y_gc,p_gc,z_e,pz_e) --> z_e=(x_e,px_e,y_e,py_e,z_e,pz_e);
#
def fromGuidingCenter(zgc_e):
mOmega=m_elec*omega_L # g/sec
rho_larm=np.sqrt(2.*zgc_e[Ipx]/mOmega) # cm
z_e = zgc_e.copy() # 6-vector
z_e[Ix] = zgc_e[Ipy]/mOmega-rho_larm*np.cos(zgc_e[Ix]) # cm
z_e[Ipx]=-mOmega*zgc_e[Iy] # g*cm/sec
z_e[Iy] = zgc_e[Iy]+rho_larm*np.sin(zgc_e[Ix]) # cm
z_e[Ipy]= mOmega*rho_larm*np.cos(zgc_e[Ix]) # g*cm/sec
return z_e
#
# Matrix to dragg electron through the solenoid with field 'B_mag'
# during time interval 'deltaT':
#
def solenoid_eMatrix(B_mag,deltaT):
slndMtrx=np.identity(6)
omega_L=omega_Larmor(m_elec,B_mag) # rad/sec
mOmega= m_elec*omega_L # g/sec
phi=omega_L*deltaT # phase, rad
cosPhi=math.cos(phi) # dimensionless
sinPhi=math.sin(phi) # dimensionless
cosPhi_1=2.*math.sin(phi/2.)**2 # dimensionless
slndMtrx[Iy, Iy ]= cosPhi # dimensionless
slndMtrx[Ipy,Ipy]= cosPhi # dimensionless
slndMtrx[Iy, Ipy]= sinPhi/mOmega # sec/g
slndMtrx[Ipy,Iy ]=-mOmega*sinPhi # g/sec
slndMtrx[Iz, Ipz]= deltaT/m_elec # sec/g
slndMtrx[Ix, Ipx]= sinPhi/mOmega # sec/g
slndMtrx[Ix, Iy ]= sinPhi # dimensionless
slndMtrx[Ix, Ipy]= cosPhi_1/mOmega # sec/g
slndMtrx[Iy, Ipx]=-cosPhi_1/mOmega # sec/g
slndMtrx[Ipy,Ipx]=-sinPhi # dimensionless
return slndMtrx
#
# Matrix to dragg particle through the drift during time interval 'deltaT':
#
def drift_Matrix(M_prtcl,deltaT):
driftMtrx = np.identity(6)
for i in (Ix,Iy,Iz):
driftMtrx[i,i+1]=deltaT/M_prtcl # sec/g
return driftMtrx
#
# Matrix to dragg electron in the "guiding center" system during time interval 'deltaT':
#
def guidingCenter_Matrix(deltaT):
gcMtrx = np.identity(6)
gcMtrx[Iz,Ipz]=deltaT/m_elec # sec/g
return gcMtrx
#
# Description of the collision during time interval 'deltaT'
# in the system coordinates of "guiding center" of electron
# input - 6-vectors for electron and ion before collision and time step deltaT;
# output - transfered momenta to ion and electron:
#
def guidingCenterCollision(vectrElec_gc,vectrIon,deltaT):
dpIon=np.zeros(3)
dpElec=np.zeros(3)
mOmegaLarm=m_elec*omega_L # g/sec
dpFactor_gc=q_elec**2 # g*cm^3/sec^2
rhoLarm_gc=np.sqrt(2.*vectrElec_gc[1]/mOmegaLarm) # cm
sinOmega_gc=math.sin(vectrElec_gc[0])
cosOmega_gc=math.cos(vectrElec_gc[0])
x_gc=vectrElec_gc[3]/mOmegaLarm # cm
numer=(vectrIon[0]-x_gc)*cosOmega_gc- \
(vectrIon[2]-vectrElec_gc[2])*sinOmega_gc # cm
denom=((vectrIon[0]-x_gc)**2+(vectrIon[2]-vectrElec_gc[2])**2+ \
(vectrIon[4]-vectrElec_gc[4])**2+rhoLarm_gc**2)**(3/2) # cm^3
action=vectrElec_gc[1]+dpFactor_gc*numer*rhoLarm_gc/(omega_L*denom) # g*cm^2/sec
b_gc=np.sqrt((vectrIon[0]-x_gc)**2+ \
(vectrIon[2]-vectrElec_gc[2])**2+ \
(vectrIon[4]-vectrElec_gc[4])**2+2.*action/mOmegaLarm) # cm
# Dimensions of dpIon, deElec are g*cm/sec:
dpIon[0]=-dpFactor_gc*deltaT*(vectrIon[0]-x_gc)/b_gc**3
dpIon[1]=-dpFactor_gc*deltaT*(vectrIon[2]-vectrElec_gc[2])/b_gc**3
dpIon[2]=-dpFactor_gc*deltaT*(vectrIon[4]-vectrElec_gc[4])/b_gc**3
dpElec[0]=-dpIon[0]
dpElec[1]=-dpIon[1]
dpElec[2]=-dpIon[2]
# print ('dpIon[0]=%e, dpIon[1]=%e, dpIon[2]=%e' % \
# (dpIon[0],dpIon[1],dpIon[2]))
return dpIon,dpElec,action,b_gc
#
# "Magnus expansion" description of the collision during time interval 'deltaT'
# in the system coordinates of "guiding center" of electron
# input - 6-vectors for electron and ion before collision and time step deltaT;
# output - transfered momenta to ion and electron and electron y_gc coordinate
# as well calculated parameters C1,C2,C3,b,D1,D2,q for testing:
#
def MagnusExpansionCollision(vectrElec_gc,vectrIon,deltaT):
# print ('Ion: x=%e, y=%e, z=%e' % (vectrIon[0],vectrIon[2],vectrIon[4]))
# print ('Electron: x=%e, y=%e, z=%e' %
# (vectrElec_gc[0],vectrElec_gc[4],vectrElec_gc[4]))
dpIon=np.zeros(3)
dpElec=np.zeros(3)
mOmegaLarm=m_elec*omega_L # g/sec
dpFactor_gc=q_elec**2 # g*cm^3/sec^2
rhoLarm_gc=np.sqrt(2.*vectrElec_gc[1]/mOmegaLarm) # cm
sinOmega_gc=math.sin(vectrElec_gc[0])
cosOmega_gc=math.cos(vectrElec_gc[0])
x_gc=vectrElec_gc[3]/mOmegaLarm # cm
numer=(vectrIon[0]-x_gc)*cosOmega_gc- \
(vectrIon[2]-vectrElec_gc[2])*sinOmega_gc # cm
denom=((vectrIon[0]-x_gc)**2+(vectrIon[2]-vectrElec_gc[2])**2+ \
(vectrIon[4]-vectrElec_gc[4])**2+rhoLarm_gc**2)**(3./2.) # cm^3
action=vectrElec_gc[1]+dpFactor_gc*numer*rhoLarm_gc/(omega_L*denom) # g*cm^2/sec
# C1=np.sqrt((vectrIon[0]-x_gc)**2+ \
# (vectrIon[2]-vectrElec_gc[2])**2+ \
# (vectrIon[4]-vectrElec_gc[4])**2+2.*action/mOmegaLarm) # cm^2
C1=(vectrIon[0]-x_gc)**2+(vectrIon[2]-vectrElec_gc[2])**2+ \
(vectrIon[4]-vectrElec_gc[4])**2+2.*action/mOmegaLarm # cm^2
C2=2.*((vectrIon[0]-x_gc)*vectrIon[1]/M_ion+ \
(vectrIon[2]-vectrElec_gc[2])*vectrIon[3]/M_ion+ \
(vectrIon[4]-vectrElec_gc[4])* \
(vectrIon[5]/M_ion-vectrElec_gc[5]/m_elec)) # cm^2/sec
C3=(vectrIon[1]/M_ion)**2+(vectrIon[3]/M_ion)**2+ \
(vectrIon[5]/M_ion-vectrElec_gc[5]/m_elec)**2 # cm^2/sec^2
b=np.sqrt(C1+C2*deltaT+C3*deltaT**2) # cm
D1=(2.*C3*deltaT+C2)/b-C2/np.sqrt(C1) # cm/sec
D2=(C2*deltaT+2.*C1)/b-2.*np.sqrt(C1) # cm
q=4.*C1*C3-C2**2 # cm^4/sec^2
# Dimensions of dpIon, deElec are g*cm/sec:
dpIon[0]=-2.*dpFactor_gc/q*((vectrIon[0]-x_gc)*D1-vectrIon[1]/M_ion*D2)
dpIon[1]=-2.*dpFactor_gc/q*((vectrIon[2]-vectrElec_gc[2])*D1- \
vectrIon[3]/M_ion*D2)
dpIon[2]=-2.*dpFactor_gc/q*((vectrIon[4]-vectrElec_gc[4])*D1- \
(vectrIon[5]/M_ion-vectrElec_gc[5]/m_elec)*D2)
dpElec[0]=-dpIon[0]
dpElec[1]=-dpIon[1]
dpElec[2]=-dpIon[2]
dy_gc=dpIon[0]/mOmegaLarm # cm
# print ('dpIon[0]=%e, dpIon[1]=%e, dpIon[2]=%e' % \
# (dpIon[0],dpIon[1],dpIon[2]))
return dpIon,dpElec,action,dy_gc,C1,C2,C3,b,D1,D2,q
#
# Minimized functional (my own Least Squares Method - LSM;
# Python has own routine for LSM - see site
# http://scipy-cookbook.readthedocs.io/items/FittingData.html):
#
# Funcional = {log10(funcY) - [fitB*log10(argX) + fitA]}^2
#
def fitting(nPar1,nPar2,argX,funcY):
log10argX = np.zeros((nPar1,nPar2))
log10funcY = np.zeros((nPar1,nPar2))
for i in range(nVion):
for n in range(nPar1):
log10argX[n,i] = np.log10(argX[n,i])
log10funcY[n,i] = np.log10(funcY[n,i])
sumArgX = np.zeros(nPar2)
sumArgX2 = np.zeros(nPar2)
sumFuncY = np.zeros(nPar2)
sumArgXfuncY= np.zeros(nPar2)
fitA = np.zeros(nPar2)
fitB = np.zeros(nPar2)
for i in range(nPar2):
for n in range(nPar1):
sumArgX[i] += log10argX[n,i]
sumArgX2[i] += log10argX[n,i]**2
sumFuncY[i] += log10funcY[n,i]
sumArgXfuncY[i] += log10argX[n,i]*log10funcY[n,i]
delta = sumArgX[i]**2-nPar1*sumArgX2[i]
fitA[i] = (sumArgX[i]*sumArgXfuncY[i]-sumArgX2[i]*sumFuncY[i])/delta
fitB[i] = (sumArgX[i]*sumFuncY[i]-nPar1*sumArgXfuncY[i])/delta
# print ('fitA(%d) = %e, fitB(%d) = %e' % (i,fitA[i],i,fitB[i]))
argXfit = np.zeros((nPar1,nPar2))
funcYfit = np.zeros((nPar1,nPar2))
funcHi2 = np.zeros(nPar2)
for i in range(nPar2):
factorA = math.pow(10.,fitA[i])
for n in range(nPar1):
argXfit[n,i] = math.pow(10.,log10argX[n,i])
funcYfit[n,i] = factorA*math.pow(argXfit[n,i],fitB[i])
funcHi2[i] += (np.log10(abs(funcY[n,i])) - np.log10(abs(funcYfit[n,i])))**2
return fitA,fitB,funcHi2,argXfit,funcYfit
#
# +-Errors for fitied parameters fitA and fitB:
#
def errFitAB(nPar1,nPar2,argX,funcY,fitA,fitB,funcHi2,errVar,errType):
log10argX = np.zeros((nPar1,nPar2))
log10funcY = np.zeros((nPar1,nPar2))
sumArgX = np.zeros(nPar2)
sumArgX2 = np.zeros(nPar2)
posErrFit = np.zeros(nPar2)
negErrFit = np.zeros(nPar2)
# return posErrFit,negErrFit
stepA = 5.e-4*mean(funcHi2)
stepB = 1.e-4*mean(funcHi2)
# print ('errFitAB: mean(funcHi2) = %e, stepA = %e, stepB = %e' % (mean(funcHi2),stepA,stepB))
for i in range(nPar2):
for n in range(nPar1):
log10argX[n,i] = np.log10(argX[n,i])
log10funcY[n,i] = np.log10(funcY[n,i])
sumArgX[i] += log10argX[n,i]
sumArgX2[i] += log10argX[n,i]**2
for i in range(nPar2):
k = 0
deltaFuncHi2 = 0.
while (deltaFuncHi2 < 1.):
k += 1
if k > 2000:
print ('Break in errFitAB (Fit funcY: case %d); positive error) for %d' % (errVar,i))
break
# print ('i=%d: fitParamtr = %e, funcHi2 = %e' % (i,fitParamtr[i], funcHi2[i]))
curFitA = fitA[i]
if (int(errVar) == 1):
curFitA = fitA[i] + k*stepA
curFuncHi2 = 0.
factorA = math.pow(10.,curFitA)
curFitB = fitB[i]
if (int(errVar) == 2):
curFitB = fitB[i] + k*stepB
curFuncHi2 = 0.
for n in range(nPar1):
curArgX = math.pow(10.,log10argX[n,i])
curFuncYfit = factorA*math.pow(curArgX,curFitB)
curFuncHi2 += (np.log10(abs(curFuncYfit)) - log10funcY[n,i])**2
deltaFuncHi2 = curFuncHi2 - funcHi2[i]
if (int(errVar) == 1):
posErrFit[i] = abs(curFitA - fitA[i])
else:
posErrFit[i] = abs(curFitB - fitB[i])
func1sigma2 = funcHi2[i]/(nPar2-3)
if (int(errVar) == 1):
fitSigma = np.sqrt(sumArgX2[i]/(nPar2*sumArgX2[i]-sumArgX[i]**2)*func1sigma2)
else:
fitSigma = np.sqrt(nPar2/(nPar2*sumArgX2[i]-sumArgX[i]**2)*func1sigma2)
if (int(errType) == 2):
posErrFit[i] = fitSigma
# if (int(errVar) == 1):
# print ('i=%d: fitA = %e + %e (%e), funcHi2 = %e (for %d steps curFuncHi2 = %e)' % \
# (i,fitA[i],posErrFit[i],fitSigma,funcHi2[i],k,curFuncHi2))
# else:
# print ('i=%d: fitB = %e + %e (%e), funcHi2 = %e (for %d steps curFuncHi2 = %e)' % \
# (i,fitB[i],posErrFit[i],fitSigma,funcHi2[i],k,curFuncHi2))
for i in range(nPar2):
k = 0
deltaFuncHi2 = 0.
while (deltaFuncHi2 < 1.):
k += 1
if k > 2000:
print ('Break in errFitAB (Fit funcY: case %d); negative error) for %d' % (errVar,i))
break
curFitA = fitA[i]
if (int(errVar) == 1):
curFitA = fitA[i] - k*stepA
factorA = math.pow(10.,curFitA)
curFitB = fitB[i]
if (int(errVar) == 2):
curFitB = fitB[i] - k*stepB
curFuncHi2 = 0.
for n in range(nPar1):
curArgX = math.pow(10.,log10argX[n,i])
curFuncYfit = factorA*math.pow(curArgX,curFitB)
curFuncHi2 += (np.log10(abs(curFuncYfit)) - log10funcY[n,i])**2
deltaFuncHi2 = curFuncHi2 - funcHi2[i]
if (int(errVar) == 1):
negErrFit[i] = abs(curFitA - fitA[i])
else:
negErrFit[i] = abs(curFitB - fitB[i])
if (int(errType) == 2):
negErrFit[i] = posErrFit[i]
# if (errVar == 1):
# print ('i=%d: fitA = %e - %e, funcHi2 = %e (for %d steps curFuncHi2 = %e)' % \
# (i,fitA[i],posErrFit[i],funcHi2[i],k,curFuncHi2))
# else:
# print ('i=%d: fitB = %e - %e, funcHi2 = %e (for %d steps curFuncHi2 = %e)' % \
# (i,fitB[i],negErrFit[i],funcHi2[i],k,curFuncHi2))
return posErrFit,negErrFit
def fittedGKintegration(xMin,xMax,fitA,fitB):
#
# "Gauss-Kronrod" method of integration (GK)
#
#
# Points (psi_i) and weigths (w_i) to integrate for interval from -1 to 1;
# These data are from <NAME>. "Handbook of Mathematical Science".
# 5th Edition, CRC Press, Inc, 1978.
#
# To integrate for interval from 0 to 1 it is necessary to change points
# psi_i with points ksi_i=(1+psi_i)/2;
#
# For method with order N for function F(x):
# int_(-1)^1 = sum_1^N [w_i* F(psi_i)];
#
# In case of integration over interval from a to b:
# int_(a)^b = (b-a)/2 * sum_1^N [w_i* F(x_i)], where
# x_i = (b-a)*psi_i/2+(a+b)/2.
#
#----------------------------------------------------
#
# Data for GK:
#
#----------------------------------------------------
nPoints_GK = 16
psi_16=np.array([-0.9894009, -0.9445750, -0.8656312, -0.7554044, -0.6178762, \
-0.4580168, -0.2816036, -0.0950125, 0.0950125, 0.2816036, \
0.4580168, 0.6178762, 0.7554044, 0.8656312, 0.9445750, \
0.9894009])
w_16 =np.array([ 0.0271525, 0.0622535, 0.0951585, 0.1246290, 0.1495960, \
0.1691565, 0.1826034, 0.1894506, 0.1894506, 0.1826034, \
0.1691565, 0.1495960, 0.1246290, 0.0951585, 0.0622535, \
0.0271525])
y = np.zeros(nPoints_GK)
yIntegrated = 0.
for n in range(nPoints_GK):
xCrrnt = psi_16[n]*(xMax-xMin)/2 + (xMax+xMin)/2.
factorA = math.pow(10.,fitA)
y[n] = factorA*math.pow(xCrrnt,fitB)
yIntegrated += (xMax-xMin)*w_16[n]*y[n]*xCrrnt
return y,yIntegrated
#------------------ End of defined functions -----------------------
#
#====================================================================
sphereNe=3.
R_e=math.pow(sphereNe/n_e,1./3) # cm
print ('R_e (cm)=%e' % R_e)
ro_Larm = eVrmsTran/omega_L # cm
print ('ro_Larm (cm)=%e' % ro_Larm)
impctPrmtrMin=2.*ro_Larm
# rhoDependenceFlag = 1 # skip calculation of rho dependence if = 0!
#============ Important flags ===========================
#
# Taking into account the transfer of momenta for both particles
# (for "classical" only):
dpTransferFlag = 1 # no taking into account if = 0!
#
saveFilesFlag = 0 # no saving if = 0!
#
plotFigureFlag = 1 # plot if = 1!
#
#========================================================
nVion=50
Vion=np.zeros(nVion)
VionLong=np.zeros(nVion)
VionTrnsv=np.zeros(nVion)
VionRel=np.zeros(nVion)
vIonMin=4.e-3*eVrmsTran
vIonMax=10.*eVrmsTran
vIonMinRel=vIonMin/V0
vIonMaxRel=vIonMax/V0
print ('VionMin=%e (vIonMinRel=%e), vIonMax=%e (vIonMaxRel=%e)' % \
(vIonMin,vIonMinRel,vIonMax,vIonMaxRel))
vIonLogStep=math.log10(vIonMax/vIonMin)/(nVion-1)
R_debye=np.zeros(nVion)
R_pass=np.zeros(nVion)
R_pass_1=np.zeros(nVion) # for longT=0. --> eVrmsLong=0.
impctPrmtrMax=np.zeros(nVion)
impctPrmtrMax_1=np.zeros(nVion) # for longT=0. --> eVrmsLong=0.
for i in range(nVion):
crrntLogVionRel=math.log10(vIonMinRel)+i*vIonLogStep
VionRel[i]=math.pow(10.,crrntLogVionRel)
Vion[i]=VionRel[i]*V0
VionLong[i]=Vion[i]*np.cos(thetaVi)
VionTrnsv[i]=Vion[i]*np.sin(thetaVi)
R_debye[i]=np.sqrt(Vion[i]**2+eVrmsTran**2+eVrmsLong**2)/omega_p
R_pass[i]=np.sqrt(Vion[i]**2+eVrmsLong**2)*coolPassTime
R_pass_1[i]=np.sqrt(Vion[i]**2+0.*eVrmsLong**2)*coolPassTime
help=max(R_debye[i],R_e)
impctPrmtrMax[i]=min(help,R_pass[i])
impctPrmtrMax_1[i]=min(help,R_pass_1[i])
#-----------------------------------------------------------------
# Checking of corection of the maximal impact parameter on depence
# of preset number of minimal Larmor turns
#
larmorTurnsMin=[10,20,30,40]
impctPrmtrMaxCrrctd=np.zeros((nVion,4))
impctPrmtrMaxCrrctdRel=np.zeros((nVion,4))
for n in range (4):
for i in range(nVion):
impctPrmtrMaxCrrctd[i,n]=impctPrmtrMax[i]* \
np.sqrt(1.- (pi*larmorTurnsMin[n]*eVrmsLong/omega_L/impctPrmtrMax[i])**2)
impctPrmtrMaxCrrctdRel[i,n]=impctPrmtrMaxCrrctd[i,n]/impctPrmtrMax[i]
#
# First plotting:
#
if (plotFigureFlag == 0):
fig10 = plt.figure(10)
plt.semilogx(impctPrmtrMax,impctPrmtrMaxCrrctdRel[:,0],'-r', \
impctPrmtrMax,impctPrmtrMaxCrrctdRel[:,1],'-b', \
impctPrmtrMax,impctPrmtrMaxCrrctdRel[:,2],'-g', \
impctPrmtrMax,impctPrmtrMaxCrrctdRel[:,3],'-m',linewidth=2)
plt.grid(True)
hold=True
plt.xlabel('Maximal Impact parameter $R_{max}$, cm',color='m',fontsize=16)
plt.ylabel('$R_{max}^{Crrctd}/R_{Max}$',color='m',fontsize=16)
# plt.xlim([.9*min(impctPrmtrMax),1.1*max(impctPrmtrMax)])
plt.xlim([1.e-2,1.1*max(impctPrmtrMax)])
plt.ylim([.986,1.001])
titleHeader='$R_{max}^{Crrctd}=R_{Max} \cdot [1-(\pi\cdot N_{Larm} \cdot'
titleHeader += '\Delta_{e||}/(\omega_{Larm} \cdot R_{max})]^{1/2}$'
plt.title(titleHeader,color='m',fontsize=16)
plt.legend([('$N_{Larm}=$%2d' % larmorTurnsMin[0]), \
('$N_{Larm}=$%2d' % larmorTurnsMin[1]), \
('$N_{Larm}=$%2d' % larmorTurnsMin[2]), \
('$N_{Larm}=$%2d' % larmorTurnsMin[3])],loc='lower center',fontsize=14)
if (saveFilesFlag == 1):
fig10.savefig('picturesCMA/correctedRmax_fig10cma.png')
print ('File "picturesCMA/correctedRmax_fig10cma.png" is written')
xLimit=[.9*VionRel[0],1.1*VionRel[nVion-1]]
#
# Typs of collisions:
#
if (plotFigureFlag == 0):
fig3151=plt.figure (3151)
plt.loglog(VionRel,impctPrmtrMax,'-r', VionRel,impctPrmtrMax_1,'--r', \
[VionRel[0],VionRel[nVion-1]],[impctPrmtrMin,impctPrmtrMin],'-b',linewidth=2)
plt.grid(True)
hold=True
plt.xlabel('Relative Ion Velocity, $V_i/V_{e0}$',color='m',fontsize=14)
plt.ylabel('Impact Parameter, cm',color='m',fontsize=14)
titleHeader= \
'Types of Collisions: $V_{e0}=%4.2f\cdot10^{%2d}$ cm/s, $B=%6.1f$ Gs'
plt.title(titleHeader % (mantV0,powV0,fieldB[0]),color='m',fontsize=16)
plt.xlim(xLimit)
yLimit=[8.e-4,.6]
plt.ylim(yLimit)
plt.plot([relVeTrnsv,relVeTrnsv],yLimit,'--m',linewidth=1)
plt.text(1.6e-3,5.e-4,'$ \Delta V_{e\perp}/ V_{e0}$',color='m',fontsize=14)
plt.plot([relVeLong,relVeLong],yLimit,'--m',linewidth=1)
plt.text(4.4e-5,.0018,'$ \Delta V_{e||}/ V_{e0}$',color='m',fontsize=14)
plt.text(3.e-4,1.75e-3,'$R_{min}=2\cdot<rho_\perp>$',color='k',fontsize=16)
plt.text(7.e-4,5.e-2,'$R_{max}$',color='k',fontsize=16)
plt.text(2.85e-5,3.3e-3,'$R_{max}$ $for$ $T_{e||}=0$',color='k',fontsize=16)
plt.plot([VionRel[0],VionRel[nVion-1]],[20.*rhoCrit,20.*rhoCrit],color='k')
plt.text(1.e-4,7.e-3,'Magnetized Collisions',color='r',fontsize=20)
plt.text(1.e-4,10.e-4,'Adiabatic or Fast Collisions',color='r',fontsize=20)
plt.text(2.25e-5,.275,'Collisions are Screened',color='r',fontsize=20)
plt.text(1.6e-5,1.e-3,'$ \cong 20\cdot R_{Crit}$',color='k',fontsize=16)
if (saveFilesFlag == 1):
fig3151.savefig('picturesCMA_v7/impctPrmtr_fig3151cma.png')
print ('File "picturesCMA_v7/impctPrmtr_fig3151cma.png" is written')
#
# Picture for HESR:
#
if (plotFigureFlag == 0):
fig3151=plt.figure (3151)
plt.loglog(VionRel,impctPrmtrMax,'-r', VionRel,impctPrmtrMax_1,'--r', \
[VionRel[0],VionRel[nVion-1]],[impctPrmtrMin,impctPrmtrMin],'-b',linewidth=2)
plt.grid(True)
hold=True
plt.xlabel('Relative Ion Velocity, $V_i/V_{e0}$',color='m',fontsize=14)
plt.ylabel('Impact Parameter, cm',color='m',fontsize=14)
titleHeader= \
'HESR Types of Collisions: $V_{e0}=%3.1f\cdot10^{%2d}$cm/s, $B=%3.1f$T'
plt.title(titleHeader % (mantV0,powV0,1.e-4*fieldB[0]),color='m',fontsize=16)
plt.xlim(xLimit)
yLimit=[8.e-4,.6]
plt.ylim(yLimit)
plt.plot([relVeTrnsv,relVeTrnsv],yLimit,'--m',linewidth=1)
plt.text(4.4e-4,8.4e-4,'$ \Delta V_{e\perp}/ V_{e0}$',color='m',fontsize=14)
plt.plot([relVeLong,relVeLong],yLimit,'--m',linewidth=1)
plt.text(1.e-4,8.4e-4,'$ \Delta V_{e||}/ V_{e0}$',color='m',fontsize=14)
plt.text(3.7e-6,3.4e-3,'$R_{min}=2\cdot<rho_\perp>$',color='b',fontsize=16)
plt.text(2.8e-4,.1,'$R_{max}$',color='k',fontsize=16)
plt.text(1.e-4,1.8e-2,'$R_{max}$ $for$ $T_{e||}=0$',color='k',fontsize=16)
plt.plot([VionRel[0],VionRel[nVion-1]],[20.*rhoCrit,20.*rhoCrit],color='k')
plt.text(6.8e-5,7.e-3,'Magnetized Collisions',color='r',fontsize=20)
plt.text(6.8e-5,1.2e-3,'Weak Collisions',color='r',fontsize=20)
plt.text(2.3e-5,1.95e-3,'Adiabatic or Fast Collisions',color='r',fontsize=20)
plt.text(2.e-5,.275,'Screened Collisions',color='r',fontsize=20)
plt.text(3.58e-6,2.05e-3,'$\cong$20$\cdot$$R_{Crit}$',color='k',fontsize=16)
if (saveFilesFlag == 1):
# fig3151.savefig('picturesCMA_v7/impctPrmtr_fig3151cma.png')
# print ('File "picturesCMA_v7/impctPrmtr_fig3151cma.png" is written')
fig3151.savefig('HESRimpctPrmtr_fig3151cma.png')
print ('File "HESRimpctPrmtr_fig3151cma.png" is written')
#
# Picture for EIC:
#
if (plotFigureFlag == 0):
fig3151=plt.figure (3151)
plt.loglog(VionRel,impctPrmtrMax,'-r', VionRel,impctPrmtrMax_1,'--r', \
[VionRel[0],VionRel[nVion-1]],[impctPrmtrMin,impctPrmtrMin],'-b',linewidth=2)
plt.grid(True)
hold=True
plt.xlabel('Relative Ion Velocity, $V_i/V_{e0}$',color='m',fontsize=14)
plt.ylabel('Impact Parameter, cm',color='m',fontsize=14)
titleHeader= \
'EIC Types of Collisions: $V_{e0}=%3.1f\cdot10^{%2d}$cm/s, $B=%3.1f$T'
plt.title(titleHeader % (mantV0,powV0,1.e-4*fieldB[0]),color='m',fontsize=16)
plt.xlim(xLimit)
yLimit=[5.e-5,.3]
plt.ylim(yLimit)
plt.plot([relVeTrnsv,relVeTrnsv],yLimit,'--m',linewidth=1)
plt.text(9.e-4,4.e-5,'$ \Delta V_{e\perp}/ V_{e0}$',color='m',fontsize=14)
plt.plot([relVeLong,relVeLong],yLimit,'--m',linewidth=1)
plt.text(1.7e-4,3.e-5,'$ \Delta V_{e||}/ V_{e0}$',color='m',fontsize=14)
plt.text(6.3e-6,1.1e-4,'$R_{min}=2\cdot<rho_\perp>$',color='b',fontsize=16)
plt.text(1.e-4,2.1e-2,'$R_{max}$',color='k',fontsize=16)
plt.text(2.57e-5,5.e-3,'$R_{max}$ $for$ $T_{e||}=0$',color='k',fontsize=16)
plt.plot([VionRel[0],VionRel[nVion-1]],[20.*rhoCrit,20.*rhoCrit],color='k')
plt.text(2.3e-5,1.e-3,'Magnetized Collisions',color='r',fontsize=20)
# plt.text(6.8e-5,1.2e-3,'Weak Collisions',color='r',fontsize=20)
plt.text(1.1e-5,5.7e-5,'Weak or Adiabatic or Fast Collisions',color='r',fontsize=16)
plt.text(2.e-5,.15,'Screened Collisions',color='r',fontsize=20)
plt.text(2.5e-3,1.7e-4,'$\cong$20$\cdot$$R_{Crit}$',color='k',fontsize=16)
if (saveFilesFlag == 1):
# fig3151.savefig('picturesCMA_v7/impctPrmtr_fig3151cma.png')
# print ('File "picturesCMA_v7/impctPrmtr_fig3151cma.png" is written')
fig3151.savefig('EICimpctPrmtr_fig3151cma.png')
print ('File "EICimpctPrmtr_fig3151cma.png" is written')
# plt.show()
# sys.exit()
#
# Magnetized collisions:
#
if (plotFigureFlag == 0):
fig209=plt.figure (209)
plt.loglog(VionRel,R_debye,'-r',VionRel,R_pass,'-b', \
VionRel,R_pass_1,'--b',linewidth=2)
plt.grid(True)
hold=True
plt.plot([VionRel[0],VionRel[nVion-1]],[R_e,R_e],color='m',linewidth=2)
plt.xlabel('Relative Ion Velocity, $V_i/V_{e0}$',color='m',fontsize=16)
plt.ylabel('$R_{Debye}$, $R_{Pass}$, $R_e$, cm',color='m',fontsize=16)
# titleHeader='Magnetized Collision: $R_{Debye}$, $R_{Pass}$, $R_e$: $V_{e0}=%5.3f\cdot10^{%2d}$cm/s'
# plt.title(titleHeader % (mantV0,powV0),color='m',fontsize=16)
plt.title('Magnetized Collisions: $R_{Debye}$, $R_{Pass}$, $R_e$',color='m',fontsize=16)
plt.xlim(xLimit)
yLimit=[1.e-3,10.]
plt.ylim(yLimit)
plt.plot([relVeTrnsv,relVeTrnsv],yLimit,'--m',linewidth=1)
plt.text(1.6e-3,5.5e-4,'$ \Delta V_{e\perp}/ V_{e0}$',color='m',fontsize=14)
plt.plot([relVeLong,relVeLong],yLimit,'--m',linewidth=1)
plt.text(4.4e-5,0.001175,'$ \Delta V_{e||}/ V_{e0}$',color='m',fontsize=14)
plt.text(3.e-5,2.45e-3,'$R_e$',color='k',fontsize=16)
plt.text(3.e-5,5.e-2,'$R_{Debye}$',color='k',fontsize=16)
plt.text(3.e-5,1.8e-2,'$R_{Pass}$',color='k',fontsize=16)
plt.text(4.5e-5,4.8e-3,'$R_{Pass}$ $for$ $T_{e||}=0$',color='k',fontsize=16)
plt.text(8.3e-5,4.0,('$V_{e0}=%5.3f\cdot10^{%2d}$cm/s' % (mantV0,powV0)), \
color='m',fontsize=16)
if (saveFilesFlag == 1):
fig209.savefig('picturesCMA/rDebye_rLikeDebye_rPass_fig209cma.png')
print ('File "picturesCMA/rDebye_rLikeDebye_rPass_fig209cma.png" is written')
#
# Coulomb logarithm evaluation:
#
clmbLog = np.zeros(nVion)
for i in range(nVion):
clmbLog[i] = math.log(impctPrmtrMax[i]/impctPrmtrMin)
# clmbLog[i] = math.log(impctPrmtrMax_1[i]/impctPrmtrMin)
if (plotFigureFlag == 0):
fig3155=plt.figure (3155)
plt.semilogx(VionRel,clmbLog,'-xr',linewidth=2)
plt.xlabel('Relative Ion Velocity, $V_i/V_{e0}$',color='m',fontsize=14)
plt.ylabel('Coulomb Logarithm $L_c$',color='m',fontsize=14)
plt.title('Coulomb Logarithm: $L_c$ = $ln(R_{max}/R_{min})$',color='m',fontsize=16)
yLimit=[min(clmbLog)-.1,max(clmbLog)+.1]
plt.ylim(yLimit)
plt.plot([relVeTrnsv,relVeTrnsv],yLimit,'--m',linewidth=1)
plt.text(1.6e-3,5.,'$ \Delta V_{e\perp}/ V_{e0}$',color='m',fontsize=14)
plt.plot([relVeLong,relVeLong],yLimit,'--m',linewidth=1)
plt.text(3.4e-5,5.,'$ \Delta V_{e||}/ V_{e0}$',color='m',fontsize=14)
if (saveFilesFlag == 1):
fig3155.savefig('picturesCMA_v7/coulombLogrthm_fig3155cma.png')
print ('File "picturesCMA_v7/coulombLogrthm_fig3155cma.png" is written')
#
# matrix for electron with .5*timeStep_c:
#
matr_elec_c=guidingCenter_Matrix(.5*timeStep_c)
#
# matrix for ion with mass M_ion and .5*timeStep_c:
#
matr_ion_c=drift_Matrix(M_ion,.5*timeStep_c)
larmorTurns = 10
nImpctPrmtr = 50
rhoMin = impctPrmtrMin
rhoMax = np.zeros(nVion)
log10rhoMin = math.log10(rhoMin)
crrntImpctPrmtr = np.zeros(nImpctPrmtr)
halfLintr = np.zeros((nImpctPrmtr,nVion))
pointAlongTrack = np.zeros((nImpctPrmtr,nVion))
totalPoints = 0
for i in range(nVion):
rhoMax[i] = impctPrmtrMax[i]* \
np.sqrt(1.- (pi*larmorTurns*eVrmsLong/omega_L/impctPrmtrMax[i])**2)
rhoMax[i] = impctPrmtrMax[i]
# rhoMax[i] = impctPrmtrMax_1[i] # for checking!
# print ('rhoMax(%d) = %e' % (i,rhoMax[i]))
log10rhoMax = math.log10(rhoMax[i])
log10rhoStep = (log10rhoMax-log10rhoMin)/(nImpctPrmtr)
# print ('Vion(%d) = %e, rhoMax = %e' % (i,Vion[i],rhoMax[i]))
for n in range(nImpctPrmtr):
log10rhoCrrnt = log10rhoMin+(n+0.5)*log10rhoStep
rhoCrrnt = math.pow(10.,log10rhoCrrnt)
# print (' rhoCrrnt(%d) = %e' % (n,rhoCrrnt))
halfLintr[n,i] = np.sqrt(rhoMax[i]**2-rhoCrrnt**2) # half length of interaction; cm
timeHalfPath = halfLintr[n,i]/eVrmsLong # 0.5 time of interaction; sec
numbLarmor = int(2.*timeHalfPath/T_larm)
pointAlongTrack[n,i] = int(2.*timeHalfPath/timeStep_c)
totalPoints += pointAlongTrack[n,i]
# print (' %d: rhoCrrnt = %e, numbLarmor = %d, pointAlongTrack = %d' % \
# (n,rhoCrrnt,numbLarmor,pointAlongTrack[n,i]))
# print ('totalPoints = %d' % totalPoints)
totalPoints = int(totalPoints)
nnTotalPoints=np.arange(0,2*totalPoints-1,1)
arrayA=np.zeros(2*totalPoints)
arrayB=np.zeros(2*totalPoints)
bCrrnt_c = np.zeros(2*totalPoints)
#
# Variables for different testing:
#
b_gc = np.zeros(totalPoints)
action_gc = np.zeros(totalPoints)
C1test = np.zeros(totalPoints)
C2test = np.zeros(totalPoints)
C3test = np.zeros(totalPoints)
b_ME = np.zeros(totalPoints)
D1test = np.zeros(totalPoints)
D2test = np.zeros(totalPoints)
qTest = np.zeros(totalPoints)
action_ME = np.zeros(totalPoints)
actn_gc_ME_rel = np.zeros(totalPoints)
indxTest = 0
rhoInit = np.zeros((nImpctPrmtr,nVion))
#
# "Classical" approach:
#
deltaPx_c = np.zeros((nImpctPrmtr,nVion))
deltaPy_c = np.zeros((nImpctPrmtr,nVion))
deltaPz_c = np.zeros((nImpctPrmtr,nVion))
ionVx_c = np.zeros((nImpctPrmtr,nVion))
ionVy_c = np.zeros((nImpctPrmtr,nVion))
ionVz_c = np.zeros((nImpctPrmtr,nVion))
deltaEnrgIon_c = np.zeros((nImpctPrmtr,nVion))
#
# "Magnus Expand" approach:
#
deltaPx_m = np.zeros((nImpctPrmtr,nVion))
deltaPy_m = np.zeros((nImpctPrmtr,nVion))
deltaPz_m = np.zeros((nImpctPrmtr,nVion))
ionVx_m = np.zeros((nImpctPrmtr,nVion))
ionVy_m = np.zeros((nImpctPrmtr,nVion))
ionVz_m = np.zeros((nImpctPrmtr,nVion))
deltaEnrgIon_m = np.zeros((nImpctPrmtr,nVion))
#
# Comparison of approaches (ratio deltaEnrgIon_c/deltaEnrgIon_m):
#
deltaPx_c_m = np.zeros((nImpctPrmtr,nVion))
deltaPy_c_m = np.zeros((nImpctPrmtr,nVion))
deltaPz_c_m = np.zeros((nImpctPrmtr,nVion))
dEion_c_m = np.zeros((nImpctPrmtr,nVion))
#
# Factor to calculate transferred energy to ion
# (the friction force is defined by this transfered energy):
#
deFactor = 0.5/M_ion # 1/g
frctnForce_cSM = np.zeros(nVion) # integration, using Simpson method
frctnForce_mSM = np.zeros(nVion) # integration, using Simpson method
numberWrongSign_c=0
numberWrongSign_m=0
posSignDeltaEnrgIon_c=0
negSignDeltaEnrgIon_c=0
posSignDeltaEnrgIon_m=0
negSignDeltaEnrgIon_m=0
timeRun = np.zeros(nVion)
totalTimeRun = 0.
indx = 0
# ----------------- Main simulation ---------------
#
for i in range(nVion):
# Taking into account the corection of the maximal impact parameter
# on depence of preset number of minimal Larmor turns:
rhoMax[i] = impctPrmtrMax[i]* \
np.sqrt(1.- (pi*larmorTurns*eVrmsLong/omega_L/impctPrmtrMax[i])**2)
# Without taking into account the corection of the maximal impact parameter
# on depence of preset number of minimal Larmor turns:
rhoMax[i] = impctPrmtrMax[i]
# rhoMax[i] = impctPrmtrMax_1[i] # for checking!
log10rhoMax = math.log10(rhoMax[i])
log10rhoStep = (log10rhoMax-log10rhoMin)/(nImpctPrmtr)
# print ('Vion(%d) = %e, rhoMax = %e' % (i,Vion[i],rhoMax[i]))
timeStart=os.times()
for n in range(nImpctPrmtr):
log10rhoCrrnt = log10rhoMin+(n+0.5)*log10rhoStep
rhoCrrnt = math.pow(10.,log10rhoCrrnt)
# rhoInit[i*nImpctPrmtr+n] = rhoCrrnt
rhoInit[n,i] = rhoCrrnt
halfLintr[n,i] = np.sqrt(rhoMax[i]**2-rhoCrrnt**2) # half length of interaction; cm
z_ionCrrnt_c = np.zeros(6) # Zeroing out of vector for ion ("GC"-approach)
z_elecCrrnt_c = np.zeros(6) # Zeroing out of vector for electron ("GC"-approach)
z_ionCrrnt_m = np.zeros(6) # Zeroing out of vector for ion ("ME"-approach)
z_elecCrrnt_m = np.zeros(6) # Zeroing out of vector for electron ("ME"-approach)
# Zeroing out of "guiding center" vector for electron (both approaches):
z_elecCrrnt_gc_c = np.zeros(6)
z_elecCrrnt_gc_m = np.zeros(6)
# Current values of transfered momemta
# (second index numerates "Guiding Center", (if 0) and
# "Magnus Expantion" (if 1) approaches:
dpCrrnt = np.zeros((3,2))
# Intermediate arrays:
dpIon_c = np.zeros(3)
dpIon_m = np.zeros(3)
dpElec_c = np.zeros(3)
dpElec_m = np.zeros(3)
# Current initial vector for electron:
z_elecCrrnt_c[Ix] = rhoCrrnt # x, cm
z_elecCrrnt_c[Iz] = -halfLintr[n,i] # z, cm
z_elecCrrnt_c[Ipy] = m_elec*eVrmsTran # py, g*cm/sec
z_elecCrrnt_c[Ipz] = m_elec*eVrmsLong # pz, g*cm/sec
z_elecCrrnt_m[Ix] = rhoCrrnt # x, cm
z_elecCrrnt_m[Iz] = -halfLintr[n,i] # z, cm
z_elecCrrnt_m[Ipy] = m_elec*eVrmsTran # py, g*cm/sec
z_elecCrrnt_m[Ipz] = m_elec*eVrmsLong # pz, g*cm/sec
# Current initial vector for ion velocity for both approaches:
ionVx_c[n,i] = VionTrnsv[i]*np.cos(phiVi)
ionVy_c[n,i] = VionTrnsv[i]*np.sin(phiVi)
ionVz_c[n,i] = VionLong[i]
ionVx_m[n,i] = VionTrnsv[i]*np.cos(phiVi)
ionVy_m[n,i] = VionTrnsv[i]*np.sin(phiVi)
ionVz_m[n,i] = VionLong[i]
# transfer to system of guiding center:
z_elecCrrnt_gc_c=toGuidingCenter(z_elecCrrnt_c)
z_elecCrrnt_gc_m=toGuidingCenter(z_elecCrrnt_m)
#
# Main loop along the each track:
#
for k in range(int(pointAlongTrack[n,i])):
#
# Dragging both particles through first half of the step of the track:
#
z_elecCrrnt_gc_c = np.dot(matr_elec_c,z_elecCrrnt_gc_c) # electron
z_elecCrrnt_gc_m = np.dot(matr_elec_c,z_elecCrrnt_gc_m) # electron
z_ionCrrnt_c = np.dot(matr_ion_c,z_ionCrrnt_c) # ion
z_ionCrrnt_m = np.dot(matr_ion_c,z_ionCrrnt_m) # ion
# transfer from system of guiding center:
z_elecCrrnt_c=fromGuidingCenter(z_elecCrrnt_gc_c)
z_elecCrrnt_m=fromGuidingCenter(z_elecCrrnt_gc_m)
# Current distance between ion and electron; cm:
bCrrnt_c[indx]=np.sqrt((z_ionCrrnt_c[0]-z_elecCrrnt_c[0])**2+ \
(z_ionCrrnt_c[2]-z_elecCrrnt_c[2])**2+ \
(z_ionCrrnt_c[4]-z_elecCrrnt_c[4])**2)
# Current values of parameters A,B:
arrayA[indx] = math.log10(ro_Larm/bCrrnt_c[indx])
arrayB[indx] = math.log10((q_elec**2/bCrrnt_c[indx])/kinEnergy)
indx += 1
#
# Dragging both particles through interaction during this step of track
# (for both approaches):
#
# "Guiding Center":
dpIon_c,dpElec_c,action,b_gc_c = \
guidingCenterCollision(z_elecCrrnt_gc_c,z_ionCrrnt_c,timeStep_c)
# "Magnus Expantion":
dpIon_m,dpElec_m,actionME,dy_gc_m,C1,C2,C3,b,D1,D2,q = \
MagnusExpansionCollision(z_elecCrrnt_gc_m,z_ionCrrnt_m,timeStep_c)
# Save data for testing:
b_gc[indxTest] = b_gc_c # "Guiding Center" approach
action_gc[indxTest] = action # -"- -"- -"- -"- -"- -"-
C1test[indxTest] = C1 # "Magnus expansion" approach
C2test[indxTest] = abs(C2) # -"- -"- -"- -"- -"- -"-
C3test[indxTest] = C3 # -"- -"- -"- -"- -"- -"-
b_ME[indxTest] = b # -"- -"- -"- -"- -"- -"-
D1test[indxTest] = D1 # -"- -"- -"- -"- -"- -"-
D2test[indxTest] = D2 # -"- -"- -"- -"- -"- -"-
qTest[indxTest] = q #-"- -"- -"- -"- -"- -"-
action_ME[indxTest] = actionME #-"- -"- -"- -"- -"- -"-
indxTest += 1
indxTestMax = indxTest
#
# Taking into account transfer of momentum for both particles:
#
if (dpTransferFlag == 1):
for ic in range(3):
z_ionCrrnt_c[2*ic+1] += dpIon_c[ic]
z_elecCrrnt_c[2*ic+1] += dpElec_c[ic]
z_ionCrrnt_m[2*ic+1] += dpIon_m[ic]
z_elecCrrnt_m[2*ic+1] += dpElec_m[ic]
# transfer to system of guiding center:
z_elecCrrnt_gc_c=toGuidingCenter(z_elecCrrnt_c)
z_elecCrrnt_gc_m=toGuidingCenter(z_elecCrrnt_m)
# Accumulation of the transfered momenta to ion along the track for both approaches:
for ic in range(3):
# if i == 0:
# print ('dpIon_c[%2d] = %20.14e, dpIon_m[%2d] = %20.14e' % \
# (ic,dpIon_c[ic],ic,dpIon_m[ic]))
dpCrrnt[ic,0] += dpIon_c[ic] # "Guiding Center", g*cm/sec
dpCrrnt[ic,1] += dpIon_m[ic] # "Magnus Expansion", g*cm/sec
#
# Ion's elocity change along the track - both approaches:
#
ionVx_c[n,i] += dpCrrnt[0,0]/M_ion # cm/sec
ionVy_c[n,i] += dpCrrnt[1,0]/M_ion # cm/sec
ionVz_c[n,i] += dpCrrnt[2,0]/M_ion # cm/sec
ionVx_m[n,i] += dpCrrnt[0,1]/M_ion # cm/sec
ionVy_m[n,i] += dpCrrnt[1,1]/M_ion # cm/sec
ionVz_m[n,i] += dpCrrnt[2,1]/M_ion # cm/sec
#
# Dragging both particles through second half of the step of the track:
#
z_elecCrrnt_gc_c = np.dot(matr_elec_c,z_elecCrrnt_gc_c) # electron
z_ionCrrnt_c = np.dot(matr_ion_c,z_ionCrrnt_c) # ion
z_elecCrrnt_gc_m = np.dot(matr_elec_c,z_elecCrrnt_gc_m) # electron
z_ionCrrnt_m = np.dot(matr_ion_c,z_ionCrrnt_m) # ion
# transfer from system of guiding center:
z_elecCrrnt_c=fromGuidingCenter(z_elecCrrnt_gc_c)
z_elecCrrnt_m=fromGuidingCenter(z_elecCrrnt_gc_m)
# Current distance between ion and electron; cm:
bCrrnt_c[indx]=np.sqrt((z_ionCrrnt_c[0]-z_elecCrrnt_c[0])**2+ \
(z_ionCrrnt_c[2]-z_elecCrrnt_c[2])**2+ \
(z_ionCrrnt_c[4]-z_elecCrrnt_c[4])**2)
# Current values of parameters A,B:
arrayA[indx] = math.log10(ro_Larm/bCrrnt_c[indx])
arrayB[indx] = math.log10((q_elec**2/bCrrnt_c[indx])/kinEnergy)
indx += 1
#
# Transferred momenta along the track - "Guiding Center" approach:
#
deltaPx_c[n,i] = dpCrrnt[0,0] # dpx, g*cm/sec
# if deltaPx_c[n,i] <= 0.:
# print ('deltaPx_c[%2d,%2d] = %e, dpCrrnt[%2d,%2d] = %e' % \
# (n,i,deltaPx_c[n,i],n,i,dpCrrnt[0,0]))
deltaPy_c[n,i] = dpCrrnt[1,0] # dpy, g*cm/sec
# if deltaPy_c[n,i] <= 0.:
# print ('deltaPy_c[%2d,%2d] = %e' % (n,i,deltaPy_c[n,i]))
deltaPz_c[n,i] = dpCrrnt[2,0] # dpz, g*cm/sec
# if deltaPz_c[n,i] <= 0.:
# print ('deltaPz_c[%2d,%2d] = %e' % (n,i,deltaPz_c[n,i]))
# Incorrect value:
# deltaEnrgIon_c[n,i] = (dpCrrnt[0,0]**2+dpCrrnt[1,0]**2+dpCrrnt[2,0]**2)* \
# deFactor/eVtoErg # eV
# Correct value:
crrntDeltaEnrg = (dpCrrnt[0,0]*ionVx_c[n,i]+ \
dpCrrnt[1,0]*ionVy_c[n,i]+ \
dpCrrnt[2,0]*ionVz_c[n,i])*deFactor/eVtoErg # eV
absDeltaEnrgIon_c = abs(crrntDeltaEnrg)
if (crrntDeltaEnrg != 0.):
signDeltaEnrgIon_c = crrntDeltaEnrg/abs(crrntDeltaEnrg)
deltaEnrgIon_c[n,i] = crrntDeltaEnrg
if (deltaEnrgIon_c[n,i] > 0.):
posSignDeltaEnrgIon_c += 1
else:
negSignDeltaEnrgIon_c += 1
#
# Transferred momenta along the track - "Magnus expansion" approach:
#
deltaPx_m[n,i] = dpCrrnt[0,1] # dpx, g*cm/sec
# if deltaPx_m[n,i] <= 0.:
# print ('deltaPx_m[%2d,%2d] = %e' % (n,i,deltaPx_m[n,i]))
deltaPy_m[n,i] = dpCrrnt[1,1]
# if deltaPy_m[n,i] <= 0.:
# print ('deltaPy_m[%2d,%2d] = %e' % (n,i,deltaPy_m[n,i]))
deltaPz_m[n,i] = dpCrrnt[2,1]
# if deltaPz_m[n,i] <= 0.:
# print ('deltaPz_m[%2d,%2d] = %e' % (n,i,deltaPz_m[n,i]))
# Incorrect value:
# deltaEnrgIon_m[n,i] = (dpCrrnt[0,1]**2+dpCrrnt[1,1]**2+dpCrrnt[2,1]**2)* \
# deFactor/eVtoErg # eV
# Correct value absolute value):
crrntDeltaEnrg = (dpCrrnt[0,1]*ionVx_m[n,i]+ \
dpCrrnt[1,1]*ionVy_m[n,i]+ \
dpCrrnt[2,1]*ionVz_m[n,i])*deFactor/eVtoErg # eV
absDeltaEnrgIon_m = abs(crrntDeltaEnrg)
if (crrntDeltaEnrg != 0.):
signDeltaEnrgIon_m = crrntDeltaEnrg/abs(crrntDeltaEnrg)
deltaEnrgIon_m[n,i] = crrntDeltaEnrg
if (deltaEnrgIon_m[n,i] > 0.):
posSignDeltaEnrgIon_m += 1
else:
negSignDeltaEnrgIon_m += 1
#
# Comparison of the approaches (%):
#
if (deltaPx_m[n,i] != 0.):
deltaPx_c_m[n,i] = 100.*(deltaPx_c[n,i]/deltaPx_m[n,i]-1.)
else:
print ('Bad value (=0.) of deltaPx_m[%d,%d] = ' % (n,i))
if (deltaPy_m[n,i] != 0.):
deltaPy_c_m[n,i] = 100.*(deltaPy_c[n,i]/deltaPy_m[n,i]-1.)
else:
print ('Bad value (=0.) of deltaPy_m[%d,%d] = ' % (n,i))
if (deltaPz_m[n,i] != 0.):
deltaPz_c_m[n,i] = 100.*(deltaPz_c[n,i]/deltaPz_m[n,i]-1.)
else:
print ('Bad value (=0.) of deltaPz_m[%d,%d] = ' % (n,i))
if (deltaEnrgIon_m[n,i] != 0.):
dEion_c_m[n,i] = 100.*(deltaEnrgIon_c[n,i]/deltaEnrgIon_m[n,i]-1.)
else:
print ('Bad value (=0.) of deltaEnrgIon_m[%d,%d] = ' % (n,i))
#
# Integration using Simpson method:
#
if (n > 0):
frctnForce_cSM[i] += pi*n_e*100.*(deltaEnrgIon_c[n,i]+deltaEnrgIon_c[n-1,i])* \
.5*(rhoInit[n,i]+rhoInit[n-1,i])* \
(rhoInit[n,i]-rhoInit[n-1,i]) # eV/m
frctnForce_mSM[i] += pi*n_e*100.*(deltaEnrgIon_m[n,i]+deltaEnrgIon_m[n-1,i])* \
.5*(rhoInit[n,i]+rhoInit[n-1,i])* \
(rhoInit[n,i]-rhoInit[n-1,i]) # eV/m
timeEnd = os.times()
timeRun[i] = float(timeEnd[0])-float(timeStart[0]) # CPU time , sec
totalTimeRun += timeRun[i]
print ('timeRun(%2d) = %6.3f seconds' % (i,timeRun[i]))
print ('Total time (icluding Simpson integration) = %6.3f seconds' % totalTimeRun)
print ('deltaEnrgIon_c: nPos=%d, nNeg=%d; deltaEnrgIon_m: nPos=%d, nNeg=%d' % \
(posSignDeltaEnrgIon_c,negSignDeltaEnrgIon_c, \
posSignDeltaEnrgIon_m,negSignDeltaEnrgIon_m))
#
# Output for checking:
#
# print \
# ('n Px_c Px_m Py_c Py_m Pz_c Pz_m Pz_c_m')
# for i in range(10,11,1):
# for n in range(nImpctPrmtr):
# print ('%d: %e %e %e %e %e %e %e' % \
# (n,deltaPx_c[n,i],deltaPx_m[n,i],deltaPy_c[n,i], \
# deltaPy_m[n,i],deltaPz_c[n,i],deltaPz_m[n,i],deltaPz_c_m[n,i]))
# print ('n dEion_c dEion_m')
# for i in range(10,11,1):
# for n in range(nImpctPrmtr):
# print ('%d: %e %e ' % (n,deltaEnrgIon_c[n,i],deltaEnrgIon_m[n,i]))
# print ('indxTestMax = %d' % indxTestMax)
#
# Plotting of the tests:
#
nn=np.arange(0,indxTestMax-1,1)
#
# C1:
#
if (plotFigureFlag == 0):
fig2020=plt.figure (2020)
plt.plot(nn,C1test[0:indxTestMax-1],'.r')
plt.xlabel('Points of Tracks',color='m',fontsize=16)
plt.ylabel('$C1$, $cm^2$',color='m',fontsize=16)
plt.title('$C1=[x_{gc}^2+y_{gc}^2+z_e^2+2J/(m_e \cdot \Omega_e)]^{0.5}$', \
color='m',fontsize=16)
plt.xlim([-5000,indxTestMax+5000])
plt.grid(True)
if (saveFilesFlag == 1):
fig2020.savefig('picturesCMA_v7/magnusExpansion_C1_fig2020cma.png')
print ('File "picturesCMA_v7/magnusExpansion_C1_fig2020cma.png" is written')
#
# C2:
#
if (plotFigureFlag == 0):
fig2030=plt.figure (2030)
plt.plot(nn,1.e-5*C2test[0:indxTestMax-1],'.r')
plt.xlabel('Points of Tracks',color='m',fontsize=16)
plt.ylabel('$C2$, $\cdot 10^5$ $cm^2/s$',color='m',fontsize=16)
plt.title('$C2=2\cdot[V_{ix}\cdot(x_i-x_{gc})+V_{iy}\cdot(y_i-y_{gc})+(V_{iz}-V_{ez})\cdot(z_i-z_e)]$', \
color='m',fontsize=14)
plt.xlim([-5000,indxTestMax+5000])
plt.grid(True)
if (saveFilesFlag == 1):
fig2030.savefig('picturesCMA_v7/magnusExpansion_C2_fig2030cma.png')
print ('File "picturesCMA_v7/magnusExpansion_C2_fig2030cma.png" is written')
#
# C3:
#
if (plotFigureFlag == 0):
fig2040=plt.figure (2040)
plt.plot(nn,1e-11*C3test[0:indxTestMax-1],'.r')
plt.xlabel('Points of Tracks',color='m',fontsize=16)
plt.ylabel('$C3$, $\cdot 10^{11}$ $cm^2/s^2$',color='m',fontsize=16)
plt.title('$C3=V_{ix}^2+V_{iy}^2+(V_{iz}-V_{ez})^2$',color='m',fontsize=16)
plt.xlim([-5000,indxTestMax+5000])
plt.grid(True)
if (saveFilesFlag == 1):
fig2040.savefig('picturesCMA_v7/magnusExpansion_C3_fig2040cma.png')
print ('File "picturesCMA_v7/magnusExpansion_C3_fig2040cma.png" is written')
#
# D1:
#
if (plotFigureFlag == 0):
fig2025=plt.figure (2025)
plt.plot(nn,1.e-5*D1test[0:indxTestMax-1],'.r')
plt.xlabel('Points of Tracks',color='m',fontsize=16)
plt.ylabel('$10^{-5}\cdot D1$, $cm/s$',color='m',fontsize=16)
plt.title('$D1=(2C_3\cdot \Delta t+C_2)/b_{ME}$ $-$ $C_2/C_1^{0.5}$',color='m',fontsize=16)
plt.xlim([-5000,indxTestMax+5000])
plt.grid(True)
if (saveFilesFlag == 1):
fig2025.savefig('picturesCMA_v7/magnusExpansion_D1_fig2025cma.png')
print ('File "picturesCMA_v7/magnusExpansion_D1_fig2025cma.png" is written')
#
# D2:
#
if (plotFigureFlag == 0):
fig2035=plt.figure (2035)
plt.plot(nn,1.e4*D2test[0:indxTestMax-1],'.r')
plt.xlabel('Points of Tracks',color='m',fontsize=16)
plt.ylabel('$10^4\cdot D2$, $cm$',color='m',fontsize=16)
plt.title('$D2=(2C_1+C_2\cdot \Delta t)/b_{ME}$ $-$ $2C_1^{0.5}$',color='m',fontsize=16)
plt.xlim([-5000,indxTestMax+5000])
plt.grid(True)
if (saveFilesFlag == 1):
fig2035.savefig('picturesCMA_v7/magnusExpansion_D2_fig2035cma.png')
print ('File "picturesCMA_v7/magnusExpansion_D2_fig2035cma.png" is written')
#
# Distance b_ME between particles for "ME" approach:
#
if (plotFigureFlag == 0):
fig2050=plt.figure (2050)
plt.plot(nn,b_ME[0:indxTestMax-1],'.r')
plt.xlabel('Points of Tracks',color='m',fontsize=16)
plt.ylabel('$b_{ME}$, $cm$',color='m',fontsize=16)
plt.title('Distance $b_{ME}$ between Particles for "ME" Approach', color='m',fontsize=16)
plt.text(3500,.4,'$b_{ME}=[C1+C2\cdot \Delta t +C3 \cdot \Delta t^2]^{0.5}$', \
color='m',fontsize=16)
plt.text(33000,.36,('$(\Delta t=%8.2e$ $s)$' % timeStep_c),color='m',fontsize=16)
plt.xlim([-5000,indxTestMax+5000])
plt.grid(True)
if (saveFilesFlag == 1):
fig2050.savefig('picturesCMA_v7/particleDistance_me_fig2050cma.png')
print ('File "picturesCMA_v7/particleDistance_me_fig2050cma.png" is written')
#
# Distance b_gc between particles for "GC" approach:
#
if (plotFigureFlag == 0):
fig2055=plt.figure (2055)
plt.plot(nn,b_gc[0:indxTestMax-1],'.r')
plt.xlabel('Points of Tracks',color='m',fontsize=16)
plt.ylabel('$b_{GC}$, $cm$',color='m',fontsize=16)
plt.title('Distance $b_{GC}$ between Particles for "GC" Approach', color='m',fontsize=16)
plt.text(0,.4,'$b_{GC}=[(x_i-x_{gc})^2+(y_i-y_{gc})^2+$',color='m',fontsize=16)
plt.text(55500,.36,'$+(z_i-z_e)^2+2J/(m_e \cdot \Omega_e)]^{0.5}$', \
color='m',fontsize=16)
plt.xlim([-5000,indxTestMax+5000])
plt.grid(True)
if (saveFilesFlag == 1):
fig2055.savefig('picturesCMA/particleDistance_gc_fig2055cma.png')
print ('File "picturesCMA/particleDistance_gc_fig2055cma.png" is written')
#
# Comparison of bCrrnt_c from "Guiding Center" with bTest from
# "Magnus expansion" approaches:
#
bCrrnt_cTest = np.zeros(indxTestMax)
bCrrnt_cTestRel = np.zeros(indxTestMax)
b_gc_ME_rel = np.zeros(indxTestMax)
for k in range(indxTestMax):
bCrrnt_cTest[k] = .5*(bCrrnt_c[2*k]+bCrrnt_c[2*k+1])
# bCrrnt_cTestRel[k] = bCrrnt_cTest[k]/b_ME[k]
b_gc_ME_rel[k] = b_gc[k]/b_ME[k]
actn_gc_ME_rel[k] = 1.e7*(action_gc[k]/action_ME[k]-1.)
if (plotFigureFlag == 0):
fig2060=plt.figure (2060)
# plt.semilogy(nn,bCrrnt_cTest[0:indxTestMax-1],'.r')
plt.plot(nn,bCrrnt_cTest[0:indxTestMax-1],'.r')
plt.xlabel('Points of Tracks',color='m',fontsize=16)
plt.ylabel('Test $b_{crrntTest}$, $cm$',color='m',fontsize=16)
plt.title('Test $b_{crrntTest} = .5 \cdot [b_{crrnt}(k)+b_{crrnt}(k+1)]$',color='m', \
fontsize=16)
plt.xlim([-5000,indxTestMax+5000])
# plt.ylim([.9*min(bCrrnt_cTest),1.1*max(bCrrnt_cTest)])
plt.grid(True)
#
# Ratio b_gc/b_ME (absolute value):
#
if (plotFigureFlag == 0):
fig2070=plt.figure (2070)
# plt.semilogy(nn,b_gc_ME_rel[0:indxTestMax-1],'.r')
plt.plot(nn,b_gc_ME_rel[0:indxTestMax-1],'.r')
plt.xlabel('Points of Tracks',color='m',fontsize=16)
plt.ylabel('$b_{GC}/b_{ME}$',color='m',fontsize=16)
plt.title('Comparison of Distances $b_{GC}$ and $b_{ME}$ between Particles',color='m',fontsize=16)
plt.xlim([-5000,indxTestMax+5000])
# plt.ylim([.9*min(b_gc_ME_rel),1.1*max(b_gc_ME_rel)])
plt.grid(True)
if (saveFilesFlag == 1):
fig2070.savefig('picturesCMA_v7/particleDistanceComprsn_gc_me_fig2070cma.png')
print ('File "picturesCMA_v7/particleDistanceComprsn_gc_me_fig2070cma.png" is written')
#
# Ratio b_gc/b_ME (relative value):
#
if (plotFigureFlag == 0):
fig2080=plt.figure (2080)
# plt.semilogy(nn,actn_gc_ME_rel[0:indxTestMax-1],'.r')
plt.plot(nn,actn_gc_ME_rel[0:indxTestMax-1],'.r')
plt.xlabel('Points of Tracks',color='m',fontsize=16)
plt.ylabel('$10^7\cdot (J_{GC}/J_{ME}$ $-$ $1)$',color='m',fontsize=16)
plt.title('Comparison of Actions $J_{GC}$ and $J_{ME}$',color='m',fontsize=16)
plt.xlim([-5000,indxTestMax+5000])
plt.ylim([.99*min(actn_gc_ME_rel),1.01*max(actn_gc_ME_rel)])
plt.grid(True)
if (saveFilesFlag == 1):
fig2080.savefig('picturesCMA_v7/actionComprsn_gc_me_fig2080cma.png')
print ('File "picturesCMA_v7/actionComprsn_gc_me_fig2080cma.png" is written')
#
# Total length of interaction (1/2 of value):
#
nn=np.arange(0,nVion*nImpctPrmtr,1)
halfLintrTest = np.zeros(nVion*nImpctPrmtr)
for i in range(nVion):
for n in range(nImpctPrmtr):
halfLintrTest[nVion*i+n] = halfLintr[i,n]
if (plotFigureFlag == 0):
fig2090=plt.figure (2090)
plt.semilogy(nn,halfLintrTest,'.r')
plt.xlabel('Points of Tracks',color='m',fontsize=16)
plt.ylabel('$0.5 \cdot L_{Intrctn}$, $cm$',color='m',fontsize=16)
plt.title('Total Length of Interaction: $L_{Intrctn}=2 \cdot [R_{max}^2-rho_{Init}^2)]^{0.5}$', \
color='m',fontsize=16)
plt.xlim([-100,nVion*nImpctPrmtr+100])
plt.ylim([.9*min(halfLintrTest),1.1*max(halfLintrTest)])
plt.grid(True)
if (saveFilesFlag == 1):
fig2090.savefig('picturesCMA/totalLengthIntrsctn_fig2090cma.png')
print ('File "picturesCMA/totalLengthIntrsctn_fig2090cma.png" is written')
#===================================================
#
# There is fitting for correct values of deltaEnrgIon_m
#
#===================================================
#
# Fitting for figures with deltaEnrgIon_m (my own Least Squares Method - LSM;
# Python has own routine for LSM - see site
# http://scipy-cookbook.readthedocs.io/items/FittingData.html):
#
#
# Fittied function:
#
# |deltaEnrgIon| = 10^fitA * rho^fitB,
# so that
#
# log10(|deltaEnrgIon|) = fitB*log10(rho) + fitA
#
# So, the dimension of expression (10^fitA * rho^fitB) is the same
# as deltaEnrgIon, i.e. eV
#
timeStart = os.times()
fitA_dEion = np.zeros(nVion) # dimensionless
fitB_dEion = np.zeros(nVion) # dimensionless
rhoInitFit_dEion = np.zeros((nImpctPrmtr,nVion))
deltaEnrgIon_m_fit = np.zeros((nImpctPrmtr,nVion))
funcHi2_dEion = np.zeros(nVion)
fitA_dEion,fitB_dEion,funcHi2_dEion,rhoInitFit_dEion, deltaEnrgIon_m_fit = \
fitting(nImpctPrmtr,nVion,rhoInit,deltaEnrgIon_m)
dPosA_dEion = np.zeros(nVion)
dNegA_dEion = np.zeros(nVion)
dPosA_dEion,dNegA_dEion = \
errFitAB(nImpctPrmtr,nVion,rhoInit,deltaEnrgIon_m_fit,fitA_dEion,fitB_dEion,funcHi2_dEion,1,2)
dPosB_dEion = np.zeros(nVion)
dNegB_dEion = np.zeros(nVion)
dPosB_dEion,dNegB_dEion = \
errFitAB(nImpctPrmtr,nVion,rhoInit,deltaEnrgIon_m_fit,fitA_dEion,fitB_dEion,funcHi2_dEion,2,2)
# print ('Fitting for deltaEion:')
# for i in range(nVion):
# print ('i=%2d: fitA_dEion = %e (+%e,-%e), fitB_dEion = %e (+%e,-%e), hi2_1 = %e' % \
# (i,fitA_dEion[i],dPosA_dEion[i],dNegA_dEion[i], \
# fitB_dEion[i],dPosB_dEion[i],dNegB_dEion[i],funcHi2_dEion[i]))
#
# Analytical Integration of the fitted dependence 10**A*rho**B.
#
# For this dependece on rho:
#
# Friction force = 10**A*n_e*integral_rhoMin^rhoMax (rho**B*rho)*dRho =
# = 10**A*n_e/(B+2)*[rhoMax**(B+2)-rhoMax**(B+2)] (dimension=eV/cm):
#
frctnForce_AI = np.zeros(nVion)
for i in range(nVion):
factorA1 = math.pow(10.,fitA_dEion[i])
factorB1 = 2.+fitB_dEion[i]
frctnForce_AI[i] = 2.*pi*n_e*100.*factorA1/factorB1* \
(math.pow(impctPrmtrMax[i],factorB1)- \
math.pow(impctPrmtrMin,factorB1)) # eV/m
timeEnd = os.times()
timeFitting = float(timeEnd[0])-float(timeStart[0]) # CPU time , sec
print ('Time of integration = %6.3f seconds' % timeFitting)
#
# Dependences of transferred energy to ion on ion velocity for
# different initial impact parameters:
#
rhoSlctd = [.004,.02,.06,.1]
nRhoSlctd = len(rhoSlctd)
deltaEnrgIon_dpnd_Vi = np.zeros((nRhoSlctd,nVion))
npStart = np.zeros((nRhoSlctd,), dtype=int)
for k in range(nRhoSlctd):
slctdFlag = 0
for i in range(nVion):
if (slctdFlag == 0):
for n in range(nImpctPrmtr):
if (rhoInit[n,i] >= rhoSlctd[k]):
npStart[k] = i
slctdFlag = 1
break
for k in range(nRhoSlctd):
for i in range(npStart[k],nVion,1):
factorA = math.pow(10.,fitA_dEion[i])
deltaEnrgIon_dpnd_Vi[k,i] = factorA*math.pow(rhoSlctd[k],fitB_dEion[i])
# print ('deltaEnrgIon_dpnd_Vi[%d,%d] = %e' %(k,i,deltaEnrgIon_dpnd_Vi[k,i]))
#===================================================
#
# There is fitting of deltaPz_m (these values > 0 always) !!!
#
#===================================================
#
# Fitting for figures with deltaPz_m (my own Least Squares Method - LSM;
# Python has own routine for LSM - see site
# http://scipy-cookbook.readthedocs.io/items/FittingData.html):
#
#
# Fittied function:
#
# deltaPz_m = 10^fitA_pz * rho^fitB_pz,
# so that
#
# log10(deltaPz_m) = fitB_pz*log10(rho) + fitA_pz
#
# So, the dimension of expression (10^fitA_pz * rho^fitB_pz) is the same
# as deltaPz_m, i.e. eV
#
fitA_pz = np.zeros(nVion) # dimensionless
fitB_pz = np.zeros(nVion) # dimensionless
rhoInitFit_pz = np.zeros((nImpctPrmtr,nVion))
deltaPz_m_fit = np.zeros((nImpctPrmtr,nVion))
fitA_pz,fitB_pz,funcHi2_pz,rhoInitFit_pz, deltaPz_m_fit = \
fitting(nImpctPrmtr,nVion,rhoInit,deltaPz_m)
dPosA_pz = np.zeros(nVion)
dNegA_pz = np.zeros(nVion)
dPosA_pz,dNegA_pz = \
errFitAB(nImpctPrmtr,nVion,rhoInit,deltaPz_m_fit,fitA_pz,fitB_pz,funcHi2_pz,1,2)
dPosB_pz = np.zeros(nVion)
dNegB_pz = np.zeros(nVion)
dPosB_pz,dNegB_pz = \
errFitAB(nImpctPrmtr,nVion,rhoInit,deltaPz_m_fit,fitA_pz,fitB_pz,funcHi2_pz,2,2)
# print ('Fitting fordeltaPz_m:')
# for i in range(nVion):
# print ('i=%2d: fitA_pz = %e (+%e,-%e), fitB_pz = %e (+%e,-%e), hi2_1 = %e' % \
# (i,fitA_pz[i],dPosA_pz[i],dNegA_pz[i], \
# fitB_pz[i],dPosB_pz[i],dNegB_pz[i],funcHi2_pz[i]))
# print ('<fitA_pz> = %e +- %e' % (mean(fitA_pz),mean(dNegA_pz)))
# print ('<fitB_pz> = %e +- %e' % (mean(fitB_pz),mean(dNegB_pz)))
#===================================================
#
# There is fitting of deltaPx_m (these values > 0 always) !!!
#
#===================================================
#
rhoInitFit_px = np.zeros((nImpctPrmtr,nVion))
deltaPx_m_fit = np.zeros((nImpctPrmtr,nVion))
funcHi2__px = np.zeros(nVion)
fitA_px = np.zeros(nVion) # dimensionless
fitB_px = np.zeros(nVion) # dimensionless
fitA_px,fitB_px,funcHi2_px,rhoInitFit_px, deltaPx_m_fit = \
fitting(nImpctPrmtr,nVion,rhoInit,deltaPx_m)
dPosA_px = np.zeros(nVion)
dNegA_px = np.zeros(nVion)
dPosA_px,dNegA_px = \
errFitAB(nImpctPrmtr,nVion,rhoInit,deltaPx_m_fit,fitA_px,fitB_px,funcHi2_px,1,2)
dPosB_px = np.zeros(nVion)
dNegB_px = | np.zeros(nVion) | numpy.zeros |
"""Contains logic for finding targets in blobs."""
import os
from pkg_resources import resource_filename
import cv2
import numpy as np
import os
import PIL.Image
import sklearn.cluster
import scipy.misc
import target_finder_model as tfm
from .darknet import Yolo3Detector, PreClassifier
from .preprocessing import extract_crops, resize_all, extract_contour
from .types import Color, Shape, Target, BBox
from .color_cube import ColorCube
# Default Models w/default weights
models = {
'yolo3': Yolo3Detector(),
'clf': PreClassifier()
}
def set_models(new_models):
models.update(new_models)
def find_targets(pil_image, **kwargs):
"""Wrapper for finding targets which accepts a PIL image"""
image_ary = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
return find_targets_from_array(image_ary, **kwargs)
def find_targets_from_array(image_ary, limit=20):
raw_bboxes = _run_models(image_ary)
targets = _bboxes_to_targets(raw_bboxes)
# Sorting with highest confidence first.
targets.sort(key=lambda t: t.confidence, reverse=True)
_identify_properties(targets, image_ary)
return targets[:limit]
def _run_models(image):
detector_model = models['yolo3']
clf_model = models['clf']
crops = extract_crops(image, tfm.CROP_SIZE, tfm.CROP_OVERLAP)
clf_crops = resize_all(crops, tfm.PRECLF_SIZE)
regions = clf_model.classify_all([box.image for box in clf_crops])
filtered_crops = [crops[i] for i, region in enumerate(regions)
if region == 'shape_target']
detector_crops = resize_all(filtered_crops, tfm.DETECTOR_SIZE)
try:
offset_bboxes = detector_model.detect_all([box.image
for box in detector_crops])
except IndexError:
print('Error processing Darknet output...assuming no shapes detected.')
offset_bboxes = []
ratio = tfm.DETECTOR_SIZE[0] / tfm.CROP_SIZE[0]
normalized_bboxes = []
for crop, bboxes in zip(detector_crops, offset_bboxes):
for name, conf, bbox in bboxes:
bw = bbox[2] / ratio
bh = bbox[3] / ratio
bx = (bbox[0] / ratio) + crop.x1
by = (bbox[1] / ratio) + crop.y1
box = BBox(bx, by, bx + bw, by + bh)
box.meta = {name: conf}
box.confidence = conf
normalized_bboxes.append(box)
return normalized_bboxes
def _bboxes_to_targets(bboxes):
"""Produce targets from bounding boxes"""
targets = []
merged_bboxes = _merge_boxes(bboxes)
for box in merged_bboxes:
shape, alpha, conf = _get_shape_and_alpha(box)
targets.append(Target(box.x1, box.y1, box.w, box.h,
shape=shape,
alphanumeric=alpha,
confidence=conf))
return targets
def _get_shape_and_alpha(box):
best_shape, conf_shape = 'unk', 0
best_alpha, conf_alpha = 'unk', 0
for class_name, conf in box.meta.items():
if len(class_name) == 1 and conf > conf_alpha:
best_alpha = class_name
conf_alpha = conf
elif len(class_name) != 1 and conf > conf_shape:
best_shape = class_name
conf_shape = conf
# convert name to object
if best_shape == 'unk':
shape = Shape.NAS
else:
shape = Shape[best_shape.upper().replace('-', '_')]
return shape, best_alpha, ((conf_shape + conf_alpha) / 2)
def _merge_boxes(boxes):
merged = []
for box in boxes:
for merged_box in merged:
if _intersect(box, merged_box):
_enlarge(merged_box, box)
merged_box.meta.update(box.meta)
break
else:
merged.append(box)
return merged
def _intersect(box1, box2):
# no intersection along x-axis
if (box1.x1 > box2.x2 or box2.x1 > box1.x2):
return False
# no intersection along y-axis
if (box1.y1 > box2.y2 or box2.y1 > box1.y2):
return False
return True
def _enlarge(main_box, new_box):
main_box.x1 = min(main_box.x1, new_box.x1)
main_box.x2 = max(main_box.x2, new_box.x2)
main_box.y1 = min(main_box.y1, new_box.y1)
main_box.y2 = max(main_box.y2, new_box.y2)
def _identify_properties(targets, full_image, padding=15):
for target in targets:
x = int(target.x) - padding
y = int(target.y) - padding
w = int(target.width) + padding * 2
h = int(target.height) + padding * 2
blob_image = full_image[y:y + h, x:x + w]
img = PIL.Image.fromarray(cv2.cvtColor(blob_image, cv2.COLOR_BGR2RGB))
target.image = img
try:
target_color, alpha_color = _get_colors(blob_image)
target.background_color = target_color
target.alphanumeric_color = alpha_color
except cv2.error:
target.background_color = Color.NONE
target.alphanumeric_color = Color.NONE
def _get_colors(image):
"""Find the primary and seconday colors of the the blob"""
contour = extract_contour(image)
(color_a, count_a), (color_b, count_b) = _find_main_colors(image, contour)
# this assumes the shape will have more pixels than alphanum
if count_a > count_b:
primary, secondary = color_a, color_b
else:
primary, secondary = color_b, color_a
primary_color = _get_color_name(primary)
secondary_color = _get_color_name(secondary)
return primary_color, secondary_color
def _find_main_colors(image, contour):
"""Find the two main colors of the blob"""
mask_img = | np.array(image) | numpy.array |
import random as rn
import numpy as np
import matplotlib.pyplot as plt
import math
np.seterr(divide='ignore', invalid='ignore')
# MINIMIZATION
# Initialize random population of parent chormosomes/solutions P
def random_population(n_var, n_sol, lb, ub):
# n_var = numver of variables
# n_sol = number of random solutions
# lb = lower bound
# ub = upper bound
pop = np.zeros((n_sol, n_var))
for i in range(n_sol):
pop[i, :] = np.random.uniform(lb, ub)
return pop
# On each iteration, out of 2 randomly selected parents we create 2 offsprings
# by taking fraction of genes from one parent and remaining fraction from other parent
def crossover(pop, crossover_rate):
offspring = np.zeros((crossover_rate, pop.shape[1]))
for i in range(int(crossover_rate/2)):
r1 = np.random.randint(0, pop.shape[0])
r2 = np.random.randint(0, pop.shape[0])
while r1 == r2:
r1 = np.random.randint(0, pop.shape[0])
r2 = np.random.randint(0, pop.shape[0])
cutting_point = np.random.randint(1, pop.shape[1])
offspring[2*i, 0:cutting_point] = pop[r1, 0:cutting_point]
offspring[2*i, cutting_point:] = pop[r2, cutting_point:]
offspring[2*i+1, 0:cutting_point] = pop[r2, 0:cutting_point]
offspring[2*i+1, cutting_point:] = pop[r1, cutting_point:]
return offspring # arr(crossover_size x n_var)
# On each iteration, out of 2 randomly selected parents we create 2 offsprings
# by excahging some amount of genes/coordinates between parents
def mutation(pop, mutation_rate):
offspring = np.zeros((mutation_rate, pop.shape[1]))
for i in range(int(mutation_rate/2)):
r1 = np.random.randint(0, pop.shape[0])
r2 = np.random.randint(0, pop.shape[0])
while r1 == r2:
r1 = np.random.randint(0, pop.shape[0])
r2 = np.random.randint(0, pop.shape[0])
# We select only one gene/coordinate per chromosomes/solution for mutation here.
# For binary solutions, number of genes for mutation can be arbitrary
cutting_point = np.random.randint(0, pop.shape[1])
offspring[2*i] = pop[r1]
offspring[2*i, cutting_point] = pop[r2, cutting_point]
offspring[2*i+1] = pop[r2]
offspring[2*i+1, cutting_point] = pop[r1, cutting_point]
return offspring # arr(mutation_size x n_var)
# Create some amount of offsprings Q by adding fixed coordinate displacement to some
# randomly selected parent's genes/coordinates
def local_search(pop, n_sol, step_size):
# number of offspring chromosomes generated from the local search
offspring = np.zeros((n_sol, pop.shape[1]))
for i in range(n_sol):
r1 = np.random.randint(0, pop.shape[0])
chromosome = pop[r1, :]
r2 = np.random.randint(0, pop.shape[1])
chromosome[r2] += np.random.uniform(-step_size, step_size)
if chromosome[r2] < lb[r2]:
chromosome[r2] = lb[r2]
if chromosome[r2] > ub[r2]:
chromosome[r2] = ub[r2]
offspring[i, :] = chromosome
return offspring # arr(loc_search_size x n_var)
# Calculate fitness (obj function) values for each chormosome/solution
# Kursawe function - https://en.wikipedia.org/wiki/Test_functions_for_optimization
def evaluation(pop):
# 2 values for each choromosome/solution
fitness_values = np.zeros((pop.shape[0], 2))
for i, x in enumerate(pop):
r = x[0]
h = x[1]
s = np.sqrt((r ** 2) + (h ** 2))
S = np.pi * r * s
B = np.pi * (r ** 2)
T = B + S
fitness_values[i, 0] = S
fitness_values[i, 1] = T
return fitness_values # arr(pop_size x 2)
# Estimate how tightly clumped fitness values are on Pareto front.
def crowding_calculation(fitness_values):
pop_size = len(fitness_values[:, 0])
# == n of objective functions
fitness_value_number = len(fitness_values[0, :])
matrix_for_crowding = np.zeros(
(pop_size, fitness_value_number)) # arr(pop_size x 2)
normalized_fitness_values = (
fitness_values - fitness_values.min(0))/fitness_values.ptp(0)
for i in range(fitness_value_number):
crowding_results = np.zeros(pop_size)
crowding_results[0] = 1 # extreme point has the max crowding distance
# extreme point has the max crowding distance
crowding_results[pop_size - 1] = 1
sorted_normalized_fitness_values = np.sort(
normalized_fitness_values[:, i])
sorted_normalized_values_index = np.argsort(
normalized_fitness_values[:, i])
# crowding distance calculation. Say for fitness1[i], crowding = fitness1[i+1] - fitness1[i-1]
crowding_results[1:pop_size - 1] = (sorted_normalized_fitness_values[2:pop_size] -
sorted_normalized_fitness_values[0:pop_size - 2])
re_sorting = np.argsort(sorted_normalized_values_index)
matrix_for_crowding[:, i] = crowding_results[re_sorting]
# on fitness1 - fitness2 plot, each point on pareto front has crowding distance number
crowding_distance = np.sum(matrix_for_crowding, axis=1)
return crowding_distance # arr(pop_size,)
# Crowding distance is used to maintain diversity of solutions on Pareto front.
# Remove some amount of solutions that are clumped together to much
def remove_using_crowding(fitness_values, number_solutions_needed):
pop_index = np.arange(fitness_values.shape[0])
crowding_distance = crowding_calculation(fitness_values)
selected_pop_index = np.zeros(number_solutions_needed)
selected_fitness_values = np.zeros((number_solutions_needed, len(
fitness_values[0, :]))) # arr(num_sol_needed x 2)
for i in range(number_solutions_needed):
pop_size = pop_index.shape[0]
solution_1 = rn.randint(0, pop_size - 1)
solution_2 = rn.randint(0, pop_size - 1)
if crowding_distance[solution_1] >= crowding_distance[solution_2]:
# solution 1 is better than solution 2
selected_pop_index[i] = pop_index[solution_1]
selected_fitness_values[i, :] = fitness_values[solution_1, :]
pop_index = np.delete(pop_index, (solution_1), axis=0)
fitness_values = np.delete(fitness_values, (solution_1), axis=0)
crowding_distance = np.delete(
crowding_distance, (solution_1), axis=0)
else:
# solution 2 is better than solution 1
selected_pop_index[i] = pop_index[solution_2]
selected_fitness_values[i, :] = fitness_values[solution_2, :]
pop_index = np.delete(pop_index, (solution_2), axis=0)
fitness_values = np.delete(fitness_values, (solution_2), axis=0)
crowding_distance = np.delete(
crowding_distance, (solution_2), axis=0)
selected_pop_index = np.asarray(selected_pop_index, dtype=int)
return selected_pop_index # arr(n_sol_needed,)
# find indices of solutions that dominate others
def pareto_front_finding(fitness_values, pop_index):
pop_size = fitness_values.shape[0]
pareto_front = np.ones(pop_size, dtype=bool) # all True initially
for i in range(pop_size):
for j in range(pop_size):
if all(fitness_values[j] <= fitness_values[i]) and any(fitness_values[j] < fitness_values[i]):
# i is not in pareto front becouse j dominates i
pareto_front[i] = 0
break
return pop_index[pareto_front] # arr(len_pareto_front,)
# repeat Pareto front selection to build a population within defined size limits
def selection(pop, fitness_values, pop_size):
pop_index_0 = np.arange(pop.shape[0]) # unselected pop ids
pop_index = np.arange(pop.shape[0]) # all pop ids. len = len(pop_size)
pareto_front_index = []
while len(pareto_front_index) < pop_size: # pop_size = initial_pop_size
if len(pop_index_0) == 0:
break
new_pareto_front = pareto_front_finding(
fitness_values[pop_index_0, :], pop_index_0)
total_pareto_size = len(pareto_front_index) + len(new_pareto_front)
# check the size of pareto_front, if larger than pop_size then remove some
if total_pareto_size > pop_size:
number_solutions_needed = pop_size - len(pareto_front_index)
selected_solutions = remove_using_crowding(
fitness_values[new_pareto_front], number_solutions_needed)
new_pareto_front = new_pareto_front[selected_solutions]
pareto_front_index = np.hstack((pareto_front_index, new_pareto_front))
remaining_index = set(pop_index) - set(pareto_front_index)
pop_index_0 = np.array(list(remaining_index))
selected_pop = pop[pareto_front_index.astype(int)]
return selected_pop # arr(pop_size x n_var)
def constraint(pop):
new_pop = np.copy(pop)
delete_index = []
for i, x in enumerate(new_pop):
r = x[0]
h = x[1]
V = (np. pi / 3) * (r ** 2) * h
if V < 200:
delete_index.append(i)
new_pop = np.delete(new_pop, delete_index, 0)
return new_pop
def delete_duplicate(arr):
unique_rows = | np.unique(arr, axis=0) | numpy.unique |
import warnings
import cv2
import numpy as np
from DLBio.rectangles import TopLeftRectangle
import config
DO_DEBUG_RECTANGLES = False
def dice_score(pred, ground_truth):
assert pred.min() >= 0. and pred.max() <= 1.
assert ground_truth.min() >= 0. and ground_truth.max() <= 1.
intersection = (pred * ground_truth).sum()
union = (pred + ground_truth).clip(max=1.).sum()
union = max(1., union)
return {'dice': intersection / union}
def phase_min_pixel_values(pred, ground_truth, phase_min):
out = {}
pred_vals = phase_min[pred > 0].flatten()
gt_vals = phase_min[ground_truth > 0].flatten()
for perc in [50, 75, 95]:
out[f'pred_pxl_{perc}'] = np.percentile(pred_vals, perc)
out[f'gt_pxl_{perc}'] = np.percentile(gt_vals, perc)
return out
def count_hits(pred, ground_truth):
assert pred.min() >= 0. and pred.max() <= 1.
assert ground_truth.min() >= 0. and ground_truth.max() <= 1.
# get rectangles around connected components
rect_p = get_rectangle_array(pred)
#ground_truth = get_rectangle_array(ground_truth)
rect_gt = get_rectangle_array(ground_truth)
if rect_gt is None:
warnings.warn('No cells found for Ground truth')
return None
if rect_p is None:
warnings.warn('No cells found for Prediction')
return None
# returns Matrix of shape num_pred x num_gt
rect_ious = estimate_rect_iou(rect_p, rect_gt)
out = greedy_match(rect_ious, rect_p, rect_gt)
return out
def greedy_match(rect_ious, pred, gt, match_thres=config.MATCH_THRES):
num_predictions = rect_ious.shape[0]
num_ground_truths = rect_ious.shape[1]
unmatched_pred = list(range(num_predictions))
unnmatched_gt = list(range(num_ground_truths))
# try to find a match for each ground truth cell
for i in range(num_ground_truths):
if not unnmatched_gt:
continue
tmp = np.argmax(rect_ious[unmatched_pred, i])
index = unmatched_pred[tmp]
if rect_ious[index, i] >= match_thres:
unmatched_pred.remove(index)
unnmatched_gt.remove(i)
# predictions = true_positives + false_positives
false_positives = len(unmatched_pred)
true_positives = num_predictions - false_positives
# ground_truth = true_positives + false_negatives
false_negatives = num_ground_truths - true_positives
# look which kind of cells are not detected (area-wise...)
out = {
'tps': true_positives,
'fps': false_positives,
'fns': false_negatives,
'num_pred_cells': true_positives + false_positives,
'num_gt_cells': true_positives + false_negatives
}
out.update({
'precision': true_positives / (true_positives + false_positives),
'recall': true_positives / (true_positives + false_negatives),
})
out['precision'] = max(out['precision'], 1e-9)
out['recall'] = max(out['recall'], 1e-9)
f1_score = 2. * out['precision'] * out['recall']
if f1_score < 1e-9:
f1_score = 0.
f1_score = f1_score / (out['precision'] + out['recall'])
out.update({
'f1_score': f1_score
})
# check areas for different types of detections
w_pred = pred[:, cv2.CC_STAT_WIDTH]
h_pred = pred[:, cv2.CC_STAT_HEIGHT]
w_gt = gt[:, cv2.CC_STAT_WIDTH]
h_gt = gt[:, cv2.CC_STAT_HEIGHT]
area_all = np.concatenate([w_pred * h_pred, w_gt * h_gt], 0).mean()
if len(unmatched_pred) > 0:
area_fps = (w_pred[unmatched_pred] * h_pred[unmatched_pred]).mean()
else:
area_fps = -1.
if len(unnmatched_gt) > 0:
area_fns = (w_gt[unnmatched_gt] * h_gt[unnmatched_gt]).mean()
else:
area_fns = -1.
out.update(
{
'area_all': area_all,
'area_fps': area_fps,
'area_fns': area_fns
}
)
return out
def estimate_rect_iou(pred, ground_truth):
X0 = pred[:, cv2.CC_STAT_LEFT]
X1 = ground_truth[:, cv2.CC_STAT_LEFT]
# left = max(x0, x1)
left = _compute_for_all_pairs(X0, X1, lambda x: np.max(x, -1))
Y0 = pred[:, cv2.CC_STAT_TOP]
Y1 = ground_truth[:, cv2.CC_STAT_TOP]
# top = max(y0, y1)
top = _compute_for_all_pairs(Y0, Y1, lambda x: np.max(x, -1))
# right = min(x0 + w0, x1 + w1)
W0 = pred[:, cv2.CC_STAT_WIDTH]
W1 = ground_truth[:, cv2.CC_STAT_WIDTH]
right = _compute_for_all_pairs(X0 + W0, X1 + W1, lambda x: np.min(x, -1))
# bottom = min(y0 + h0, y1 + h1)
H0 = pred[:, cv2.CC_STAT_HEIGHT]
H1 = ground_truth[:, cv2.CC_STAT_HEIGHT]
bottom = _compute_for_all_pairs(Y0 + H0, Y1 + H1, lambda x: np.min(x, -1))
# a = max(right - left, 0)
# b = max(bottom - top, 0)
A = (right - left).clip(min=0)
B = (bottom - top).clip(min=0)
# area_intersection = a * b
intersection = A * B
# union = W0 * H0 + W1 * H1 - intersection
union = _compute_for_all_pairs(
W0 * H0, W1 * H1, lambda x: x[..., 0] + x[..., 1])
union = union - intersection
# make sure to not divide by zero
union[union == 0] = 1.
rectangle_iou = intersection / union
return rectangle_iou
def _compute_for_all_pairs(P, Q, func):
NP = P.shape[0]
NQ = Q.shape[0]
P = P.reshape(-1, 1)
Q = Q.reshape(1, -1)
P = np.repeat(P, NQ, 1)
Q = | np.repeat(Q, NP, 0) | numpy.repeat |
import pickle
from hashlib import md5
from shutil import which
from textwrap import dedent
import geopandas
import numpy as np
import pandas as pd
import pytest
from shapely import wkt
from shapely.geometry import Point
import swn
import swn.modflow
from swn.file import gdf_to_shapefile
from swn.spatial import force_2d, interp_2d_to_3d, wkt_to_geoseries
if __name__ != "__main__":
from .conftest import datadir, matplotlib, plt
else:
from conftest import datadir, matplotlib, plt
try:
import flopy
except ImportError:
pytest.skip("skipping tests that require flopy", allow_module_level=True)
mfnwt_exe = which("mfnwt")
mf2005_exe = which("mf2005")
requires_mfnwt = pytest.mark.skipif(not mfnwt_exe, reason="requires mfnwt")
requires_mf2005 = pytest.mark.skipif(not mf2005_exe, reason="requires mf2005")
if mfnwt_exe is None:
mfnwt_exe = "mfnwt"
if mf2005_exe is None:
mf2005_exe = "mf2005"
# same valid network used in test_basic
n3d_lines = wkt_to_geoseries([
"LINESTRING Z (60 100 14, 60 80 12)",
"LINESTRING Z (40 130 15, 60 100 14)",
"LINESTRING Z (70 130 15, 60 100 14)",
])
def get_basic_swn(has_z: bool = True, has_diversions: bool = False):
if has_z:
n = swn.SurfaceWaterNetwork.from_lines(n3d_lines)
else:
n = swn.SurfaceWaterNetwork.from_lines(force_2d(n3d_lines))
if has_diversions:
diversions = geopandas.GeoDataFrame(geometry=[
Point(58, 97), Point(62, 97), Point(61, 89), Point(59, 89)])
n.set_diversions(diversions=diversions)
return n
def get_basic_modflow(
outdir=".", with_top: bool = False, nper: int = 1,
hk=1e-2, rech=1e-4):
"""Returns a basic Flopy MODFLOW model"""
if with_top:
top = np.array([
[16.0, 15.0],
[15.0, 15.0],
[14.0, 14.0],
])
else:
top = 15.0
m = flopy.modflow.Modflow(
version="mf2005", exe_name=mf2005_exe, model_ws=outdir)
flopy.modflow.ModflowDis(
m, nlay=1, nrow=3, ncol=2, nper=nper,
delr=20.0, delc=20.0, top=top, botm=10.0,
xul=30.0, yul=130.0)
_ = flopy.modflow.ModflowBas(m, strt=top, stoper=5.0)
_ = flopy.modflow.ModflowSip(m)
_ = flopy.modflow.ModflowLpf(m, ipakcb=52, laytyp=0, hk=hk)
_ = flopy.modflow.ModflowRch(m, ipakcb=52, rech=rech)
_ = flopy.modflow.ModflowOc(
m, stress_period_data={
(0, 0): ["print head", "save head", "save budget"]})
return m
def read_head(hed_fname, reaches=None):
"""Reads MODFLOW Head file
If reaches is not None, it is modified inplace to add a "head" column
Returns numpy array
"""
with flopy.utils.HeadFile(hed_fname) as b:
data = b.get_data()
if reaches is not None:
reaches["head"] = data[reaches["k"], reaches["i"], reaches["j"]]
return data
def read_budget(bud_fname, text, reaches=None, colname=None):
"""Reads MODFLOW cell-by-cell file
If reaches is not None, it is modified inplace to add data in "colname"
Returns numpy array
"""
with flopy.utils.CellBudgetFile(bud_fname) as b:
res = b.get_data(text=text)
if len(res) != 1:
from warnings import warn
warn(f"get_data(text={text!r}) returned more than one array")
data = res[0]
if reaches is not None:
if isinstance(data, np.recarray) and "q" in data.dtype.names:
reaches[colname] = data["q"]
else:
reaches[colname] = data[reaches["k"], reaches["i"], reaches["j"]]
return data
def read_sfl(sfl_fname, reaches=None):
"""Reads MODFLOW stream flow listing ASCII file
If reaches is not None, it is modified inplace to add new columns
Returns DataFrame of stream flow listing file
"""
sfl = flopy.utils.SfrFile(sfl_fname).get_dataframe()
# this index modification is only valid for steady models
if sfl.index.name is None:
sfl.index += 1
sfl.index.name = "reachID"
if "col16" in sfl.columns:
sfl.rename(columns={"col16": "gradient"}, inplace=True)
dont_copy = ["layer", "row", "column", "segment", "reach", "k", "i", "j"]
if reaches is not None:
if not (reaches.index == sfl.index).all():
raise IndexError("reaches.index is different")
for cn in sfl.columns:
if cn == "kstpkper": # split tuple into two columns
reaches["kstp"] = sfl[cn].apply(lambda x: x[0])
reaches["kper"] = sfl[cn].apply(lambda x: x[1])
elif cn not in dont_copy:
reaches[cn] = sfl[cn]
return sfl
def test_init_errors():
with pytest.raises(ValueError, match="expected 'logger' to be Logger"):
swn.SwnModflow(object())
def test_from_swn_flopy_errors():
n = get_basic_swn()
m = flopy.modflow.Modflow(version="mf2005", exe_name=mf2005_exe)
_ = flopy.modflow.ModflowDis(
m, nlay=1, nrow=3, ncol=2, nper=4, delr=20.0, delc=20.0)
with pytest.raises(
ValueError,
match="swn must be a SurfaceWaterNetwork object"):
swn.SwnModflow.from_swn_flopy(object(), m)
_ = flopy.modflow.ModflowBas(m)
m.modelgrid.set_coord_info(epsg=2193)
# n.segments.crs = {"init": "epsg:27200"}
# with pytest.raises(
# ValueError,
# match="CRS for segments and modelgrid are different"):
# nm = swn.SwnModflow.from_swn_flopy(n, m)
n.segments.crs = None
with pytest.raises(
ValueError,
match="modelgrid extent does not cover segments extent"):
swn.SwnModflow.from_swn_flopy(n, m)
m.modelgrid.set_coord_info(xoff=30.0, yoff=70.0)
with pytest.raises(ValueError, match="ibound_action must be one of"):
swn.SwnModflow.from_swn_flopy(n, m, ibound_action="foo")
@pytest.mark.parametrize("has_diversions", [False, True], ids=["nodiv", "div"])
def test_new_segment_data(has_diversions):
n = get_basic_swn(has_diversions=has_diversions)
m = get_basic_modflow()
nm = swn.SwnModflow.from_swn_flopy(n, m)
assert nm.segment_data is None
assert nm.segment_data_ts is None
nm.new_segment_data()
assert nm.segment_data_ts == {}
assert (nm.segment_data.icalc == 0).all()
if has_diversions:
pd.testing.assert_index_equal(
nm.segment_data.index,
pd.Int64Index([1, 2, 3, 4, 5, 6, 7], name="nseg"))
assert list(nm.segment_data.segnum) == [1, 2, 0, -1, -1, -1, -1]
assert list(nm.segment_data.divid) == [0, 0, 0, 0, 1, 2, 3]
assert list(nm.segment_data.outseg) == [3, 3, 0, 0, 0, 0, 0]
assert list(nm.segment_data.iupseg) == [0, 0, 0, 1, 2, 3, 3]
else:
pd.testing.assert_index_equal(
nm.segment_data.index,
pd.Int64Index([1, 2, 3], name="nseg"))
assert list(nm.segment_data.segnum) == [1, 2, 0]
assert "divid" not in nm.segment_data.columns
assert list(nm.segment_data.outseg) == [3, 3, 0]
assert list(nm.segment_data.iupseg) == [0, 0, 0]
@requires_mf2005
def test_n3d_defaults(tmp_path):
n = get_basic_swn()
m = get_basic_modflow(tmp_path)
nm = swn.SwnModflow.from_swn_flopy(n, m)
nm.default_segment_data()
nm.set_sfr_obj(ipakcb=52, istcb2=-53)
assert m.sfr.ipakcb == 52
assert m.sfr.istcb2 == -53
# Data set 1c
assert abs(m.sfr.nstrm) == 7
assert m.sfr.nss == 3
assert m.sfr.const == 86400.0
# Data set 2
# Base-0
assert list(m.sfr.reach_data.node) == [0, 1, 3, 1, 3, 3, 5]
assert list(m.sfr.reach_data.k) == [0, 0, 0, 0, 0, 0, 0]
assert list(m.sfr.reach_data.i) == [0, 0, 1, 0, 1, 1, 2]
assert list(m.sfr.reach_data.j) == [0, 1, 1, 1, 1, 1, 1]
# Base-1
assert list(m.sfr.reach_data.reachID) == [1, 2, 3, 4, 5, 6, 7]
assert list(m.sfr.reach_data.iseg) == [1, 1, 1, 2, 2, 3, 3]
assert list(m.sfr.reach_data.ireach) == [1, 2, 3, 1, 2, 1, 2]
np.testing.assert_array_almost_equal(
m.sfr.reach_data.rchlen,
[18.027756, 6.009252, 12.018504, 21.081851, 10.540926, 10.0, 10.0])
np.testing.assert_array_almost_equal(
m.sfr.reach_data.strtop,
[14.75, 14.416667, 14.16666667, 14.66666667, 14.16666667, 13.5, 12.5])
np.testing.assert_array_almost_equal(
m.sfr.reach_data.slope,
[0.027735, 0.027735, 0.027735, 0.031622775, 0.031622775, 0.1, 0.1])
np.testing.assert_array_equal(m.sfr.reach_data.strthick, [1.0] * 7)
np.testing.assert_array_equal(m.sfr.reach_data.strhc1, [1.0] * 7)
# Data set 6
assert len(m.sfr.segment_data) == 1
sd = m.sfr.segment_data[0]
np.testing.assert_array_equal(sd.nseg, [1, 2, 3])
np.testing.assert_array_equal(sd.icalc, [1, 1, 1])
np.testing.assert_array_equal(sd.outseg, [3, 3, 0])
np.testing.assert_array_equal(sd.iupseg, [0, 0, 0])
np.testing.assert_array_equal(sd.iprior, [0, 0, 0])
np.testing.assert_array_almost_equal(sd.flow, [0.0, 0.0, 0.0])
np.testing.assert_array_almost_equal(sd.runoff, [0.0, 0.0, 0.0])
np.testing.assert_array_almost_equal(sd.etsw, [0.0, 0.0, 0.0])
np.testing.assert_array_almost_equal(sd.pptsw, [0.0, 0.0, 0.0])
np.testing.assert_array_almost_equal(sd.roughch, [0.024, 0.024, 0.024])
np.testing.assert_array_almost_equal(sd.hcond1, [1.0, 1.0, 1.0])
np.testing.assert_array_almost_equal(sd.thickm1, [1.0, 1.0, 1.0])
np.testing.assert_array_almost_equal(sd.elevup, [14.75, 14.66666667, 13.5])
np.testing.assert_array_almost_equal(sd.width1, [10.0, 10.0, 10.0])
np.testing.assert_array_almost_equal(sd.hcond2, [1.0, 1.0, 1.0])
np.testing.assert_array_almost_equal(sd.thickm2, [1.0, 1.0, 1.0])
np.testing.assert_array_almost_equal(
sd.elevdn, [14.16666667, 14.16666667, 12.5])
np.testing.assert_array_almost_equal(sd.width2, [10.0, 10.0, 10.0])
assert repr(nm) == dedent("""\
<SwnModflow: flopy mf2005 'modflowtest'
7 in reaches (reachID): [1, 2, ..., 6, 7]
3 in segment_data (nseg): [1, 2, 3]
3 from segments: [1, 2, 0]
1 stress period with perlen: [1.0] />""")
if matplotlib:
_ = nm.plot()
plt.close()
# Run model and read outputs
m.model_ws = str(tmp_path)
m.write_input()
success, buff = m.run_model()
assert success
heads = read_head(tmp_path / "modflowtest.hds")
sl = read_budget(tmp_path / "modflowtest.cbc",
"STREAM LEAKAGE", nm.reaches, "sfrleakage")
sf = read_budget(tmp_path / "modflowtest.sfr.bin",
"STREAMFLOW OUT", nm.reaches, "sfr_Q")
# Write some files
nm.grid_cells.to_file(tmp_path / "grid_cells.shp")
gdf_to_shapefile(nm.reaches, tmp_path / "reaches.shp")
gdf_to_shapefile(nm.segments, tmp_path / "segments.shp")
# Check results
assert heads.shape == (1, 3, 2)
np.testing.assert_array_almost_equal(
heads,
np.array([[
[14.604243, 14.409589],
[14.172486, 13.251323],
[13.861891, 12.751296]]], np.float32))
np.testing.assert_array_almost_equal(
sl["q"],
np.array([-0.00859839, 0.00420513, 0.00439326, 0.0, 0.0,
-0.12359641, -0.12052996], np.float32))
np.testing.assert_array_almost_equal(
sf["q"],
np.array([0.00859839, 0.00439326, 0.0, 0.0, 0.0,
0.12359641, 0.24412636], np.float32))
def test_model_property():
nm = swn.SwnModflow()
with pytest.raises(
ValueError, match="model must be a flopy Modflow object"):
nm.model = 0
m = flopy.modflow.Modflow()
with pytest.raises(ValueError, match="DIS package required"):
nm.model = m
_ = flopy.modflow.ModflowDis(
m, nlay=1, nrow=3, ncol=2, delr=20.0, delc=20.0, top=15.0, botm=10.0,
xul=30.0, yul=130.0, start_datetime="2001-02-03")
with pytest.raises(ValueError, match="BAS6 package required"):
nm.model = m
_ = flopy.modflow.ModflowBas(m, strt=15.0, stoper=5.0)
assert not hasattr(nm, "time_index")
assert not hasattr(nm, "grid_cells")
# Success!
nm.model = m
pd.testing.assert_index_equal(
nm.time_index,
pd.DatetimeIndex(["2001-02-03"], dtype="datetime64[ns]"))
assert nm.grid_cells.shape == (6, 2)
# Swap model with same and with another
# same object
nm.model = m
dis_args = {
"nper": 1, "nlay": 1, "nrow": 3, "ncol": 2, "delr": 20.0, "delc": 20.0,
"xul": 30.0, "yul": 130.0, "start_datetime": "2001-03-02"}
m = flopy.modflow.Modflow()
_ = flopy.modflow.ModflowDis(m, **dis_args)
_ = flopy.modflow.ModflowBas(m)
# this is allowed
nm.model = m
dis_args_replace = {
"nper": 2, "nrow": 4, "ncol": 3, "delr": 30.0, "delc": 40.0,
"xul": 20.0, "yul": 120.0}
for vn, vr in dis_args_replace.items():
# print(f"{vn}: {vr}")
dis_args_use = dis_args.copy()
dis_args_use[vn] = vr
m = flopy.modflow.Modflow()
_ = flopy.modflow.ModflowDis(m, **dis_args_use)
_ = flopy.modflow.ModflowBas(m)
# this is not allowed
with pytest.raises(AttributeError, match="properties are too differe"):
nm.model = m
def test_time_index():
n = get_basic_swn()
m = get_basic_modflow(nper=12)
m.dis.start_datetime = "1999-07-01"
m.dis.perlen = [31, 31, 30, 31, 30, 31, 31, 29, 31, 30, 31, 30]
nm = swn.SwnModflow.from_swn_flopy(n, m)
assert nm.time_index.freqstr == "MS" # "month start" or <MonthBegin>
assert list(nm.time_index.day) == [1] * 12
assert list(nm.time_index.month) == list((np.arange(12) + 6) % 12 + 1)
assert list(nm.time_index.year) == [1999] * 6 + [2000] * 6
def test_set_segment_data_from_scalar():
n = get_basic_swn(has_diversions=True)
m = get_basic_modflow(nper=2)
nm = swn.SwnModflow.from_swn_flopy(n, m)
nm.set_segment_data_from_scalar("icalc", 0)
assert list(nm.segment_data.icalc) == [0, 0, 0, 0, 0, 0, 0]
nm.set_segment_data_from_scalar("icalc", 1, "segments")
assert list(nm.segment_data.icalc) == [1, 1, 1, 0, 0, 0, 0]
nm.set_segment_data_from_scalar("icalc", 2, "diversions")
assert list(nm.segment_data.icalc) == [1, 1, 1, 2, 2, 2, 2]
# check that segment_data_ts item is dropped by this method
nm.segment_data_ts["flow"] = 1.2
assert nm.segment_data_ts["flow"] == 1.2
nm.set_segment_data_from_scalar("flow", 2.3)
assert "flow" not in nm.segment_data_ts
# check errors
with pytest.raises(KeyError, match="could not find 'nope'"):
nm.set_segment_data_from_scalar("nope", 1.0)
with pytest.raises(ValueError, match="data is not scalar"):
nm.set_segment_data_from_scalar("flow", [1.0])
with pytest.raises(ValueError, match="'which' should be one of"):
nm.set_segment_data_from_scalar("flow", 1.0, "nope")
def test_set_segment_data_from_segments():
n = get_basic_swn(has_diversions=True)
n.segments["upstream_area"] = n.segments["upstream_length"] ** 2 * 100
n.estimate_width()
m = get_basic_modflow(nper=2)
nm = swn.SwnModflow.from_swn_flopy(n, m)
nm.new_segment_data()
assert list(nm.segment_data.icalc) == [0, 0, 0, 0, 0, 0, 0]
assert list(nm.segment_data.width1) == [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
# scalar -- most other tests are in test_set_segment_data_from_scalar
nm.set_segment_data_from_segments("icalc", 1)
assert list(nm.segment_data.icalc) == [1, 1, 1, 0, 0, 0, 0]
# dict
nm.set_segment_data_from_segments("flow", {0: 0.1, 2: 1.2, 1: 2.3})
assert list(nm.segment_data.flow) == [2.3, 1.2, 0.1, 0.0, 0.0, 0.0, 0.0]
nm.set_segment_data_from_segments("flow", {})
assert list(nm.segment_data.flow) == [2.3, 1.2, 0.1, 0.0, 0.0, 0.0, 0.0]
nm.set_segment_data_from_segments("flow", {0: 4.0})
assert list(nm.segment_data.flow) == [2.3, 1.2, 4.0, 0.0, 0.0, 0.0, 0.0]
# errors
with pytest.raises(KeyError, match="dict has a disjoint segnum set"):
nm.set_segment_data_from_segments("flow", {"1": 0.1})
with pytest.raises(KeyError, match="dict has a disjoint segnum set"):
nm.set_segment_data_from_segments("flow", {3: 0.1})
with pytest.raises(KeyError, match="dict has 1 key not found in segnum"):
nm.set_segment_data_from_segments("flow", {3: 0.1, 2: 1.2})
# series
nm.set_segment_data_from_segments("flow", pd.Series([1.1, 2.2, 3.3]))
assert list(nm.segment_data.flow) == [2.2, 3.3, 1.1, 0.0, 0.0, 0.0, 0.0]
nm.set_segment_data_from_segments("flow", pd.Series([], dtype=float))
assert list(nm.segment_data.flow) == [2.2, 3.3, 1.1, 0.0, 0.0, 0.0, 0.0]
nm.set_segment_data_from_segments("flow", pd.Series([4.0], index=[1]))
assert list(nm.segment_data.flow) == [4.0, 3.3, 1.1, 0.0, 0.0, 0.0, 0.0]
nm.set_segment_data_from_segments("width1", n.segments.width)
np.testing.assert_array_almost_equal(
nm.segment_data.width1,
[1.766139, 1.721995, 2.292183, 0.0, 0.0, 0.0, 0.0])
# frame
assert "runoff" not in nm.segment_data_ts
nm.set_segment_data_from_segments(
"runoff",
pd.DataFrame(index=nm.time_index))
assert "runoff" not in nm.segment_data_ts
nm.set_segment_data_from_segments(
"runoff",
pd.DataFrame({0: [1.1, 2.2]}, index=nm.time_index))
assert list(nm.segment_data.runoff) == [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
pd.testing.assert_frame_equal(
nm.segment_data_ts["runoff"],
pd.DataFrame({3: [1.1, 2.2]}, index=nm.time_index))
nm.set_segment_data_from_segments(
"runoff",
pd.DataFrame(index=nm.time_index))
pd.testing.assert_frame_equal(
nm.segment_data_ts["runoff"],
pd.DataFrame({3: [1.1, 2.2]}, index=nm.time_index))
# check that segment_data_ts item is not dropped by this method
nm.set_segment_data_from_segments("runoff", {0: 0.1})
assert "runoff" in nm.segment_data_ts
# check errors
with pytest.raises(TypeError, match="missing 1 required positional"):
nm.set_segment_data_from_segments(1)
with pytest.raises(ValueError, match="name must be str typ"):
nm.set_segment_data_from_segments(1, 2)
@pytest.mark.parametrize(
"nper,inflow,expected",
[(1, {3: 9.6, 4: 9.7}, {1: 19.3}),
(1, {}, {}),
(2, {3: 9.6, 4: 9.7}, {1: 19.3}),
(2, {}, {}),
])
def test_set_segment_data_inflow(nper, inflow, expected):
n = get_basic_swn()
n.segments.at[1, "from_segnums"] = {3, 4}
m = get_basic_modflow(nper=nper)
nm = swn.SwnModflow.from_swn_flopy(n, m)
assert "inflow_segnums" not in nm.segments.columns
assert nm.segment_data is None
nm.set_segment_data_inflow(inflow)
if inflow:
assert list(nm.segments.inflow_segnums) == [set(), {3, 4}, set()]
assert list(nm.segment_data.inflow_segnums) == [{3, 4}, set(), set()]
else:
assert "inflow_segnums" not in nm.segments.columns
assert "inflow_segnums" not in nm.segment_data.columns
expected = pd.Series(expected, dtype=float)
if hasattr(nm.segment_data_ts, "inflow"):
pd.testing.assert_frame_equal(
nm.segment_data["inflow"],
pd.DataFrame(expected, index=nm.time_index))
else:
expected_series = pd.Series(
0.0, index=nm.segment_data.index, name="inflow")
expected_series.update(expected)
pd.testing.assert_series_equal(
nm.segment_data["inflow"],
expected_series)
if matplotlib:
_ = nm.plot()
plt.close()
@pytest.mark.parametrize(
"has_z", [False, True], ids=["n2d", "n3d"])
def test_default_segment_data(has_z):
n = get_basic_swn(has_z=has_z)
m = get_basic_modflow()
nm = swn.SwnModflow.from_swn_flopy(n, m)
assert nm.segment_data is None
assert nm.segment_data_ts is None
nm.default_segment_data()
assert nm.segment_data is not None
assert nm.segment_data_ts == {}
sd = nm.segment_data
assert sd.index.name == "nseg"
np.testing.assert_array_equal(sd.index, [1, 2, 3])
np.testing.assert_array_equal(sd.icalc, [1, 1, 1])
np.testing.assert_array_equal(sd.outseg, [3, 3, 0])
np.testing.assert_array_equal(sd.iupseg, [0, 0, 0])
np.testing.assert_array_equal(sd.iprior, [0, 0, 0])
np.testing.assert_array_almost_equal(sd.flow, [0.0, 0.0, 0.0])
np.testing.assert_array_almost_equal(sd.runoff, [0.0, 0.0, 0.0])
np.testing.assert_array_almost_equal(sd.etsw, [0.0, 0.0, 0.0])
np.testing.assert_array_almost_equal(sd.pptsw, [0.0, 0.0, 0.0])
np.testing.assert_array_almost_equal(sd.roughch, [0.024, 0.024, 0.024])
np.testing.assert_array_almost_equal(sd.hcond1, [1.0, 1.0, 1.0])
np.testing.assert_array_almost_equal(sd.thickm1, [1.0, 1.0, 1.0])
if has_z:
expected_elevup = [14.75, 14.66666667, 13.5]
expected_elevdn = [14.16666667, 14.16666667, 12.5]
else:
expected_elevup = [15.0, 15.0, 15.0]
expected_elevdn = [15.0, 15.0, 15.0]
np.testing.assert_array_almost_equal(sd.elevup, expected_elevup)
np.testing.assert_array_almost_equal(sd.width1, [10.0, 10.0, 10.0])
np.testing.assert_array_almost_equal(sd.hcond2, [1.0, 1.0, 1.0])
np.testing.assert_array_almost_equal(sd.thickm2, [1.0, 1.0, 1.0])
np.testing.assert_array_almost_equal(sd.elevdn, expected_elevdn)
np.testing.assert_array_almost_equal(sd.width2, [10.0, 10.0, 10.0])
# auto determine width
n.catchments = wkt_to_geoseries([
"POLYGON ((35 100, 75 100, 75 80, 35 80, 35 100))",
"POLYGON ((35 135, 60 135, 60 100, 35 100, 35 135))",
"POLYGON ((60 135, 75 135, 75 100, 60 100, 60 135))",
])
nm = swn.SwnModflow.from_swn_flopy(n, m)
nm.default_segment_data()
sd = nm.segment_data
np.testing.assert_array_almost_equal(
sd.width1, [1.4456947376374667, 1.439700753532406, 1.4615011177787172])
np.testing.assert_array_almost_equal(
sd.width2, [1.4456947376374667, 1.439700753532406, 1.4615011177787172])
@requires_mf2005
def test_n3d_vars(tmp_path):
# Repeat, but with min_slope enforced, and other options
n = get_basic_swn()
# manually add outside flow from extra segnums, referenced with inflow
n.segments.at[1, "from_segnums"] = {3, 4}
m = get_basic_modflow(tmp_path, hk=1.0, rech=0.01)
nm = swn.SwnModflow.from_swn_flopy(n, m)
nm.set_reach_slope(min_slope=0.03)
nm.default_segment_data(hyd_cond1=2, thickness1=2.0)
nm.set_segment_data_inflow({3: 9.6, 4: 9.7})
nm.set_segment_data_from_segments("flow", {1: 18.4})
nm.set_segment_data_from_segments("runoff", {1: 5})
nm.set_segment_data_from_segments("pptsw", {2: 1.8})
nm.set_segment_data_from_segments("etsw", {0: 0.01, 1: 0.02, 2: 0.03})
nm.set_sfr_obj(ipakcb=52, istcb2=-53)
# Data set 2
np.testing.assert_array_almost_equal(
m.sfr.reach_data.rchlen,
[18.027756, 6.009252, 12.018504, 21.081851, 10.540926, 10.0, 10.0])
np.testing.assert_array_almost_equal(
m.sfr.reach_data.strtop,
[14.75, 14.416667, 14.166667, 14.666667, 14.166667, 13.5, 12.5])
np.testing.assert_array_almost_equal(
m.sfr.reach_data.slope,
[0.03, 0.03, 0.03, 0.031622775, 0.031622775, 0.1, 0.1])
np.testing.assert_array_equal(m.sfr.reach_data.strthick, [2.0] * 7)
np.testing.assert_array_equal(m.sfr.reach_data.strhc1, [2.0] * 7)
# Data set 6
assert len(m.sfr.segment_data) == 1
sd = m.sfr.segment_data[0]
| np.testing.assert_array_equal(sd.nseg, [1, 2, 3]) | numpy.testing.assert_array_equal |
# This module has been generated automatically from space group information
# obtained from the Computational Crystallography Toolbox
#
"""
Space groups
This module contains a list of all the 230 space groups that can occur in
a crystal. The variable space_groups contains a dictionary that maps
space group numbers and space group names to the corresponding space
group objects.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 The Mosaic Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file LICENSE.txt, distributed as part of this software.
#-----------------------------------------------------------------------------
import numpy as N
class SpaceGroup(object):
"""
Space group
All possible space group objects are created in this module. Other
modules should access these objects through the dictionary
space_groups rather than create their own space group objects.
"""
def __init__(self, number, symbol, transformations):
"""
:param number: the number assigned to the space group by
international convention
:type number: int
:param symbol: the Hermann-Mauguin space-group symbol as used
in PDB and mmCIF files
:type symbol: str
:param transformations: a list of space group transformations,
each consisting of a tuple of three
integer arrays (rot, tn, td), where
rot is the rotation matrix and tn/td
are the numerator and denominator of the
translation vector. The transformations
are defined in fractional coordinates.
:type transformations: list
"""
self.number = number
self.symbol = symbol
self.transformations = transformations
self.transposed_rotations = N.array([N.transpose(t[0])
for t in transformations])
self.phase_factors = N.exp(N.array([(-2j*N.pi*t[1])/t[2]
for t in transformations]))
def __repr__(self):
return "SpaceGroup(%d, %s)" % (self.number, repr(self.symbol))
def __len__(self):
"""
:return: the number of space group transformations
:rtype: int
"""
return len(self.transformations)
def symmetryEquivalentMillerIndices(self, hkl):
"""
:param hkl: a set of Miller indices
:type hkl: Scientific.N.array_type
:return: a tuple (miller_indices, phase_factor) of two arrays
of length equal to the number of space group
transformations. miller_indices contains the Miller
indices of each reflection equivalent by symmetry to the
reflection hkl (including hkl itself as the first element).
phase_factor contains the phase factors that must be applied
to the structure factor of reflection hkl to obtain the
structure factor of the symmetry equivalent reflection.
:rtype: tuple
"""
hkls = N.dot(self.transposed_rotations, hkl)
p = N.multiply.reduce(self.phase_factors**hkl, -1)
return hkls, p
space_groups = {}
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(1, 'P 1', transformations)
space_groups[1] = sg
space_groups['P 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(2, 'P -1', transformations)
space_groups[2] = sg
space_groups['P -1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(3, 'P 1 2 1', transformations)
space_groups[3] = sg
space_groups['P 1 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(4, 'P 1 21 1', transformations)
space_groups[4] = sg
space_groups['P 1 21 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(5, 'C 1 2 1', transformations)
space_groups[5] = sg
space_groups['C 1 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(6, 'P 1 m 1', transformations)
space_groups[6] = sg
space_groups['P 1 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(7, 'P 1 c 1', transformations)
space_groups[7] = sg
space_groups['P 1 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(8, 'C 1 m 1', transformations)
space_groups[8] = sg
space_groups['C 1 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(9, 'C 1 c 1', transformations)
space_groups[9] = sg
space_groups['C 1 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(10, 'P 1 2/m 1', transformations)
space_groups[10] = sg
space_groups['P 1 2/m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(11, 'P 1 21/m 1', transformations)
space_groups[11] = sg
space_groups['P 1 21/m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(12, 'C 1 2/m 1', transformations)
space_groups[12] = sg
space_groups['C 1 2/m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(13, 'P 1 2/c 1', transformations)
space_groups[13] = sg
space_groups['P 1 2/c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(14, 'P 1 21/c 1', transformations)
space_groups[14] = sg
space_groups['P 1 21/c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(15, 'C 1 2/c 1', transformations)
space_groups[15] = sg
space_groups['C 1 2/c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(16, 'P 2 2 2', transformations)
space_groups[16] = sg
space_groups['P 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(17, 'P 2 2 21', transformations)
space_groups[17] = sg
space_groups['P 2 2 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(18, 'P 21 21 2', transformations)
space_groups[18] = sg
space_groups['P 21 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(19, 'P 21 21 21', transformations)
space_groups[19] = sg
space_groups['P 21 21 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(20, 'C 2 2 21', transformations)
space_groups[20] = sg
space_groups['C 2 2 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(21, 'C 2 2 2', transformations)
space_groups[21] = sg
space_groups['C 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(22, 'F 2 2 2', transformations)
space_groups[22] = sg
space_groups['F 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(23, 'I 2 2 2', transformations)
space_groups[23] = sg
space_groups['I 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(24, 'I 21 21 21', transformations)
space_groups[24] = sg
space_groups['I 21 21 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(25, 'P m m 2', transformations)
space_groups[25] = sg
space_groups['P m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(26, 'P m c 21', transformations)
space_groups[26] = sg
space_groups['P m c 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(27, 'P c c 2', transformations)
space_groups[27] = sg
space_groups['P c c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(28, 'P m a 2', transformations)
space_groups[28] = sg
space_groups['P m a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(29, 'P c a 21', transformations)
space_groups[29] = sg
space_groups['P c a 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(30, 'P n c 2', transformations)
space_groups[30] = sg
space_groups['P n c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(31, 'P m n 21', transformations)
space_groups[31] = sg
space_groups['P m n 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(32, 'P b a 2', transformations)
space_groups[32] = sg
space_groups['P b a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(33, 'P n a 21', transformations)
space_groups[33] = sg
space_groups['P n a 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(34, 'P n n 2', transformations)
space_groups[34] = sg
space_groups['P n n 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(35, 'C m m 2', transformations)
space_groups[35] = sg
space_groups['C m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(36, 'C m c 21', transformations)
space_groups[36] = sg
space_groups['C m c 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(37, 'C c c 2', transformations)
space_groups[37] = sg
space_groups['C c c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(38, 'A m m 2', transformations)
space_groups[38] = sg
space_groups['A m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(39, 'A b m 2', transformations)
space_groups[39] = sg
space_groups['A b m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(40, 'A m a 2', transformations)
space_groups[40] = sg
space_groups['A m a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(41, 'A b a 2', transformations)
space_groups[41] = sg
space_groups['A b a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(42, 'F m m 2', transformations)
space_groups[42] = sg
space_groups['F m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(43, 'F d d 2', transformations)
space_groups[43] = sg
space_groups['F d d 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(44, 'I m m 2', transformations)
space_groups[44] = sg
space_groups['I m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(45, 'I b a 2', transformations)
space_groups[45] = sg
space_groups['I b a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(46, 'I m a 2', transformations)
space_groups[46] = sg
space_groups['I m a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(47, 'P m m m', transformations)
space_groups[47] = sg
space_groups['P m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(48, 'P n n n :2', transformations)
space_groups[48] = sg
space_groups['P n n n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(49, 'P c c m', transformations)
space_groups[49] = sg
space_groups['P c c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(50, 'P b a n :2', transformations)
space_groups[50] = sg
space_groups['P b a n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(51, 'P m m a', transformations)
space_groups[51] = sg
space_groups['P m m a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(52, 'P n n a', transformations)
space_groups[52] = sg
space_groups['P n n a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(53, 'P m n a', transformations)
space_groups[53] = sg
space_groups['P m n a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(54, 'P c c a', transformations)
space_groups[54] = sg
space_groups['P c c a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(55, 'P b a m', transformations)
space_groups[55] = sg
space_groups['P b a m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(56, 'P c c n', transformations)
space_groups[56] = sg
space_groups['P c c n'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(57, 'P b c m', transformations)
space_groups[57] = sg
space_groups['P b c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(58, 'P n n m', transformations)
space_groups[58] = sg
space_groups['P n n m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(59, 'P m m n :2', transformations)
space_groups[59] = sg
space_groups['P m m n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(60, 'P b c n', transformations)
space_groups[60] = sg
space_groups['P b c n'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(61, 'P b c a', transformations)
space_groups[61] = sg
space_groups['P b c a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(62, 'P n m a', transformations)
space_groups[62] = sg
space_groups['P n m a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(63, 'C m c m', transformations)
space_groups[63] = sg
space_groups['C m c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(64, 'C m c a', transformations)
space_groups[64] = sg
space_groups['C m c a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(65, 'C m m m', transformations)
space_groups[65] = sg
space_groups['C m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(66, 'C c c m', transformations)
space_groups[66] = sg
space_groups['C c c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(67, 'C m m a', transformations)
space_groups[67] = sg
space_groups['C m m a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(68, 'C c c a :2', transformations)
space_groups[68] = sg
space_groups['C c c a :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(69, 'F m m m', transformations)
space_groups[69] = sg
space_groups['F m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(70, 'F d d d :2', transformations)
space_groups[70] = sg
space_groups['F d d d :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(71, 'I m m m', transformations)
space_groups[71] = sg
space_groups['I m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(72, 'I b a m', transformations)
space_groups[72] = sg
space_groups['I b a m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(73, 'I b c a', transformations)
space_groups[73] = sg
space_groups['I b c a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(74, 'I m m a', transformations)
space_groups[74] = sg
space_groups['I m m a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(75, 'P 4', transformations)
space_groups[75] = sg
space_groups['P 4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(76, 'P 41', transformations)
space_groups[76] = sg
space_groups['P 41'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(77, 'P 42', transformations)
space_groups[77] = sg
space_groups['P 42'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(78, 'P 43', transformations)
space_groups[78] = sg
space_groups['P 43'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(79, 'I 4', transformations)
space_groups[79] = sg
space_groups['I 4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(80, 'I 41', transformations)
space_groups[80] = sg
space_groups['I 41'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(81, 'P -4', transformations)
space_groups[81] = sg
space_groups['P -4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(82, 'I -4', transformations)
space_groups[82] = sg
space_groups['I -4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(83, 'P 4/m', transformations)
space_groups[83] = sg
space_groups['P 4/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(84, 'P 42/m', transformations)
space_groups[84] = sg
space_groups['P 42/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(85, 'P 4/n :2', transformations)
space_groups[85] = sg
space_groups['P 4/n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(86, 'P 42/n :2', transformations)
space_groups[86] = sg
space_groups['P 42/n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(87, 'I 4/m', transformations)
space_groups[87] = sg
space_groups['I 4/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(88, 'I 41/a :2', transformations)
space_groups[88] = sg
space_groups['I 41/a :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(89, 'P 4 2 2', transformations)
space_groups[89] = sg
space_groups['P 4 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(90, 'P 4 21 2', transformations)
space_groups[90] = sg
space_groups['P 4 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(91, 'P 41 2 2', transformations)
space_groups[91] = sg
space_groups['P 41 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(92, 'P 41 21 2', transformations)
space_groups[92] = sg
space_groups['P 41 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(93, 'P 42 2 2', transformations)
space_groups[93] = sg
space_groups['P 42 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(94, 'P 42 21 2', transformations)
space_groups[94] = sg
space_groups['P 42 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(95, 'P 43 2 2', transformations)
space_groups[95] = sg
space_groups['P 43 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(96, 'P 43 21 2', transformations)
space_groups[96] = sg
space_groups['P 43 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(97, 'I 4 2 2', transformations)
space_groups[97] = sg
space_groups['I 4 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(98, 'I 41 2 2', transformations)
space_groups[98] = sg
space_groups['I 41 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(99, 'P 4 m m', transformations)
space_groups[99] = sg
space_groups['P 4 m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(100, 'P 4 b m', transformations)
space_groups[100] = sg
space_groups['P 4 b m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(101, 'P 42 c m', transformations)
space_groups[101] = sg
space_groups['P 42 c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(102, 'P 42 n m', transformations)
space_groups[102] = sg
space_groups['P 42 n m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(103, 'P 4 c c', transformations)
space_groups[103] = sg
space_groups['P 4 c c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(104, 'P 4 n c', transformations)
space_groups[104] = sg
space_groups['P 4 n c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(105, 'P 42 m c', transformations)
space_groups[105] = sg
space_groups['P 42 m c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(106, 'P 42 b c', transformations)
space_groups[106] = sg
space_groups['P 42 b c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(107, 'I 4 m m', transformations)
space_groups[107] = sg
space_groups['I 4 m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(108, 'I 4 c m', transformations)
space_groups[108] = sg
space_groups['I 4 c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(109, 'I 41 m d', transformations)
space_groups[109] = sg
space_groups['I 41 m d'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(110, 'I 41 c d', transformations)
space_groups[110] = sg
space_groups['I 41 c d'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(111, 'P -4 2 m', transformations)
space_groups[111] = sg
space_groups['P -4 2 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(112, 'P -4 2 c', transformations)
space_groups[112] = sg
space_groups['P -4 2 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(113, 'P -4 21 m', transformations)
space_groups[113] = sg
space_groups['P -4 21 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(114, 'P -4 21 c', transformations)
space_groups[114] = sg
space_groups['P -4 21 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(115, 'P -4 m 2', transformations)
space_groups[115] = sg
space_groups['P -4 m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(116, 'P -4 c 2', transformations)
space_groups[116] = sg
space_groups['P -4 c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(117, 'P -4 b 2', transformations)
space_groups[117] = sg
space_groups['P -4 b 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(118, 'P -4 n 2', transformations)
space_groups[118] = sg
space_groups['P -4 n 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(119, 'I -4 m 2', transformations)
space_groups[119] = sg
space_groups['I -4 m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(120, 'I -4 c 2', transformations)
space_groups[120] = sg
space_groups['I -4 c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(121, 'I -4 2 m', transformations)
space_groups[121] = sg
space_groups['I -4 2 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(122, 'I -4 2 d', transformations)
space_groups[122] = sg
space_groups['I -4 2 d'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(123, 'P 4/m m m', transformations)
space_groups[123] = sg
space_groups['P 4/m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(124, 'P 4/m c c', transformations)
space_groups[124] = sg
space_groups['P 4/m c c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(125, 'P 4/n b m :2', transformations)
space_groups[125] = sg
space_groups['P 4/n b m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(126, 'P 4/n n c :2', transformations)
space_groups[126] = sg
space_groups['P 4/n n c :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(127, 'P 4/m b m', transformations)
space_groups[127] = sg
space_groups['P 4/m b m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(128, 'P 4/m n c', transformations)
space_groups[128] = sg
space_groups['P 4/m n c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(129, 'P 4/n m m :2', transformations)
space_groups[129] = sg
space_groups['P 4/n m m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(130, 'P 4/n c c :2', transformations)
space_groups[130] = sg
space_groups['P 4/n c c :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(131, 'P 42/m m c', transformations)
space_groups[131] = sg
space_groups['P 42/m m c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(132, 'P 42/m c m', transformations)
space_groups[132] = sg
space_groups['P 42/m c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(133, 'P 42/n b c :2', transformations)
space_groups[133] = sg
space_groups['P 42/n b c :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(134, 'P 42/n n m :2', transformations)
space_groups[134] = sg
space_groups['P 42/n n m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(135, 'P 42/m b c', transformations)
space_groups[135] = sg
space_groups['P 42/m b c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(136, 'P 42/m n m', transformations)
space_groups[136] = sg
space_groups['P 42/m n m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(137, 'P 42/n m c :2', transformations)
space_groups[137] = sg
space_groups['P 42/n m c :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(138, 'P 42/n c m :2', transformations)
space_groups[138] = sg
space_groups['P 42/n c m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(139, 'I 4/m m m', transformations)
space_groups[139] = sg
space_groups['I 4/m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(140, 'I 4/m c m', transformations)
space_groups[140] = sg
space_groups['I 4/m c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(141, 'I 41/a m d :2', transformations)
space_groups[141] = sg
space_groups['I 41/a m d :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(142, 'I 41/a c d :2', transformations)
space_groups[142] = sg
space_groups['I 41/a c d :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(143, 'P 3', transformations)
space_groups[143] = sg
space_groups['P 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(144, 'P 31', transformations)
space_groups[144] = sg
space_groups['P 31'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(145, 'P 32', transformations)
space_groups[145] = sg
space_groups['P 32'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(146, 'R 3 :H', transformations)
space_groups[146] = sg
space_groups['R 3 :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(147, 'P -3', transformations)
space_groups[147] = sg
space_groups['P -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(148, 'R -3 :H', transformations)
space_groups[148] = sg
space_groups['R -3 :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(149, 'P 3 1 2', transformations)
space_groups[149] = sg
space_groups['P 3 1 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(150, 'P 3 2 1', transformations)
space_groups[150] = sg
space_groups['P 3 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(151, 'P 31 1 2', transformations)
space_groups[151] = sg
space_groups['P 31 1 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(152, 'P 31 2 1', transformations)
space_groups[152] = sg
space_groups['P 31 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(153, 'P 32 1 2', transformations)
space_groups[153] = sg
space_groups['P 32 1 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(154, 'P 32 2 1', transformations)
space_groups[154] = sg
space_groups['P 32 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(155, 'R 3 2 :H', transformations)
space_groups[155] = sg
space_groups['R 3 2 :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(156, 'P 3 m 1', transformations)
space_groups[156] = sg
space_groups['P 3 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(157, 'P 3 1 m', transformations)
space_groups[157] = sg
space_groups['P 3 1 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(158, 'P 3 c 1', transformations)
space_groups[158] = sg
space_groups['P 3 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(159, 'P 3 1 c', transformations)
space_groups[159] = sg
space_groups['P 3 1 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(160, 'R 3 m :H', transformations)
space_groups[160] = sg
space_groups['R 3 m :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(161, 'R 3 c :H', transformations)
space_groups[161] = sg
space_groups['R 3 c :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(162, 'P -3 1 m', transformations)
space_groups[162] = sg
space_groups['P -3 1 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(163, 'P -3 1 c', transformations)
space_groups[163] = sg
space_groups['P -3 1 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(164, 'P -3 m 1', transformations)
space_groups[164] = sg
space_groups['P -3 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(165, 'P -3 c 1', transformations)
space_groups[165] = sg
space_groups['P -3 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(166, 'R -3 m :H', transformations)
space_groups[166] = sg
space_groups['R -3 m :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,-1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,-1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,-1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(167, 'R -3 c :H', transformations)
space_groups[167] = sg
space_groups['R -3 c :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(168, 'P 6', transformations)
space_groups[168] = sg
space_groups['P 6'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(169, 'P 61', transformations)
space_groups[169] = sg
space_groups['P 61'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(170, 'P 65', transformations)
space_groups[170] = sg
space_groups['P 65'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(171, 'P 62', transformations)
space_groups[171] = sg
space_groups['P 62'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(172, 'P 64', transformations)
space_groups[172] = sg
space_groups['P 64'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(173, 'P 63', transformations)
space_groups[173] = sg
space_groups['P 63'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(174, 'P -6', transformations)
space_groups[174] = sg
space_groups['P -6'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(175, 'P 6/m', transformations)
space_groups[175] = sg
space_groups['P 6/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(176, 'P 63/m', transformations)
space_groups[176] = sg
space_groups['P 63/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(177, 'P 6 2 2', transformations)
space_groups[177] = sg
space_groups['P 6 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(178, 'P 61 2 2', transformations)
space_groups[178] = sg
space_groups['P 61 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(179, 'P 65 2 2', transformations)
space_groups[179] = sg
space_groups['P 65 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(180, 'P 62 2 2', transformations)
space_groups[180] = sg
space_groups['P 62 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(181, 'P 64 2 2', transformations)
space_groups[181] = sg
space_groups['P 64 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(182, 'P 63 2 2', transformations)
space_groups[182] = sg
space_groups['P 63 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(183, 'P 6 m m', transformations)
space_groups[183] = sg
space_groups['P 6 m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(184, 'P 6 c c', transformations)
space_groups[184] = sg
space_groups['P 6 c c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(185, 'P 63 c m', transformations)
space_groups[185] = sg
space_groups['P 63 c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(186, 'P 63 m c', transformations)
space_groups[186] = sg
space_groups['P 63 m c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(187, 'P -6 m 2', transformations)
space_groups[187] = sg
space_groups['P -6 m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(188, 'P -6 c 2', transformations)
space_groups[188] = sg
space_groups['P -6 c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(189, 'P -6 2 m', transformations)
space_groups[189] = sg
space_groups['P -6 2 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(190, 'P -6 2 c', transformations)
space_groups[190] = sg
space_groups['P -6 2 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(191, 'P 6/m m m', transformations)
space_groups[191] = sg
space_groups['P 6/m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(192, 'P 6/m c c', transformations)
space_groups[192] = sg
space_groups['P 6/m c c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(193, 'P 63/m c m', transformations)
space_groups[193] = sg
space_groups['P 63/m c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(194, 'P 63/m m c', transformations)
space_groups[194] = sg
space_groups['P 63/m m c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(195, 'P 2 3', transformations)
space_groups[195] = sg
space_groups['P 2 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(196, 'F 2 3', transformations)
space_groups[196] = sg
space_groups['F 2 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(197, 'I 2 3', transformations)
space_groups[197] = sg
space_groups['I 2 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(198, 'P 21 3', transformations)
space_groups[198] = sg
space_groups['P 21 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(199, 'I 21 3', transformations)
space_groups[199] = sg
space_groups['I 21 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(200, 'P m -3', transformations)
space_groups[200] = sg
space_groups['P m -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(201, 'P n -3 :2', transformations)
space_groups[201] = sg
space_groups['P n -3 :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(202, 'F m -3', transformations)
space_groups[202] = sg
space_groups['F m -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(203, 'F d -3 :2', transformations)
space_groups[203] = sg
space_groups['F d -3 :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(204, 'I m -3', transformations)
space_groups[204] = sg
space_groups['I m -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(205, 'P a -3', transformations)
space_groups[205] = sg
space_groups['P a -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(206, 'I a -3', transformations)
space_groups[206] = sg
space_groups['I a -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(207, 'P 4 3 2', transformations)
space_groups[207] = sg
space_groups['P 4 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(208, 'P 42 3 2', transformations)
space_groups[208] = sg
space_groups['P 42 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(209, 'F 4 3 2', transformations)
space_groups[209] = sg
space_groups['F 4 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(210, 'F 41 3 2', transformations)
space_groups[210] = sg
space_groups['F 41 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(211, 'I 4 3 2', transformations)
space_groups[211] = sg
space_groups['I 4 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(212, 'P 43 3 2', transformations)
space_groups[212] = sg
space_groups['P 43 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(213, 'P 41 3 2', transformations)
space_groups[213] = sg
space_groups['P 41 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(214, 'I 41 3 2', transformations)
space_groups[214] = sg
space_groups['I 41 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(215, 'P -4 3 m', transformations)
space_groups[215] = sg
space_groups['P -4 3 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(216, 'F -4 3 m', transformations)
space_groups[216] = sg
space_groups['F -4 3 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(217, 'I -4 3 m', transformations)
space_groups[217] = sg
space_groups['I -4 3 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(218, 'P -4 3 n', transformations)
space_groups[218] = sg
space_groups['P -4 3 n'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(219, 'F -4 3 c', transformations)
space_groups[219] = sg
space_groups['F -4 3 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(220, 'I -4 3 d', transformations)
space_groups[220] = sg
space_groups['I -4 3 d'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = | N.array([0,0,0]) | numpy.array |
# coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Example script how to get started with research using disentanglement_lib.
To run the example, please change the working directory to the containing folder
and run:
>> python example.py
In this example, we show how to use disentanglement_lib to:
1. Train a standard VAE (already implemented in disentanglement_lib).
2. Train a custom VAE model.
3. Extract the mean representations for both of these models.
4. Compute the Mutual Information Gap (already implemented) for both models.
5. Compute a custom disentanglement metric for both models.
6. Aggregate the results.
7. Print out the final Pandas data frame with the results.
"""
# We group all the imports at the top.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os, argparse, yaml
# from disentanglement_lib.evaluation import evaluate
from disentanglement_lib.evaluation.metrics import utils
from disentanglement_lib.methods.unsupervised import train
from disentanglement_lib.methods.unsupervised import vae
from disentanglement_lib.postprocessing import postprocess
from disentanglement_lib.utils import aggregate_results
from disentanglement_lib.evaluation.metrics import factor_vae
import tensorflow.compat.v1 as tf
import time
import pdb
import gin.tf
import numpy as np
import torch
from torchvision import models, transforms
import sys
import random
from disentanglement_lib.data.ground_truth import ground_truth_data
from disentanglement_lib.data.ground_truth import util
from six.moves import range
import tensorflow.compat.v1 as tf
from torchvision.models import resnet50
import torch.nn as nn
from disentanglement_lib.evaluation.metrics import mig, beta_vae, factor_vae, sap_score, dci
import h5py
# issue https://github.com/google-research/disentanglement_lib/issues/18 for the reference
# of customizing the 3dshapes dataset definition
SHAPES3D_PATH = os.path.join(
os.environ.get("DISENTANGLEMENT_LIB_DATA", "."), "3dshapes", "3dshapes.h5"
)
class Shapes3D(ground_truth_data.GroundTruthData):
"""Shapes3D dataset.
The data set was originally introduced in "Disentangling by Factorising".
The ground-truth factors of variation are:
0 - floor color (10 different values)
1 - wall color (10 different values)
2 - object color (10 different values)
3 - object size (8 different values)
4 - object type (4 different values)
5 - azimuth (15 different values)
"""
def __init__(self):
# with tf.gfile.GFile(SHAPES3D_PATH, "rb") as f:
# # Data was saved originally using python2, so we need to set the encoding.
# data = np.load(f, encoding="latin1")
# images = data["images"]
# labels = data["labels"]
# n_samples = np.prod(images.shape[0:6])
with h5py.File(SHAPES3D_PATH, 'r') as dataset:
images = dataset['images'][()]
labels = dataset['labels'][()]
n_samples = images.shape[0]
self.images = (
images.reshape([n_samples, 64, 64, 3]).astype(np.float32) / 255.)
features = labels.reshape([n_samples, 6])
self.factor_sizes = [10, 10, 10, 8, 4, 15]
self.latent_factor_indices = list(range(6))
self.num_total_factors = features.shape[1]
self.state_space = util.SplitDiscreteStateSpace(self.factor_sizes,
self.latent_factor_indices)
self.factor_bases = np.prod(self.factor_sizes) / np.cumprod(
self.factor_sizes)
@property
def num_factors(self):
return self.state_space.num_latent_factors
@property
def factors_num_values(self):
return self.factor_sizes
@property
def observation_shape(self):
return [64, 64, 3]
def sample_factors(self, num, random_state):
"""Sample a batch of factors Y."""
return self.state_space.sample_latent_factors(num, random_state)
def sample_observations_from_factors(self, factors, random_state):
all_factors = self.state_space.sample_all_factors(factors, random_state)
indices = np.array(np.dot(all_factors, self.factor_bases), dtype=np.int64)
return self.images[indices]
### This part is for ICE-BeeM ######
from models.nets import ConvMLP, FullMLP, SimpleLinear, SimpleEncoder
def feature_net(config):
if config.model.architecture.lower() == 'convmlp':
return ConvMLP(config)
elif config.model.architecture.lower() == 'mlp':
return FullMLP(config)
elif config.model.architecture.lower() == 'unet':
return RefineNetDilated(config)
elif config.model.architecture == "simple":
# follow the default encoder we use for other datasets
return SimpleEncoder(config)
# @gin.configurable(
# "evaluation_new", blacklist=["model_dir", "output_dir", "overwrite"])
def evaluate_disentanglement(model_dir,
output_dir,
overwrite=False,
evaluation_fn=gin.REQUIRED,
random_seed=gin.REQUIRED,
name="",
image_size=64,
gamma=0.1,
batch_size=64,
z_dim=50,
tag="",
config=None,
dataset=None
):
"""Loads a representation TFHub module and computes disentanglement metrics.
Args:
model_dir: String with path to directory where the representation function
is saved.
output_dir: String with the path where the results should be saved.
overwrite: Boolean indicating whether to overwrite output directory.
evaluation_fn: Function used to evaluate the representation (see metrics/
for examples).
random_seed: Integer with random seed used for training.
name: Optional string with name of the metric (can be used to name metrics).
"""
# Delete the output directory if it already exists.
if tf.gfile.IsDirectory(output_dir):
if overwrite:
tf.gfile.DeleteRecursively(output_dir)
else:
raise ValueError("Directory {} already exists and overwrite is False.".format(output_dir))
# Set up time to keep track of elapsed time in results.
experiment_timer = time.time()
model_all = feature_net(config)
def model_representation(data):
data = torch.from_numpy(data)
if data.shape[1:] == (64, 64, 1):
data = torch.permute(data, (0,3,1,2))
# data = data.repeat([1, 3, 1, 1])
elif data.shape[1:] == (64, 64, 3):
data = torch.permute(data, (0,3,1,2))
if torch.cuda.is_available():
data = data.cuda()
representation = model(data).squeeze()
# import pdb; pdb.set_trace()
return representation.detach().cpu().numpy()
dataset_name = config.data.dataset
if dataset_name.lower() == "dsprites":
epoch_to_eval = [30]
elif dataset_name.lower() == "smallnorb":
epoch_to_eval = [20, 40, 60, 80, 100, 120, 140, 160]
elif dataset_name.lower() == "cars3d":
epoch_to_eval = [50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900]
elif dataset_name.lower() == "3dshapes":
epoch_to_eval = [100]
for epoch in epoch_to_eval:
print("----- epoch = {} | metric = {} | dataset = {} | trial = {} ------".format(epoch, config.metric, dataset_name, config.trial_name))
checkpoint_path = "run/checkpoints/{}/{}/{}/checkpoint_{}.pth".format(dataset_name, tag, config.trial_name, epoch)
print("Load checkpoint from ", checkpoint_path)
state_dict = torch.load(checkpoint_path)
weights, optimizer = state_dict
model_all.load_state_dict(weights)
model = model_all.encode
# the line comes from disentanglement_lib/evaluation/metrics/factor_vae_test.py
# representation_function = lambda x: np.hstack((x,x/2,x))
if config.metric == "factor_vae":
scores = factor_vae.compute_factor_vae(dataset, model_representation,
np.random.RandomState(0), None, batch_size, 10000, 5000, 10000)
elif config.metric == "beta_vae":
scores = beta_vae.compute_beta_vae_sklearn(dataset, model_representation,
np.random.RandomState(0), None, batch_size, 10000, 5000)
elif config.metric == "mig":
# may still buggy, raises UserWarning: Clustering metrics expects discrete val \
# ues but received multiclass values for label, and continuous values for target
def _identity_discretizer(target, num_bins):
del num_bins
return target
def _histogram_discretize(target, num_bins):
"""Discretization based on histograms."""
discretized = np.zeros_like(target)
for i in range(target.shape[0]):
discretized[i, :] = np.digitize(target[i, :], np.histogram(
target[i, :], num_bins)[1][:-1])
return discretized
# gin_bindings = [
# # "evaluation.evaluation_fn = @mig",
# # "evaluation.random_seed = 0",
# "mig.num_train=10000",
# "discretizer.discretizer_fn = @histogram_discretizer",
# "discretizer.num_bins = 20"
# ]
# if gin_config_files is None:
# gin_config_files = []
# if gin_bindings is None:
# gin_bindings = []
# gin.parse_config_files_and_bindings(gin_config_files, gin_bindings)
gin.bind_parameter("discretizer.discretizer_fn", _histogram_discretize)
gin.bind_parameter("discretizer.num_bins", 20)
# gin.bind_parameter(gin_bindings)
scores = mig.compute_mig(dataset, model_representation, np.random.RandomState(0), None, num_train=10000, batch_size=16)
elif config.metric == "sap":
scores = sap_score.compute_sap(dataset, model_representation, np.random.RandomState(0), None, num_train=10000,
num_test=16, continuous_factors=True)
elif config.metric == "dci":
scores = dci.compute_dci(dataset, model_representation, | np.random.RandomState(0) | numpy.random.RandomState |
from collections import OrderedDict
import numpy as np
import os
from hazel.atmosphere import General_atmosphere
from hazel.util import i0_allen
from hazel.codes import sir_code
from hazel.io import Generic_SIR_file
import scipy.interpolate as interp
from hazel.exceptions import NumericalErrorSIR
from hazel.transforms import transformed_to_physical, jacobian_transformation
try:
from hazel.forward_nn import Forward
except:
pass
__all__ = ['SIR_atmosphere']
# sir_parameters = OrderedDict.fromkeys('T B thetaB phiB v')
class SIR_atmosphere(General_atmosphere):
def __init__(self, working_mode, name='', root='', verbose=0):
super().__init__('photosphere', name=name)
self.ff = 1.0
self.macroturbulence = np.zeros(1)
self.working_mode = working_mode
self.graphnet_nlte = None
self.root = root
self.parameters['T'] = None
self.parameters['vmic'] = None
self.parameters['v'] = None
self.parameters['Bx'] = None
self.parameters['By'] = None
self.parameters['Bz'] = None
self.parameters['ff'] = None
self.parameters['vmac'] = None
self.nodes_location['T'] = None
self.nodes_location['vmic'] = None
self.nodes_location['v'] = None
self.nodes_location['Bx'] = None
self.nodes_location['By'] = None
self.nodes_location['Bz'] = None
self.nodes_location['ff'] = None
self.nodes_location['vmac'] = None
self.n_nodes['T'] = 0
self.n_nodes['vmic'] = 0
self.n_nodes['v'] = 0
self.n_nodes['Bx'] = 0
self.n_nodes['By'] = 0
self.n_nodes['Bz'] = 0
self.n_nodes['ff'] = 0
self.n_nodes['vmac'] = 0
self.nodes['T'] = 0
self.nodes['vmic'] = 0
self.nodes['v'] = 0
self.nodes['Bx'] = 0
self.nodes['By'] = 0
self.nodes['Bz'] = 0
self.nodes['ff'] = 0
self.nodes['vmac'] = 0
self.rf_analytical = OrderedDict()
self.rf_analytical['T'] = None
self.rf_analytical['vmic'] = None
self.rf_analytical['v'] = None
self.rf_analytical['Bx'] = None
self.rf_analytical['By'] = None
self.rf_analytical['Bz'] = None
self.rf_analytical['ff'] = None
self.rf_analytical['vmac'] = None
self.ranges['T'] = None
self.ranges['vmic'] = None
self.ranges['v'] = None
self.ranges['Bx'] = None
self.ranges['By'] = None
self.ranges['Bz'] = None
self.ranges['ff'] = None
self.ranges['vmac'] = None
self.cycles['T'] = None
self.cycles['vmic'] = None
self.cycles['v'] = None
self.cycles['Bx'] = None
self.cycles['By'] = None
self.cycles['Bz'] = None
self.cycles['ff'] = None
self.cycles['vmac'] = None
self.epsilon['T'] = 0.01
self.epsilon['vmic'] = 0.01
self.epsilon['v'] = 0.01
self.epsilon['Bx'] = 0.01
self.epsilon['By'] = 0.01
self.epsilon['Bz'] = 0.01
self.epsilon['ff'] = 0.01
self.epsilon['vmac'] = 0.01
self.regularization['T'] = None
self.regularization['vmic'] = None
self.regularization['v'] = None
self.regularization['Bx'] = None
self.regularization['By'] = None
self.regularization['Bz'] = None
self.regularization['ff'] = None
self.regularization['vmac'] = None
self.verbose = verbose
def list_lines(self):
"""
List the lines available in SIR for synthesis
"""
f = open('LINEAS', 'r')
lines = f.readlines()
f.close()
print("Available lines:")
for l in lines[:-1]:
print(l[:-1])
def add_active_line(self, lines, spectrum, wvl_range, verbose):
"""
Add an active lines in this atmosphere
Parameters
----------
lines : str
Line to activate
spectrum : Spectrum
Spectrum object
wvl_range : float
Vector containing wavelength range over which to synthesize this line
Returns
-------
None
"""
self.lines = lines
self.wvl_range_lambda = wvl_range
ind_low = (np.abs(spectrum.wavelength_axis - wvl_range[0])).argmin()
ind_top = (np.abs(spectrum.wavelength_axis - wvl_range[1])).argmin()
self.spectrum = spectrum
self.wvl_axis = spectrum.wavelength_axis[ind_low:ind_top+1]
self.wvl_range = np.array([ind_low, ind_top+1])
# Check if Ca II 8542 is in the list of lines and instantiate the neural networks
if (self.nlte):
if 301 in self.lines:
if self.graphnet_nlte is None:
path = str(__file__).split('/')
checkpoint = '/'.join(path[0:-1])+'/data/20211114-131045_best.prd.pth'
if (verbose >= 1):
self.logger.info(' * Reading NLTE Neural Network')
self.graphnet_nlte = Forward(checkpoint=checkpoint, verbose=verbose)
def interpolate_nodes(self, log_tau, reference, nodes):
"""
Generate a model atmosphere by interpolating the defined nodes. The interpolation
order depends on the number of nodes.
Parameters
----------
log_tau : float
Vector of log optical depth at 500 nm
reference : float
Vector with the reference atmosphere to which the nodes are added
nodes : float
List with the position of the nodes
Returns
-------
real
Vector with the interpolated atmosphere
"""
n_nodes = len(nodes)
n_depth = len(log_tau)
if (n_nodes == 0):
return reference, 0
if (n_nodes == 1):
return reference + nodes[0], n_depth//2
# if (n_nodes >= 2):
# # pos = np.linspace(n_depth-1, 0, n_nodes+2, dtype=int)[1:-1]
# pos = np.linspace(n_depth-1, 0, n_nodes, dtype=int)
# f = interp.PchipInterpolator(log_tau[pos], nodes, extrapolate=True)
# return reference + f(log_tau), pos
if (n_nodes == 2):
# pos = np.linspace(0, n_depth-1, n_nodes+2, dtype=int)[1:-1]
pos = np.linspace(0, n_depth-1, n_nodes, dtype=int)
f = interp.interp1d(log_tau[pos], nodes, 'linear', bounds_error=False, fill_value='extrapolate')
return reference + f(log_tau), pos
if (n_nodes == 3):
# pos = np.linspace(0, n_depth-1, n_nodes+2, dtype=int)[1:-1]
pos = np.linspace(0, n_depth-1, n_nodes, dtype=int)
f = interp.interp1d(log_tau[pos], nodes, 'quadratic', bounds_error=False, fill_value='extrapolate')
return reference + f(log_tau), pos
if (n_nodes > 3):
# pos = np.linspace(n_depth-1, 0, n_nodes+2, dtype=int)[1:-1]
pos = np.linspace(n_depth-1, 0, n_nodes, dtype=int)
f = interp.PchipInterpolator(log_tau[pos], nodes, extrapolate=True)
return reference + f(log_tau), pos
def interpolate_nodes_rf(self, log_tau, reference, nodes, lower, upper):
"""
Generate a model atmosphere by interpolating the defined nodes. The interpolation
order depends on the number of nodes.
Parameters
----------
log_tau : float
Vector of log optical depth at 500 nm
reference : float
Vector with the reference atmosphere to which the nodes are added
nodes : float
List with the position of the nodes
Returns
-------
real
Vector with the interpolated atmosphere
"""
n_nodes = len(nodes)
n_depth = len(log_tau)
if (n_nodes == 0):
return np.zeros(n_depth)
if (n_nodes == 1):
rf = np.zeros((n_nodes, n_depth))
tmp0 = reference + nodes[0]
# Add the Jacobian to each height
jacobian = jacobian_transformation(tmp0, lower, upper)
rf[0,:] = 1.0 * jacobian
return rf
if (n_nodes == 2):
rf = np.zeros((n_nodes, n_depth))
pos = np.linspace(0, n_depth-1, n_nodes+2, dtype=int)[1:-1]
f = interp.interp1d(log_tau[pos], nodes, 'linear', bounds_error=False, fill_value='extrapolate')
tmp0 = reference + f(log_tau)
jacobian = jacobian_transformation(tmp0, lower, upper)
delta = 1e-3
for i in range(n_nodes):
tmp_nodes = np.copy(nodes)
tmp_nodes[i] += delta
f = interp.interp1d(log_tau[pos], tmp_nodes, 'linear', bounds_error=False, fill_value='extrapolate')
tmp1 = reference + f(log_tau)
rf[i,:] = (tmp1 - tmp0) / delta * jacobian
return rf
if (n_nodes == 3):
rf = np.zeros((n_nodes, n_depth))
pos = np.linspace(0, n_depth-1, n_nodes+2, dtype=int)[1:-1]
f = interp.interp1d(log_tau[pos], nodes, 'quadratic', bounds_error=False, fill_value='extrapolate')
tmp0 = reference + f(log_tau)
jacobian = jacobian_transformation(tmp0, lower, upper)
delta = 1e-3
for i in range(n_nodes):
tmp_nodes = np.copy(nodes)
tmp_nodes[i] += delta
f = interp.interp1d(log_tau[pos], tmp_nodes, 'quadratic', bounds_error=False, fill_value='extrapolate')
tmp1 = reference + f(log_tau)
rf[i,:] = (tmp1 - tmp0) / delta * jacobian
return rf
if (n_nodes > 3):
rf = np.zeros((n_nodes, n_depth))
pos = np.linspace(n_depth-1, 0, n_nodes+2, dtype=int)[1:-1]
f = interp.PchipInterpolator(log_tau[pos], nodes, extrapolate=True)
tmp0 = reference + f(log_tau)
jacobian = jacobian_transformation(tmp0, lower, upper)
delta = 1e-3
for i in range(n_nodes):
tmp_nodes = np.copy(nodes)
tmp_nodes[i] += delta
f = interp.PchipInterpolator(log_tau[pos], tmp_nodes, extrapolate=True)
tmp1 = reference + f(log_tau)
rf[i,:] = (tmp1 - tmp0) / delta * jacobian
return rf
def load_reference_model(self, model_file, verbose):
"""
Load a reference model or a model for every pixel for synthesis/inversion
Parameters
----------
model_file : str
String with the name of the file. Extensions can currently be "1d" or "h5"
verbose : bool
Verbosity
Returns
-------
None
"""
extension = os.path.splitext(model_file)[1][1:]
if (extension == '1d'):
if (verbose >= 1):
self.logger.info(' * Reading 1D model {0} as reference'.format(model_file))
self.model_type = '1d'
self.model_filename = model_file
if (extension == 'h5'):
if (verbose >= 1):
self.logger.info(' * Reading 3D model {0} as reference'.format(model_file))
self.model_type = '3d'
self.model_handler = Generic_SIR_file(model_file)
self.model_handler.open()
out, ff, vmac = self.model_handler.read(pixel=0)
self.model_handler.close()
self.set_parameters(out, ff, vmac)
self.t_old = np.zeros_like(self.parameters['T'])
self.init_reference(check_borders=True)
self.departure = np.ones((2, len(self.lines), len(self.log_tau)))
def set_parameters(self, model, ff, vmac):
"""
Set the parameters of the current model to those passed as argument
Parameters
----------
model_in : float
Array with the model
ff : float
Value of the filling factor
vmac : float
Value of the macroturbulent velocity
Returns
-------
None
"""
self.log_tau = model[:,0]
self.parameters['T'] = model[:,1]
self.parameters['vmic'] = model[:,3]
self.parameters['v'] = model[:,4]
self.parameters['Bx'] = model[:,5]
self.parameters['By'] = model[:,6]
self.parameters['Bz'] = model[:,7]
if (np.min(model[:,2]) > 0.0):
self.Pe = model[:,2]
else:
self.Pe = -np.ones(len(self.log_tau))
self.Pe[-1] = 1.11634e-1
self.parameters['ff'] = ff
self.parameters['vmac'] = vmac
# Check that parameters are inside borders by clipping inside the interval with a border of 1e-8
if (self.working_mode == 'inversion'):
for k, v in self.parameters.items():
self.parameters[k] = np.clip(v, self.ranges[k][0] + 1e-8, self.ranges[k][1] - 1e-8)
def get_parameters(self):
"""
Get the curent parameters as a model
Parameters
----------
None
Returns
-------
model: a 6xN photspheric model
"""
model = np.zeros((len(self.log_tau),8))
model[:,0] = self.log_tau
model[:,1] = self.parameters['T']
model[:,2] = self.Pe
model[:,3] = self.parameters['vmic']
model[:,4] = self.parameters['v']
model[:,5] = self.parameters['Bx']
model[:,6] = self.parameters['By']
model[:,7] = self.parameters['Bz']
return model
def nodes_to_model(self):
"""
Transform from nodes to model
Parameters
----------
None
Returns
-------
None
"""
for k, v in self.nodes.items():
if (self.n_nodes[k] > 0):
self.parameters[k], self.nodes_location[k] = self.interpolate_nodes(self.log_tau, self.reference[k], self.nodes[k])
else:
self.parameters[k] = self.reference[k]
self.Pe = -np.ones(len(self.log_tau))
self.Pe[-1] = 1.11634e-1
def model_to_nodes(self):
"""
Transform from model to nodes
Parameters
----------
None
Returns
-------
None
"""
pass
# for k, v in self.parameters.items():
# if (k is not 'log_tau'):
# self.interpolate_nodes(self.parameters['log_tau'], self.reference['T'], [1000])
# stop()
# for k, v in self.parameters.items():
# if (k is not 'log_tau'):
# def print_parameters_old(self, first=False, error=False):
# breakpoint()
# for k, v in self.nodes.items():
# if (self.n_nodes[k] > 0):
# if (k != 'ff'):
# lower = self.ranges[k][0] #- self.eps_borders
# upper = self.ranges[k][1] #+ self.eps_borders
# nodes = transformed_to_physical(v, lower, upper)
# self.logger.info('{0} -> {1}'.format(k, nodes))
def print_parameters(self, first=False, error=False):
for k, v in self.parameters.items():
if (self.n_nodes[k] > 0):
if (k != 'ff'):
pars = v[self.nodes_location[k]]
self.logger.info('{0} -> {1}'.format(k, pars))
def synthesize(self, stokes_in, returnRF=False, nlte=False):
"""
Carry out the synthesis and returns the Stokes parameters and the response
functions to all physical variables at all depths
Parameters
----------
stokes_in : float
An array of size [4 x nLambda] with the input Stokes parameter. It is irrelevant in this case
because we assume that all SIR atmospheres have the Planck function as boundary.
returnRF : bool, optional
Return response functions
Returns
-------
stokes : float
Stokes parameters, with the first index containing the wavelength displacement and the remaining
containing I, Q, U and V. Size (5,nLambda)
rf: float (optional)
Response functions to T, Pe, vmic, B, v, theta, phi, all of size (4,nLambda,nDepth), plus the RF to macroturbulence of size (4,nLambda)
It is not returned if returnRF=False
"""
if (self.working_mode == 'inversion'):
self.nodes_to_model()
self.to_physical()
if (returnRF):
stokes, cmass, rf, error = sir_code.synthRF(self.index, self.n_lambda, self.log_tau, self.parameters['T'],
self.Pe, 1e5*self.parameters['vmic'], 1e5*self.parameters['v'], self.parameters['Bx'], self.parameters['By'],
self.parameters['Bz'], self.parameters['vmac'])
if (error == 1):
raise NumericalErrorSIR()
B = np.sqrt(self.parameters['Bx']**2 + self.parameters['By']**2 + self.parameters['Bz']**2)
thetaB = np.arccos(self.parameters['Bz'] / B)
thetaB[B == 0] = 0.0
phiB = np.arctan2(self.parameters['By'], self.parameters['Bx'])
# rfn = np.zeros((150, 73))
# pars = copy.deepcopy(self.parameters)
# for pos in range(73):
# ind_sto = 0
# self.parameters = copy.deepcopy(pars)
# delta = 5e-4*self.parameters['T'][pos]
# self.parameters['T'][pos] += delta
# stokes2, rf2, error = sir_code.synthRF(self.index, self.n_lambda, self.log_tau, self.parameters['T'],
# self.Pe, 1e5*self.parameters['vmic'], 1e5*self.parameters['v'], self.parameters['Bx'], self.parameters['By'],
# self.parameters['Bz'], self.parameters['vmac'])
# error = 0
# rfn[:, pos] = (stokes2[ind_sto+1,:]-stokes[ind_sto+1,:])/delta
# breakpoint()
# import matplotlib.pyplot as pl
# pl.plot(rfn[:, 40], '-o', label='numerical')
self.rf_analytical['T'] = rf[0]+rf[1] #OK
self.rf_analytical['vmic'] = 1e5*rf[6] #OK
self.rf_analytical['v'] = 1e5*rf[3] #OK
# Transform SIR RFs into response functions to Bx, By and Bz.
# To this end, we have:
# [RF_B ] [dBxdB dBydB dBzdB ][RF_Bx]
# [RF_th] = [dBxdthB dBydthB dBzdthB][RF_By]
# [RF_ph] [dBxdphB dBydphB dBzdphB][RF_Bz]
# and then invert the Jacobian
RFB = rf[2]
RFt = rf[4]
RFp = rf[5]
self.rf_analytical['Bx'] = RFB * np.sin(thetaB) * np.cos(phiB) + \
RFt * np.cos(thetaB) * np.cos(phiB) / (B + 1e-6) - \
RFp * np.sin(phiB) / (B * np.sin(thetaB))
self.rf_analytical['By'] = RFB * np.sin(thetaB) * np.sin(phiB) + \
RFt * np.cos(thetaB) * np.sin(phiB) / (B + 1e-6) + \
RFp * np.cos(phiB) / (B * np.sin(thetaB))
self.rf_analytical['Bz'] = RFB * np.cos(thetaB) - RFt * np.sin(thetaB) / (B + 1e-6)
self.rf_analytical['vmac'] = rf[7][:, :, None]
# pl.plot(self.rf_analytical['T'][ind_sto,:,pos], label='analytical')
# pl.legend()
# pl.show()
# import matplotlib.pyplot as pl
# f, ax = pl.subplots(nrows=3, ncols=3, figsize=(10,10))
# ax = ax.flatten()
# for i in range(9):
# ax[i].plot(np.log(self.rf_analytical['T'][0,i*10,:]), color=f'C{i}')
# ax[i].plot(np.log(rfn[i*10,:]), 'o', color=f'C{i}')
# pl.show()
i0 = i0_allen(np.mean(self.wvl_axis), self.spectrum.mu)
for k, v in self.nodes.items():
if (k != 'vmac'):
if (self.n_nodes[k] > 0):
lower = self.ranges[k][0]
upper = self.ranges[k][1]
rf = self.interpolate_nodes_rf(self.log_tau, self.reference[k], self.nodes[k], lower, upper)
# import matplotlib.pyplot as pl
# f, ax = pl.subplots(nrows=3, ncols=3, figsize=(10,10))
# ax = ax.flatten()
# for i in range(9):
# ax[i].plot(rfn[i*10,:] / self.rf_analytical['T'][0,i*10,:], color=f'C{i}')
# ax[i].set_ylim([0,2])
# pl.show()
# print(k)
# breakpoint()
self.rf_analytical[k] = np.einsum('ijk,lk->ijl', self.rf_analytical[k], rf) * i0
return self.parameters['ff'] * stokes[1:,:] * i0, self.rf_analytical, error
else:
# stokes, error = sir_code.synth(self.index, self.n_lambda, self.log_tau, self.parameters['T'],
# self.Pe, 1e5*self.parameters['vmic'], 1e5*self.parameters['v'], self.parameters['Bx'], self.parameters['By'],
# self.parameters['Bz'], self.parameters['vmac'])
# If we need to put the atmosphere in hydrostatic eq.
if (self.working_mode == 'inversion'):
self.Pe = sir_code.hydroeq(self.log_tau, self.parameters['T'],
self.Pe, 1e5*self.parameters['vmic'], 1e5*self.parameters['v'], self.parameters['Bx'], self.parameters['By'],
self.parameters['Bz'])
# Check if the line is 8542 and we want NLTE. If that is the case, then evaluate the
# neural network to return the departure coefficients
if (nlte):
if (self.nlte):
dif = (self.parameters['T'] - self.t_old)
if ( | np.max(dif) | numpy.max |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.