prompt
stringlengths 19
879k
| completion
stringlengths 3
53.8k
| api
stringlengths 8
59
|
---|---|---|
import importlib
import xarray as xr
import numpy as np
import pandas as pd
import sys
import os
from math import nan
from CASutils import calendar_utils as cal
from CASutils import filter_utils as filt
importlib.reload(cal)
importlib.reload(filt)
pathout="/project/cas/islas/python_savs/snowpaper/DATA_SORT/t850_laggedregs/"
def deseasonalize(dat):
datseas = dat.groupby('time.dayofyear').mean('time')
dat4harm = filt.calc_season_nharm(datseas,4,dimtime=1)
datanoms = dat.groupby('time.dayofyear') - dat4harm
datdjfanoms = cal.group_season_daily(datanoms,'DJF')
datmean = datdjfanoms.mean('day')
datdjfanoms = datdjfanoms - datmean
return datdjfanoms
def readanddeseas(file1, var):
dat1 = xr.open_dataset(file1).sel(time=slice("1979-01-01","2014-12-31"))
dat1 = dat1[var]
dat1deseas = deseasonalize(dat1)
return dat1deseas
#def readanddeseas(file1,var):
# dat = xr.open_dataset(file1).sel(time=slice("1979-01-01","2014-12-31"))
# dat = dat[var]
# datdeseas = deseasonalize(dat)
# return datdeseas
cities=['Saskatoon','Toronto','Siderovsk']
filepath = "/project/cas/islas/python_savs/snowpaper/DATA_SORT/3cities/SCAM_CLMINIT_60days_withclearsky/"
t850_clm5 = readanddeseas(filepath+"T850_SCAM_CLM5_CLM5F_01.nc","t850")
t850_snowd = readanddeseas(filepath+"T850_SCAM_SNOWD_CLM5F_01.nc","t850")
trefht_clm5 = readanddeseas(filepath+"TREFHT_SCAM_CLM5_CLM5F_01.nc","t850")
trefht_snowd = readanddeseas(filepath+"TREFHT_SCAM_SNOWD_CLM5F_01.nc","t850")
flns_clm5 = readanddeseas(filepath+"FLNS_SCAM_CLM5_CLM5F_01.nc","flns")
flns_snowd = readanddeseas(filepath+"FLNS_SCAM_SNOWD_CLM5F_01.nc","flns")
flnsc_clm5 = readanddeseas(filepath+"FLNSC_SCAM_CLM5_CLM5F_01.nc","flnsc")
flnsc_snowd = readanddeseas(filepath+"FLNSC_SCAM_SNOWD_CLM5F_01.nc","flnsc")
nyears = len(t850_clm5[:,0,0]) ; ndays = len(t850_clm5[0,:,0])
lag = np.arange(-10,11,1)
dat1clm5 = np.reshape(np.array(t850_clm5[:,10:ndays-10,:]),[nyears*(ndays-lag.size+1),3])
dat1snowd = np.reshape(np.array(t850_snowd[:,10:ndays-10,:]),[nyears*(ndays-lag.size+1),3])
trefhtregclm5 = np.zeros([lag.size,3]) ; trefhtregsnowd = np.zeros([lag.size,3])
t850regclm5 = np.zeros([lag.size,3]) ; t850regsnowd = np.zeros([lag.size,3])
flnsregclm5 = np.zeros([lag.size,3]) ; flnsregsnowd = | np.zeros([lag.size,3]) | numpy.zeros |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 28 13:25:28 2020
@author: <NAME>, <NAME>
"""
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import operator
import sklearn as sklearn
import xgboost as xgb
from Functions_downselection_training_RF import plot_RF_test #plot_heatmap, plot_RF_test, splitAndScale, scale, inverseScale, compare_features_barplot
# In[4]:
def analyze_XGB_for_multiple_seeds(list_X, list_y, ho_params = None, n_seeds = 20, save_pickle = False, bar_plot = True, groups = None, groups_only_for_plotting = False, test_proportion = 0.21, top_n = 20, plotting=True, saveas = None, title=True):
n_datasets = len(list_X)
# Let's repeat y stratification. At the same, let's create a dataset for
# RF hyperparameter optimization.
R2_all2 = np.zeros((n_seeds,n_datasets))
RMSE_all2 = np.zeros((n_seeds,n_datasets))
top_features_all2 = []
features_all2 = []
X_tests = []
y_tests = []
X_trains = []
y_trains = []
regressors = []
filenames = ['X_tests_imp', 'y_tests_imp', 'X_tests', 'y_tests',
'X_trains_imp', 'y_trains_imp', 'X_trains', 'y_trains']
for j in range(n_datasets):
if ho_params is not None:
n_estimators = ho_params[j]['n_estimators']
max_depth = ho_params[j]['max_depth']
gamma = ho_params[j]['gamma']
eta = ho_params[j]['eta']
top_features_temp = []
features_temp = []
X_tests_temp = []
y_tests_temp = []
X_trains_temp = []
y_trains_temp = []
regressors_temp = []
if title is not None:
title_temp = True
else:
title_temp = None
for i in range(n_seeds):
if saveas is not None:
saveas_temp = saveas+str(i)
else:
saveas_temp = saveas
if ho_params is None:
feature_weights, top_feature_weights, regressor, R2, RMSE, scaler_test, X_test, y_test, y_pred, X_train, y_train = XGB_feature_analysis(
list_X[j], list_y[j], groups=groups,
groups_only_for_plotting = groups_only_for_plotting,
test_indices = None, test_proportion = test_proportion,
top_n = top_n, i='', random_state = i,
sample_weighing = False, plotting=plotting, saveas = saveas_temp, title = title_temp)
else:
feature_weights, top_feature_weights, regressor, R2, RMSE, scaler_test, X_test, y_test, y_pred, X_train, y_train = XGB_feature_analysis(
list_X[j], list_y[j], groups=groups,
groups_only_for_plotting = groups_only_for_plotting,
test_indices = None, test_proportion = test_proportion,
top_n = top_n, i='', random_state = i,
sample_weighing = False, plotting=plotting, saveas = saveas_temp, title = title_temp,
max_depth= int(max_depth), gamma = gamma, n_estimators=n_estimators, eta = eta)
R2_all2[i,j] = R2
RMSE_all2[i,j] = RMSE
top_features_temp.append(top_feature_weights.copy())
features_temp.append(feature_weights.copy())
X_tests_temp.append(X_test.copy())
y_tests_temp.append(y_test.copy())
X_trains_temp.append(X_train.copy())
y_trains_temp.append(y_train.copy())
regressors_temp.append(regressor)
top_features_all2.append(top_features_temp)
features_all2.append(features_temp)
X_tests.append(X_tests_temp)
y_tests.append(y_tests_temp)
X_trains.append(X_trains_temp)
y_trains.append(y_trains_temp)
regressors.append(regressors_temp)
print('R2 and RMSE for dataset ', j, ': ', R2_all2[:,j], RMSE_all2[:,j])
print('Mean: ', np.mean(R2_all2[:,j]), np.mean(RMSE_all2[:,j]))
print('Std: ', np.std(R2_all2[:,j]), np.std(RMSE_all2[:,j]))
print('Min: ', np.min(R2_all2[:,j]), np.min(RMSE_all2[:,j]))
print('Max: ', np.max(R2_all2[:,j]), np.max(RMSE_all2[:,j]))
if save_pickle == True:
# Pickles for HO:
if j == 0:
save_to_pickle(X_tests, filenames[2])
save_to_pickle(y_tests, filenames[3])
save_to_pickle(X_trains, filenames[6])
save_to_pickle(y_trains, filenames[7])
if j == 1:
save_to_pickle(X_tests, filenames[0])
save_to_pickle(y_tests, filenames[1])
save_to_pickle(X_trains, filenames[4])
save_to_pickle(y_trains, filenames[5])
# Plot the results. Compare feature weights of two methods. E.g., here the top
# 50 feature weights of FilteredImportant dataset are compared to the top 50
# feature weights of the Filtered dataset.
if (bar_plot == True) and (n_datasets>1):
compare_features_barplot(top_features_all2[0][0], top_features_all2[1][0])
return R2_all2, RMSE_all2, top_features_all2, features_all2, X_tests, y_tests, X_trains, y_trains, regressors
# In[ ]:
# In[6]:
def XGB_feature_analysis(X, y, groups = None, groups_only_for_plotting = False,
test_indices = None, test_proportion = 0.1, top_n = 5,
n_estimators = 100, max_depth = 10,
gamma = 2, eta = 0.5, i='',
random_state = None, sample_weighing = None,
plotting = True, saveas = None, title = True):
"""
Splits 'X' and 'y' to train and test sets so that 'test_proportion' of
samples is in the test set. Fits a
(sklearn) random forest model to the data according to RF parameters
('n_estimators', 'max_depth', 'min_samples_split', 'min_samples_leaf',
'max_features', 'bootstrap'). Estimates feature importances and determines
'top_n' most important features. A plot and printouts for describing the
results.
Parameters:
X (df): X data (features in columns, samples in rows)
y (df): y data (one column, samples in rows)
test_proportion (float, optional): Proportion of the test size from the original data.
top_n (float, optional): The number of features in output 'top_feature_weights'
n_estimators (int, optional): Number of trees in the forest
max_depth (int, optional): Maximum depth of the tree
min_samples split (int, optional): minimum number of samples required to split an internal node (could also be a float, see sklearn documentation)
min_samples_leaf (int, optional): The minimum number od samples to be at a leaf node (could also be a float, see sklearn documentation)
max_features (str, float, string, or None, optional): The number of features to consider when looking for the best split (see the options in sklearn documentation, 'sqrt' means max number is sqrt(number of features))
bootstrap (boolean, optional): False means the whole dataset is used for building each tree, True means bootstrap of samples is used
TO DO: Add value range that works for 5K dataset
i (int, optional): Optional numeric index for figure filename.
random_state (int, optional): Seed for train test split.
Returns:
feature_weights (df): weights of all the features
top_feature_weights (df): weights of the features with the most weight
regressor (RandomForestRegressor) RF regressor
R2 (float): R2 value of the prediction for the test set.
"""
if test_proportion == 0:
# Use the whole dataset for both training and "testing".
X_train = X.copy()
X_test = X.copy()
y_train = y.copy()
y_test = y.copy()
elif test_proportion == None:
# Assume X and y are lists with two datasets...
# Use dataset 0 as train and dataset 1 as test.
X_train = X[0].copy()
X_test = X[1].copy()
y_train = y[0].copy()
y_test = y[1].copy()
else:
# Split into test and train sets, and scale with StandardScaler.
if test_indices is None:
if groups is not None:
if groups_only_for_plotting == False:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_proportion, random_state=random_state, stratify=groups)
else:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_proportion, random_state=random_state)
#shufflesplit = sklearn.model_selection.ShuffleSplit(n_splits=1, test_size=test_proportion, random_state=random_state)
#X_train, X_test, y_train, y_test = shufflesplit.split(X, y, groups=groups)
else:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_proportion, random_state=random_state)
else:
#X_test = X.copy() # Are these needed?
#y_test = y.copy() # Are these needed?
X_test = X[test_indices].copy()
y_test = y[test_indices].copy()
#X_train = X.copy()
#y_train = y.copy()
X_train = X[~test_indices].copy()
y_train = y[~test_indices].copy()
print(y_test)
if sample_weighing:
#sample_weight = np.divide(1,y_train.iloc[:,0]+0.1)
#sample_weight = np.abs(y_train.iloc[:,0]-8.5)
#sample_weight = np.abs(y_train.iloc[:,0]-4.1)
sample_weight = y_train.copy()
sample_weight[y_train<=3] = 5
sample_weight[y_train>=8] = 5
sample_weight[(y_train>3)&(y_train<8)] = 1
sample_weight = sample_weight.squeeze()
else:
sample_weight = None
params = {'eta': eta,
'gamma': gamma,
'max_depth': max_depth,
'n_estimators': n_estimators}
# if you want to do weighting, you can do it manually on y_train.
#print(params)
#print(np.array(X_train))
#print(np.array(y_train))
regressor = xgb.XGBRegressor(**params).fit(np.array(X_train), np.ravel( | np.array(y_train) | numpy.array |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 19 14:58:38 2021
@author: TD
"""
import numpy as np
class GLM:
def __init__(self, basis_funcs=([lambda x: np.ones_like(x), lambda x:x],)):
"""
Parameters
----------
basis_funcs : list or tuple
List of lists of functions, where each list in the list is
the basis functions corresponding to a single dimension.
For example, if passed
([lambda x: np.ones_like(x), lambda x: x], [lambda x: x])
this is equivalent to the basis {1, x, y} for the equation
z = Ax + By + C; an equation for a plane.
The default is the basis for an equation of a line
in 1-dimension ([lambda x: 1, lambda x:x],).
"""
self.basis_funcs = basis_funcs
def fit(self, X, y, sample_weights=None):
A = GLM.create_design_matrix(self.basis_funcs, X)
W = GLM.get_sample_weight_matrix(sample_weights, y)
B = GLM.compute_b_matrix(A, W)
self.beta = np.dot(B, y)
### for diagnotics and stats
# trace(W.M)
self.dof = np.trace(
np.dot(
W,
GLM.compute_m_matrix(
GLM.compute_projection_matrix(A, B)
)
)
)
self.sigma_sqrd = GLM.compute_sigma_sqrd(
y - GLM._func_glm(A, self.beta),
W,
self.dof
)
self.var_beta = GLM.compute_var_beta(self.sigma_sqrd, B)
return self
def predict(self, X):
### TODO address trade off here:
# must recompute design matrix each predict call
# not saving design matrix during fit reduces memory footprint
return GLM.func_glm(self.basis_funcs, self.beta, X)
@staticmethod
def create_design_matrix(basis_funcs, X):
A = np.concatenate(
[
np.array(
[f(X[:, i]) for f in bf_coord]
).T
for i, bf_coord in enumerate(basis_funcs)
],
axis=1
)
return A
@staticmethod
def _func_glm(A, beta):
return np.dot(A, beta)
@staticmethod
def func_glm(basis_funcs, beta, X):
A = GLM.create_design_matrix(basis_funcs, X)
return GLM._func_glm(A, beta)
@staticmethod
def jac_glm(basis_funcs, X):
return GLM.create_design_matrix(basis_funcs, X)
@staticmethod
def jac_objective(basis_funcs, beta, X, y, sample_weights=None):
A = GLM.create_design_matrix(basis_funcs, X)
e = y - np.dot(A, beta) # faster not to call func_glm
W = GLM.get_sample_weight_matrix(sample_weights, y)
return 2 * np.dot(np.dot(e.T, W), A)
@staticmethod
def get_sample_weight_matrix(sample_weights, y):
if sample_weights is None:
sample_weights = np.identity(y.shape[0])
if not isinstance(sample_weights, np.ndarray):
sample_weights = np.array(sample_weights)
W = sample_weights
if len(W.shape) < 2:
W = np.diag(W)
if len(W.shape) != 2:
raise ValueError(
f'{W.shape} -- weights matrix shape. 2-d matrix required!'
)
if (W.shape[0] != W.shape[1]):
raise ValueError(
f'{W.shape} -- weights matrix shape. Matrix is not square!'
)
if (W.shape[0] != len(y)):
raise ValueError(
f'{W.shape} -- weights matrix shape.\n'
f'{len(y)} -- number of samples.\n'
'Weight matrix should have shape nsamples x nsamples!'
)
return W
@staticmethod
def compute_b_matrix(A, W):
"""
beta = B.y
"""
ATW = np.dot(A.T, W)
V = np.dot(ATW, A)
if np.linalg.det(V) == 0:
raise ValueError(
'NO SOLUTION: det(A^T.W.A)=0\n'
'Check design matrix or sample weight matrix!'
)
B = np.dot(np.linalg.inv(V), ATW)
del V, ATW
return B
@staticmethod
def compute_projection_matrix(A, B):
"""
projection matrix is idempotent P^2 = P
y_fit = P.y
"""
return np.dot(A, B)
@staticmethod
def compute_m_matrix(PA):
"""
residual operator matrix
e = M.y
"""
return np.identity(PA.shape[0]) - PA
@staticmethod
def compute_sigma_sqrd(e, W, dof):
return np.dot( | np.dot(e.T, W) | numpy.dot |
# std
import warnings
from collections import defaultdict
# third-party
import numpy as np
from scipy.signal import get_window
from astropy.stats import sigma_clipped_stats
# relative
from recipes.array import fold
from .spectral import resolve_overlap
# TODO: OCSVM, Tietjen-Moore, Topological Anomaly detection
def generalizedESD(x, maxOLs, alpha=0.05, fullOutput=False):
"""
Carry out a Generalized ESD Test for Outliers.
The Generalized Extreme Studentized Deviate (ESD) test for
outliers can be used to search for outliers in a univariate
data set, which approximately follows a normal distribution.
A description of the algorithm is, e.g., given at
`Nist <http://www.itl.nist.gov/div898/handbook/eda/section3/eda35h3.htm>`_
or [Rosner1983]_.
Parameters
----------
maxOLs : int
Maximum number of outliers in the data set.Rectangle
alpha : float, optional
Significance (default is 0.05).
fullOutput : boolean, optional
Determines whether additional return values
are provided. Default is False.
Returns
-------
Number of outliers : int
The number of data points characterized as
outliers by the test.
Indices : list of intsRectangle
The indices of the data points found to
be outliers.
R : list of floats, optional
The values of the "R statistics". Only provided
if `fullOutput` is set to True.
L : list of floats, optional
The lambda values needed to test whether a point
should be regarded an outlier. Only provided
if `fullOutput` is set to True.
"""
from scipy.stats import t
if maxOLs < 1:
raise ValueError
xm = np.ma.array(x.copy())
n = len(xm)
maxOLs = min(maxOLs, n) # can't have more outliers than points!
# Compute R-values
R, L = [], []
idx = []
for i in range(maxOLs + 1):
# Compute mean and std of x
xmean, xstd = xm.mean(), xm.std()
# Find maximum deviation
rr = np.abs((xm - xmean) / xstd) # Malhanobis distance
wrr = np.argmax(rr)
idx.append(wrr) # index of data point with maximal Malhanobis distance
R.append(rr[wrr])
if i >= 1:
p = 1.0 - alpha / (2.0 * (n - i + 1))
perPoint = t.ppf(p, n - i - 1)
# the 100p percentage point from the t-distribution
L.append((n - i) * perPoint / np.sqrt(
(n - i - 1 + perPoint ** 2) * (n - i + 1)))
# Mask that value and proceed
xm[idx[-1]] = np.ma.masked
# Remove the last entry from R, which is of
# no meaning for the test
R.pop(-1)
# Find the number of outliers
ofound = False
for i in range(maxOLs - 1, -1, -1):
if R[i] > L[i]:
ofound = True
break
# Prepare return value
if ofound:
# There are outliers
if fullOutput:
return idx[0:i + 1], i + 1, R, L, idx
return idx[0:i + 1]
# No outliers could be detected
if fullOutput:
return [], 0, R, L, idx
return []
# def CovEstOD(data, classifier=None, threshold=0):
# if classifier is None:
# from sklearn.covariance import EllipticEnvelope
# classifier = EllipticEnvelope(support_fraction=1., contamination=0.1)
#
# classifier.fit(data)
# idx, = np.where( classifier.decision_function(data) < threshold )
#
# return idx
def CovEstOD(data, classifier=None, n=1, **kw):
# multivariate outlier detection
if classifier is None:
from sklearn.covariance import EllipticEnvelope
contamination = n / data.shape[0]
classifier = EllipticEnvelope(support_fraction=1.,
contamination=contamination)
classifier.fit(data)
outliers, = np.where(classifier.predict(data) == -1)
return outliers
def get_ellipse(classifier, **kws):
from matplotlib.patches import Ellipse
# todo: probably check that data is 2d
w, T = np.linalg.eigh(classifier.precision_)
# T (eigenvectors of precision matrix) is the transformation matrix
# between principle axes and data coordinates
Ti = np.linalg.inv(T)
M = np.dot(Ti, classifier.precision_) * T
# Diagonalizing the precision matrix ==> quadratic representation of
# decision boundary (ellipse): z^T M z = threshold. where x-<x> = Tz
# transforms to principle axes
a, b = np.sqrt(classifier.threshold / np.diag(M))
# a, b are semi-major & semi-minor axes
# T is (im)proper rotation matrix
theta = np.degrees( | np.arccos(T[0, 0]) | numpy.arccos |
"""Trains model and exposes predictor class objects"""
from datetime import datetime
import logging
import operator
import os
import pickle
from armchair_analysis.game_data import game_data
from hyperopt import fmin, hp, tpe, Trials
import matplotlib.pyplot as plt
from melo import Melo
import numpy as np
import pandas as pd
from . import cachedir
class MeloNFL(Melo):
"""
Generate NFL point-spread or point-total predictions
using the Margin-dependent Elo (MELO) model.
"""
def __init__(self, mode, kfactor, regress_coeff,
rest_bonus, exp_bonus, weight_qb, burnin=512):
# hyperparameters
self.mode = mode
self.kfactor = kfactor
self.regress_coeff = regress_coeff
self.rest_bonus = rest_bonus
self.exp_bonus = exp_bonus
self.weight_qb = weight_qb
self.burnin = burnin
# model operation mode: "spread" or "total"
if self.mode not in ["spread", "total"]:
raise ValueError(
"Unknown mode; valid options are 'spread' and 'total'")
# mode-specific training hyperparameters
self.commutes, self.compare, self.lines = {
"total": (True, operator.add, | np.arange(-0.5, 111.5) | numpy.arange |
import numpy as np
import random
from kmc.particles import *
import sys
# Personalized errors
class randomized_error(Exception):
def __init__(self,number):
self.message="We were not able to include the " + str(number) + " particle(s) into the lattice. Loosen up the spacial restrictions for particle creation!"
super().__init__(self.message)
# SET OF FUNCS THAT GENERATE THE MORPHOLOGY OF THE SYSTEM
# note: always define the function by list (param) that contains the things needed
#### CHOOSE A FUNC TO GENERATE PARTICLES
'''
def randomized(available, number, system, kwargs):
mat = kwargs['mat']
selected = random.sample(list(available),number)
selected = [s for s in selected if system.mats[s] in mat]
count = 0
cutoff = number*10
while len(selected) < number and count < cutoff:
count = count + 1
new = random.sample(list(available),number-len(selected))
for n in new:
if system.mats[n] in mat:
selected.append(n)
if count >= cutoff and len(selected) != number:
raise randomized_error(number)
return selected
'''
def randomized(available, number, system, kwargs):
mat = kwargs['mat']
selected = random.sample(list(available),number)
selected = [s for s in selected if system.mats[s] in mat]
selec_size_old = len(selected)
selec_size_new = number # could be anything that satisfies selec_size_old != selec_size_new = True, but this way is granted to work if len(selected) < number = True
count = 1
cutoff = 10000*number*np.sqrt(len(list(available)))
#print(count,number,selec_size_old,selec_size_new)
while len(selected) < number and count < cutoff:
count = count + 1
selec_size_old = len(selected)
sel_old = selected.copy()
new = random.sample(list(available),number-len(selected))
new_mat = [sel for sel in new if system.mats[sel] in mat]
selected = list(set(selected + new_mat)) #enforcing uniqueness
selec_size_new = len(selected)
'''
print()
print('--->',count,selec_size_old,selec_size_new,new, [system.mats[a] for a in new])
print('---> sel. old',sel_old)
print('---> sel. new',selected)
'''
'''
print('#')
print(count,selec_size_old,selec_size_new, len(selected) < number,selec_size_old != selec_size_new )
print(cutoff,count)
print(selected)
'''
if count == cutoff:#if we could not find suitable sites for particle creation
raise randomized_error(number)
return selected
def interface(available, number, system, kwargs):
mat = kwargs['mat']
neighbors = kwargs['neigh']
available = [i for i in available if system.mats[i] in mat]
new_available = []
for i in range(len(available)):
R = np.copy(system.R)
dR = R - R[i,:]
modulo = np.sqrt(np.sum(dR*dR,axis=1))
indices = np.argsort(modulo)[1:neighbors+1]
if np.any(system.mats[indices] != system.mats[i]):
new_available.append(i)
selected = random.sample(new_available,number)
return selected
##CLASS FOR GENERATING PARTICLES IN THE SYSTEM###########################################
class Create_Particles():
def __init__(self,kind, num, method, **kwargs):
self.kind = kind
self.num = num
self.method = method
self.argv = kwargs
def assign_to_system(self,system):
selected = self.method(range(len(system.X)),self.num, system, self.argv)
Particula = getattr(sys.modules[__name__], self.kind.title())
particles = [Particula(number) for number in selected]
system.set_particles(particles)
#########################################################################################
##CLASSES TO ASSIGN ENERGIES TO LATTICE##################################################
class Gaussian_energy():
def __init__(self,s1s):
self.s1s = s1s
def assign_to_system(self,system):
type_en = self.s1s['level']
uniq = system.uniq
N = len(system.mats)
means = np.empty(N)
stds = np.empty(N)
means.fill(self.s1s[uniq[0]][0])
stds.fill(self.s1s[uniq[0]][1])
for m in uniq[1:]:
mask = system.mats == m
means[mask] = self.s1s[m][0]
stds[mask] = self.s1s[m][1]
s1 = np.random.normal(means,stds,N)
#if type(self.s1s[uniq[0]]) == str: #if the user provides a file that contains the energies
# s1 = np.random.choice(np.loadtxt(self.s1s[uniq[0]]),size = N)
#else: #if you want to generate an on-the-fly gaussian distr.
# s1 = np.random.normal(self.s1s[uniq[0]][0],self.s1s[uniq[0]][1],N)
#materials = [i for i in uniq if i != uniq[0]]
#for m in materials:
# print('aqui')
# if type(self.s1s[m]) == str:
# s11 = np.random.choice(np.loadtxt(self.s1s[m]),size = N)
# else:
# s11 = np.random.normal(self.s1s[m][0],self.s1s[m][1],N)
# s1[system.mats == m] = s11[system.mats == m]
#print(s1)
system.set_energies(s1,type_en)
#########################################################################################
# FUNCS TO SHAPE THE GENERATION OF PARTICLES
#funcs that define the filtering, like inside a sphere, plane etc
class sphere_conditional():
def __init__(self):
self.args = ['origin','radius_min']
def test_cond(self,pos,args):
r0 = args.get('origin')
r_min = args.get('radius_min')
x = pos[0] - r0[0]
y = pos[1] - r0[1]
z = pos[2] - r0[2]
r_pos = np.sqrt(x**2 + y**2 + z**2)
return r_pos <= r_min #condition to be inside the sphere
class plane_conditional():
def __init__(self):
self.args = ['origin','coefs']
def test_cond(self,pos,args):
r0 = args.get('origin')
coefs = args.get('coefs')
#Equation of plane is defined as
# A(X-X0) + B(Y-Y0) + C(Z-Z0) = 0
x = pos[0] - r0[0]
y = pos[1] - r0[1]
z = pos[2] - r0[2]
A,B,C = coefs
cond = A*x + B*y + C*z == 0 #condition to be in the plane
return cond
class cone_conditional(): #hollow cone
def __init__(self):
self.args = ['origin','coefs']
def test_cond(self,pos,args):
r0 = args.get('origin')
coefs = args.get('coefs')
#Equation of cone is defined as
# (X-X0)^2/A^2 + (Y-Y0)^2/B^2 + (Z-Z0)^2/C^2 = 0
x = pos[0] - r0[0]
y = pos[1] - r0[1]
z = pos[2] - r0[2]
A,B,C = coefs
cond = (x**2)/(A**2) + (y**2)/(B**2) -(z**2)/(C**2) == 0 #condition to be in the cone
return cond
class cilinder_conditional():
def __init__(self):
self.args = ['origin','radius_min']
def test_cond(self,pos,args):
r0 = args.get('origin')
RHO_min = args.get('radius_min')
x = pos[0] - r0[0]
y = pos[1] - r0[1]
z = pos[2] - r0[2]
cond = np.sqrt( x**2 + y**2) <= RHO_min
return cond
class no_conditional():
def __init__(self):
pass
def test_cond(self,pos,args):
return True
class rectangle_conditional():
def __init__(self):
self.args = ['limits']
def test_cond(self,pos,args):
limits = args.get('limits')
x,y,z = pos
xlim,ylim,zlim = limits
x_i,x_f = xlim
y_i,y_f = ylim
z_i,z_f = zlim
if (( x >= x_i) and ( x <= x_f)):
if (( y >= y_i) and ( y <= y_f)):
if (( z >= z_i) and ( z <= z_f)):
return True
#main function, regardless of the conditional, filters the sites according to it
def conditional_selection(available, number, system, kwargs):
# dictonary of all possible geometric creation of particles
type_dic = {'sphere': sphere_conditional, 'plane':plane_conditional,'cone':cone_conditional,
'cilinder':cilinder_conditional,'rectangle': rectangle_conditional,'free':no_conditional}
selected = []
mat_restric = kwargs['mat']
shape = kwargs['type_cond']
conditional = type_dic.get(shape)()
try:#getting all kwargs given by the user
list_kwargs = conditional.args
dict_kwargs = {}
for arg in list_kwargs:
dict_kwargs[arg] = kwargs[arg]
except:#in case that the conditional does no require additiona kwargs
dict_kwargs = []
X_cop = system.X.copy()
Y_cop = system.Y.copy()
Z_cop = system.Z.copy()
Mats_cop = system.mats.copy()
for index_mol in range(len(X_cop)):
x = X_cop[index_mol]
y = Y_cop[index_mol]
z = Z_cop[index_mol]
mat = Mats_cop[index_mol]
if conditional.test_cond([x,y,z],dict_kwargs) and (mat in mat_restric):
selected.append(index_mol)
return random.sample(selected,number)
##LATTICE CLASSES####################################################################################
class ReadLattice():
def __init__(self,file):
self.file = file
def assign_to_system(self,system):
data = np.loadtxt(self.file,comments='#')
system.set_morph(data[:,0],data[:,1],data[:,2],data[:,3])
class Lattice():
def __init__(self,num_sites,vector,disorder,composition): #initializing the lattice class with some basic info given by the user
self.num_sites = num_sites
self.vector = vector
self.disorder = disorder
self.composition = np.cumsum([i/np.sum(composition) for i in composition])
def make(self): #Generating the set X,Y,Z,Mats
dim = []
for elem in self.vector:
if elem != 0:
dim.append(1)
else:
dim.append(0)
numx = max(dim[0]*int(self.num_sites**(1/np.sum(dim))),1)
numy = max(dim[1]*int(self.num_sites**(1/np.sum(dim))),1)
numz = max(dim[2]*int(self.num_sites**(1/np.sum(dim))),1)
Numx = np.random.normal(np.array(range(numx))*self.vector[0],self.disorder[0],numx)
Numy = np.random.normal(np.array(range(numy))*self.vector[1],self.disorder[1],numy)
Numz = np.random.normal(np.array(range(numz))*self.vector[2],self.disorder[2],numz)
total = numx*numy*numz
X,Y,Z = np.meshgrid(Numx,Numy,Numz,indexing = 'ij')
X,Y,Z = X.reshape(total,),Y.reshape(total,),Z.reshape(total,)
luck = np.random.uniform(0,1,total)
Mats = np.zeros(total)
for i in reversed(range(len(self.composition))):
Mats[ luck < self.composition[i] ] = i
return X,Y,Z,Mats
def assign_to_system(self, system): #adding the X,Y,Z,Mats to the system
X, Y, Z, Mats = self.make()
system.set_morph(X,Y,Z,Mats)
#list sites' indexes of all neighbors of one given position
def filter_mats_by_distance(r,X,Y,Z,Mats,cutoff,r_index):
x = r[0]
y = r[1]
z = r[2]
neighbors = []
for n in range(len(X)):
dx = (x - X[n])
dy = (y - Y[n])
dz = (z - Z[n])
dist = np.sqrt(dx**2+dy**2+dz**2)
if(dist <= cutoff and r_index != n):
neighbors.append(n)
#return np.array(neighbors)
return neighbors
class Lattice_BHJ():
def __init__(self,n_loops,cutoff,num_sites,vector,disorder,composition):
self.n_loops = n_loops
self.cutoff = cutoff
self.num_sites = num_sites
self.vector = vector
self.disorder = disorder
self.composition = composition #np.cumsum([i/np.sum(composition) for i in composition])
self.lattice = Lattice(self.num_sites,self.vector,self.disorder,self.composition)
def make(self):
X,Y,Z,Mats = self.lattice.make()
#finding the neighbors around each site based on a cutoff distance
neighbors_lattice = []
for j in range(len(X)):
r = [X[j],Y[j],Z[j]]
neighbors = filter_mats_by_distance(r,X,Y,Z,Mats,self.cutoff,j)
neighbors_lattice.append(neighbors)
#interating the BHJ process
for i in range(self.n_loops):
Mats_new = np.copy(Mats)
for k in range(len(X)): #finding which material is more present around the j-th site
mats_selected = [ Mats[ind] for ind in neighbors_lattice[k] ]
unique, counts = np.unique(mats_selected, return_counts=True)
mat_dict = dict(zip(unique, counts))
max_mat = max(mat_dict, key=mat_dict.get)
#dealing with mats having equal max occurence
max_occurence = mat_dict[max_mat]
max_dict = {}
for entry in mat_dict:
if mat_dict[entry] == max_occurence:
max_dict[entry] = max_occurence
mat_keys = list(max_dict.keys())
ps = np.zeros([len(mat_keys)])
ps = ps +1
ps = [i/np.sum(ps) for i in ps]
ps = np.cumsum(ps)
dice = random.uniform(0,1)
chosen = np.where(dice < ps)[0][0]
Mats_new[k] = mat_keys[chosen]
Mats = np.copy(Mats_new)
Mats = np.copy(Mats_new)
unique, counts = np.unique(Mats, return_counts=True)
mat_dict = dict(zip(unique, counts))
return X,Y,Z,Mats
def assign_to_system(self, system): #adding the X,Y,Z,Mats to the system
X, Y, Z, Mats = self.make()
system.set_morph(X,Y,Z,Mats)
def multiply_lattice(lattice,n_times_ar,delta):
X_lenght = delta[0] #Increments
Y_lenght = delta[1]
Z_lenght = delta[2]
n_times_x = n_times_ar[0]
n_times_y = n_times_ar[1]
n_times_z = n_times_ar[2]
new_lattice = np.copy(lattice)
n_sites = len(lattice)
for dx in range(n_times_x):
for dy in range(n_times_y):
for dz in range(n_times_z):
new_cell = np.copy(lattice)
for i in range(n_sites):
#multipling the X position in the unit cell dx times
#beware of the convention X,Y,Z,Mats in the lattice
new_cell[i][0] = new_cell[i][0] +dx*X_lenght
new_cell[i][1] = new_cell[i][1] +dy*Y_lenght
new_cell[i][2] = new_cell[i][2] +dz*Z_lenght
new_lattice = | np.vstack((new_lattice,new_cell)) | numpy.vstack |
"""Performs face alignment and stores face thumbnails in the output directory."""
# MIT License
#
# Copyright (c) 2016 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import random
import sys
import detect_face
# import facenet
import facenet.src.facenet as facenet
import numpy as np
import tensorflow as tf
from scipy import misc
def main(args):
output_dir = args.output_dir
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Store some git revision info in a text file in the log directory
src_path, _ = os.path.split(os.path.realpath(__file__))
facenet.store_revision_info(src_path, output_dir, ' '.join(sys.argv))
dataset = facenet.get_dataset(args.input_dir)
print('Creating networks and loading parameters')
with tf.Graph().as_default():
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=args.gpu_memory_fraction)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
with sess.as_default():
pnet, rnet, onet = detect_face.create_mtcnn(sess, None)
minsize = 20 # minimum size of face
threshold = [0.6, 0.7, 0.7] # three steps's threshold
factor = 0.709 # scale factor
# Add a random key to the filename to allow alignment using multiple processes
random_key = np.random.randint(0, high=99999)
bounding_boxes_filename = os.path.join(output_dir, 'bounding_boxes_%05d.txt' % random_key)
with open(bounding_boxes_filename, "w") as text_file:
nrof_images_total = 0
nrof_successfully_aligned = 0
if args.random_order:
random.shuffle(dataset)
for cls in dataset:
output_class_dir = os.path.join(output_dir, cls.name)
if not os.path.exists(output_class_dir):
os.makedirs(output_class_dir)
if args.random_order:
random.shuffle(cls.image_paths)
for image_path in cls.image_paths:
nrof_images_total += 1
filename = os.path.splitext(os.path.split(image_path)[1])[0]
output_filename = os.path.join(output_class_dir, filename + '.png')
print(image_path)
if not os.path.exists(output_filename):
try:
img = misc.imread(image_path)
except (IOError, ValueError, IndexError) as e:
errorMessage = '{}: {}'.format(image_path, e)
print(errorMessage)
else:
if img.ndim < 2:
print('Unable to align "%s"' % image_path)
text_file.write('%s\n' % (output_filename))
continue
if img.ndim == 2:
img = facenet.to_rgb(img)
img = img[:, :, 0:3]
bounding_boxes, _ = detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)
nrof_faces = bounding_boxes.shape[0]
if nrof_faces > 0:
det = bounding_boxes[:, 0:4]
det_arr = []
img_size = np.asarray(img.shape)[0:2]
if nrof_faces > 1:
if args.detect_multiple_faces:
for i in range(nrof_faces):
det_arr.append(np.squeeze(det[i]))
else:
bounding_box_size = (det[:, 2] - det[:, 0]) * (det[:, 3] - det[:, 1])
img_center = img_size / 2
offsets = np.vstack([(det[:, 0] + det[:, 2]) / 2 - img_center[1],
(det[:, 1] + det[:, 3]) / 2 - img_center[0]])
offset_dist_squared = np.sum(np.power(offsets, 2.0), 0)
index = np.argmax(
bounding_box_size - offset_dist_squared * 2.0) # some extra weight on the centering
det_arr.append(det[index, :])
else:
det_arr.append(np.squeeze(det))
for i, det in enumerate(det_arr):
det = np.squeeze(det)
bb = | np.zeros(4, dtype=np.int32) | numpy.zeros |
# -*- coding: utf-8 -*-
"""
Created on Sat May 19 16:01:19 2018
@author: kirichoi
"""
import os, sys
import tellurium as te
import roadrunner
import numpy as np
import antimony
import scipy.optimize
import networkGenerator as ng
import plotting as pt
import ioutils
import analysis
import matplotlib.pyplot as plt
import time
import copy
#np.seterr(all='raise')
def f1(k_list, *args):
global counts
global countf
args[0].reset()
args[0].setValues(args[0].getGlobalParameterIds(), k_list)
try:
args[0].steadyStateApproximate()
objCCC = args[0].getScaledConcentrationControlCoefficientMatrix()
if np.isnan(objCCC).any():
dist_obj = 10000
else:
objCCC[np.abs(objCCC) < 1e-12] = 0 # Set small values to zero
objCCC_row = objCCC.rownames
objCCC_col = objCCC.colnames
objCCC = objCCC[np.argsort(objCCC_row)]
objCCC = objCCC[:,np.argsort(objCCC_col)]
dist_obj = ((np.linalg.norm(realConcCC - objCCC))*(1 +
np.sum(np.not_equal(np.sign(np.array(realConcCC)),
np.sign(np.array(objCCC))))))
except:
countf += 1
dist_obj = 10000
counts += 1
return dist_obj
def callbackF(X, convergence=0.):
global counts
global countf
print(str(counts) + ", " + str(countf))
return False
def mutate_and_evaluate(listantStr, listdist, listrl):
global countf
global counts
eval_dist = np.empty(mut_size)
eval_model = np.empty(mut_size, dtype='object')
eval_rl = np.empty(mut_size, dtype='object')
for m in mut_range:
r = te.loada(listantStr[m])
r.steadyStateApproximate()
concCC = r.getScaledConcentrationControlCoefficientMatrix()
cFalse = (1 + np.sum(np.not_equal(np.sign( | np.array(realConcCC) | numpy.array |
"""
<NAME>
University of Manitoba
September 10th, 2021
"""
import os
import numpy as np
import matplotlib.pyplot as plt
from umbms import get_proj_path, verify_path
from umbms.loadsave import load_pickle
###############################################################################
__OUT_DIR = os.path.join(get_proj_path(), 'output/g3/diagnostic-figs/')
verify_path(__OUT_DIR)
# Define RGB colors for plotting
das_col = [0, 0, 0]
dmas_col = [80, 80, 80]
orr_col = [160, 160, 160]
das_col = [ii / 255 for ii in das_col]
dmas_col = [ii / 255 for ii in dmas_col]
orr_col = [ii / 255 for ii in orr_col]
###############################################################################
def plt_adi_ref_performance():
"""Plot the diagnostic performance when adipose-only used as ref
"""
# Define x-coords for bars
das_xs = [0, 3.5]
dmas_xs = [1, 4.5]
orr_xs = [2, 5.5]
# Init plot
plt.figure(figsize=(12, 6))
plt.rc('font', family='Times New Roman')
plt.tick_params(labelsize=20)
# Plot DAS sensitivity and specificity
plt.bar(das_xs,
height=[das_sens[0], das_spec],
width=0.75,
linewidth=1,
color=das_col,
edgecolor='k',
label='DAS')
# Plot DMAS sensitivity and specificity
plt.bar(dmas_xs,
height=[dmas_sens[0], dmas_spec],
width=0.75,
capsize=10,
linewidth=1,
color=dmas_col,
edgecolor='k',
label='DMAS')
# Plot
plt.bar(orr_xs,
height=[orr_sens[0], orr_spec],
width=0.75,
capsize=10,
linewidth=1,
color=orr_col,
edgecolor='k',
label='ORR')
plt.legend(fontsize=18,
loc='upper left',
framealpha=0.95)
plt.xticks([1, 4.5],
["Sensitivity", "Specificity"],
size=20)
plt.ylabel('Metric Value (%)', fontsize=22)
# Put text on the bars
das_text_ys = [15, 40]
das_for_text = [das_sens[0], das_spec]
dmas_text_ys = [16, 36]
dmas_for_text = [dmas_sens[0], dmas_spec]
gd_text_ys = [23, 52]
gd_for_text = [orr_sens[0], orr_spec]
for ii in range(len(das_text_ys)):
plt.text(das_xs[ii], das_text_ys[ii],
"%d" % das_for_text[ii],
size=16,
color='k',
horizontalalignment='center',
verticalalignment='center',
bbox={'facecolor': 'w',
'alpha': 0.9})
for ii in range(len(dmas_text_ys)):
plt.text(dmas_xs[ii], dmas_text_ys[ii],
"%d" % dmas_for_text[ii],
size=16,
color='k',
horizontalalignment='center',
verticalalignment='center',
bbox={'facecolor': 'w',
'alpha': 0.9})
for ii in range(len(gd_text_ys)):
plt.text(orr_xs[ii], gd_text_ys[ii],
"%d" % gd_for_text[ii],
size=16,
color='k',
horizontalalignment='center',
verticalalignment='center',
bbox={'facecolor': 'w',
'alpha': 0.9})
# Set appropriate y-limit
plt.ylim([0, 100])
plt.tight_layout() # Make everything fit nicely
plt.show() # Display the plot
# Save the figure
plt.savefig(os.path.join(__OUT_DIR, 'sens_spec_adi_refs.png'),
dpi=300, transparent=False)
def plt_fib_ref_performance():
"""Plot the diagnostic performance when healthy scan as reference
"""
# Define x-coords for bars
das_xs = [0, 3.5]
dmas_xs = [1, 4.5]
orr_xs = [2, 5.5]
# Init fig
plt.figure(figsize=(12, 6))
plt.rc('font', family='Times New Roman')
plt.tick_params(labelsize=20)
plt.bar(das_xs,
height=[das_sens[1], das_spec],
width=0.75,
linewidth=1,
color=das_col,
edgecolor='k',
label='DAS')
plt.bar(dmas_xs,
height=[dmas_sens[1], dmas_spec],
width=0.75,
capsize=10,
linewidth=1,
color=dmas_col,
edgecolor='k',
label='DMAS')
plt.bar(orr_xs,
height=[orr_sens[1], orr_spec],
width=0.75,
capsize=10,
linewidth=1,
color=orr_col,
edgecolor='k',
label='ORR')
plt.legend(fontsize=18,
loc='upper left',
framealpha=0.95)
plt.xticks([1, 4.5],
["Sensitivity", "Specificity"],
size=20)
plt.ylabel('Metric Value (%)', fontsize=22)
# Put text on the bars
das_text_ys = [67, 40]
das_for_text = [das_sens[1], das_spec]
dmas_text_ys = [74, 36]
dmas_for_text = [dmas_sens[1], dmas_spec]
gd_text_ys = [78, 52]
gd_for_text = [orr_sens[1], orr_spec]
for ii in range(len(das_text_ys)):
plt.text(das_xs[ii], das_text_ys[ii],
"%d" % das_for_text[ii],
size=16,
color='k',
horizontalalignment='center',
verticalalignment='center',
bbox={'facecolor': 'w',
'alpha': 0.9})
for ii in range(len(dmas_text_ys)):
plt.text(dmas_xs[ii], dmas_text_ys[ii],
"%d" % dmas_for_text[ii],
size=16,
color='k',
horizontalalignment='center',
verticalalignment='center',
bbox={'facecolor': 'w',
'alpha': 0.9})
for ii in range(len(gd_text_ys)):
plt.text(orr_xs[ii], gd_text_ys[ii],
"%d" % gd_for_text[ii],
size=16,
color='k',
horizontalalignment='center',
verticalalignment='center',
bbox={'facecolor': 'w',
'alpha': 0.9})
# Set appropriate y-limit
plt.ylim([0, 100])
plt.tight_layout() # Make everything fit nicely
plt.show() # Display the plot
# Save fig
plt.savefig(os.path.join(__OUT_DIR, 'sens_spec_fib_refs.png'),
dpi=300, transparent=False)
def plt_sens_by_tum_adi():
"""Plot sensitivity as a function of tumour size with adi refs
"""
# Define x-coords of bars
das_xs = [0, 3.5, 7, 10.5, 14]
dmas_xs = [1, 4.5, 8, 11.5, 15]
orr_xs = [2, 5.5, 9, 12.5, 16]
# Init fig
plt.figure(figsize=(12, 6))
plt.rc('font', family='Times New Roman')
plt.tick_params(labelsize=20)
plt.bar(das_xs,
height=das_by_tum_adi,
width=0.75,
linewidth=1,
color=das_col,
edgecolor='k',
label='DAS')
plt.bar(dmas_xs,
height=dmas_by_tum_adi,
width=0.75,
capsize=10,
linewidth=1,
color=dmas_col,
edgecolor='k',
label='DMAS')
plt.bar(orr_xs,
height=orr_by_tum_adi,
width=0.75,
capsize=10,
linewidth=1,
color=orr_col,
edgecolor='k',
label='ORR')
plt.legend(fontsize=18,
loc='upper left',
framealpha=0.95)
plt.xticks(dmas_xs,
["30", "25", "20", "15", "10"],
size=20)
plt.ylabel('Sensitivity (%)', fontsize=22)
plt.xlabel('Tumour Diameter (mm)', fontsize=22)
# Put text on the fig
das_text_ys = np.array(das_by_tum_adi) - 4
das_text_ys[np.array(das_by_tum_adi) == 0] = 4
das_for_text = das_by_tum_adi
dmas_text_ys = np.array(dmas_by_tum_adi) - 4
dmas_text_ys[np.array(dmas_by_tum_adi) == 0] = 4
dmas_for_text = dmas_by_tum_adi
orr_text_ys = np.array(orr_by_tum_adi) - 4
orr_text_ys[np.array(orr_by_tum_adi) == 0] = 4
orr_for_text = orr_by_tum_adi
for ii in range(len(das_text_ys)):
plt.text(das_xs[ii], das_text_ys[ii],
"%d" % das_for_text[ii],
size=16,
color='k',
horizontalalignment='center',
verticalalignment='center',
bbox={'facecolor': 'w',
'alpha': 0.9})
for ii in range(len(dmas_text_ys)):
plt.text(dmas_xs[ii], dmas_text_ys[ii],
"%d" % dmas_for_text[ii],
size=16,
color='k',
horizontalalignment='center',
verticalalignment='center',
bbox={'facecolor': 'w',
'alpha': 0.9})
for ii in range(len(orr_text_ys)):
plt.text(orr_xs[ii], orr_text_ys[ii],
"%d" % orr_for_text[ii],
size=16,
color='k',
horizontalalignment='center',
verticalalignment='center',
bbox={'facecolor': 'w',
'alpha': 0.9})
# Set appropriate y-limit
plt.ylim([0, 100])
plt.tight_layout() # Make everything fit nicely
plt.show() # Display the plot
# Save fig
plt.savefig(os.path.join(__OUT_DIR, 'sens_by_tum_adi.png'),
dpi=300, transparent=False)
def plt_sens_by_tum_fib():
"""Plot sensitivity vs tumour size when healthy scan used as refs
"""
# Define x-coords for bars
das_xs = [0, 3.5, 7, 10.5, 14]
dmas_xs = [1, 4.5, 8, 11.5, 15]
orr_xs = [2, 5.5, 9, 12.5, 16]
# Init fig
plt.figure(figsize=(12, 6))
plt.rc('font', family='Times New Roman')
plt.tick_params(labelsize=20)
# Plot bars
plt.bar(das_xs,
height=das_by_tum_fib,
width=0.75,
linewidth=1,
color=das_col,
edgecolor='k',
label='DAS')
plt.bar(dmas_xs,
height=dmas_by_tum_fib,
width=0.75,
capsize=10,
linewidth=1,
color=dmas_col,
edgecolor='k',
label='DMAS')
plt.bar(orr_xs,
height=orr_by_tum_fib,
width=0.75,
capsize=10,
linewidth=1,
color=orr_col,
edgecolor='k',
label='ORR')
plt.legend(fontsize=18,
loc='upper right',
framealpha=0.95)
plt.xticks(dmas_xs,
["30", "25", "20", "15", "10"],
size=20)
plt.ylabel('Sensitivity (%)', fontsize=22)
plt.xlabel('Tumour Diameter (mm)', fontsize=22)
das_text_ys = np.array(das_by_tum_fib) - 4
das_text_ys[ | np.array(das_by_tum_fib) | numpy.array |
"""
Sentiment Classification Task
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time
import argparse
import numpy as np
import multiprocessing
import sys
import paddle
import paddle.fluid as fluid
sys.path.append("../shared_modules/models/classification/")
sys.path.append("../shared_modules/")
print(sys.path)
from nets import bow_net
from nets import lstm_net
from nets import cnn_net
from nets import bilstm_net
from nets import gru_net
from nets import ernie_base_net
from nets import ernie_bilstm_net
from preprocess.ernie import task_reader
from models.representation.ernie import ErnieConfig
from models.representation.ernie import ernie_encoder, ernie_encoder_with_paddle_hub
#from models.representation.ernie import ernie_pyreader
from models.model_check import check_cuda
from config import PDConfig
from utils import init_checkpoint
def ernie_pyreader(args, pyreader_name):
src_ids = fluid.layers.data(
name="src_ids", shape=[None, args.max_seq_len, 1], dtype="int64")
sent_ids = fluid.layers.data(
name="sent_ids", shape=[None, args.max_seq_len, 1], dtype="int64")
pos_ids = fluid.layers.data(
name="pos_ids", shape=[None, args.max_seq_len, 1], dtype="int64")
input_mask = fluid.layers.data(
name="input_mask", shape=[None, args.max_seq_len, 1], dtype="float32")
labels = fluid.layers.data(name="labels", shape=[None, 1], dtype="int64")
seq_lens = fluid.layers.data(name="seq_lens", shape=[None], dtype="int64")
pyreader = fluid.io.DataLoader.from_generator(
feed_list=[src_ids, sent_ids, pos_ids, input_mask, labels, seq_lens],
capacity=50,
iterable=False,
use_double_buffer=True)
ernie_inputs = {
"src_ids": src_ids,
"sent_ids": sent_ids,
"pos_ids": pos_ids,
"input_mask": input_mask,
"seq_lens": seq_lens
}
return pyreader, ernie_inputs, labels
def create_model(args, embeddings, labels, is_prediction=False):
"""
Create Model for sentiment classification based on ERNIE encoder
"""
sentence_embeddings = embeddings["sentence_embeddings"]
token_embeddings = embeddings["token_embeddings"]
if args.model_type == "ernie_base":
ce_loss, probs = ernie_base_net(sentence_embeddings, labels,
args.num_labels)
elif args.model_type == "ernie_bilstm":
ce_loss, probs = ernie_bilstm_net(token_embeddings, labels,
args.num_labels)
else:
raise ValueError("Unknown network type!")
if is_prediction:
return probs
loss = fluid.layers.mean(x=ce_loss)
num_seqs = fluid.layers.create_tensor(dtype='int64')
accuracy = fluid.layers.accuracy(input=probs, label=labels, total=num_seqs)
return loss, accuracy, num_seqs
def evaluate(exe, test_program, test_pyreader, fetch_list, eval_phase):
"""
Evaluation Function
"""
test_pyreader.start()
total_cost, total_acc, total_num_seqs = [], [], []
time_begin = time.time()
while True:
try:
np_loss, np_acc, np_num_seqs = exe.run(program=test_program,
fetch_list=fetch_list,
return_numpy=False)
np_loss = np.array(np_loss)
np_acc = np.array(np_acc)
np_num_seqs = | np.array(np_num_seqs) | numpy.array |
import sys
from datetime import date, datetime, timedelta
from numbers import Number
from typing import (
Any,
Callable,
Dict,
List,
Optional,
Sequence,
Tuple,
Type,
Union,
overload,
)
import numpy as np
try:
import pyarrow as pa
_PYARROW_AVAILABLE = True
except ImportError: # pragma: no cover
_PYARROW_AVAILABLE = False
import math
from polars import internals as pli
from polars.internals.construction import (
arrow_to_pyseries,
numpy_to_pyseries,
pandas_to_pyseries,
sequence_to_pyseries,
series_to_pyseries,
)
try:
from polars.polars import PyDataFrame, PySeries
_DOCUMENTING = False
except ImportError: # pragma: no cover
_DOCUMENTING = True
from polars.datatypes import (
Boolean,
DataType,
Date,
Datetime,
Duration,
Float32,
Float64,
Int8,
Int16,
Int32,
Int64,
)
from polars.datatypes import List as PlList
from polars.datatypes import (
Object,
Time,
UInt8,
UInt16,
UInt32,
UInt64,
Utf8,
dtype_to_ctype,
dtype_to_ffiname,
maybe_cast,
py_type_to_dtype,
)
from polars.utils import (
_date_to_pl_date,
_datetime_to_pl_timestamp,
_ptr_to_numpy,
_to_python_datetime,
range_to_slice,
)
try:
import pandas as pd
_PANDAS_AVAILABLE = True
except ImportError: # pragma: no cover
_PANDAS_AVAILABLE = False
if sys.version_info >= (3, 8):
from typing import Literal
else:
from typing_extensions import Literal # pragma: no cover
def get_ffi_func(
name: str,
dtype: Type["DataType"],
obj: "PySeries",
) -> Optional[Callable[..., Any]]:
"""
Dynamically obtain the proper ffi function/ method.
Parameters
----------
name
function or method name where dtype is replaced by <>
for example
"call_foo_<>"
dtype
polars dtype.
obj
Object to find the method for.
Returns
-------
ffi function, or None if not found
"""
ffi_name = dtype_to_ffiname(dtype)
fname = name.replace("<>", ffi_name)
return getattr(obj, fname, None)
def wrap_s(s: "PySeries") -> "Series":
return Series._from_pyseries(s)
ArrayLike = Union[
Sequence[Any], "Series", "pa.Array", np.ndarray, "pd.Series", "pd.DatetimeIndex"
]
class Series:
"""
A Series represents a single column in a polars DataFrame.
Parameters
----------
name : str, default None
Name of the series. Will be used as a column name when used in a DataFrame.
When not specified, name is set to an empty string.
values : ArrayLike, default None
One-dimensional data in various forms. Supported are: Sequence, Series,
pyarrow Array, and numpy ndarray.
dtype : DataType, default None
Polars dtype of the Series data. If not specified, the dtype is inferred.
strict
Throw error on numeric overflow
nan_to_null
In case a numpy arrow is used to create this Series, indicate how to deal with np.nan
Examples
--------
Constructing a Series by specifying name and values positionally:
>>> s = pl.Series("a", [1, 2, 3])
>>> s
shape: (3,)
Series: 'a' [i64]
[
1
2
3
]
Notice that the dtype is automatically inferred as a polars Int64:
>>> s.dtype
<class 'polars.datatypes.Int64'>
Constructing a Series with a specific dtype:
>>> s2 = pl.Series("a", [1, 2, 3], dtype=pl.Float32)
>>> s2
shape: (3,)
Series: 'a' [f32]
[
1
2
3
]
It is possible to construct a Series with values as the first positional argument.
This syntax considered an anti-pattern, but it can be useful in certain
scenarios. You must specify any other arguments through keywords.
>>> s3 = pl.Series([1, 2, 3])
>>> s3
shape: (3,)
Series: '' [i64]
[
1
2
3
]
"""
def __init__(
self,
name: Optional[Union[str, ArrayLike]] = None,
values: Optional[ArrayLike] = None,
dtype: Optional[Type[DataType]] = None,
strict: bool = True,
nan_to_null: bool = False,
):
# Handle case where values are passed as the first argument
if name is not None and not isinstance(name, str):
if values is None:
values = name
name = None
else:
raise ValueError("Series name must be a string.")
# TODO: Remove if-statement below once Series name is allowed to be None
if name is None:
name = ""
if values is None:
self._s = sequence_to_pyseries(name, [], dtype=dtype)
elif isinstance(values, Series):
self._s = series_to_pyseries(name, values)
elif _PYARROW_AVAILABLE and isinstance(values, pa.Array):
self._s = arrow_to_pyseries(name, values)
elif isinstance(values, np.ndarray):
self._s = numpy_to_pyseries(name, values, strict, nan_to_null)
if dtype is not None:
self._s = self.cast(dtype, strict=True)._s
elif isinstance(values, Sequence):
self._s = sequence_to_pyseries(name, values, dtype=dtype, strict=strict)
elif _PANDAS_AVAILABLE and isinstance(values, (pd.Series, pd.DatetimeIndex)):
self._s = pandas_to_pyseries(name, values)
else:
raise ValueError("Series constructor not called properly.")
@classmethod
def _from_pyseries(cls, pyseries: "PySeries") -> "Series":
series = cls.__new__(cls)
series._s = pyseries
return series
@classmethod
def _repeat(
cls, name: str, val: Union[int, float, str, bool], n: int, dtype: Type[DataType]
) -> "Series":
return cls._from_pyseries(PySeries.repeat(name, val, n, dtype))
@classmethod
def _from_arrow(
cls, name: str, values: "pa.Array", rechunk: bool = True
) -> "Series":
"""
Construct a Series from an Arrow Array.
"""
return cls._from_pyseries(arrow_to_pyseries(name, values, rechunk))
@classmethod
def _from_pandas(
cls,
name: str,
values: Union["pd.Series", "pd.DatetimeIndex"],
nan_to_none: bool = True,
) -> "Series":
"""
Construct a Series from a pandas Series or DatetimeIndex.
"""
return cls._from_pyseries(
pandas_to_pyseries(name, values, nan_to_none=nan_to_none)
)
def inner(self) -> "PySeries":
return self._s
def __getstate__(self) -> Any:
return self._s.__getstate__()
def __setstate__(self, state: Any) -> None:
self._s = sequence_to_pyseries("", [], Float32)
self._s.__setstate__(state)
def __str__(self) -> str:
return self._s.as_str()
def __repr__(self) -> str:
return self.__str__()
def __and__(self, other: "Series") -> "Series":
if not isinstance(other, Series):
other = Series([other])
return wrap_s(self._s.bitand(other._s))
def __rand__(self, other: "Series") -> "Series":
return self.__and__(other)
def __or__(self, other: "Series") -> "Series":
if not isinstance(other, Series):
other = Series([other])
return wrap_s(self._s.bitor(other._s))
def __ror__(self, other: "Series") -> "Series":
return self.__or__(other)
def __xor__(self, other: "Series") -> "Series":
if not isinstance(other, Series):
other = Series([other])
return wrap_s(self._s.bitxor(other._s))
def __rxor__(self, other: "Series") -> "Series":
return self.__xor__(other)
def _comp(self, other: Any, op: str) -> "Series":
if isinstance(other, datetime) and self.dtype == Datetime:
ts = _datetime_to_pl_timestamp(other, self.time_unit)
f = get_ffi_func(op + "_<>", Int64, self._s)
assert f is not None
return wrap_s(f(ts))
if isinstance(other, date) and self.dtype == Date:
d = _date_to_pl_date(other)
f = get_ffi_func(op + "_<>", Int32, self._s)
assert f is not None
return wrap_s(f(d))
if isinstance(other, Sequence) and not isinstance(other, str):
other = Series("", other)
if isinstance(other, Series):
return wrap_s(getattr(self._s, op)(other._s))
other = maybe_cast(other, self.dtype, self.time_unit)
f = get_ffi_func(op + "_<>", self.dtype, self._s)
if f is None:
return NotImplemented
return wrap_s(f(other))
def __eq__(self, other: Any) -> "Series": # type: ignore[override]
return self._comp(other, "eq")
def __ne__(self, other: Any) -> "Series": # type: ignore[override]
return self._comp(other, "neq")
def __gt__(self, other: Any) -> "Series":
return self._comp(other, "gt")
def __lt__(self, other: Any) -> "Series":
return self._comp(other, "lt")
def __ge__(self, other: Any) -> "Series":
return self._comp(other, "gt_eq")
def __le__(self, other: Any) -> "Series":
return self._comp(other, "lt_eq")
def _arithmetic(self, other: Any, op_s: str, op_ffi: str) -> "Series":
if isinstance(other, Series):
return wrap_s(getattr(self._s, op_s)(other._s))
if isinstance(other, float) and not self.is_float():
_s = sequence_to_pyseries("", [other])
if "rhs" in op_ffi:
return wrap_s(getattr(_s, op_s)(self._s))
else:
return wrap_s(getattr(self._s, op_s)(_s))
else:
other = maybe_cast(other, self.dtype, self.time_unit)
f = get_ffi_func(op_ffi, self.dtype, self._s)
if f is None:
raise ValueError(
f"cannot do arithmetic with series of dtype: {self.dtype} and argument of type: {type(other)}"
)
return wrap_s(f(other))
def __add__(self, other: Any) -> "Series":
if isinstance(other, str):
other = Series("", [other])
return self._arithmetic(other, "add", "add_<>")
def __sub__(self, other: Any) -> "Series":
return self._arithmetic(other, "sub", "sub_<>")
def __truediv__(self, other: Any) -> "Series":
if self.is_datelike():
raise ValueError("first cast to integer before dividing datelike dtypes")
# this branch is exactly the floordiv function without rounding the floats
if self.is_float():
return self._arithmetic(other, "div", "div_<>")
return self.cast(Float64) / other
def __floordiv__(self, other: Any) -> "Series":
if self.is_datelike():
raise ValueError("first cast to integer before dividing datelike dtypes")
result = self._arithmetic(other, "div", "div_<>")
# todo! in place, saves allocation
if self.is_float() or isinstance(other, float):
result = result.floor()
return result
def __mul__(self, other: Any) -> "Series":
if self.is_datelike():
raise ValueError("first cast to integer before multiplying datelike dtypes")
return self._arithmetic(other, "mul", "mul_<>")
def __mod__(self, other: Any) -> "Series":
if self.is_datelike():
raise ValueError(
"first cast to integer before applying modulo on datelike dtypes"
)
return self._arithmetic(other, "rem", "rem_<>")
def __rmod__(self, other: Any) -> "Series":
if self.is_datelike():
raise ValueError(
"first cast to integer before applying modulo on datelike dtypes"
)
return self._arithmetic(other, "rem", "rem_<>_rhs")
def __radd__(self, other: Any) -> "Series":
return self._arithmetic(other, "add", "add_<>_rhs")
def __rsub__(self, other: Any) -> "Series":
return self._arithmetic(other, "sub", "sub_<>_rhs")
def __invert__(self) -> "Series":
if self.dtype == Boolean:
return wrap_s(self._s._not())
return NotImplemented
def __rtruediv__(self, other: Any) -> "Series":
if self.is_datelike():
raise ValueError("first cast to integer before dividing datelike dtypes")
if self.is_float():
self.__rfloordiv__(other)
if isinstance(other, int):
other = float(other)
return self.cast(Float64).__rfloordiv__(other)
def __rfloordiv__(self, other: Any) -> "Series":
if self.is_datelike():
raise ValueError("first cast to integer before dividing datelike dtypes")
return self._arithmetic(other, "div", "div_<>_rhs")
def __rmul__(self, other: Any) -> "Series":
if self.is_datelike():
raise ValueError("first cast to integer before multiplying datelike dtypes")
return self._arithmetic(other, "mul", "mul_<>")
def __pow__(self, power: float, modulo: None = None) -> "Series":
if self.is_datelike():
raise ValueError(
"first cast to integer before raising datelike dtypes to a power"
)
return np.power(self, power) # type: ignore
def __rpow__(self, other: Any) -> "Series":
if self.is_datelike():
raise ValueError(
"first cast to integer before raising datelike dtypes to a power"
)
return np.power(other, self) # type: ignore
def __neg__(self) -> "Series":
return 0 - self
def __getitem__(self, item: Union[int, "Series", range, slice]) -> Any:
if isinstance(item, int):
if item < 0:
item = self.len() + item
if self.dtype in (PlList, Object):
f = get_ffi_func("get_<>", self.dtype, self._s)
if f is None:
return NotImplemented
out = f(item)
if self.dtype == PlList:
if out is None:
return None
return wrap_s(out)
return out
return self._s.get_idx(item)
# assume it is boolean mask
if isinstance(item, Series):
return wrap_s(self._s.filter(item._s))
if isinstance(item, range):
return self[range_to_slice(item)]
# slice
if isinstance(item, slice):
start, stop, stride = item.indices(self.len())
out = self.slice(start, stop - start)
if stride != 1:
return out.take_every(stride)
else:
return out
raise NotImplementedError
def __setitem__(
self, key: Union[int, "Series", np.ndarray, List, Tuple], value: Any
) -> None:
if isinstance(value, list):
raise ValueError("cannot set with a list as value, use a primitive value")
if isinstance(key, Series):
if key.dtype == Boolean:
self._s = self.set(key, value)._s
elif key.dtype == UInt64:
self._s = self.set_at_idx(key.cast(UInt32), value)._s
elif key.dtype == UInt32:
self._s = self.set_at_idx(key, value)._s
# TODO: implement for these types without casting to series
elif isinstance(key, np.ndarray) and key.dtype == np.bool_:
# boolean numpy mask
self._s = self.set_at_idx(np.argwhere(key)[:, 0], value)._s
elif isinstance(key, (np.ndarray, list, tuple)):
s = wrap_s(PySeries.new_u32("", np.array(key, np.uint32), True))
self.__setitem__(s, value)
elif isinstance(key, int) and not isinstance(key, bool):
self.__setitem__([key], value)
else:
raise ValueError(f'cannot use "{key}" for indexing')
def estimated_size(self) -> int:
"""
Returns an estimation of the total (heap) allocated size of the `Series` in bytes.
This estimation is the sum of the size of its buffers, validity, including nested arrays.
Multiple arrays may share buffers and bitmaps. Therefore, the size of 2 arrays is not the
sum of the sizes computed from this function. In particular, [`StructArray`]'s size is an upper bound.
When an array is sliced, its allocated size remains constant because the buffer unchanged.
However, this function will yield a smaller number. This is because this function returns
the visible size of the buffer, not its total capacity.
FFI buffers are included in this estimation.
"""
return self._s.estimated_size()
def sqrt(self) -> "Series":
"""
Compute the square root of the elements
Syntactic sugar for
>>> pl.Series([1, 2]) ** 0.5
shape: (2,)
Series: '' [f64]
[
1
1.4142135623730951
]
"""
return self ** 0.5
def any(self) -> bool:
"""
Check if any boolean value in the column is `True`
Returns
-------
Boolean literal
"""
return self.to_frame().select(pli.col(self.name).any()).to_series()[0]
def all(self) -> bool:
"""
Check if all boolean values in the column are `True`
Returns
-------
Boolean literal
"""
return self.to_frame().select(pli.col(self.name).all()).to_series()[0]
def log(self, base: float = math.e) -> "Series":
"""
Compute the logarithm to a given base
"""
return self.to_frame().select(pli.col(self.name).log(base)).to_series()
def log10(self) -> "Series":
"""
Return the base 10 logarithm of the input array, element-wise.
"""
return np.log10(self) # type: ignore
def exp(self) -> "Series":
"""
Return the exponential element-wise
"""
return | np.exp(self) | numpy.exp |
# -*- coding: utf-8 -*-
"""
@author: <NAME>
@time: 2022-2-18 16:55
"""
import numpy as np
class HMM(object):
def __init__(self, state_num, observe_num, train_params = 'ste'):
self.s_n = state_num
self.o_n = observe_num
self.A = np.random.rand(self.s_n, self.s_n)
self.A = self.A/self.A.sum(axis = 1).reshape([-1,1])
self.B = np.random.rand(self.s_n, self.o_n)
self.B = self.B/self.B.sum(axis = 1).reshape([-1,1])
self.pi = np.random.rand(self.s_n)
self.pi = self.pi/sum(self.pi)
self.train_data = []
self.train_params = train_params
#input_data 格式为 [[o1,o2,o3,...,ox], [o1,o2,o3,...,oy]]
#支持多观测序列输入,观测序列的输入是index化后的值,需要提前根据实际的观测值字典去映射,解码出的隐状态值也是一样,都是index数据,需要再根据映射还原
def add_data(self, input_data):
self.train_data.extend(input_data)
#计算所有的前向概率
# [[o1,o2,o3,...,ot1], [o1,o2,o3,...,ot2]]
# [t1 * s_n, t2 * s_n]
def forward(self, o_seqs):
self.alpha = []
for seq in o_seqs:
alpha = np.zeros((len(seq),self.s_n))
for i in range(self.s_n):
alpha[0,i] = self.pi[i] * self.B[i,seq[0]]
for r in range(1,len(seq)):
for i in range(self.s_n):
alpha[r,i] = sum([alpha[r-1,j]*self.A[j,i] for j in range(self.s_n)])*self.B[i,seq[r]]
self.alpha.append(alpha)
#计算所有的后向概率
# [[o1,o2,o3,...,ot1], [o1,o2,o3,...,ot2]]
# [t1 * s_n, t2 * s_n]
def backward(self, o_seqs):
self.beta = []
for seq in o_seqs:
beta = np.zeros((len(seq),self.s_n))
for i in range(self.s_n):
beta[len(seq)-1,i] = 1
for r in range(len(seq)-2,-1,-1):
for i in range(self.s_n):
beta[r,i] = sum([self.A[i,j]*self.B[j,seq[r+1]]*beta[r+1,j] for j in range(self.s_n)])
self.beta.append(beta)
#给定模型参数和观测序列,时刻t的状态为xx的概率
# t * s_n
# 多条观测序列输入 则为[t1 * s_n, t2 * s_n, ... , tk * s_n]
def gamma_matrix(self):
self.gamma = []
for i in range(len(self.alpha)):
alpha = self.alpha[i]
beta = self.beta[i]
self.gamma.append(alpha*beta/sum(alpha[len(alpha)-1]))
#给定模型参数和观测序列,时刻t的状态为xx,且t+1的状态为yy的概率
# t * s_n * s_n
# 多条观测序列输入 则为[t1-1 * s_n * s_n, t2-1 * s_n * s_n, ... , tk-1 * s_n * s_n]
def ksi_matrix(self):
self.ksi = []
for i in range(len(self.train_data)):
seq = self.train_data[i]
alpha = self.alpha[i]
beta = self.beta[i]
ksi = np.zeros((len(seq)-1, self.s_n, self.s_n))
for t in range(len(seq)-1):
for i in range(self.s_n):
for j in range(self.s_n):
ksi[t,i,j] = alpha[t,i]*self.A[i,j]*self.B[j,seq[t+1]]*beta[t+1,j]/sum(alpha[len(alpha)-1])
self.ksi.append(ksi)
#EM思想 Baum-Welch算法
def train(self, maxStep = 10, delta = 0.01):
step = 0
while step < maxStep:
print("=============== step {} ===============".format(step))
#固定模型参数计算隐含数据
'''
self.forward(self.train_data)
'''
#这里estimate_prob中计算了forward,所以 不用单独计算一次forward
log_prob = [np.log(p) for p in self.estimate_prob(self.train_data)]
self.backward(self.train_data)
self.gamma_matrix()
self.ksi_matrix()
#固定隐含数据计算模型参数
new_pi = sum([gamma[0] for gamma in self.gamma])/len(self.gamma)
new_A = sum([ksi.sum(axis = 0) for ksi in self.ksi])/np.reshape(sum([gamma[:-1].sum(axis = 0) for gamma in self.gamma]), [-1,1])
sn_on_list = []
for i in range(len(self.train_data)):
seq = np.array(self.train_data[i])
gamma = self.gamma[i]
sn_on = []
for o in range(self.o_n):
sn_o = (np.reshape(seq == o, [-1,1]) * gamma).sum(axis = 0).reshape([-1,1])
sn_on.append(sn_o)
sn_on_list.append(np.concatenate(sn_on,axis = 1))
new_B = sum(sn_on_list)/np.reshape(sum([gamma.sum(axis = 0) for gamma in self.gamma]), [-1,1])
#误差小也停止
pi_error = np.sum(np.square(new_pi - self.pi))
A_error = np.sum(np.square(new_A - self.A))
B_error = np.sum(np.square(new_B - self.B))
print("pi_error is {}".format(pi_error))
print("A_error is {}".format(A_error))
print("B_error is {}".format(B_error))
print("log_prob is {}".format(log_prob))
if pi_error < delta and A_error < delta and B_error < delta:
if 's' in self.train_params:
self.pi = new_pi
if 't' in self.train_params:
self.A = new_A
if 'e' in self.train_params:
self.B = new_B
break
if 's' in self.train_params:
self.pi = new_pi
if 't' in self.train_params:
self.A = new_A
if 'e' in self.train_params:
self.B = new_B
step += 1
#viterbi算法
#单条输入:[[o1,o2,o3,...,ot1]]
#多条输入:[[o1,o2,o3,...,ot1],[o1,o2,o3,...,ot2]]
#输出:[(prob1, [s1,s2,s3,...,st1]), (prob2, [s1,s2,s3,...,st2])]
def decode(self, o_seq):
result = []
for i in range(len(o_seq)):
seq = o_seq[i]
last_max_state = [[-1]*self.s_n]
max_state_prob_now = [self.pi[s]*self.B[s,seq[0]] for s in range(self.s_n)]
for o in seq[1:]:
current_last_max_state = [0]*self.s_n
max_state_prob_new = [0]*self.s_n
for ns in range(self.s_n):
candidates = [max_state_prob_now[bs]*self.A[bs,ns]*self.B[ns,o] for bs in range(self.s_n)]
max_index = np.argmax(candidates)
current_last_max_state[ns] = max_index
max_state_prob_new[ns] = candidates[max_index]
last_max_state.append(current_last_max_state)
max_state_prob_now = max_state_prob_new
#状态回溯
hidden_state = []
current_state = | np.argmax(max_state_prob_now) | numpy.argmax |
from __future__ import print_function
import os
import numpy as np
import csv
import matplotlib
from matplotlib import pyplot as plt
from matplotlib.ticker import PercentFormatter
from PIL import Image, ImageOps
from skimage import io
from utils.preprocess import load_pfm
FONTSIZE=20
matplotlib.rcParams.update({'font.size': FONTSIZE})
#matplotlib.rc('xtick', labelsize=FONTSIZE)
#matplotlib.rc('ytick', labelsize=FONTSIZE)
#matplotlib.rc('xlabel', labelsize=FONTSIZE)
#matplotlib.rc('ylabel', labelsize=FONTSIZE)
#DATAPATH = '/media/sf_Shared_Data/gpuhomedataset/dispnet'
#DATAPATH = '/home/datasets/imagenet/dispnet/virtual'
#DATAPATH = '/home/datasets/imagenet/dispnet'
DATAPATH = './data'
OUTPUTPATH = '/tmp'
#FILELIST = 'FlyingThings3D_release_TEST.list'
#FILELIST = 'FlyingThings3D_release_TRAIN.list'
#FILELIST='lists/real_release.list'
#FILELIST='lists/kitti-groundtruth.list'
#FILELIST='lists/kitti2015_train.list'
#FILELIST='lists/MB2014_TRAIN.list'
#FILELIST='lists/eth3d_train.list'
FILELIST='lists/FlyingThings3D_release_TRAIN_100.list'
RESULTLIST = 'NEW_' + FILELIST
CLEANRESULTLIST = 'CLEAN_' + FILELIST
def plot_hist(d, save=False, filename=None, plot=True, color='r'):
flatten = d.ravel()
mean = np.mean(flatten)
max = np.max(flatten)
std = np.std(flatten)
print('len: %d, mean: %.3f, std: %.3f' % (len(flatten), mean, std))
#return n_neg, flatten.size # return #negative, total
if plot:
#count, bins, ignored = plt.hist(flatten, 50, color=color)
flatten = flatten[np.abs(flatten) > 0.0]
count, bins, ignored = plt.hist(flatten, bins=np.arange(0,300), density=True, color=color)
plt.gca().yaxis.set_major_formatter(PercentFormatter(1))
plt.xlabel('Disparity')
plt.ylabel('Percentage')
if save:
plt.savefig(os.path.join(OUTPUTPATH, '%s.pdf'%filename), bbox_inches='tight')
else:
#plt.show()
pass
#plt.clf()
return mean, std, max
def statistic(file_list):
img_pairs = []
with open(file_list, "r") as f:
img_pairs = f.readlines()
csv_file = open(RESULTLIST, 'a')
for f in img_pairs:
names = f.split()
name = names[2]
print('Name: ', name)
gt_disp_name = os.path.join(DATAPATH, name)
gt_disp, scale = load_pfm(gt_disp_name)
print('Shape: ', gt_disp.shape, ', Mean: ', np.mean(gt_disp))
name_items = name.split('/')
save_name = 'hist_{}_{}_{}'.format(name_items[-4], name_items[-3], name_items[-1].split('.')[0])
mean, std, max = plot_hist(gt_disp, save=True, filename=save_name, plot=False)
writer = csv.writer(csv_file, delimiter='\t')
writer.writerow([name, mean, std, max])
csv_file.close()
def statistic_with_file(fn):
result_file = open(CLEANRESULTLIST, 'a')
with open(fn, 'r') as f:
total_array = []
fns = []
for line in f.readlines():
items = line.split('\t')
total_array.append([float(i) for i in items[1:]])
fns.append(items[0])
total_array = np.array(total_array)
print('Shape: ', total_array[:, 0].shape)
for i, mean in enumerate(total_array[:, 0]):
if mean < 150:
grt = fns[i]
name_items = grt.split('/')
left = 'FlyingThings3D_release/frames_cleanpass/%s/%s/%s/left/%s.png' % (name_items[-5], name_items[-4], name_items[-3], name_items[-1].split('.')[0])
right = 'FlyingThings3D_release/frames_cleanpass/%s/%s/%s/right/%s.png' % (name_items[-5], name_items[-4], name_items[-3], name_items[-1].split('.')[0])
#result_file.write("%s %s %s\n" % (left, right, fns[i]))
plot_hist(total_array[:, 0])
#plot_hist(total_array[:, 1])
#plot_hist(total_array[:, 2])
result_file.close()
def statistic_mean_std(filelist):
img_pairs = []
with open(filelist, "r") as f:
img_pairs = f.readlines()
means = []
for f in img_pairs:
names = f.split()
leftname = names[0]
rightname = names[1]
leftfn = os.path.join(DATAPATH, leftname)
rightfn = os.path.join(DATAPATH, rightname)
leftimgdata = io.imread(leftfn)
rightimgdata = io.imread(rightfn)
leftmean = np.mean(leftimgdata.ravel())
rightmean = np.mean(rightimgdata.ravel())
print('leftmean: ', leftmean)
print('rightmean: ', rightmean)
means.append((leftmean+rightmean)/2)
means = np.array(means)
print('total mean: ', np.mean(means))
print('total std: ', np.std(means))
def statistic_disparity(filelist):
img_pairs = []
with open(filelist, "r") as f:
img_pairs = f.readlines()
all = np.array([], dtype=np.float32)
for f in img_pairs:
names = f.split()
dispname = names[2]
fn = os.path.join(DATAPATH, dispname)
print('fn: ', fn)
if fn.find('.png') >= 0:
gt_disp = Image.open(fn)
gt_disp = np.ascontiguousarray(gt_disp,dtype=np.float32)/256
else:
gt_disp, _ = load_pfm(fn)
gt_disp[np.isinf(gt_disp)] = 0
all = np.concatenate((gt_disp.ravel(), all))
mean = np.mean(all)
std = np.std(all)
color='#A9D18E'
mean, std, max = plot_hist(all, save=True, filename=filelist, plot=True, color=color)
print('total mean: ', mean)
print('total std: ', std)
def statistic_kitti_disparity(filelist):
img_pairs = []
with open(filelist, "r") as f:
img_pairs = f.readlines()
all = np.array([], dtype=np.float32)
for f in img_pairs:
dispname = f[:-1]
fn = dispname
gt_disp = Image.open(fn)
gt_disp = np.ascontiguousarray(gt_disp,dtype=np.float32)/256
#gt_disp, _ = load_pfm(fn)
all = np.concatenate((gt_disp.ravel(), all))
np.save('stat.npy', all)
mean = np.mean(all)
std = np.std(all)
print('total mean: ', mean)
print('total std: ', std)
mean, std, max = plot_hist(all, save=True, filename='real_disp.png', plot=False, color='r')
def force_plot():
all = np.load('stat.npy')
mean, std, max = plot_hist(all, save=True, filename='real_disp.png', plot=True, color='r')
def plot_hist_with_filename(fn):
fnt='img00000.bmp'
leftfn = '/media/sf_Shared_Data/gpuhomedataset/dispnet/real_release/frames_cleanpass/left/%s'%fnt
rightfn = '/media/sf_Shared_Data/gpuhomedataset/dispnet/real_release/frames_cleanpass/right/%s'%fnt
realimgdata = io.imread(leftfn)
#leftfn = '/media/sf_Shared_Data/gpuhomedataset/FlyingThings3D_release/frames_cleanpass/TRAIN/A/0001/left/%s'%fn
#rightfn = '/media/sf_Shared_Data/gpuhomedataset/FlyingThings3D_release/frames_cleanpass/TRAIN/A/0001/right/%s'%fn
#realimgdata = io.imread(leftfn)
leftfn = '/media/sf_Shared_Data/gpuhomedataset/FlyingThings3D_release/frames_cleanpass/TRAIN/A/0000/left/%s'%fn
rightfn = '/media/sf_Shared_Data/gpuhomedataset/FlyingThings3D_release/frames_cleanpass/TRAIN/A/0000/right/%s'%fn
leftimgdata = io.imread(leftfn)
rightimgdata = io.imread(rightfn)
mean, std, max = plot_hist(leftimgdata, save=False, filename=None, plot=True, color='r')
mean, std, max = plot_hist(realimgdata, save=False, filename=None, plot=True, color='b')
plt.show()
def extract_exception_of_occulution():
#occulution_list = 'CC_FlyingThings3D_release_TRAIN.list'
#occulution_list = './lists/CC_FlyingThings3D_release_TRAIN.list'
occulution_list = './lists/girl20_TRAIN.list'
img_pairs = []
with open(occulution_list, "r") as f:
img_pairs = f.readlines()
means = []
maxcount = 10000
i = 0
for f in img_pairs:
names = f.split()
name = names[2]
#gt_disp_name = os.path.join(DATAPATH, 'clean_dispnet', name)
gt_disp_name = os.path.join(DATAPATH, name)
if not os.path.isfile(gt_disp_name):
#print('Not found: ', gt_disp_name)
continue
gt_disp, scale = load_pfm(gt_disp_name)
mean = np.mean(gt_disp)
means.append(mean)
i+=1
if i > maxcount:
break
print('Name: ', name, ', Mean: ', mean, ', std: ', | np.std(gt_disp) | numpy.std |
import tensorflow as tf
import numpy as np
from scipy.io import loadmat
from tensorflow.examples.tutorials.mnist import input_data
import copy
import hashlib
import errno
from numpy.testing import assert_array_almost_equal
def return_Obj_data(path_data):
Obj_data_all = loadmat(path_data)
xx = Obj_data_all['fts'].astype(np.float32)
yy = Obj_data_all['label']-1
yy = dense_to_one_hot_amazon(yy, 40)
return xx, xx, yy, yy
def return_Amazon(path_data, data_name):
amazon_data_all = loadmat(path_data)
xx = amazon_data_all['xx'].toarray()
xxl = xx[0:5000][:]
offset = amazon_data_all['offset']
yy = amazon_data_all['yy']
yy = dense_to_one_hot_amazon(yy,2)
if data_name == 'book':
i = 0
ind1 = int(offset[i])
ind2 = int(offset[i+1])
train_feature = np.transpose(xxl[:,ind1:ind1+2000])
test_feature = np.transpose(xxl[:,ind1+2000:ind2-1])
train_labels = yy[ind1:2000,:]
test_labels = yy[ind1+2000:ind2-1,:]
if data_name == 'dvd':
i = 1
ind1 = int(offset[i])
ind2 = int(offset[i+1])
train_feature = np.transpose(xxl[:,ind1:ind1+2000])
test_feature = np.transpose(xxl[:,ind1+2000:ind2-1])
train_labels = yy[ind1:ind1+2000,:]
test_labels = yy[ind1+2000:ind2-1,:]
if data_name == 'electronics':
i = 2
ind1 = int(offset[i])
ind2 = int(offset[i+1])
train_feature = np.transpose(xxl[:,ind1:ind1+2000])
test_feature = np.transpose(xxl[:,ind1+2000:ind2-1])
train_labels = yy[ind1:ind1+2000,:]
test_labels = yy[ind1+2000:ind2-1,:]
if data_name == 'kitchen':
i = 3
ind1 = int(offset[i])
ind2 = int(offset[i+1])
train_feature = np.transpose(xxl[:,ind1:ind1+2000])
test_feature = np.transpose(xxl[:,ind1+2000:ind2-1])
train_labels = yy[ind1:ind1+2000,:]
test_labels = yy[ind1+2000:ind2-1,:]
return train_feature, test_feature, train_labels, test_labels
def return_svhn(path_train, path_test):
svhn_train = loadmat(path_train)
svhn_test = loadmat(path_test)
svhn_train_im = svhn_train['X']
svhn_train_im = svhn_train_im.transpose(3, 0, 1, 2)
svhn_train_im = np.reshape(svhn_train_im, (svhn_train_im.shape[0], 32, 32, 3))
svhn_label = dense_to_one_hot_svhn(svhn_train['y'])
svhn_test_im = svhn_test['X']
svhn_test_im = svhn_test_im.transpose(3, 0, 1, 2)
svhn_label_test = dense_to_one_hot_svhn(svhn_test['y'])
svhn_test_im = np.reshape(svhn_test_im, (svhn_test_im.shape[0], 32, 32, 3))
return svhn_train_im, svhn_test_im, svhn_label, svhn_label_test
def return_mnist(path_train, path_test):
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
mnist_train = np.reshape(np.load(path_train), (55000, 32, 32, 1))
mnist_train = np.reshape(mnist_train, (55000, 32, 32, 1))
mnist_train = mnist_train.astype(np.float32)
mnist_test = np.reshape(np.load(path_test), (10000, 32, 32, 1)).astype(
np.float32)
mnist_test = np.reshape(mnist_test, (10000, 32, 32, 1))
mnist_train = np.concatenate([mnist_train, mnist_train, mnist_train], 3)
mnist_test = np.concatenate([mnist_test, mnist_test, mnist_test], 3)
return mnist_train, mnist_test, mnist.train.labels, mnist.test.labels
def select_class(labels, data, num_class=10, per_class=10):
classes = np.argmax(labels, axis=1)
labeled = []
train_label = []
unlabels = []
for i in range(num_class):
class_list = np.array(np.where(classes == i))
class_list = class_list[0]
class_ind = labels[np.where(classes == i), :]
rands = np.random.permutation(len(class_list))
unlabels.append(class_list[rands[per_class:]])
labeled.append(class_list[rands[:per_class]])
label_i = np.zeros((per_class, num_class))
label_i[:, i] = 1
train_label.append(label_i)
unlabel_ind = []
label_ind = []
for t in unlabels:
for i in t:
unlabel_ind.append(i)
for t in labeled:
for i in t:
label_ind.append(i)
unlabel_data = data[unlabel_ind, :, :, :]
labeled_data = data[label_ind, :, :, :]
train_label = np.array(train_label).reshape((num_class * per_class, num_class))
return np.array(labeled_data), np.array(train_label), unlabel_data
def judge_func(data, pred1, pred2, upper=0.95, num_class=10):
num = pred1.shape[0]
new_ind = []
new_data = []
new_label = []
for i in range(num):
cand_data = data[i, :, :, :]
label_data = np.zeros((1, num_class))
ind1 = np.argmax(pred1[i, :])
value1 = np.max(pred1[i, :])
ind2 = np.argmax(pred2[i, :])
value2 = np.max(pred2[i, :])
if ind1 == ind2:
if max(value1, value2) > upper:
label_data[0, ind1] = 1
new_label.append(label_data)
new_data.append(cand_data)
new_ind.append(i)
return np.array(new_data), np.array(new_label)
def judge_func_amazon(data, pred1, pred2, upper, num_class=2):
num = pred1.shape[0]
new_ind = []
new_data = []
new_label = []
for i in range(num):
cand_data = data[i, :]
label_data = np.zeros((1, num_class))
ind1 = np.argmax(pred1[i, :])
value1 = np.max(pred1[i, :])
ind2 = np.argmax(pred2[i, :])
value2 = np.max(pred2[i, :])
if ind1 == ind2:
if max(value1, value2) > upper:
label_data[0, ind1] = 1
new_label.append(label_data)
new_data.append(cand_data)
new_ind.append(i)
return np.array(new_data), np.array(new_label)
def judge_func_obj(data, pred1, pred2, upper, num_class=40):
num = pred1.shape[0]
new_ind = []
new_data = []
new_label = []
for i in range(num):
cand_data = data[i, :]
label_data = np.zeros((1, num_class))
ind1 = np.argmax(pred1[i, :])
value1 = np.max(pred1[i, :])
ind2 = np.argmax(pred2[i, :])
value2 = np.max(pred2[i, :])
if ind1 == ind2:
# print(max(value1, value2))
if max(value1, value2) > upper:
label_data[0, ind1] = 1
new_label.append(label_data)
new_data.append(cand_data)
new_ind.append(i)
return | np.array(new_data) | numpy.array |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/9/20 18:26
# @Author : ganliang
# @File : ndsplit.py
# @Desc : 数组切割
import numpy as np
a = np.arange(16).reshape(4, 4)
print(a)
print(np.split(a, 2))
print(np.hsplit(a, 4))
print( | np.vsplit(a, 4) | numpy.vsplit |
import sys
from datetime import datetime
from functools import wraps
from inspect import getcallargs
from pathlib import Path
import json
from traceback import format_exc
import matplotlib
import numpy as np
from IPython.display import display
from scipy import interpolate
from scipy.spatial.distance import euclidean
from skimage import measure
from sklearn.linear_model import LinearRegression
from sklearn.utils.validation import check_is_fitted
import ipywidgets as widgets
from remote_control.control import save_coords
from remote_control.email import send_email
from remote_control.preview import PhysicalPreview, ImzMLCoordPreview
from remote_control.utils import acquire, NpEncoder
SLIDES = {
"spot30":
{ "spot_spacing": (6, 5, 1), #h,v (mm)
"spot_size":(2., 2., 1.), #h, v (mm)
"grid_size":(3, 10), # h, v
"shape": "circle",
},
"spot10":
{"spot_spacing": (11.7, 9.7, 1), #h,v (mm) centre to centre distance
"spot_size": (6.7, 6.7, 1), #h, v (mm)
"grid_size": (2,5), # h, v,
"shape": "circle",
},
"labtek":
{"spot_spacing": (1.2, 1.2, 1), #h,v (mm) centre to centre distance
"spot_size": (3., 2., 1.), #h, v (mm)
"grid_size": (1, 4), # h, v,
"shape": "rectangle",
}
}
MASK_FUNCTIONS = {
"circle": lambda xv, yv, r, c: np.square(xv - c[0])/((r[0]/2)**2) + np.square(yv - c[1])/((r[0]/2)** 2) <= 1,
"ellipse": lambda xv, yv, r, c: np.square(xv - c[0])/(r[0]/2)**2 + np.square(yv - c[1])/(r[1]/2) ** 2 < 1,
"rectangle": lambda xv, yv, r, c: (xv < c[0] + r[0]/2.) & (xv > c[0] - r[0]/2.) & (yv < c[1] + r[1]/2.) & (yv > c[1] - r[1]/2.),
}
AREA_FUNCTIONS = {
None: lambda xv, yv, r, c, m: True,
"left": lambda xv, yv, r, c, m: (xv < c[0] - m),
"right": lambda xv, yv, r, c, m: (xv > c[0] + m),
"upper": lambda xv, yv, r, c, m: (yv > c[1] + m),
"lower": lambda xv, yv, r, c, m: (yv < c[1] - m),
"upper_left": lambda xv, yv, r, c, m: (xv < c[0] - m) & (yv > c[1] + m),
"upper_right": lambda xv, yv, r, c, m: (xv > c[0] + m) & (yv > c[1] + m),
"lower_left": lambda xv, yv, r, c, m: (xv < c[0] - m) & (yv < c[1] - m),
"lower_right": lambda xv, yv, r, c, m: (xv > c[0] + m) & (yv < c[1] - m),
}
def get_plate_info(name):
return [SLIDES[name][val] for val in ["spot_spacing", "spot_size", "grid_size"]]
def rms(v):
return np.sqrt(np.square(v).sum())
def unit_vector(v):
return v / np.linalg.norm(v)
pad = lambda x: np.hstack([x, np.ones((x.shape[0], 1))])
unpad = lambda x: x[:, :-1]
def grid_deviation(coords):
"""Models a linear transform based on the 4 supplied coords and returns the maximum error for each axis"""
base_coords = [(0, 0, 1), (1, 0, 1), (0, 1, 1), (1, 1, 1)]
coords = np.array(list(coords))
tform = np.linalg.lstsq(base_coords, coords, rcond=None)[0]
result_coords = np.array([np.dot(base_coord, tform) for base_coord in base_coords])
error = np.max(np.abs(result_coords - coords), axis=0)
return error
def grid_skew(coords):
ll, lh, hl, hh = coords[:4]
x_vector = unit_vector(ll - lh + hl - hh)
y_vector = unit_vector(ll - hl + lh - hh)
grid_skew = np.dot(x_vector, y_vector)
return np.rad2deg(np.arcsin(grid_skew))
def _record_args(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
if getattr(self, '_recorded_args', None) is None:
self._recorded_args = {'__class__': self.__class__.__name__}
all_args = getcallargs(func, self, *args, **kwargs)
all_args.pop('self', None)
self._recorded_args[func.__name__] = all_args
return func(self, *args, **kwargs)
return wrapper
class Acquisition():
def __init__(self, config_fn, datadir=None):
self.config = json.load(open(config_fn))
self.targets = []
self.image_bounds = None
self.subpattern_coords = [(0, 0)] # Physical X/Y offsets (in µm)
self.subpattern_pixels = [(0, 0)] # Pixel-space X/Y offsets
self.plots = []
def coords_fname(self, dataset_name):
return dataset_name + 'positions.json'
def write_imzml_coords(self, dataset_name):
import json
fn = self.coords_fname(dataset_name)
coords = json.load(open(fn))
fn2 = fn.replace(".json", "imzc.txt")
with open(fn2, "w+") as f:
for x, y in zip(coords['index x'], coords['index y']):
f.write("{} {}\n".format(int(x), int(y)))
def write_imzc_coords_file(self, filename):
xys = np.asarray([t[0] for t in self.targets])
with open(filename, "w") as f:
for x, y in xys[:, :2]:
f.write("{} {}\n".format(int(x), int(y)))
def write_json_coords_file(self, filename):
xys = np.asarray([t[0] for t in self.targets])
pos = np.asarray([t[1] for t in self.targets])
save_coords(filename, xys, pos, [], [])
@_record_args
def set_image_bounds(self, image_bounds=None, *, min_x=None, max_x=None, min_y=None, max_y=None):
if image_bounds is not None:
self.image_bounds = image_bounds
else:
valid_args = all(val is not None for val in [min_x, max_x, min_y, max_y])
assert valid_args, 'set_image_bounds must be called with either image_bounds or the min/max x/y named arguments'
assert min_x < max_x, 'min_x must be less than max_x'
assert min_y < max_y, 'min_y must be less than max_y'
self.image_bounds = [[max_x, min_y], [min_x, max_y]]
@_record_args
def apply_subpattern(self, subpattern_pixels, subpattern_coords, size_x, size_y):
self.subpattern_pixels = subpattern_pixels
self.subpattern_coords = subpattern_coords
self.targets = [
((px * size_x + pox, py * size_y + poy), (cx + cox, cy + coy, cz))
for (px, py), (cx, cy, cz) in self.targets
for (pox, poy), (cox, coy) in zip(self.subpattern_pixels, self.subpattern_coords)
]
@_record_args
def apply_spiral_subpattern(self, spacing_x, spacing_y):
subpattern_pixels = [
(1,1),
(1,0),
(2,0),
(2,1),
(2,2),
(1,2),
(0,2),
(0,1),
(0,0)
]
subpattern_coords = (np.array(subpattern_pixels) * [[spacing_x, spacing_y]]).tolist()
psx, psy = np.max(subpattern_pixels, axis=0) + 1 # size of pixel grid
self.apply_subpattern(subpattern_pixels, subpattern_coords, psx, psy)
def _get_recorded_args_json(self):
try:
if getattr(self, '_recorded_args', None) is not None:
return json.dumps(self._recorded_args, indent=2, cls=NpEncoder)
except:
print(f'Failed to dump recorded acquisition parameters:\n{format_exc()}')
def _save_recorded_args(self, suffix=''):
args_json = self._get_recorded_args_json()
if self.config.get('saved_parameters') and args_json is not None:
base_path = Path(self.config.get('saved_parameters'))
base_path.mkdir(parents=True, exist_ok=True)
f = base_path / f'{datetime.now().isoformat().replace(":","_")}{suffix}.json'
f.open('w').write(args_json)
@_record_args
def acquire(self, filename, dummy=True, measure=True, email_on_success=None, email_on_failure=None):
"""
:param filename: output filename prefix (should match .raw filename)
:param dummy: dummy run (True, False)
:param measure: True to measure, False to only send goto commands (True, False)
:return:
"""
assert self.targets is not None and len(self.targets), 'No targets - call generate_targets first'
try:
print("Acquiring {} ({} pixels)".format(filename, len(self.targets)))
xys = np.asarray([t[0] for t in self.targets])
pos = np.asarray([t[1] for t in self.targets])
self._recorded_args['raw_xys'] = xys.tolist()
self._recorded_args['raw_pos'] = pos.tolist()
self._save_recorded_args('_dummy' if dummy else '_moveonly' if not measure else '_real')
acquire(
config=self.config,
xys=xys,
pos=pos,
image_bounds=self.image_bounds,
dummy=dummy,
coords_fname=self.coords_fname(filename),
measure=measure
)
if not dummy:
self.write_imzml_coords(filename)
send_email(
self.config,
email_on_success,
'MALDI notebook success',
f'Acquisition completed for {filename}'
)
except:
send_email(
self.config,
email_on_failure,
'MALDI notebook error',
f'The following exception occurred while acquiring {filename}:\n{format_exc()}'
)
raise
def mask_function(self, mask_function_name):
return MASK_FUNCTIONS[mask_function_name]
def area_function(self, area_function_name):
return AREA_FUNCTIONS[area_function_name]
def apply_image_mask(self, filename, threshold=0.5):
import matplotlib.pyplot as plt
img = np.atleast_3d(plt.imread(filename))
mask = np.mean(img, axis=2) > threshold
self.targets = [([cx, cy], pos) for ((cx, cy), pos) in self.targets
if cx < mask.shape[0] and cy < mask.shape[1] and mask[cx, cy]]
print(f'Number of pixels after mask: {len(self.targets)}')
def plot_targets(self, annotate=False, show=True, dummy=False):
""" Plot output data coordinates and physical coordinates.
:param annotate: bool, whether to annotate start and stop.
:param show: bool, whether to show the plots and control panel, if False return just the plots
:param dummy: bool, whether to set dummy mode in the control panel
:return: a tuple of two plt.Figure objects containing the plots if show == False.
"""
import matplotlib.pyplot as plt
from remote_control.control_panel import ControlPanel
def handle_select(idx, data_coord, pos_coord):
pos_plot.set_selection(idx)
path_plot.set_selection(idx)
control_panel.set_selected_position(idx, pos_coord)
xys = np.asarray([t[0] for t in self.targets])
pos = np.asarray([t[1] for t in self.targets])
for plot in self.plots:
plot.close()
self.plots.clear()
if show:
# Close any existing figures that may have accumulated from other acquisition instances
plt.close('all')
plt.ion()
logs_out = widgets.Output()
pos_out = widgets.Output()
with pos_out:
pos_plot = PhysicalPreview(pos, logs_out, self.image_bounds)
pos_plot.on_select(handle_select)
self.plots.append(pos_plot)
path_out = widgets.Output()
with path_out:
path_plot = ImzMLCoordPreview(xys, pos, logs_out, annotate)
path_plot.on_select(handle_select)
self.plots.append(path_plot)
if show:
tabs = widgets.Tab()
tabs.children = [pos_out, path_out]
tabs.set_title(1, 'ImzML layout')
tabs.set_title(0, 'Stage positions')
display(tabs)
control_panel = ControlPanel(self, logs_out, dummy=dummy)
control_panel.on_select(handle_select)
display(control_panel.panel_out)
display(logs_out)
if len(pos):
handle_select(0, xys[0], pos[0])
else:
return pos_plot.fig, path_plot.fig
class RectangularAquisition(Acquisition):
@_record_args
def generate_targets(self, calibration_positions, target_positions,
x_pitch=None, y_pitch=None,
x_size=None, y_size=None,
interpolate_xy=False):
"""
:param calibration_positions: Coordinates used for calculating the Z axis.
:param target_positions: Coordinates of the 4 corners to sample
:param x_pitch: Distance between pixels in the X axis (calculated from x_size if needed)
:param y_pitch: Distance between pixels in the Y axis (calculated from y_size if needed)
:param x_size: Number of pixels in the X axis (calculated from x_pitch if needed)
:param y_size: Number of pixels in the Y axis (calculated from y_pitch if needed)
:param interpolate_xy: False to use a linear transform for calculating X/Y, which ensures the shape is at least
a parallelogram so that the x/y pitch is consistent.
True to use interpolation, which allows the shape to be trapezoidal, which ensures that
target_positions are hit exactly, but can lead to uneven pitches
"""
# Normalize inputs
calibration_positions = np.array(calibration_positions)
target_positions = np.array(target_positions)[:, :2]
if x_pitch is not None and x_size is None:
x_size = int(euclidean(target_positions[0], target_positions[1]) / x_pitch)
elif x_pitch is None and x_size is not None:
x_pitch = euclidean(target_positions[0], target_positions[1]) / x_size
else:
raise ValueError("either x_pitch or x_size must be specified, but not both")
if y_pitch is not None and y_size is None:
y_size = int(euclidean(target_positions[0], target_positions[2]) / y_pitch)
elif y_pitch is None and y_size is not None:
y_pitch = euclidean(target_positions[0], target_positions[2]) / y_size
else:
raise ValueError("either y_pitch or y_size must be specified, but not both")
# Calculate the coordinate frames and print debug info
corner_coords = np.array([(0, 0, 1), (x_size, 0, 1), (0, y_size, 1), (x_size, y_size, 1)])
print(f"Output size: {x_size} x {y_size} pixels (= {x_size*y_size} total pixels)")
print(f"Output grid pitch: {x_pitch:#.5g} x {y_pitch:#.5g}")
xy_to_z = interpolate.interp2d(calibration_positions[:, 0], calibration_positions[:, 1], calibration_positions[:, 2])
error_x, error_y, error_z = grid_deviation([(x, y, *xy_to_z(x, y)) for x, y in target_positions])
print(f"Maximum error due to grid irregularity: x±{error_x:#.2f}, y±{error_y:#.2f}, z±{error_z:#.2f}")
print(f"Grid skew: {grid_skew(target_positions):#.1f}°")
if interpolate_xy:
coord_to_x = interpolate.interp2d(corner_coords[:, 0], corner_coords[:, 1], target_positions[:, 0])
coord_to_y = interpolate.interp2d(corner_coords[:, 0], corner_coords[:, 1], target_positions[:, 1])
coord_to_xy = lambda cx, cy: (coord_to_x(cx, cy).item(0), coord_to_y(cx, cy).item(0))
else:
coord_to_xy_matrix = np.linalg.lstsq(corner_coords, target_positions, rcond=None)[0]
coord_to_xy = lambda cx, cy: tuple(np.dot((cx, cy, 1), coord_to_xy_matrix).tolist())
# Write all coordinates to self.targets
self.targets = []
for cy in range(y_size):
for cx in range(x_size):
x_pos, y_pos = coord_to_xy(cx, cy)
z_pos = xy_to_z(x_pos, y_pos).item(0)
self.targets.append(([cx, cy], [x_pos, y_pos, z_pos]))
class WellPlateGridAquisition(Acquisition):
@_record_args
def __init__(self, plate_type, *args, **kwargs):
if isinstance(plate_type, dict):
self.plate_type = plate_type['name']
self.plate=plate_type
else:
self.plate_type = plate_type
self.plate = SLIDES[plate_type]
self.tform = [] #transformation matrix
super().__init__(*args, **kwargs)
@_record_args
def calibrate(self, instrument_positions, wells, ref_loc='centre'):
"""
:param instrument_positions: positions of known locations from MCP (um). This should be the centre of the well.
:param wells: x, y index of wells used for calibration.
:return:
"""
def get_transform(primary, secondary):
# Pad the data with ones, so that our transformation can do translations too
n = primary.shape[0]
X = pad(primary)
Y = pad(secondary)
# Solve the least squares problem X * A = Y
# to find our transformation matrix A
A, res, rank, s = np.linalg.lstsq(X, Y, rcond=None)
return A
instrument_positions, wells = map(lambda x: np.asarray(x), [instrument_positions, wells])
reference_positions = self._well_coord(wells, ref_loc)
self.tform = get_transform(reference_positions, instrument_positions)
print("RMS error:", rms(instrument_positions - self._transform(reference_positions)))
@property
def _origin(self):
return np.asarray([self.plate["spot_size"][0]/2., self.plate["spot_size"][1]/2., 0])
def _well_coord(self, wells, location):
LOCATIONS= ["centre", "top_left", "top_right", "bottom_left", "bottom_right"]
TRANSFORMS = {
"centre": lambda wellixs: spacing * wellixs + self._origin,
"top_left": lambda wellixs: spacing * wellixs,
"top_right": lambda wellixs: spacing * wellixs + np.asarray([2 * self._origin[0], 0, 0]),
"bottom_left": lambda wellixs: spacing * wellixs + np.asarray([0, 2 * self._origin[1], 0]),
"bottom_right": lambda wellixs: spacing * wellixs + 2*self._origin
}
assert location in LOCATIONS, "location not in {}".format(LOCATIONS)
spacing = np.asarray(self.plate["spot_spacing"])
transform = TRANSFORMS[location]
wells = np.asarray(wells)
assert wells.ndim == 2, 'wells must be a 2D array'
assert wells.shape[1] in (2, 3), 'well coordinates must each have 2 or 3 axes'
if wells.shape[1] == 2:
# Pad to 3 components per coordinate, as that's expected by self.get_transform
wells = np.pad(wells, pad_width=((0, 0), (0, 3 - wells.shape[1])))
return transform(wells)
def _transform(self, vect):
return unpad(np.dot(pad(vect), self.tform))
def _get_measurement_bounds(self, wells_to_acquire):
wells_to_acquire = np.asarray(wells_to_acquire)
mins = np.min(wells_to_acquire, axis=0)
maxs = np.max(wells_to_acquire, axis=0)
extremes =[
[mins[0], mins[1], 0],
[maxs[0], mins[1], 0],
[mins[0], maxs[1], 0],
[maxs[0], maxs[1], 0]
]
locations = ["top_left", "top_right", "bottom_left", "bottom_right"]
t = [self._transform(self._well_coord([e], l))[0] for e, l in zip(extremes, locations)]
return np.asarray(t)
@_record_args
def generate_targets(self, wells_to_acquire, pixelsize_x, pixelsize_y,
offset_x, offset_y,
mask_function_name=None, area_function_name=None,
area_function_margin=0, shared_grid=False):
"""
:param wells_to_acquire: index (x,y) of wells to image
:param pixelsize_x: spatial separation in x (um)
:param pixelsize_y: spatial separation in y (um)
:param offset_x: (default=0) offset from 0,0 position for acquisition points in x (um)
:param offset_y: (default=0) offset from 0,0 position for acquisition points in y (um)
:param mask_function_name: None, 'circle', 'ellipse', 'rectangle'
:param area_function_name: None, 'left', 'upper', 'upper_left', etc.
:param area_function_margin: distance (um) between opposing areas defined by area function
:param shared_grid: if True, one big grid is used for the whole acquisition,
so pixels are perfectly evenly spaced, even between wells.
This allows the optical image to perfectly match the ablated area
if False, each well gets its own pixel grid. This allows a better fit
for the well shape, but may physically be up to 1 pixelsize away from
the optically registered point.
:return:
"""
if mask_function_name is None:
mask_function_name = self.plate['shape']
def well_mask(c, xv, yv):
r = [_d * 1000 for _d in self.plate["spot_size"]]
if | np.round(r[0] / pixelsize_x) | numpy.round |
import numpy as np
from dissonant.tuning import harmonic_tone, freq_to_pitch, pitch_to_freq
def test_harmonic_tone():
assert np.allclose(harmonic_tone(440, 1)[0], np.array([[440]]))
assert np.allclose(harmonic_tone(440, 1)[1], np.array([[1.]]))
assert np.allclose(harmonic_tone(440, 5)[0], np.array([[440, 880, 1320, 1760, 2200]]))
assert np.allclose(harmonic_tone(440, 5)[1], np.array([[1, 0.5, 0.33333333, 0.25, 0.2]]))
assert np.allclose(harmonic_tone([440, 441], 1)[0], np.array([[440], [441]]))
assert np.allclose(harmonic_tone([440, 441], 1)[1], np.array([[1], [1]]))
assert np.allclose(harmonic_tone([440, 441], 5)[0],
np.array([[440, 880, 1320, 1760, 2200], [441, 882, 1323, 1764, 2205]]))
assert np.allclose(harmonic_tone([440, 441], 5)[1],
| np.array([[1, 0.5, 0.33333333, 0.25, 0.2], [1, 0.5, 0.33333333, 0.25, 0.2]]) | numpy.array |
# Copyright (c) OpenMMLab. All rights reserved.
import functools
import operator
import cv2
import numpy as np
import pyclipper
import torch
from mmcv.ops import contour_expand, pixel_group
from numpy.fft import ifft
from numpy.linalg import norm
from shapely.geometry import Polygon
from skimage.morphology import skeletonize
from mmocr.core import points2boundary
from mmocr.core.evaluation.utils import boundary_iou
def filter_instance(area, confidence, min_area, min_confidence):
return bool(area < min_area or confidence < min_confidence)
def decode(
decoding_type='pan', # 'pan' or 'pse'
**kwargs):
if decoding_type == 'pan':
return pan_decode(**kwargs)
if decoding_type == 'pse':
return pse_decode(**kwargs)
if decoding_type == 'db':
return db_decode(**kwargs)
if decoding_type == 'textsnake':
return textsnake_decode(**kwargs)
if decoding_type == 'fcenet':
return fcenet_decode(**kwargs)
if decoding_type == 'drrg':
return drrg_decode(**kwargs)
raise NotImplementedError
def pan_decode(preds,
text_repr_type='poly',
min_text_confidence=0.5,
min_kernel_confidence=0.5,
min_text_avg_confidence=0.85,
min_text_area=16):
"""Convert scores to quadrangles via post processing in PANet. This is
partially adapted from https://github.com/WenmuZhou/PAN.pytorch.
Args:
preds (tensor): The head output tensor of size 6xHxW.
text_repr_type (str): The boundary encoding type 'poly' or 'quad'.
min_text_confidence (float): The minimal text confidence.
min_kernel_confidence (float): The minimal kernel confidence.
min_text_avg_confidence (float): The minimal text average confidence.
min_text_area (int): The minimal text instance region area.
Returns:
boundaries: (list[list[float]]): The instance boundary and its
instance confidence list.
"""
preds[:2, :, :] = torch.sigmoid(preds[:2, :, :])
preds = preds.detach().cpu().numpy()
text_score = preds[0].astype(np.float32)
text = preds[0] > min_text_confidence
kernel = (preds[1] > min_kernel_confidence) * text
embeddings = preds[2:].transpose((1, 2, 0)) # (h, w, 4)
region_num, labels = cv2.connectedComponents(
kernel.astype(np.uint8), connectivity=4)
contours, _ = cv2.findContours((kernel * 255).astype(np.uint8),
cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
kernel_contours = np.zeros(text.shape, dtype='uint8')
cv2.drawContours(kernel_contours, contours, -1, 255)
text_points = pixel_group(text_score, text, embeddings, labels,
kernel_contours, region_num,
min_text_avg_confidence)
boundaries = []
for text_inx, text_point in enumerate(text_points):
text_confidence = text_point[0]
text_point = text_point[2:]
text_point = np.array(text_point, dtype=int).reshape(-1, 2)
area = text_point.shape[0]
if filter_instance(area, text_confidence, min_text_area,
min_text_avg_confidence):
continue
vertices_confidence = points2boundary(text_point, text_repr_type,
text_confidence)
if vertices_confidence is not None:
boundaries.append(vertices_confidence)
return boundaries
def pse_decode(preds,
text_repr_type='poly',
min_kernel_confidence=0.5,
min_text_avg_confidence=0.85,
min_kernel_area=0,
min_text_area=16):
"""Decoding predictions of PSENet to instances. This is partially adapted
from https://github.com/whai362/PSENet.
Args:
preds (tensor): The head output tensor of size nxHxW.
text_repr_type (str): The boundary encoding type 'poly' or 'quad'.
min_text_confidence (float): The minimal text confidence.
min_kernel_confidence (float): The minimal kernel confidence.
min_text_avg_confidence (float): The minimal text average confidence.
min_kernel_area (int): The minimal text kernel area.
min_text_area (int): The minimal text instance region area.
Returns:
boundaries: (list[list[float]]): The instance boundary and its
instance confidence list.
"""
preds = torch.sigmoid(preds) # text confidence
score = preds[0, :, :]
masks = preds > min_kernel_confidence
text_mask = masks[0, :, :]
kernel_masks = masks[0:, :, :] * text_mask
score = score.data.cpu().numpy().astype(np.float32) # to numpy
kernel_masks = kernel_masks.data.cpu().numpy().astype(np.uint8) # to numpy
region_num, labels = cv2.connectedComponents(
kernel_masks[-1], connectivity=4)
# labels = pse(kernel_masks, min_kernel_area)
labels = contour_expand(kernel_masks, labels, min_kernel_area, region_num)
labels = np.array(labels)
label_num = np.max(labels)
boundaries = []
for i in range(1, label_num + 1):
points = np.array(np.where(labels == i)).transpose((1, 0))[:, ::-1]
area = points.shape[0]
score_instance = np.mean(score[labels == i])
if filter_instance(area, score_instance, min_text_area,
min_text_avg_confidence):
continue
vertices_confidence = points2boundary(points, text_repr_type,
score_instance)
if vertices_confidence is not None:
boundaries.append(vertices_confidence)
return boundaries
def box_score_fast(bitmap, _box):
h, w = bitmap.shape[:2]
box = _box.copy()
xmin = np.clip(np.floor(box[:, 0].min()).astype(np.int32), 0, w - 1)
xmax = np.clip(np.ceil(box[:, 0].max()).astype(np.int32), 0, w - 1)
ymin = np.clip(np.floor(box[:, 1].min()).astype(np.int32), 0, h - 1)
ymax = np.clip(np.ceil(box[:, 1].max()).astype(np.int32), 0, h - 1)
mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)
box[:, 0] = box[:, 0] - xmin
box[:, 1] = box[:, 1] - ymin
cv2.fillPoly(mask, box.reshape(1, -1, 2).astype(np.int32), 1)
return cv2.mean(bitmap[ymin:ymax + 1, xmin:xmax + 1], mask)[0]
def unclip(box, unclip_ratio=1.5):
poly = Polygon(box)
distance = poly.area * unclip_ratio / poly.length
offset = pyclipper.PyclipperOffset()
offset.AddPath(box, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)
expanded = np.array(offset.Execute(distance))
return expanded
def db_decode(preds,
text_repr_type='poly',
mask_thr=0.3,
min_text_score=0.3,
min_text_width=5,
unclip_ratio=1.5,
max_candidates=3000):
"""Decoding predictions of DbNet to instances. This is partially adapted
from https://github.com/MhLiao/DB.
Args:
preds (Tensor): The head output tensor of size nxHxW.
text_repr_type (str): The boundary encoding type 'poly' or 'quad'.
mask_thr (float): The mask threshold value for binarization.
min_text_score (float): The threshold value for converting binary map
to shrink text regions.
min_text_width (int): The minimum width of boundary polygon/box
predicted.
unclip_ratio (float): The unclip ratio for text regions dilation.
max_candidates (int): The maximum candidate number.
Returns:
boundaries: (list[list[float]]): The predicted text boundaries.
"""
prob_map = preds[0, :, :]
text_mask = prob_map > mask_thr
score_map = prob_map.data.cpu().numpy().astype(np.float32)
text_mask = text_mask.data.cpu().numpy().astype(np.uint8) # to numpy
contours, _ = cv2.findContours((text_mask * 255).astype(np.uint8),
cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
boundaries = []
for i, poly in enumerate(contours):
if i > max_candidates:
break
epsilon = 0.01 * cv2.arcLength(poly, True)
approx = cv2.approxPolyDP(poly, epsilon, True)
points = approx.reshape((-1, 2))
if points.shape[0] < 4:
continue
score = box_score_fast(score_map, points)
if score < min_text_score:
continue
poly = unclip(points, unclip_ratio=unclip_ratio)
if len(poly) == 0 or isinstance(poly[0], list):
continue
poly = poly.reshape(-1, 2)
if text_repr_type == 'quad':
poly = points2boundary(poly, text_repr_type, score, min_text_width)
elif text_repr_type == 'poly':
poly = poly.flatten().tolist()
if score is not None:
poly = poly + [score]
if len(poly) < 8:
poly = None
else:
raise ValueError(f'Invalid text repr type {text_repr_type}')
if poly is not None:
boundaries.append(poly)
return boundaries
def fill_hole(input_mask):
h, w = input_mask.shape
canvas = | np.zeros((h + 2, w + 2), np.uint8) | numpy.zeros |
import pytest
import cv2
import numpy as np
from plantcv.plantcv import report_size_marker_area, outputs
@pytest.mark.parametrize("marker,exp", [["detect", 1257], ["define", 2601]])
def test_report_size_marker(marker, exp, test_data):
"""Test for PlantCV."""
# Clear outputs
outputs.clear()
# Read in test data
img = cv2.imread(test_data.small_rgb_img)
# Draw a marker
img = cv2.circle(img, (50, 100), 20, (0, 0, 255), thickness=-1)
# ROI contour
roi_contour = [np.array([[[25, 75]], [[25, 125]], [[75, 125]], [[75, 75]]], dtype=np.int32)]
roi_hierarchy = np.array([[[-1, -1, -1, -1]]], dtype=np.int32)
_ = report_size_marker_area(img=img, roi_contour=roi_contour, roi_hierarchy=roi_hierarchy, marker=marker,
objcolor='light', thresh_channel='s', thresh=120)
assert int(outputs.observations["default"]["marker_area"]["value"]) == exp
def test_report_size_marker_grayscale_input(test_data):
"""Test for PlantCV."""
# Clear outputs
outputs.clear()
# Read in test data
img = cv2.imread(test_data.small_gray_img, -1)
# ROI contour
roi_contour = [ | np.array([[[25, 75]], [[25, 125]], [[75, 125]], [[75, 75]]], dtype=np.int32) | numpy.array |
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense
from tf2rl.algos.policy_base import OffPolicyAgent
from tf2rl.networks.noisy_dense import NoisyDense
from tf2rl.envs.atari_wrapper import LazyFrames
from tf2rl.misc.target_update_ops import update_target_variables
from tf2rl.misc.huber_loss import huber_loss
class QFunc(tf.keras.Model):
def __init__(self, state_shape, action_dim, units=(32, 32),
name="QFunc", enable_dueling_dqn=False, enable_noisy_dqn=False):
super().__init__(name=name)
self._enable_dueling_dqn = enable_dueling_dqn
self._enable_noisy_dqn = enable_noisy_dqn
DenseLayer = NoisyDense if enable_noisy_dqn else Dense
self.l1 = DenseLayer(units[0], name="L1", activation="relu")
self.l2 = DenseLayer(units[1], name="L2", activation="relu")
self.l3 = DenseLayer(action_dim, name="L3", activation="linear")
if enable_dueling_dqn:
self.l4 = DenseLayer(1, name="L3", activation="linear")
with tf.device("/cpu:0"):
self(inputs=tf.constant(np.zeros(shape=(1,) + state_shape,
dtype=np.float32)))
def call(self, inputs):
features = self.l1(inputs)
features = self.l2(features)
if self._enable_dueling_dqn:
advantages = self.l3(features)
v_values = self.l4(features)
q_values = (v_values
+ (advantages
- tf.reduce_mean(advantages, axis=1, keepdims=True)))
else:
q_values = self.l3(features)
return q_values
class DQN(OffPolicyAgent):
"""
DQN Agent: https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf
DQN supports following algorithms;
* DDQN: https://arxiv.org/abs/1509.06461
* Dueling Network: https://arxiv.org/abs/1511.06581
* Noisy Network: https://arxiv.org/abs/1706.10295
Command Line Args:
* ``--n-warmup`` (int): Number of warmup steps before training. The default is ``1e4``.
* ``--batch-size`` (int): Batch size of training. The default is ``32``.
* ``--gpu`` (int): GPU id. ``-1`` disables GPU. The default is ``0``.
* ``--memory-capacity`` (int): Replay Buffer size. The default is ``1e6``.
* ``--enable-double-dqn``: Enable DDQN
* ``--enable-dueling-dqn``: Enable Dueling Network
* ``--enable-noisy-dqn``: Enable Noisy Network
"""
def __init__(
self,
state_shape,
action_dim,
q_func=None,
name="DQN",
lr=0.001,
adam_eps=1e-07,
units=(32, 32),
epsilon=0.1,
epsilon_min=None,
epsilon_decay_step=int(1e6),
n_warmup=int(1e4),
target_replace_interval=int(5e3),
memory_capacity=int(1e6),
enable_double_dqn=False,
enable_dueling_dqn=False,
enable_noisy_dqn=False,
optimizer=None,
**kwargs):
"""
Initialize DQN agent
Args:
state_shape (iterable of int): Observation space shape
action_dim (int): Dimension of discrete action
q_function (QFunc): Custom Q function class. If ``None`` (default), Q function is constructed with ``QFunc``.
name (str): Name of agent. The default is ``"DQN"``
lr (float): Learning rate. The default is ``0.001``.
adam_eps (float): Epsilon for Adam. The default is ``1e-7``
units (iterable of int): Units of hidden layers. The default is ``(32, 32)``
espilon (float): Initial epsilon of e-greedy. The default is ``0.1``
epsilon_min (float): Minimum epsilon of after decayed.
epsilon_decay_step (int): Number of steps decaying. The default is ``1e6``
n_warmup (int): Number of warmup steps befor training. The default is ``1e4``
target_replace_interval (int): Number of steps between target network update. The default is ``5e3``
memory_capacity (int): Size of replay buffer. The default is ``1e6``
enable_double_dqn (bool): Whether use Double DQN. The default is ``False``
enable_dueling_dqn (bool): Whether use Dueling network. The default is ``False``
enable_noisy_dqn (bool): Whether use noisy network. The default is ``False``
optimizer (tf.keras.optimizers.Optimizer): Custom optimizer
batch_size (int): Batch size. The default is ``256``.
discount (float): Discount factor. The default is ``0.99``.
max_grad (float): Maximum gradient. The default is ``10``.
gpu (int): GPU id. ``-1`` disables GPU. The default is ``0``.
"""
super().__init__(name=name, memory_capacity=memory_capacity, n_warmup=n_warmup, **kwargs)
q_func = q_func if q_func is not None else QFunc
# Define and initialize Q-function network
kwargs_dqn = {
"state_shape": state_shape,
"action_dim": action_dim,
"units": units,
"enable_dueling_dqn": enable_dueling_dqn,
"enable_noisy_dqn": enable_noisy_dqn}
self.q_func = q_func(**kwargs_dqn)
self.q_func_target = q_func(**kwargs_dqn)
self.q_func_optimizer = optimizer or tf.keras.optimizers.Adam(learning_rate=lr, epsilon=adam_eps)
update_target_variables(self.q_func_target.weights,
self.q_func.weights, tau=1.)
self._action_dim = action_dim
# This is used to check if input state to `get_action` is multiple (batch) or single
self._state_ndim = | np.array(state_shape) | numpy.array |
import warnings
import numpy as np
import scipy
import matplotlib.pyplot as plt
from scipy.ndimage.filters import gaussian_filter1d
from scipy.interpolate import UnivariateSpline
from astropy import log
from astropy.table import Table
from ..crossspectrum import AveragedCrossspectrum, normalize_crossspectrum
from ..powerspectrum import AveragedPowerspectrum
from ..gti import cross_two_gtis, bin_intervals_from_gtis
__all__ = ["calculate_FAD_correction", "get_periodograms_from_FAD_results"]
def _get_fourier_intv(lc, start_ind, end_ind):
"""Calculate the Fourier transform of a light curve chunk.
Parameters
----------
lc : a :class:`Lightcurve` object
Input light curve
start_ind : int
Start index of the light curve chunk
end_ind : int
End index of the light curve chunk
Returns
-------
freq : array of floats
Frequencies of the Fourier transform
fft : array of complex numbers
The Fourier transform
nph : int
Number of photons in the interval of the light curve
nbins : int
Number of bins in the light curve segment
meancounts : float
The mean counts/bin in the light curve
"""
time = lc.time[start_ind:end_ind]
counts = lc.counts[start_ind:end_ind]
fourier = scipy.fftpack.fft(counts)
freq = scipy.fftpack.fftfreq(len(time), lc.dt)
good = freq > 0
nbins = time.size
return freq[good], fourier[good], np.sum(counts), nbins
def calculate_FAD_correction(lc1, lc2, segment_size, norm="none", gti=None,
plot=False, ax=None, smoothing_alg='gauss',
smoothing_length=None, verbose=False,
tolerance=0.05, strict=False, all_leahy=False,
output_file=None, return_objects=False):
"""Calculate Frequency Amplitude Difference-corrected (cross)power spectra.
Reference: Bachetti \& Huppenkothen, 2018, ApJ, 853L, 21
The two input light curve must be strictly simultaneous, and recorded by
two independent detectors with similar responses, so that the count rates
are similar and dead time is independent.
The method does not apply to different energy channels of the same
instrument, or to the signal observed by two instruments with very
different responses. See the paper for caveats.
Parameters
----------
lc1: class:`stingray.ligthtcurve.Lightcurve`
Light curve from channel 1
lc2: class:`stingray.ligthtcurve.Lightcurve`
Light curve from channel 2. Must be strictly simultaneous to ``lc1``
and have the same binning time. Also, it must be strictly independent,
e.g. from a different detector. There must be no dead time cross-talk
between the two light curves.
segment_size: float
The final Fourier products are averaged over many segments of the
input light curves. This is the length of each segment being averaged.
Note that the light curve must be long enough to have at least 30
segments, as the result gets better as one averages more and more
segments.
norm: {``frac``, ``abs``, ``leahy``, ``none``}, default ``none``
The normalization of the (real part of the) cross spectrum.
Other parameters
----------------
plot : bool, default False
Plot diagnostics: check if the smoothed Fourier difference scatter is
a good approximation of the data scatter.
ax : :class:`matplotlib.axes.axes` object
If not None and ``plot`` is True, use this axis object to produce
the diagnostic plot. Otherwise, create a new figure.
smoothing_alg : {'gauss', ...}
Smoothing algorithm. For now, the only smoothing algorithm allowed is
``gauss``, which applies a Gaussian Filter from `scipy`.
smoothing_length : int, default ``segment_size * 3``
Number of bins to smooth in gaussian window smoothing
verbose: bool, default False
Print out information on the outcome of the algorithm (recommended)
tolerance : float, default 0.05
Accepted relative error on the FAD-corrected Fourier amplitude, to be
used as success diagnostics.
Should be
```
stdtheor = 2 / np.sqrt(n)
std = (average_corrected_fourier_diff / n).std()
np.abs((std - stdtheor) / stdtheor) < tolerance
```
strict : bool, default False
Decide what to do if the condition on tolerance is not met. If True,
raise a ``RuntimeError``. If False, just throw a warning.
all_leahy : **deprecated** bool, default False
Save all spectra in Leahy normalization. Otherwise, leave unnormalized.
output_file : str, default None
Name of an output file (any extension automatically recognized by
Astropy is fine)
Returns
-------
results : class:`astropy.table.Table` object or ``dict`` or ``str``
The content of ``results`` depends on whether ``return_objects`` is
True or False.
If ``return_objects==False``,
``results`` is a `Table` with the following columns:
+ pds1: the corrected PDS of ``lc1``
+ pds2: the corrected PDS of ``lc2``
+ cs: the corrected cospectrum
+ ptot: the corrected PDS of lc1 + lc2
If ``return_objects`` is True, ``results`` is a ``dict``, with keys
named like the columns
listed above but with `AveragePowerspectrum` or
`AverageCrossspectrum` objects instead of arrays.
"""
if smoothing_length is None:
smoothing_length = segment_size * 3
if gti is None:
gti = cross_two_gtis(lc1.gti, lc2.gti)
if all_leahy:
warnings.warn("`all_leahy` is deprecated. Use `norm` instead! " +
" Setting `norm`=`leahy`.", DeprecationWarning)
norm="leahy"
lc1.gti = gti
lc2.gti = gti
lc1.apply_gtis()
lc2.apply_gtis()
summed_lc = lc1 + lc2
start_inds, end_inds = \
bin_intervals_from_gtis(gti, segment_size, lc1.time,
dt=lc1.dt)
freq = 0
# These will be the final averaged periodograms. Initializing with a single
# scalar 0, but the final products will be arrays.
pds1 = 0
pds2 = 0
ptot = 0
cs = 0
n = 0
nph1_tot = nph2_tot = nph_tot = 0
average_diff = average_diff_uncorr = 0
if plot:
if ax is None:
fig, ax = plt.subplots()
for start_ind, end_ind in zip(start_inds, end_inds):
freq, f1, nph1, nbins1 = _get_fourier_intv(lc1, start_ind,
end_ind)
f1_leahy = f1 * | np.sqrt(2 / nph1) | numpy.sqrt |
import comet_ml, json
import numpy as np
import torch
from torch import optim
from misc import clear_gradients
from lib import create_agent
from util.env_util import create_env
from util.plot_util import load_checkpoint
from lib.distributions import kl_divergence
from local_vars import PROJECT_NAME, WORKSPACE, LOADING_API_KEY, LOGGING_API_KEY
alim = [-1, 1]
aint = 0.01
BATCH_SIZE = 256
N_ACTION_SAMPLES = 100
# Reacher Experiments:
# direct: 48edb0b9aca847c09c6893793c982884
# iterative: 58ec5bc5273044e59ae30a969c3d7de4
def estimate_opt_landscape(exp_key, states=None, ckpt_timestep=None, device_id=None):
"""
Estimates the optimization landscape for a checkpointed agent. Also gets the
policy estimates during inference optimization.
Args:
exp_key (str): the comet experiment ID
state (list of torch.Tensor, optional): the state(s) used for estimation
ckpt_timestep (int, optional): the checkpoint for estimation
device_id (int, optional): the GPU ID
"""
# load the experiment
comet_api = comet_ml.API(api_key=LOADING_API_KEY)
experiment = comet_api.get_experiment(project_name=PROJECT_NAME,
workspace=WORKSPACE,
experiment=exp_key)
# create the environment (just to create agent)
param_summary = experiment.get_parameters_summary()
env_name = [a for a in param_summary if a['name'] == 'env'][0]['valueCurrent']
env = create_env(env_name)
# create the agent
asset_list = experiment.get_asset_list()
agent_config_asset_list = [a for a in asset_list if 'agent_args' in a['fileName']]
agent_args = None
if len(agent_config_asset_list) > 0:
# if we've saved the agent config dict, load it
agent_args = experiment.get_asset(agent_config_asset_list[0]['assetId'])
agent_args = json.loads(agent_args)
agent_args = agent_args if 'opt_type' in agent_args['inference_optimizer_args'] else None
agent = create_agent(env, agent_args=agent_args, device_id=device_id)[0]
# load the checkpoint
load_checkpoint(agent, exp_key, ckpt_timestep)
if states is None:
# load a random state from the most recently collected episode
state_asset = None
if ckpt_timestep is not None:
# load the corresponding episode if it is present
state_asset_list = [a for a in asset_list if 'episode_step_' + str(ckpt_timestep) + '_state' in a['fileName']]
if len(state_asset_list) > 0:
state_asset = state_asset_list[0]
if state_asset is None:
# get most recently collected episode
asset_times = [asset['createdAt'] for asset in asset_list if 'state' in asset['fileName']]
state_asset = [a for a in asset_list if a['createdAt'] == max(asset_times)][0]
episode_states = experiment.get_asset(state_asset['assetId'])
episode_states = json.loads(episode_states)
# state_timestep = [np.random.randint(len(episode_states)) for _ in range(100)]
state_timesteps = range(100)
states = [torch.from_numpy( | np.array(episode_states[state_timestep]) | numpy.array |
import numpy as np
def linear(t):
return t
def in_quad(t):
return t * t
def out_quad(t):
return -t * (t - 2)
def in_out_quad(t):
u = 2 * t - 1
a = 2 * t * t
b = -0.5 * (u * (u - 2) - 1)
return np.where(t < 0.5, a, b)
def in_cubic(t):
return t * t * t
def out_cubic(t):
u = t - 1
return u * u * u + 1
def in_out_cubic(t):
u = t * 2
v = u - 2
a = 0.5 * u * u * u
b = 0.5 * (v * v * v + 2)
return np.where(u < 1, a, b)
def in_quart(t):
return t * t * t * t
def out_quart(t):
u = t - 1
return -(u * u * u * u - 1)
def in_out_quart(t):
u = t * 2
v = u - 2
a = 0.5 * u * u * u * u
b = -0.5 * (v * v * v * v - 2)
return np.where(u < 1, a, b)
def in_quint(t):
return t * t * t * t * t
def out_quint(t):
u = t - 1
return u * u * u * u * u + 1
def in_out_quint(t):
u = t * 2
v = u - 2
a = 0.5 * u * u * u * u * u
b = 0.5 * (v * v * v * v * v + 2)
return np.where(u < 1, a, b)
def in_sine(t):
return -np.cos(t * np.pi / 2) + 1
def out_sine(t):
return np.sin(t * np.pi / 2)
def in_out_sine(t):
return -0.5 * (np.cos(np.pi * t) - 1)
def in_expo(t):
a = np.zeros(len(t))
b = 2 ** (10 * (t - 1))
return np.where(t == 0, a, b)
def out_expo(t):
a = np.zeros(len(t)) + 1
b = 1 - 2 ** (-10 * t)
return | np.where(t == 1, a, b) | numpy.where |
# System
import time, os, h5py, re
import logging
# Structure
from collections import deque
# Data
import scipy
import numpy as np
import pandas as pd
from scipy.sparse import diags as spdiags
from scipy.sparse import linalg as sp_linalg
from scipy import interpolate, signal
from utils_models import auc_roc_2dist
from packages.photometry_functions import get_dFF
# Plotting
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import seaborn as sns
from packages.photometry_functions import get_f0_Martianova_jove, jove_fit_reference, jove_find_best_param
# caiman
try:
from caiman.source_extraction.cnmf.deconvolution import GetSn
from caiman.source_extraction.cnmf.utilities import fast_prct_filt
from caiman.utils.stats import df_percentile
except ModuleNotFoundError:
print("CaImAn not installed or environment not activated, certain functions might not be usable")
RAND_STATE = 230
# TODO: Move project specific portions to pipeline_*.py as things scale
##################################################
#################### Loading #####################
##################################################
def get_probswitch_session_by_condition(folder, group='all', region='NAc', signal='all'):
""" Searches through [folder] and find all of probswitch experiment sessions that match the
description; Returns lists of session files of different recording type
:param group: str, expression
:param region: str, region of recording
:param signal: str, signal type (DA or Ca 05/25/21)
:param photometry:
:param choices:
:param processed:
:return:
"""
if group == 'all':
groups = ('D1', 'A2A')
else:
groups = [group]
if region == 'all':
regions = ['NAc', 'DMS']
else:
regions = [region]
if signal == 'all':
signals = ['DA', 'Ca']
else:
signals = [signal]
results = {}
for g in groups:
grouppdf = pd.read_csv(os.path.join(folder, f"ProbSwitch_FP_Mice_{g}.csv"))
rsel = grouppdf['Region'].isin(regions)
if signals[0] == 'none':
animal_sessions = grouppdf[rsel]
else:
fpsel = grouppdf['FP'] >= 1
sigsel = np.logical_and.reduce([grouppdf[f'FP_{s}_zoom'] > 0 for s in signals])
animal_sessions = grouppdf[rsel & fpsel & sigsel]
results[g] = {}
for animal in animal_sessions['animal'].unique():
results[g][animal] = sorted(animal_sessions[animal_sessions['animal'] == animal]['session'])
return results
def get_prob_switch_all_sessions(folder, groups):
""" Exhaustively check all folder that contains ProbSwitch task .mat files and encode all sessions.
.mat -> decode -> return group
:param folder:
:return:
"""
only_Ca = []
only_DA = []
results = {g: {a: [] for a in groups[g]} for g in groups}
for d in os.listdir(folder):
if os.path.isdir(os.path.join(folder, d)):
m = re.match("^(?P<animal>\w{2,3}-\d{2,}[-\w*]*_[A-Z]{2})_(?P<session>p\d+\w+)", d)
if m:
animal, day = m.group('animal'), m.group('session')
group_dict = results[animal.split("-")[0]]
if animal in group_dict:
group_dict[animal].append(day)
elif animal not in group_dict and '*' in group_dict:
group_dict[animal] = [day]
for g in results:
del results[g]['*']
return results
def check_FP_contain_dff_method(fp, methods, sig='DA'):
""" Utility function that helps check whether the <fp> hdf5 file contains <dff> signals preprocessed.
"""
if fp is None:
return False
if isinstance(methods, str):
methods = [methods]
with h5py.File(fp, 'r') as hf:
return np.all([f'{sig}/dff/{m}' in hf for m in methods])
def get_sources_from_csvs(csvfiles, window=400, aux_times=None, tags=None, show=False):
"""
Extract sources from a list of csvfiles, with csvfile[0] be channels with cleaniest
TODO: potentially use the fact that 415 has the same timestamps to speed up the process
:param csvfiles:
:param window:
:return:
"""
if isinstance(csvfiles, str):
csvfiles = [csvfiles]
try:
pdf = pd.read_csv(csvfiles[0], delimiter=" ", names=['time', 'calcium'], usecols=[0, 1])
FP_times = [None] * len(csvfiles)
FP_signals = [None] * len(csvfiles)
for i in range(len(csvfiles)):
csvfile = csvfiles[i]
# Signal Sorting
pdf = pd.read_csv(csvfile, delimiter=" ", names=['time', 'calcium'], usecols=[0, 1])
FP_times[i] = pdf.time.values
FP_signals[i] = pdf.calcium.values
if aux_times:
old_zero = FP_times[0][0]
if old_zero == aux_times[0][0]:
print('WARNING: NO UPDATE, something is up')
assert len(FP_times) == len(aux_times), 'MUST BE SAME dim'
FP_times = aux_times
if tags is None:
tags = [f'REC{i}' for i in range(len(csvfiles))]
except:
print('OOPPS')
# TODO: aux_time input potentially needed
FP_times = [None] * len(csvfiles) * 2
FP_signals = [None] * len(csvfiles) * 2
for i in range(len(csvfiles)):
# Signal Sorting
csvfile = csvfiles[i]
pdf = pd.read_csv(csvfile, delimiter=",")
red_sig = pdf['Region1R'].values
green_sig = pdf['Region0G'].values
times = pdf['Timestamp'].values
FP_times[2 * i], FP_times[2*i+1] = times, times
FP_signals[2 * i], FP_signals[2*i+1] = green_sig, red_sig
if tags is None:
tags = np.concatenate([[f'REC{i}_G', f'REC{i}_R'] for i in range(len(csvfiles))])
FP_REC_signals = [None] * len(FP_signals)
FP_REC_times = [None] * len(FP_signals)
FP_415_signals = [None] * len(FP_signals)
FP_415_times = [None] * len(FP_signals)
FP_415_sel = None
for i in range(len(FP_signals)):
FP_time, FP_signal = FP_times[i], FP_signals[i]
# # Plain Threshold
# min_signal, max_signal = np.min(FP_signal), np.max(FP_signal)
# intensity_threshold = min_signal+(max_signal - min_signal)*0.4
# Dynamic Threshold
n_win = len(FP_signal) // window
bulk = n_win * window
edge = len(FP_signal) - bulk
first_batch = FP_signal[:bulk].reshape((n_win, window), order='C')
end_batch = FP_signal[-window:]
edge_batch = FP_signal[-edge:]
sigT_sels = np.concatenate([(first_batch > np.mean(first_batch, keepdims=True, axis=1))
.reshape(bulk, order='C'), edge_batch > np.mean(end_batch)])
sigD_sels = ~sigT_sels
FP_top_signal, FP_top_time = FP_signal[sigT_sels], FP_time[sigT_sels]
FP_down_signal, FP_down_time = FP_signal[sigD_sels], FP_time[sigD_sels]
topN, downN = len(FP_top_signal)//window, len(FP_down_signal)//window
top_dyn_std = np.std(FP_top_signal[:topN * window].reshape((topN, window),order='C'), axis=1).mean()
down_dyn_std = np.std(FP_down_signal[:downN * window].reshape((downN,window),order='C'),axis=1).mean()
# TODO: check for consecutives
# TODO: check edge case when only 415 has signal
if top_dyn_std >= down_dyn_std:
sigREC_sel, sig415_sel = sigT_sels, sigD_sels
FP_REC_signals[i], FP_REC_times[i] = FP_top_signal, FP_top_time
FP_415_signals[i], FP_415_times[i] = FP_down_signal, FP_down_time
else:
sigREC_sel, sig415_sel = sigD_sels, sigT_sels
FP_REC_signals[i], FP_REC_times[i] = FP_down_signal, FP_down_time
FP_415_signals[i], FP_415_times[i] = FP_top_signal, FP_top_time
if show:
fig, axes = plt.subplots(nrows=len(FP_REC_signals), ncols=1, sharex=True)
for i in range(len(FP_REC_signals)):
ax = axes[i] if len(FP_REC_signals) > 1 else axes
itag = tags[i]
ax.plot(FP_REC_times[i], FP_REC_signals[i], label=itag)
ax.plot(FP_415_times[i], FP_415_signals[i], label='415')
ax.legend()
# TODO: save as pd.DataFrame
if len(FP_REC_signals) == 1:
return FP_REC_times[0], FP_REC_signals[0], FP_415_times[0], FP_415_signals[0]
# TODO: if shape uniform merge signals
return FP_REC_times, FP_REC_signals, FP_415_times, FP_415_signals
def path_prefix_free(path):
symbol = os.path.sep
if path[-len(symbol):] == symbol:
return path[path.rfind(symbol, 0, -len(symbol))+len(symbol):-len(symbol)]
else:
return path[path.rfind(symbol) + len(symbol):]
def file_folder_path(f):
symbol = os.path.sep
len_sym = len(symbol)
if f[-len_sym:] == symbol:
return f[:f.rfind(symbol, 0, -len_sym)]
else:
return f[:f.rfind(symbol)]
def summarize_sessions(data_root, implant_csv, save_path, sort_key='aID'):
"""
implant_csv: pd.DataFrame from implant csv file
"""
# add region of implant, session number, signal quality
# input a list of names implant locations
# "/A2A-15B-B_RT_20200229_learning-switch-2_p39.mat" supposed to be 139
# sorting with p notation mess up if p is less 100\
# bug /D1-27H_LT_20200229_ToneSamp_p89.mat read as 022
alles = {'animal': [], 'aID':[], 'session': [], 'date': [], 'ftype':[],
'age':[], 'FP': [], 'region': [], 'note': []}
implant_lookup = {}
for i in range(len(implant_csv)):
animal_name = implant_csv.loc[i, 'Name']
if animal_name and (str(animal_name) != 'nan'):
LH_target = implant_csv.loc[i, 'LH Target']
RH_target = implant_csv.loc[i, 'RH Target']
print(animal_name)
name_first, name_sec = animal_name.split(' ')
name_first = "-".join(name_first.split('-')[:2])
implant_lookup[name_first+'_'+name_sec] = {'LH': LH_target, 'RH': RH_target}
for f in os.listdir(data_root):
options = decode_from_filename(f)
if options is None:
pass
#print(f, "ALERT")
elif ('FP_' in f) and ('FP_' not in options['session']):
print(f, options['session'])
else:
for q in ['animal', 'ftype', 'session']:
alles[q].append(options[q])
name_first2, name_sec2 = options['animal'].split('_')
name_first2 = "-".join(name_first2.split('-')[:2])
aID = name_first2+"_"+name_sec2
alles['aID'].append(aID)
alles['date'].append(options['T'])
opts = options['session'].split("_FP_")
alles['age'].append(opts[0])
if len(opts) > 1:
alles['FP'].append(opts[1])
if aID not in implant_lookup:
print('skipping', options, )
alles['region'].append('')
else:
alles['region'].append(implant_lookup[aID][opts[1]])
else:
alles['FP'].append("")
alles['region'].append('')
alles['note'].append(options['DN'] + options['SP'])
apdf = pd.DataFrame(alles)
sorted_pdf = apdf.sort_values(['date', 'session'], ascending=True)
sorted_pdf['S_no'] = 0
new_pdfs = []
for anim in sorted_pdf[sort_key].unique():
tempslice = sorted_pdf[sorted_pdf[sort_key] == anim]
sorted_pdf.loc[sorted_pdf[sort_key] == anim, 'S_no'] = np.arange(1, len(tempslice)+1)
#final_pdf = pd.concat(new_pdfs, axis=0)
final_pdf = sorted_pdf
final_pdf.to_csv(os.path.join(save_path, f"exper_list_final_{sort_key}.csv"), index=False)
def encode_to_filename(folder, animal, session, ftypes="processed_all"):
"""
:param folder: str
folder for data storage
:param animal: str
animal name: e.g. A2A-15B-B_RT
:param session: str
session name: e.g. p151_session1_FP_RH
:param ftype: list or str:
list (or a single str) of typed files to return
'exper': .mat files
'bin_mat': binary file
'green': green fluorescence
'red': red FP
'behavior': .mat behavior file
'FP': processed dff hdf5 file
if ftypes=="all"
:return:
returns all 5 files in a dictionary; otherwise return all file types
in a dictionary, None if not found
"""
# TODO: enable aliasing
paths = [os.path.join(folder, animal, session), os.path.join(folder, animal+'_'+session),
os.path.join(folder, animal), folder]
if ftypes == "raw all":
ftypes = ["exper", "bin_mat", "green", "red"]
elif ftypes == "processed_all":
ftypes = ["processed", "green", "red", "FP"]
elif isinstance(ftypes, str):
ftypes = [ftypes]
results = {ft: None for ft in ftypes}
registers = 0
for p in paths:
if os.path.exists(p):
for f in os.listdir(p):
opt = decode_from_filename(f)
if opt is not None:
ift = opt['ftype']
check_mark = opt['animal'] == animal and opt['session'] == session
#print(opt['session'], animal, session)
check_mark_mdl = (opt['animal'] == animal) and (opt['session'] in session)
cm_mdl = (ift == 'modeling' and check_mark_mdl)
# TODO: temporary hacky method for modeling
#print(opt['session'], animal, session, check_mark_mdl, ift, cm_mdl)
if ift in ftypes and results[ift] is None and (check_mark or cm_mdl):
results[ift] = os.path.join(p, f)
registers += 1
if registers == len(ftypes):
return results if len(results) > 1 else results[ift]
return results if len(results) > 1 else list(results.values())[0]
def decode_from_filename(filename):
"""
Takes in filenames of the following formats and returns the corresponding file options
`A2A-15B_RT_20200612_ProbSwitch_p243_FP_RH`, `D1-27H_LT_20200314_ProbSwitch_FP_RH_p103`
behavioral: * **Gen-ID_EarPoke_Time_DNAME_Age_special.mat**
FP: **Gen-ID_EarPoke_DNAME2_Hemi_Age_channel_Time(dash)[Otherthing].csv**
binary matrix: **Drug-ID_Earpoke_DNAME_Hemi_Age_(NIDAQ_Ai0_Binary_Matrix)Time[special].etwas**
timestamps: **Drug-ID_Earpoke_DNAME_Hemi_Age_(NIDAQ_Ai0_timestamps)Time[special].csv**
GEN: genetic line, ID: animal ID, EP: ear poke, T: time of expr, TD: detailed HMS DN: Data Name, A: Age,
H: hemisphere, S: session, SP: special extension
:param filename:
:return: options: dict
ftype
animal
session
"""
filename = path_prefix_free(filename)
# case exper
mBMat = re.match(r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_(?P<T>\d+)_(?P<DN>[-&\w]+)_("
r"?P<A>p\d+)(?P<SP>[-&\w]*)\.mat", filename)
# case processed behavior
mPBMat = re.match(r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_"
r"(?P<A>p\d+)(?P<S>_session\d+_|_?)(?P<H>FP_[LR]H)_processed_data.mat", filename)
mPBOMat = re.match(r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_"
r"(?P<A>p\d+)(?P<S>_session\d+_|_?)(?P<H>FP_[LR]H)_behavior_data.mat", filename)
mFPMat = re.match(r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_"
r"(?P<A>p\d+)(?P<S>_session\d+_|_?)(?P<H>FP_[LR]H).hdf5", filename)
mMDMat = re.match(r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_"
r"(?P<A>p\d+)(?P<S>_session\d+_|_?)(?P<H>(FP_[LR]H)?)_modeling.hdf5", filename)
mTBMat =re.match(r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_"
r"(?P<A>p\d+)(?P<S>_session\d+_|_?)_trialB.csv", filename)
# case binary
mBIN = None
options, ftype = None, None
if mBMat is not None:
# TODO: handle session#
options = mBMat.groupdict()
ftype = "exper"
oS = options["SP"]
options["H"] = ""
dn_match = re.match(".*(FP_[LR]H).*", options['DN'])
sp_match = re.match(".*(FP_[LR]H).*", options['SP'])
if dn_match:
options["H"] = dn_match.group(1)
elif sp_match:
options['H'] = sp_match.group(1)
elif mTBMat is not None:
options = mTBMat.groupdict()
ftype = 'trialB'
oS = options['S']
elif mMDMat is not None:
options = mMDMat.groupdict()
ftype = 'modeling'
oS = options['S']
elif mPBMat is not None:
options = mPBMat.groupdict()
ftype = "processed"
oS = options["S"]
elif mPBOMat is not None:
options = mPBOMat.groupdict()
ftype = "behavior_old"
oS = options["S"]
elif mFPMat is not None:
options = mFPMat.groupdict()
ftype = "FP"
oS = options['S']
elif mBIN is not None:
# TODO: fill it up
options = mBIN.groupdict()
oS = ""
ftype = "bin_mat"
else:
#TODO: print("Warning! Certain sessions have inconsistent naming! needs more through check")
# case csv
#todo: merge cage id and earpoke
"""A2A-16B-1_RT_ChR2_switch_no_cue_LH_p147_red_2020-03-17T15_38_40.csv"""
channels = ['keystrokes', "MetaData", "NIDAQ_Ai0_timestamp", "red", "green", "FP", 'FPTS']
for c in channels:
mCSV = re.match(
r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_(?P<DN>[-&\w]+)_(?P<H>[LR]H)_"
r"(?P<A>p\d+)(?P<SP>[-&\w]*)" + f"_{c}" + r"(?P<S>_session\d+_|_?)(?P<T>\d{4}-?\d{2}-?\d{2})T"
r"(?P<TD>[_\d]+)\.csv", filename)
if mCSV is not None:
options = mCSV.groupdict()
ftype = c
oS = options["S"]
options['H'] = "FP_" + options['H']
break
# print(filename)
# print(options)
if ftype is None:
#print("special:", filename)
return None
mS = re.match(r".*(session\d+).*", oS)
fS = ""
if mS:
fS = "_"+mS.group(1)
options["ftype"] = ftype
options["animal"] = options['GEN'] + "-" + options["ID"] + "_" + options["EP"]
options["session"] = options['A'] + fS + (("_"+options['H']) if options['H'] else "")
return options
# Figure out rigorous representation; also keep old version intact
def encode_to_filename_new(folder, animal, session, ftypes="processed_all"):
"""
:param folder: str
folder for data storage
:param animal: str
animal name: e.g. A2A-15B-B_RT
:param session: str
session name: e.g. p151_session1_FP_RH
:param ftype: list or str:
list (or a single str) of typed files to return
'exper': .mat files
'bin_mat': binary file
'green': green fluorescence
'red': red FP
'behavior': .mat behavior file
'FP': processed dff hdf5 file
if ftypes=="all"
:return:
returns all 5 files in a dictionary; otherwise return all file types
in a dictionary, None if not found
"""
# TODO: enable aliasing
paths = [os.path.join(folder, animal, session), os.path.join(folder, animal+'_'+session),
os.path.join(folder, animal), folder]
if ftypes == "raw all":
ftypes = ["exper", "bin_mat", "green", "red"]
elif ftypes == "processed_all":
ftypes = ["processed", "green", "red", "FP"]
elif isinstance(ftypes, str):
ftypes = [ftypes]
results = {ft: None for ft in ftypes}
registers = 0
for p in paths:
if os.path.exists(p):
for f in os.listdir(p):
for ift in ftypes:
if ift == 'FP':
ift_arg = 'FP_'
else:
ift_arg = ift
if (ift_arg in f) and (animal in f) and (session in f):
results[ift] = os.path.join(p, f)
registers += 1
if registers == len(ftypes):
return results if len(results) > 1 else results[ift]
# opt = decode_from_filename(f)
# if opt is not None:
# ift = opt['ftype']
# check_mark = opt['animal'] == animal and opt['session'] == session
# #print(opt['session'], animal, session)
# check_mark_mdl = (opt['animal'] == animal) and (opt['session'] in session)
# cm_mdl = (ift == 'modeling' and check_mark_mdl)
# # TODO: temporary hacky method for modeling
# #print(opt['session'], animal, session, check_mark_mdl, ift, cm_mdl)
# if ift in ftypes and results[ift] is None and (check_mark or cm_mdl):
# results[ift] = os.path.join(p, f)
# registers += 1
# if registers == len(ftypes):
# return results if len(results) > 1 else results[ift]
return results if len(results) > 1 else list(results.values())[0]
def decode_from_filename_new(filename):
"""
Takes in filenames of the following formats and returns the corresponding file options
`A2A-15B_RT_20200612_ProbSwitch_p243_FP_RH`, `D1-27H_LT_20200314_ProbSwitch_FP_RH_p103`
behavioral: * **Gen-ID_EarPoke_Time_DNAME_Age_special.mat**
FP: **Gen-ID_EarPoke_DNAME2_Hemi_Age_channel_Time(dash)[Otherthing].csv**
binary matrix: **Drug-ID_Earpoke_DNAME_Hemi_Age_(NIDAQ_Ai0_Binary_Matrix)Time[special].etwas**
timestamps: **Drug-ID_Earpoke_DNAME_Hemi_Age_(NIDAQ_Ai0_timestamps)Time[special].csv**
GEN: genetic line, ID: animal ID, EP: ear poke, T: time of expr, TD: detailed HMS DN: Data Name, A: Age,
H: hemisphere, S: session, SP: special extension
:param filename:
:return: options: dict
ftype
animal
session
"""
filename = path_prefix_free(filename)
# case exper
mBMat = re.match(r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_(?P<T>\d+)_(?P<DN>[-&\w]+)_("
r"?P<A>p\d+)(?P<SP>[-&\w]*)\.mat", filename)
# case processed behavior
mPBMat = re.match(r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_"
r"(?P<A>p\d+)(?P<S>_session\d+_|_?)(?P<H>FP_[LR]H)_processed_data.mat", filename)
mPBOMat = re.match(r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_"
r"(?P<A>p\d+)(?P<S>_session\d+_|_?)(?P<H>FP_[LR]H)_behavior_data.mat", filename)
mFPMat = re.match(r"^(?P<GEN>\w{2,3})-(?P<ID>\d{2,}[-\w*]*)_(?P<EP>[A-Z]{2})_"
r"(?P<A>p\d+)(?P<S>_session\d+_|_?)(?P<H>FP_[LR]H).hdf5", filename)
mMDMat = re.match(r"^(?P<GEN>\w{2,3})-(?P<ID>(\d|\w){3,}[-\w*]*)_(?P<EP>[A-Z]{2})_"
r"(?P<A>p\d+)(?P<S>_session\d+_|_?)(?P<H>(FP_[LR]H)?)_modeling.hdf5", filename)
mTBMat = re.match(r"^(?P<GEN>\w{2,3})-(?P<ID>(\d|\w){3,}[-\w*]*)_(?P<EP>[A-Z]{2})_(?P<A>p\d+)(?P<S>(_session\d+)?)_trialB.csv", filename)
# case binary
mBIN = None
options, ftype = None, None
if mBMat is not None:
# TODO: handle session#
options = mBMat.groupdict()
ftype = "exper"
oS = options["SP"]
options["H"] = ""
dn_match = re.match(".*(FP_[LR]H).*", options['DN'])
sp_match = re.match(".*(FP_[LR]H).*", options['SP'])
if dn_match:
options["H"] = dn_match.group(1)
elif sp_match:
options['H'] = sp_match.group(1)
elif mTBMat is not None:
options = mTBMat.groupdict()
ftype = 'trialB'
oS = options['S']
options['H'] = ''
elif mMDMat is not None:
options = mMDMat.groupdict()
ftype = 'modeling'
oS = options['S']
elif mPBMat is not None:
options = mPBMat.groupdict()
ftype = "processed"
oS = options["S"]
elif mPBOMat is not None:
options = mPBOMat.groupdict()
ftype = "behavior_old"
oS = options["S"]
elif mFPMat is not None:
options = mFPMat.groupdict()
ftype = "FP"
oS = options['S']
elif mBIN is not None:
# TODO: fill it up
options = mBIN.groupdict()
oS = ""
ftype = "bin_mat"
else:
#TODO: print("Warning! Certain sessions have inconsistent naming! needs more through check")
# case csv
#todo: merge cage id and earpoke
"""A2A-16B-1_RT_ChR2_switch_no_cue_LH_p147_red_2020-03-17T15_38_40.csv"""
channels = ['keystrokes', "MetaData", "NIDAQ_Ai0_timestamp", "red", "green", "FP", 'FPTS']
for c in channels:
mCSV = re.match(r"^(?P<GEN>\w{2,3})-(?P<ID>(\d|\w){3,}[-\w*]*)_(?P<EP>[A-Z]{2})_(?P<DN>[-&\w]+)_(?P<H>([LR]H_)?)"
r"(?P<A>p\d+)(?P<SP>[-&\w]*)" + f"_{c}" + r"(?P<S>_session\d+_|_?)(?P<T>\d{4}-?\d{2}-?\d{2})T"
r"(?P<TD>[_\d]+)\.csv", filename)
if mCSV is not None:
options = mCSV.groupdict()
ftype = c
oS = options["S"]
options['H'] = ("FP_" + options['H']) if options['H'] else ''
break
# print(filename)
# print(options)
if ftype is None:
#print("special:", filename)
return None
mS = re.match(r".*(session\d+).*", oS)
fS = ""
if mS:
fS = "_"+mS.group(1)
options["ftype"] = ftype
options["animal"] = options['GEN'] + "-" + options["ID"] + "_" + options["EP"]
options["session"] = options['A'] + fS + (("_"+options['H']) if options['H'] else "")
return options
def access_mat_with_path(mat, p, ravel=False, dtype=None, raw=False):
""" Takes in .mat file or hdf5 file and path like structure p and return the entry
:param mat:
glml matfiles: modified from Belief_State_FP_Analysis.m legacy Chris Hall GLM structure:
glml/
notes/
hemisphere/
region/
time/
center_in/
contra/
contra_rew/
contra_unrew/
execute/
initiate/
ipsi/
ipsi_rew/
ipsi_unrew/
left_in_choice/
right_in_choice/
trial_event_FP_time/
trials/
ITI/
center_in/
center_to_side/
contra/
contra_rew/
contra_unrew/
execute/
initiate/ termination of the trial.
ipsi/
ipsi_rew/
ipsi_unrew/
left_in_choice/
omission/
right_in_choice/
side_to_center/
time_indexs/
value/
center_to_side_times/
contra/
cue_port_side/ 2=left 1=right
execute/
initiate/
ipsi/
port_side/
result/ : 1.2=reward, 1.1 = correct omission, 2 = incorrect, 3 = no choice, 0: undefined
side_to_center_time/
time_to_left/
time_to_right/
:param p:
:return:
"""
result = mat
for ip in p.split("/"):
result = result[ip]
if raw:
return result
result = np.array(result, dtype=dtype)
return result.ravel() if ravel else result
def recursive_mat_dict_view(mat, prefix=''):
""" Recursively print out mat in file structure for visualization, only support pure dataset like"""
for p in mat:
print(prefix + p+"/")
if not isinstance(mat[p], h5py.Dataset) and not isinstance(mat[p], np.ndarray):
recursive_mat_dict_view(mat[p], prefix+" ")
###################################################
#################### Cleaning #####################
###################################################
def flip_back_2_channels(animal, session):
pass
########################################################
#################### Preprocessing #####################
########################################################
def raw_fluor_to_dff(rec_time, rec_sig, iso_time, iso_sig, baseline_method='robust', zscore=False, **kwargs):
""" Takes in 1d signal and convert to dff (zscore dff)
:param rec_sig:
:param rec_time:
:param iso_sig:
:param iso_time:
:param baseline_method:
:param zscore:
:param kwargs:
:return:
"""
# TODO: figure out the best policy for removal currently no removal
# TODO: More in-depth analysis of the best baselining approach with quantitative metrics
bms = baseline_method.split('_')
fast = False
if len(bms) > 1:
fast = bms[-1] == 'fast'
baseline_method = bms[0]
if baseline_method == 'robust':
f0 = f0_filter_sig(rec_time, rec_sig, buffer=not fast, **kwargs)[:, 0]
elif baseline_method == 'mode':
f0 = percentile_filter(rec_time, rec_sig, perc=None, **kwargs)
elif baseline_method.startswith('perc'):
pc = int(baseline_method[4:])
f0 = percentile_filter(rec_time, rec_sig, perc=pc, **kwargs)
elif baseline_method == 'isosbestic':
# cite jove paper
reference = interpolate.interp1d(iso_time, iso_sig, fill_value='extrapolate')(rec_time)
signal = rec_sig
f0 = get_f0_Martianova_jove(reference, signal)
elif baseline_method == 'isosbestic_old':
dc_rec, dc_iso = np.mean(rec_sig), np.mean(iso_sig)
dm_rec_sig, dm_iso_sig = rec_sig - dc_rec, iso_sig - dc_iso
# TODO: implement impulse based optimization
f0_iso = isosbestic_baseline_correct(iso_time, dm_iso_sig, **kwargs) + dc_rec
f0 = f0_iso
if iso_time.shape != rec_time.shape or np.allclose(iso_time, rec_time):
f0 = interpolate.interp1d(iso_time, f0_iso, fill_value='extrapolate')(rec_time)
else:
raise NotImplementedError(f"Unknown baseline method {baseline_method}")
dff = (rec_sig - f0) / (f0 + np.mean(rec_sig)+1e-16) # arbitrary DC shift to avoid issue
return (dff - np.mean(dff)) / np.std(dff, ddof=1) if zscore else dff
def sources_get_noise_power(s415, s470):
npower415 = GetSn(s415)
npower470 = GetSn(s470)
return npower415, npower470
def get_sample_interval(times):
return np.around((np.max(times) - np.min(times)) / len(times), 0)
def resample_quasi_uniform(sig, times, method='interpolate'):
if np.sum(np.diff(times) < 0) > 0:
shuffles = np.argsort(times)
sig = sig[shuffles]
times = times[shuffles]
si = get_sample_interval(times)
T0, Tm = np.min(times), np.max(times)
if method == 'interpolate':
new_times = np.arange(T0, Tm, si)
new_sig = interpolate.interp1d(times, sig, fill_value='extrapolate')(new_times)
elif method == 'fft':
new_sig, new_times = signal.resample(sig, int((Tm-T0) // si), t=times)
else:
raise NotImplementedError(f'unknown method {method}')
return new_sig, new_times
def denoise_quasi_uniform(sig, times, method='wiener'):
new_sig, new_times = resample_quasi_uniform(sig, times)
if method == 'wiener':
return signal.wiener(new_sig), new_times
else:
raise NotImplementedError(f'Unknown method {method}')
def f0_filter_sig(xs, ys, method=12, window=200, optimize_window=2, edge_method='prepend', buffer=False,
**kwargs):
"""
First 2 * windows re-estimate with mode filter
To avoid edge effects as beginning, it uses mode filter; better solution: specify initial conditions
Return:
dff: np.ndarray (T, 2)
col0: dff
col1: boundary scale for noise level
"""
if method < 10:
mf, mDC = median_filter(window, method)
else:
mf, mDC = std_filter(window, method%10, buffer=buffer)
opt_w = int(np.rint(optimize_window * window))
# prepend
init_win_ys = ys[:opt_w]
init_win_xs = xs[:opt_w]
if edge_method == 'init':
# subpar method so far, use prepend
initial = percentile_filter(init_win_xs, init_win_ys, window)
initial_std = np.sqrt(max(0, np.mean(np.square(init_win_ys - initial))))
m2 = np.mean(np.square(init_win_ys[init_win_ys - initial < (method % 10) * initial_std]))
mDC.set_init(np.mean(initial[:window]), np.std(initial, ddof=1))
dff = np.array([(mf(ys, i), mDC.get_dev()) for i in range(len(ys))])
elif edge_method == 'prepend':
prepend_xs = init_win_xs[opt_w-1:0:-1]
prepend_ys = init_win_ys[opt_w-1:0:-1]
prepend_xs = 2 * np.min(init_win_xs) - prepend_xs
ys_pp = np.concatenate([prepend_ys, ys])
xs_pp = np.concatenate([prepend_xs, xs])
dff = np.array([(mf(ys_pp, i), mDC.get_dev()) for i in range(len(ys_pp))])[opt_w-1:]
elif edge_method == 'mode':
dff = np.array([(mf(ys, i), mDC.get_dev()) for i in range(len(ys))])
dff[:opt_w, 0] = percentile_filter(init_win_xs, init_win_ys, window)
else:
raise NotImplementedError(f"Unknown method {edge_method}")
return dff
def percentile_filter(xs, ys, window=200, perc=None, **kwargs):
# TODO: 1D signal only
if perc is None:
perc, val = df_percentile(ys[:window])
return scipy.ndimage.percentile_filter(ys, perc, window)
def isosbestic_baseline_correct_old(xs, ys, window=200, perc=50, **kwargs):
# TODO: this is the greedy method with only the mean estimation
#return f0_filter_sig(xs, ys, method=method, window=window)[:, 0]
return percentile_filter(xs, ys, window, perc)
def isosbestic_baseline_correct(xs, ys, window=200, perc=50, **kwargs):
# TODO: current use simplest directly import zdff method but want to rigorously test baselining effect
# TODO: this is the greedy method with only the mean estimation
#return f0_filter_sig(xs, ys, method=method, window=window)[:, 0]
return percentile_filter(xs, ys, window, perc)
def calcium_dff(xs, ys, xs0=None, y0=None, method=12, window=200):
f0 =f0_filter_sig(xs, ys, method=method, window=window)[:, 0]
return (ys-f0) / f0
def wiener_deconvolution(y, h):
# TODO: wiener filter performance not well as expected
# perform wiener deconvolution on 1d array
T = len(y)
sn = GetSn(y)
freq, Yxx = scipy.signal.welch(y, nfft=T)
Yxx[1:] = Yxx[1:] / 2 # divide evenly between pos and neg
from scipy.signal import fftconvolve
Hf = np.fft.rfft(h, n=T)
Hf2 = Hf.conjugate() * Hf
Sxx = | np.maximum(Yxx - sn**2, 1e-16) | numpy.maximum |
#
# Evaluate trained models
#
import warnings
warnings.simplefilter(action='ignore')
from keras import backend as K
from src.model1 import uResNet34
from src.train import get_train_test_split, get_norm_dict
from src.gen1 import SliceIterator, primary_transform
from src.const import (
model_dir, model_input_size,
wells, ilines, xlines, nsamples, dt,
slices_dir, crossval_dict
)
import numpy as np
import cv2
from itertools import chain
import matplotlib.pyplot as plt
from typing import List
from pathlib import Path
model_class = uResNet34
# model weights
weights = {
'Gamma_Ray': [
'uResNet34.Gamma_Ray.sz480x512.smtd_0.14-0.78.hdf5',
'uResNet34.Gamma_Ray.sz480x512.smtd_1.11-0.37.hdf5',
'uResNet34.Gamma_Ray.sz480x512.smtd_2.07-0.65.hdf5',
'uResNet34.Gamma_Ray.sz480x512.smtd_3.42-0.67.hdf5'
],
}
def predict_on_fold(slice_list: List[Path], carotage: str, model_weights: Path, verbose: bool = False) -> dict:
"""predict model for a single fold
return: dict[slice/well]{'seism', 'mask', 'y_true', 'y_pred', 'corr'}"""
norm_dict = get_norm_dict()
norm = [(norm_dict[c]['mean'], norm_dict[c]['std']) for c in ['seismic', carotage]]
K.clear_session()
model = model_class(input_size=model_input_size, weights=model_weights, n_carotage=1)
gen = SliceIterator(slice_list, [carotage], model_input_size, transform_fun=primary_transform, norm=norm, aug=False,
batch_size=10, shuffle=False, seed=None, verbose=False, output_ids=True, infinite_loop=False)
x_m, y, ids = zip(*gen)
x, m = zip(*x_m)
x = np.concatenate(x)
m = | np.concatenate(m) | numpy.concatenate |
"""Misc utilities"""
import sys
from time import strftime
import pickle as pickle
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from sklearn.cross_validation import StratifiedShuffleSplit
from sklearn.manifold import TSNE
# Allow pickle to work with very deep recursion
sys.setrecursionlimit(10000000)
def multiclass_log_loss(y_true, y_pred, eps=1e-15):
"""Multi class version of Logarithmic Loss metric.
https://www.kaggle.com/wiki/MultiClassLogLoss
Taken from https://www.kaggle.com/c/predict-closed-questions-on-stack-overflow/forums/t/2644/multi-class-log-loss-function/14250#post14250
idea from this post:
http://www.kaggle.com/c/emc-data-science/forums/t/2149/is-anyone-noticing-difference-betwen-validation-and-leaderboard-error/12209#post12209
Parameters
----------
y_true : array, shape = [n_samples]
y_pred : array, shape = [n_samples, n_classes]
Returns
-------
loss : float
"""
predictions = np.clip(y_pred, eps, 1 - eps)
# normalize row sums to 1
predictions /= predictions.sum(axis=1)[:, np.newaxis]
actual = np.zeros(y_pred.shape)
rows = actual.shape[0]
actual[ | np.arange(rows) | numpy.arange |
"""Tests for nonlinear activation functions."""
import numpy as np
import numpy.testing as npt
from nn.activations import Sigmoid, Tanh, ReLU
from nn.utils import finite_difference_derivative
def test_sigmoid():
sigmoid = Sigmoid()
# Intercept at exactly 0.5
npt.assert_equal(np.full(2, 0.5), sigmoid.forward(np.zeros(2)))
# Check limits
npt.assert_allclose(sigmoid.forward(np.array([-6, 6])), np.array([0, 1]), atol=1e-2)
npt.assert_allclose(sigmoid.forward(np.array([-10, 10])), np.array([0, 1]), atol=1e-4)
# Check preserves shape
assert sigmoid.forward(np.zeros((2, 1))).shape == (2, 1)
assert sigmoid.forward(np.zeros((2, ))).shape == (2, )
def test_sigmoid_derivative():
sigmoid = Sigmoid()
# Do forward the check that backward updates error correctly
sigmoid.forward(np.asarray([0]))
npt.assert_array_equal(sigmoid.backward(np.ones(1)), np.asarray([0.25]))
sigmoid.forward( | np.asarray([0]) | numpy.asarray |
# Created on Wed May 31 14:48:46 2017
#
# @author: <NAME>
"""Containes a helper class for image input pipelines in tensorflow."""
import tensorflow as tf
import numpy as np
from scipy.sparse import vstack
import pickle
from collections import Counter
from tensorflow.python.framework import dtypes
from tensorflow.python.framework.ops import convert_to_tensor
class Dataset(object):
"""Wrapper class around the new Tensorflows dataset pipeline.
Requires Tensorflow >= version 1.12rc0
"""
def __init__(self, pickle_file, batch_size, num_classes, shuffle=True):
"""Create a new ImageDataGenerator.
Recieves a path string to a text file, which consists of many lines,
where each line has first a path string to an image and seperated by
a space an integer, referring to the class number. Using this data,
this class will create TensrFlow datasets, that can be used to train
e.g. a convolutional neural network.
Args:
txt_file: Path to the text file.
batch_size: Number of images per batch.
num_classes: Number of classes in the dataset.
shuffle: Wether or not to shuffle the data in the dataset and the
initial file list.
buffer_size: Number of images used as buffer for TensorFlows
shuffling of the dataset.
Raises:
ValueError: If an invalid mode is passed.
"""
self.pickle_file = pickle_file
self.num_classes = num_classes
self.batch_size = batch_size
# load the data from the pickle file
self._load_from_pickle_file()
# number of samples in the dataset
self.data_size = self.labels.shape[0]
# shuffle the first `buffer_size` elements of the dataset
if shuffle:
self.shuffle()
# Initialise the counter
self.counter = 0
def _load_from_pickle_file(self):
self.img_contents, self.labels, _ = pickle.load(open(self.pickle_file, 'rb'))
if type(self.img_contents) is list:
self.img_contents = np.vstack(self.img_contents)
def _one_hot(self, labels, num_classes):
one_hot_labels = np.zeros((labels.size, num_classes), dtype=np.float32)
one_hot_labels[ | np.arange(labels.size) | numpy.arange |
import os
import numpy as np
import cv2
import pathlib
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
from plyfile import PlyData, PlyElement
from CGAL.CGAL_Kernel import Point_3
from CGAL.CGAL_Kernel import Vector_3
from CGAL.CGAL_Point_set_processing_3 import *
#import pypcd
from joblib import Parallel, delayed
import multiprocessing
import json
import random
import sys
sys.path.append('../action/')
sys.path.append('../human_pose/')
from IKEAActionDataset import IKEAActionDataset as Dataset
import joint_ids
import math
import trimesh
import pyrender
from pyrender.constants import RenderFlags
from smpl import get_smpl_faces
# import smplx
def get_subdirs(input_path):
'''
get a list of subdirectories in input_path directory
:param input_path: parent directory (in which to get the subdirectories)
:return:
subdirs: list of subdirectories in input_path
'''
subdirs = [os.path.join(input_path, dir_i) for dir_i in os.listdir(input_path)
if os.path.isdir(os.path.join(input_path, dir_i))]
subdirs.sort()
return subdirs
def get_files(input_path, file_type='.png'):
'''
get a list of files in input_path directory
:param input_path: parent directory (in which to get the file list)
:return:
files: list of files in input_path
'''
files = [os.path.join(input_path, file_i) for file_i in os.listdir(input_path)
if os.path.isfile(os.path.join(input_path, file_i)) and file_i.endswith(file_type)]
files.sort()
return files
def get_list_of_all_files(dir_path, file_type='.jpg'):
'''
get a list of all files of a given type in input_path directory
:param dir_path: parent directory (in which to get the file list)
:return:
allFiles: list of files in input_path
'''
listOfFile = os.listdir(dir_path)
allFiles = list()
# Iterate over all the entries
for entry in listOfFile:
# Create full path
fullPath = os.path.join(dir_path, entry)
# If entry is a directory then get the list of files in this directory
if os.path.isdir(fullPath):
allFiles = allFiles + get_list_of_all_files(fullPath, file_type=file_type)
else:
if fullPath.endswith(file_type):
allFiles.append(fullPath)
return allFiles
def get_depth_ins_params(param_file):
'''
read the depth intrinsic parameters file
:param param_file: path to depth intrinsic parameters file DepthIns.txt
:return:
ir_camera_params_obj: a libfreenect2 IrCameraParams object
'''
with open(param_file, 'r') as f:
depth_ins_params = [float(line.strip()) for line in f if line]
ir_camera_params_obj = {
"fx" : depth_ins_params[0],
"fy" : depth_ins_params[1],
"cx" : depth_ins_params[2],
"cy" : depth_ins_params[3],
"k1" : depth_ins_params[4],
"k2" : depth_ins_params[5],
"k3" : depth_ins_params[6],
"p1" : depth_ins_params[7],
"p2" : depth_ins_params[8]
}
return ir_camera_params_obj
def get_rgb_ins_params(param_file):
'''
read the rgb intrinsic parameters file
:param param_file: path to depth intrinsic parameters file DepthIns.txt
:return:
rgb_ins_params: a libfreenect2 ColorCameraParams object
'''
with open(param_file, 'r') as f:
rgb_ins_params = [float(line.strip()) for line in f if line]
rgb_camera_params_obj = {
"fx" : rgb_ins_params[0],
"fy" : rgb_ins_params[1],
"cx" : rgb_ins_params[2],
"cy" : rgb_ins_params[3],
"shift_d" : rgb_ins_params[4],
"shift_m" : rgb_ins_params[5],
"mx_x3y0" : rgb_ins_params[6],
"mx_x0y3" : rgb_ins_params[7],
"mx_x2y1" : rgb_ins_params[8],
"mx_x1y2" : rgb_ins_params[9],
"mx_x2y0" : rgb_ins_params[10],
"mx_x0y2" : rgb_ins_params[11],
"mx_x1y1" : rgb_ins_params[12],
"mx_x1y0" : rgb_ins_params[13],
"mx_x0y1" : rgb_ins_params[14],
"mx_x0y0" : rgb_ins_params[15],
"my_x3y0" : rgb_ins_params[16],
"my_x0y3" : rgb_ins_params[17],
"my_x2y1" : rgb_ins_params[18],
"my_x1y2" : rgb_ins_params[19],
"my_x2y0" : rgb_ins_params[20],
"my_x0y2" : rgb_ins_params[21],
"my_x1y1" : rgb_ins_params[22],
"my_x1y0" : rgb_ins_params[23],
"my_x0y1" : rgb_ins_params[24],
"my_x0y0" : rgb_ins_params[25]
}
return rgb_camera_params_obj
def get_prop_path_list(input_path, property_name='normals'):
category_path_list = get_subdirs(input_path)
scan_path_list = []
for category in category_path_list:
if os.path.basename(category) != 'Calibration':
category_scans = get_subdirs(category)
for category_scan in category_scans:
scan_path_list.append(category_scan)
pose_path_list = []
for scan in scan_path_list:
device_list = get_subdirs(scan)
for device in device_list:
pose_path = os.path.join(device, property_name) # property names: 'normals','point_clouds'
if os.path.exists(pose_path):
pose_path_list.append(pose_path)
return pose_path_list
def get_scan_list(input_path, devices='all'):
'''
get_scan_list retreieves all of the subdirectories under the dataset main directories:
:param input_path: path to ANU IKEA Dataset directory
:return:
scan_path_list: path to all available scans
category_path_list: path to all available categories
'''
category_path_list = get_subdirs(input_path)
scan_path_list = []
for category in category_path_list:
if os.path.basename(category) != 'Calibration':
category_scans = get_subdirs(category)
for category_scan in category_scans:
scan_path_list.append(category_scan)
rgb_path_list = []
depth_path_list = []
normals_path_list = []
rgb_params_files = []
depth_params_files = []
for scan in scan_path_list:
device_list = get_subdirs(scan)
for device in device_list:
if os.path.basename(device) in devices:
rgb_path = os.path.join(device, 'images')
depth_path = os.path.join(device, 'depth')
normals_path = os.path.join(device, 'normals')
if os.path.exists(rgb_path):
rgb_path_list.append(rgb_path)
rgb_params_files.append(os.path.join(device, 'ColorIns.txt'))
if os.path.exists(depth_path):
if 'dev3' in device: # remove redundant depths - remove this line for full 3 views
depth_path_list.append(depth_path)
depth_params_files.append(os.path.join(device, 'DepthIns.txt'))
if os.path.exists(normals_path):
normals_path_list.append(normals_path)
return category_path_list, scan_path_list, rgb_path_list, depth_path_list, depth_params_files, rgb_params_files, normals_path_list
def distort(mx, my, depth_ins):
# see http://en.wikipedia.org/wiki/Distortion_(optics) for description
# based on the C++ implementation in libfreenect2
dx = (float(mx) - depth_ins['cx']) / depth_ins['fx']
dy = (float(my) - depth_ins['cy']) / depth_ins['fy']
dx2 = np.square(dx)
dy2 = np.square(dy)
r2 = dx2 + dy2
dxdy2 = 2 * dx * dy
kr = 1 + ((depth_ins['k3'] * r2 + depth_ins['k2']) * r2 + depth_ins['k1']) * r2
x = depth_ins['fx'] * (dx * kr + depth_ins['p2'] * (r2 + 2 * dx2) + depth_ins['p1'] * dxdy2) + depth_ins['cx']
y = depth_ins['fy'] * (dy * kr + depth_ins['p1'] * (r2 + 2 * dy2) + depth_ins['p2'] * dxdy2) + depth_ins['cy']
return x, y
def depth_to_color(mx, my, dz, depth_ins, color_ins):
# based on the C++ implementation in libfreenect2, constants are hardcoded into sdk
depth_q = 0.01
color_q = 0.002199
mx = (mx - depth_ins['cx']) * depth_q
my = (my - depth_ins['cy']) * depth_q
wx = (mx * mx * mx * color_ins['mx_x3y0']) + (my * my * my * color_ins['mx_x0y3']) + \
(mx * mx * my * color_ins['mx_x2y1']) + (my * my * mx * color_ins['mx_x1y2']) + \
(mx * mx * color_ins['mx_x2y0']) + (my * my * color_ins['mx_x0y2']) + \
(mx * my * color_ins['mx_x1y1']) +(mx * color_ins['mx_x1y0']) + \
(my * color_ins['mx_x0y1']) + (color_ins['mx_x0y0'])
wy = (mx * mx * mx * color_ins['my_x3y0']) + (my * my * my * color_ins['my_x0y3']) +\
(mx * mx * my * color_ins['my_x2y1']) + (my * my * mx * color_ins['my_x1y2']) +\
(mx * mx * color_ins['my_x2y0']) + (my * my * color_ins['my_x0y2']) + (mx * my * color_ins['my_x1y1']) +\
(mx * color_ins['my_x1y0']) + (my * color_ins['my_x0y1']) + color_ins['my_x0y0']
rx = (wx / (color_ins['fx'] * color_q)) - (color_ins['shift_m'] / color_ins['shift_d'])
ry = int((wy / color_q) + color_ins['cy'])
rx = rx + (color_ins['shift_m'] / dz)
rx = int(rx * color_ins['fx'] + color_ins['cx'])
return rx, ry
def getPointXYZ(undistorted, r, c, depth_ins):
depth_val = undistorted[r, c] #/ 1000.0 # map from mm to meters
if np.isnan(depth_val) or depth_val <= 0.001:
x = 0
y = 0
z = 0
else:
x = (c + 0.5 - depth_ins['cx']) * depth_val / depth_ins['fx']
y = (r + 0.5 - depth_ins['cy']) * depth_val / depth_ins['fy']
z = depth_val
point = [x, y, z]
return point
def get_rc_from_xyz(x, y, z, depth_ins):
'''
project a 3d point back to the image row and column indices
:param point: xyz 3D point
:param depth_ins: depth camera intrinsic parameters
:return:
'''
c = int((x * depth_ins['fx'] / z) + depth_ins['cx'])
r = int((y * depth_ins['fy'] / z) + depth_ins['cy'])
return c, r
def apply(dz, rx, ry, rgb_ins_params):
cy = int(ry)
rx = rx + (rgb_ins_params['shift_m'] / dz)
cx = int(rx * rgb_ins_params['fx'] + rgb_ins_params['cx'])
return cx, cy
def compute_point_clouds(depth_ins_params, rgb_ins_params, depth_frames, rgb_frames, j, point_cloud_dir_name):
frame_filename, depth_frame_file_extension = os.path.splitext(os.path.basename(depth_frames[j]))
depth_img = cv2.imread(depth_frames[j], cv2.IMREAD_ANYDEPTH).astype(np.float32)
depth_img = cv2.flip(depth_img, 1) # images were saved flipped
# relative_depth_frame = get_relative_depth(depth_img)
color_img = cv2.imread(rgb_frames[j])
color_img = cv2.flip(color_img, 1) # images were saved flipped
# # Compute point cloud from images
point_cloud = []
new_vertices = []
registered = np.zeros([424, 512, 3], dtype=np.uint8)
undistorted = np.zeros([424, 512, 3], dtype=np.float32)
for y in range(424):
for x in range(512):
# point = registration.getPointXYZ(depth_frame, y, x)
mx, my = distort(x, y, depth_ins_params)
ix = int(mx + 0.5)
iy = int(my + 0.5)
point = getPointXYZ(depth_img, y, x, depth_ins_params)
if (ix >= 0 and ix < 512 and iy >= 0 and iy < 424): # check if pixel is within the image
undistorted[iy, ix] = depth_img[y, x]
z = depth_img[y, x]
if z > 0 and not np.isnan(z):
# point_cloud.append(point)
cx, cy = depth_to_color(x, y, z, depth_ins_params, rgb_ins_params)
if (cx >= 0 and cx < 1920 and cy >= 0 and cy < 1080):
registered[y, x, :] = color_img[cy, cx].flatten()
registered[y, x, :] = cv2.cvtColor(registered[y, x].reshape([1, 1, 3]),
cv2.COLOR_BGR2RGB)
point_cloud.append([(point), registered[y, x, :]])
new_vertices.append((point[0], point[1], point[2], registered[y, x, 0],
registered[y, x, 1], registered[y, x, 2]))
# cv2.imshow('relative depth', relative_depth_frame)
# cv2.imshow('registered image', cv2.cvtColor(registered,cv2.COLOR_RGB2BGR))
# cv2.waitKey(0)
# if point_cloud_type == '.ply':
pc_file_name = os.path.join(point_cloud_dir_name, frame_filename + '.ply')
new_vertices = np.array(new_vertices, dtype=[('x', 'f4'), ('y', 'f4'), ('z', 'f4'),
('red', 'u1'), ('green', 'u1'), ('blue', 'u1')])
el = PlyElement.describe(new_vertices, 'vertex')
PlyData([el]).write(pc_file_name)
print('Saved Point cloud ' + frame_filename + '.ply to ' + point_cloud_dir_name)
# else:
# Add support for other file types
# pc_file_name = os.path.join(point_cloud_dir_name, frame_filename+'.pcd')
# pcl.save(new_vertices, pc_file_name, format='.pcd', binary=False)
# fig = plt.figure()
# ax = fig.add_subplot(111, projection='3d')
# point_cloud = np.array(point_cloud)
# ax.scatter(point_cloud[:, 0], point_cloud[:, 1], point_cloud[:, 2], marker='.', s=1, c=point_cloud[:, 3:])
# ax.set_xlabel('X Label')
# ax.set_ylabel('Y Label')
# ax.set_zlabel('Z Label')
# plt.show()
def export_point_clouds(input_path, pc_per_scan=1.0, include_rgb=True, point_cloud_type='.ply', output_path='',
devices='dev3'):
'''
Export point clouds per frame. Assumes sync and same number of depth and rgb frames.
:param input_path: path to dataset
:param pc_per_scan: fration of point clouds to generate, default generate all
:return:
'''
if output_path == '':
output_path = input_path
category_path_list, scan_path_list, rgb_path_list, depth_path_list, depth_params_files,\
rgb_params_files, normals_path_list = get_scan_list(input_path, devices=devices)
for i, scan in enumerate(depth_path_list):
depth_param_filename = depth_params_files[i]
color_param_filename = rgb_params_files[i]
depth_frames = get_files(scan, file_type='.png')
rgb_frames = get_files(rgb_path_list[i], file_type='.jpg')
if depth_frames: # check if empty
depth_ins_params = get_depth_ins_params(depth_param_filename)
if rgb_frames:
rgb_ins_params = get_rgb_ins_params(color_param_filename)
out_dir = scan.replace(scan[:scan.index("ANU_ikea_dataset") + 17], output_path)
point_cloud_dir_name = os.path.join(os.path.abspath(os.path.join(out_dir, os.pardir)), 'point_clouds')
if not os.path.exists(point_cloud_dir_name):
os.makedirs(point_cloud_dir_name)
# for j, _ in enumerate(depth_frames):
# parallel point cloud computation and export
num_cores = multiprocessing.cpu_count()
Parallel(n_jobs=num_cores)(delayed(compute_point_clouds)(depth_ins_params, rgb_ins_params, depth_frames, rgb_frames, j, point_cloud_dir_name) for j, _ in enumerate(depth_frames))
######################################### Video export utils #######################################
def get_relative_depth(img, min_depth_val=0.0, max_depth_val = 4500, colormap='jet'):
'''
Convert the depth image to relative depth for better visualization. uses fixed minimum and maximum distances
to avoid flickering
:param img: depth image
min_depth_val: minimum depth in mm (default 50cm)
max_depth_val: maximum depth in mm ( default 10m )
:return:
relative_depth_frame: relative depth converted into cv2 GBR
'''
relative_depth_frame = cv2.convertScaleAbs(img, alpha=(255.0/max_depth_val),
beta=-255.0*min_depth_val/max_depth_val)
relative_depth_frame = cv2.cvtColor(relative_depth_frame, cv2.COLOR_GRAY2BGR)
# relative_depth_frame = cv2.applyColorMap(relative_depth_frame, cv2.COLORMAP_JET)
return relative_depth_frame
def get_absolute_depth(img, min_depth_val=0.0, max_depth_val = 4500, colormap='jet'):
'''
Convert the relative depth image to absolute depth. uses fixed minimum and maximum distances
to avoid flickering
:param img: depth image
min_depth_val: minimum depth in mm (default 50cm)
max_depth_val: maximum depth in mm ( default 10m )
:return:
absolute_depth_frame: absolute depth converted into cv2 gray
'''
absolute_depth_frame = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# absolute_depth_frame = cv2.convertScaleAbs(absolute_depth_frame, alpha=(max_depth_val/255.0),
# beta=min_depth_val).astype(np.uint16) #converts to 8 bit
absolute_depth_frame = absolute_depth_frame * float(max_depth_val/255.0)
return absolute_depth_frame.astype(np.uint16)
def get_fps(frames, native=False):
if native:
start = os.path.getmtime(frames[0])
end = os.path.getmtime(frames[-1])
duration = end - start
n_frames = len(frames)
fps = n_frames / duration
else:
fps = 30
return fps
def export_video_par(scan, depth_flag, normals_flag, output_path, fps, overide, vid_scale, vid_format):
"""
function that can run in parallel to export videos from individual frames. supports avi and webm.
Parameters
----------
scan : scan name [string]
depth_flag : true | false - use depth stream
normals_flag : true | false - use normal vectors stream
output_path : outpue path
fps : frames per seconds
overide : true | false if to override existing files in the output dir[bool]
vid_scale : indicting the scale. to unscale use 1. [float]
vid_format : 'avi' | 'webm' video format [string]
Returns
-------
"""
if 'processed' not in scan: # if output path changes this will break
out_dir = scan.replace(scan[:scan.index("ANU_ikea_dataset") + 17], output_path)
else:
out_dir = scan
if not os.path.exists(out_dir):
os.makedirs(out_dir)
video_file_name = os.path.join(out_dir, 'scan_video.' + vid_format)
if not os.path.exists(video_file_name) or overide:
frames = get_files(scan, file_type='.png') if depth_flag or normals_flag else get_files(scan, file_type='.jpg')
if frames:
if depth_flag:
img = cv2.imread(frames[0], cv2.IMREAD_ANYDEPTH)
img = get_relative_depth(img.astype(np.float32)) # better for visualization
else:
img = cv2.imread(frames[0])
if not vid_scale == 1:
img = cv2.resize(img, dsize=(int(img.shape[1]/vid_scale), int(img.shape[0]/vid_scale)))
img_shape = img.shape
size = (img_shape[1], img_shape[0])
print('Saving video file to ' + video_file_name)
fourcc = cv2.VideoWriter_fourcc(*'VP09') if vid_format == 'webm' else cv2.VideoWriter_fourcc(*'DIVX')
out = cv2.VideoWriter(video_file_name, fourcc, fps, size)
for j, _ in enumerate(frames):
if depth_flag:
img = cv2.imread(frames[j], cv2.IMREAD_ANYDEPTH).astype(np.float32)
img = get_relative_depth(img) # use default min depth 0 and max depth 4500 for reconstruction from the video
else:
img = cv2.imread(frames[j])
if not vid_scale == 1:
img = cv2.resize(img, dsize=(int(img.shape[1] / vid_scale), int(img.shape[0] / vid_scale)))
out.write(img)
out.release()
print('Done\n')
def video_export_helper(path_list, depth_flag=False, normals_flag=False, output_path='', fps=25, overide=False,
vid_scale=1, vid_format='avi'):
'''
Helper function to handle different cases of AVI export (for rgb and depth)
:param path_list: list of paths to image folders to convert to AVI
:param depth_flag: True / False is for depth
:return:
TO DO: Remove this function, after the parallelization it is redundant
'''
num_cores = multiprocessing.cpu_count()
Parallel(n_jobs=num_cores)(delayed(export_video_par)(scan, depth_flag, normals_flag, output_path, fps, overide,
vid_scale, vid_format) for i, scan in enumerate(path_list))
# for i, scan in enumerate(path_list):
def export_videos(input_path, rgb_flag=False, depth_flag=False, normals_flag=False, pose_flag=False, seg_flag=False,
perception_demo_flag=False, output_path='', vid_scale=1, vid_format='avi', overide=False,
devices='all'):
'''
Saves video files of the scanned rgb and/or depth images
note: on Ubuntu install SMplayer to view video file
:param input_path: path to ikea dataset
:param rgb_flag: True / False if to export the rgb video file
:param depth_flag: True / False if to export the depth video file
:param depth_flag: True / False if to export the normals vodeo file
:param fps: frames per second for videos
:return:
'''
if output_path == '':
output_path = input_path
category_path_list, scan_path_list, rgb_path_list, depth_path_list, depth_params_files,\
rgb_params_files, _ = get_scan_list(input_path, devices=devices)
if rgb_flag:
video_export_helper(rgb_path_list, depth_flag=False, output_path=output_path, vid_scale=vid_scale,
vid_format=vid_format, overide=overide)
if depth_flag:
video_export_helper(depth_path_list, depth_flag=True, output_path=output_path, vid_scale=vid_scale,
vid_format=vid_format, overide=overide)
if normals_flag:
normals_path_list = get_prop_path_list(output_path, property_name='normals')
video_export_helper(normals_path_list, depth_flag=False, normals_flag=True, output_path=output_path,
vid_scale=vid_scale, vid_format=vid_format, overide=overide)
if pose_flag:
# pose_path_list = get_pose_path_list(input_path)
pose_path_list = get_prop_path_list(output_path, property_name='2DposeImages')
video_export_helper(pose_path_list, depth_flag=False, output_path=output_path, vid_scale=vid_scale,
vid_format=vid_format, overide=overide)
if seg_flag:
seg_path_list = get_prop_path_list(output_path, property_name='seg')
video_export_helper(seg_path_list, depth_flag=False, output_path=output_path, vid_scale=vid_scale,
vid_format=vid_format, overide=overide)
if perception_demo_flag:
seg_path_list = get_prop_path_list(output_path, property_name='perception_demo')
video_export_helper(seg_path_list, depth_flag=False, output_path=output_path, vid_scale=vid_scale,
vid_format=vid_format, overide=overide)
######################################### Normal Estimation utils #######################################
def convert_normals_to_rgb(normal):
'''
Maps the normal direction to the rgb cube and returns the corresponsing rgb color
:param normal: normal vector
:return: rgb: corresponsing rgb values
'''
r = int(127.5*normal.x()+127.5)
g = int(127.5*normal.y()+127.5)
b = int(127.5*normal.z()+127.5)
rgb = [r, g, b]
return rgb
def estimate_normals(point_cloud_filename, depth_param_filename, normals_dir_name, n_neighbors=100):
'''
:param point_cloud_filename: full path and name of point cloud file to load
:param depth_param_filename: full path and name of depth parameter file
:param normals_dir_name: full path to normal estimation output directory
:param n_neighbors: number of neighbors for computing the normal vector
:return: None. Saves the normal estimation as .png file.
'''
frame_filename, point_cloud_file_extension = os.path.splitext(os.path.basename(point_cloud_filename))
depth_ins_params = get_depth_ins_params(depth_param_filename)
ply = PlyData.read(point_cloud_filename)
vertex = ply['vertex']
(x, y, z) = (vertex[t].tolist() for t in ('x', 'y', 'z'))
points = []
for j in range(len(x)):
points.append(Point_3(x[j], y[j], z[j]))
normals = []
jet_estimate_normals(points, normals, n_neighbors) # compute the normal vectors
new_vertices = []
normal_image = np.zeros([424, 512, 3], dtype=np.uint8)
for k, point in enumerate(points):
if -(point.x() * normals[k].x() + point.y() * normals[k].y() + point.z() * normals[k].z()) < 0:
normals[k] = -normals[k] # determine normal ambiguous direction using the camera position
normal_rgb = convert_normals_to_rgb(normals[k])
new_vertices.append((point.x(), point.y(), point.z(), normal_rgb[0], normal_rgb[1], normal_rgb[2]))
r, c = get_rc_from_xyz(point.x(), point.y(), point.z(), depth_ins_params)
normal_image[c, r] = normal_rgb
# export normals to .png
normals_img_file_name = os.path.join(normals_dir_name, frame_filename + '_normals.png')
cv2.imwrite(normals_img_file_name, cv2.flip(normal_image, 1))
print('Saved normals image ' + frame_filename + '_normals.png to ' + normals_dir_name)
# # export the normals to color of ply, normal direction can be stored directly to ply
# normals_file_name = os.path.join(normals_dir_name, frame_filename+'_normals.ply')
# new_vertices = np.array(new_vertices, dtype=[('x', 'f4'), ('y', 'f4'), ('z', 'f4'),
# ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')])
# el = PlyElement.describe(new_vertices, 'vertex')
# PlyData([el]).write(normals_file_name)
# print('Saved Point cloud ' + frame_filename+'_normals.ply to' + normals_dir_name)
def export_normal_vectors(input_path, n_neighbors = 100, output_path='', devices='dev3'):
'''
Saves normal vector images of the scanned point clouds
:param input_path: path to ikea dataset
:return: None, exports all png files to output directry
'''
if output_path == '':
output_path = input_path
category_path_list, scan_path_list, rgb_path_list, depth_path_list, depth_params_files,\
rgb_params_files, normals_path_list = get_scan_list(input_path, devices=devices)
for i, scan in enumerate(depth_path_list):
out_dir = scan.replace(scan[:scan.index("ANU_ikea_dataset") + 17], output_path)
out_dir = out_dir[:-5] # remove the depth directory
point_cloud_path = os.path.join(out_dir, 'point_clouds')
if os.path.exists(point_cloud_path):
point_cloud_path_list = get_files(point_cloud_path, file_type='.ply')
if not os.path.exists(out_dir):
os.makedirs(out_dir)
normals_dir_name = os.path.join(out_dir, 'normals')
depth_param_filename = depth_params_files[i]
if not os.path.exists(normals_dir_name):
os.makedirs(normals_dir_name)
# for point_cloud_filename in point_cloud_path_list:
# parallelize the normal estimation for speed
num_cores = multiprocessing.cpu_count()
Parallel(n_jobs=num_cores)(delayed(estimate_normals)(point_cloud_filename, depth_param_filename, normals_dir_name, n_neighbors) for point_cloud_filename in point_cloud_path_list)
def export_video_montage(input_path, output_path, devices='dev3'):
"""
export a single video containing videos from different captured modalities including depth, rgb,
normal vectors, point clouds, 2D poses.
Note: Assumes all modality videos already exist in the input directory
Parameters
----------
input_path : dataset directory (where all modality videos are available)
output_path : path to save the montage videos
Returns
-------
Saves the montage video
"""
_, scan_path_list, _, _, _, _, _ = get_scan_list(input_path, devices)
fps = 30
size = (512*3, 424*2 + 2*50)
for i, scan in enumerate(scan_path_list):
device_list = get_subdirs(scan)
for device in device_list:
scan_device_path = os.path.join(scan, device)
processed_scan_path = scan_device_path.replace(scan_device_path[:scan_device_path.index("ANU_ikea_dataset") + 17], output_path)
rgb_video_file = os.path.join(processed_scan_path, 'images/scan_video.avi')
depth_video_file = os.path.join(processed_scan_path, 'depth/scan_video.avi')
normals_video_file = os.path.join(processed_scan_path, 'normals/scan_video.avi')
point_clouds_video_file = os.path.join(processed_scan_path, 'point_clouds/point_cloud_video.avi')
pose2D_video_file = os.path.join(processed_scan_path, '2DposeImages/scan_video.avi')
video_file_name = os.path.join(processed_scan_path, 'montage.avi')
if os.path.exists(rgb_video_file) and os.path.exists(depth_video_file) and \
os.path.exists(normals_video_file) and os.path.exists(point_clouds_video_file) and \
os.path.exists(pose2D_video_file):
rgb_vid = cv2.VideoCapture(rgb_video_file)
depth_vid = cv2.VideoCapture(depth_video_file)
normals_vid = cv2.VideoCapture(normals_video_file)
pc_vid = cv2.VideoCapture(point_clouds_video_file)
pose2D_vid = cv2.VideoCapture(pose2D_video_file)
montage_video_writer = cv2.VideoWriter(video_file_name, cv2.VideoWriter_fourcc(*'DIVX'), fps, size)
while (rgb_vid.isOpened()):
rgb_ret, rgb_frame = rgb_vid.read()
depth_ret, depth_frame = depth_vid.read()
normals_ret, normals_frame = normals_vid.read()
normals_frame = cv2.flip(normals_frame, 1)
pc_ret, pc_frame = pc_vid.read()
pc_frame = cv2.flip(pc_frame, 1)
pose2D_ret, pose2D_frame = pose2D_vid.read()
if rgb_ret and depth_ret and normals_ret and pc_ret and pose2D_ret:
rgb_frame = cv2.resize(rgb_frame, (512, 424))
pose2D_frame = cv2.resize(pose2D_frame, (512, 424))
pc_frame = cv2.resize(pc_frame, (512, 424))
rgb_frame = insert_text_to_image(rgb_frame, 'RGB')
depth_frame = insert_text_to_image(depth_frame, 'Depth')
normals_frame = insert_text_to_image(normals_frame, 'Normal Vectors')
pose2D_frame = insert_text_to_image(pose2D_frame, '2D Pose')
pc_frame =insert_text_to_image(pc_frame, '3D Point Cloud')
montage_row1 = cv2.hconcat([rgb_frame, depth_frame])
montage_row2 = cv2.hconcat([normals_frame, pc_frame, pose2D_frame])
side_margin = int((montage_row2.shape[1] - montage_row1.shape[1]) / 2)
montage_row1 = cv2.copyMakeBorder(montage_row1, 0, 0, side_margin, side_margin, cv2.BORDER_CONSTANT,
value=[0, 0, 0])
montage_frame = cv2.vconcat([montage_row1, montage_row2])
montage_video_writer.write(montage_frame)
else:
break
rgb_vid.release()
depth_vid.release()
normals_vid.release()
pc_vid.release()
pose2D_vid.release()
montage_video_writer.release()
print('Saved ' + video_file_name)
else:
print('One or more videos required for the montage is not available, please preprocess the dataset first')
def insert_text_to_image(img, txt, font=cv2.FONT_HERSHEY_SIMPLEX, font_size=1):
# get boundary of this text
textsize = cv2.getTextSize(txt, font, 1, 2)[0]
# get coords based on boundary
textX = int((img.shape[1] - textsize[0]) / 2)
img = cv2.copyMakeBorder(img, 50, 0, 0, 0, cv2.BORDER_CONSTANT, value=[0, 0, 0])
cv2.putText(img, txt, (textX, 40), font, 1, (255, 255, 255), 2, cv2.LINE_AA)
return img
def export_pose_images(input_path, output_path='', device='dev3', scan_name=None, mode='skeleton', skeleton_type='openpose'):
"""
Saves images with human pose
Parameters
----------
input_path : path to ikea dataset
output_path : path to save the output images
scan_name : None | scane name to export. if None traverses the entire dataset
Returns
-------
exports all jpg files to output directry
"""
if output_path == '':
output_path = input_path
if not scan_name is None:
scan_path = os.path.join(input_path, scan_name, device)
output_path = os.path.join(output_path, scan_name, device, '2DposeImages')
os.makedirs(output_path, exist_ok=True)
rgb_frames = get_files(os.path.join(scan_path, 'images'), file_type='.jpg')
n_frames = len(rgb_frames)
num_cores = multiprocessing.cpu_count()
Parallel(n_jobs=num_cores)(delayed(export_pose_helper)(scan_path, rgb_frames, j, output_path, mode, skeleton_type)
for j in range(n_frames))
# # debug
# for j in range(n_frames):
# export_pose_helper(scan_path, rgb_frames, j, output_path, mode, skeleton_type=skeleton_type)
else:
#TODO implement dataset traversal pose export
pass
def get_seg_data(input_path, output_path='', device='dev3', scan_name=None):
color_cat = {1: (255, 0, 0), 2: (0, 0, 255), 3: (0, 255, 0), 4: (127, 0, 127), 5: (127, 64, 0), 6: (64, 0, 127),
7: (64, 0, 64)}
cat_dict = {1: 'table_top', 2: 'leg', 3: 'shelf', 4: 'side_panel', 5: 'front_panel', 6: 'bottom_panel',
7: 'rear_panel'}
if output_path == '':
output_path = input_path
scan_path = os.path.join(input_path, scan_name, device)
# output_path = os.path.join(output_path, scan_name, device, 'seg')
# os.makedirs(output_path, exist_ok=True)
rgb_frames = get_files(os.path.join(scan_path, 'images'), file_type='.jpg')
n_frames = len(rgb_frames)
scan_name = scan_path.split('/')[-2]
seg_json_filename = os.path.join(scan_path, 'seg', scan_name + '.json')
tracking_path = os.path.join(scan_path, 'seg', 'tracklets_interp_' + scan_name + '.txt')
all_segments, dict_tracks, track_id = get_all_segments_and_tracks(seg_json_filename, tracking_path)
# Obtain Unique colors for each part
dict_colors = get_object_segment_color_dict(track_id)
all_segments_dict = {}
for item in all_segments['annotations']:
if item['image_id'] not in all_segments_dict:
all_segments_dict[item['image_id']] = []
all_segments_dict[item['image_id']].append(item)
return rgb_frames, dict_tracks, all_segments, all_segments_dict, dict_colors, color_cat, cat_dict, n_frames
def get_seg_data_v2(input_path, output_path='', device='dev3', scan_name=None):
# This function works specifically for the training data where psudo ground truth is available and tracking data isnt.
color_cat = {1: (129, 0, 70), 2: (220, 120, 0), 3: (255, 100, 220), 4: (6, 231, 255), 5: (89, 0, 251), 6: (251, 121, 64),
7: (171, 128, 126)}
cat_dict = {1: 'table_top', 2: 'leg', 3: 'shelf', 4: 'side_panel', 5: 'front_panel', 6: 'bottom_panel',
7: 'rear_panel'}
if output_path == '':
output_path = input_path
scan_path = os.path.join(input_path, scan_name, device)
rgb_frames = get_files(os.path.join(scan_path, 'images'), file_type='.jpg')
n_frames = len(rgb_frames)
seg_pgt_json_filename = os.path.join(scan_path, 'pseudo_gt_coco_format.json')
seg_gt_json_filename = os.path.join(scan_path, 'manual_coco_format.json')
gt_segments = json.load(open(seg_gt_json_filename))
pgt_segments = json.load(open(seg_pgt_json_filename))
all_segments = {'images': np.concatenate([gt_segments['images'], pgt_segments['images']]),
'annotations': np.concatenate([gt_segments['annotations'], pgt_segments['annotations']]),
'categories': gt_segments['categories']}
all_segments_dict = {}
for item in gt_segments['annotations']:
file_name = gt_segments['images'][item['image_id']]['file_name']
if file_name not in all_segments_dict:
all_segments_dict[file_name] = []
all_segments_dict[file_name].append(item)
for item in pgt_segments['annotations']:
file_name = pgt_segments['images'][item['image_id']-1]['file_name'] # TODO: remove -1 after indexing is fixed
if file_name not in all_segments_dict:
all_segments_dict[file_name] = []
all_segments_dict[file_name].append(item)
return rgb_frames, all_segments, all_segments_dict, color_cat, cat_dict, n_frames
def export_seg_images(input_path, output_path='', device='dev3', scan_name=None):
"""
Saves images with object segmentation
Parameters
----------
input_path : path to ikea dataset
output_path : path to save the output images
scan_name : None | scane name to export. if None traverses the entire dataset
Returns
-------
exports all jpg files to output directry
"""
if not scan_name is None:
rgb_frames, dict_tracks, all_segments, all_segments_dict, dict_colors, color_cat, cat_dict, n_frames =\
get_seg_data(input_path=input_path, output_path=output_path, device=device, scan_name=scan_name)
else:
#TODO implement dataset traversal pose export
pass
num_cores = multiprocessing.cpu_count()
Parallel(n_jobs=num_cores)(delayed(export_seg_helper)(rgb_frames, j, output_path, dict_tracks,
all_segments, all_segments_dict, dict_colors, color_cat,
cat_dict) for j in range(n_frames))
def get_all_segments_and_tracks(seg_json_filename, tracking_path):
"""
Load the part segments and tracks from json and txt files
Parameters
----------
seg_json_filename : path to .json segments file
tracking_path : path to tracking txt file
Returns
-------
"""
all_segments = json.load(open(seg_json_filename))
fid_track = open(tracking_path)
tracking_results = str.split(fid_track.read(), '\n')
track_id = []
dict_tracks = {}
for track in tracking_results:
if track != "":
track_id.append(int(str.split(track, ' ')[-3]))
items = str.split(track, ' ')
if items[-2] not in dict_tracks:
dict_tracks[items[-2]] = []
dict_tracks[items[-2]].append([items[0:5], items[-1]])
return all_segments, dict_tracks, track_id
def get_object_segment_color_dict(track_id):
"""
Parameters
----------
track_id :
Returns
-------
"""
dict_colors = {}
max_part = np.max(np.unique(track_id))
r = random.sample(range(0, 255), max_part)
g = random.sample(range(0, 255), max_part)
b = random.sample(range(0, 255), max_part)
for part_id in np.unique(track_id):
dict_colors[str(part_id)] = (int(r[part_id - 1]), int(g[part_id - 1]), int(b[part_id - 1]))
return dict_colors
def export_pose_helper(scan_path, rgb_frames, file_idx, output_path, mode, skeleton_type='openpose'):
"""
export pose for a single image - allows parallelization
Parameters
----------
scan_path :
rgb_frames :
file_idx :
output_path :
Returns
-------
"""
frame_filename = str(file_idx).zfill(6)
pose_json_filename = os.path.join(scan_path, 'predictions', 'pose2d', skeleton_type,
'scan_video_' + str(file_idx).zfill(12) + '_keypoints.json')
output_filename = os.path.join(output_path, frame_filename + '.jpg')
img = cv2.imread(rgb_frames[file_idx])
if mode == 'skeleton':
img = img_pose_skeleton_overlay(img, pose_json_filename, skeleton_type=skeleton_type )
else:
img = img_pose_mesh_overlay(img, pose_json_filename)
cv2.imwrite(output_filename, img)
print('Saved pose for ' + frame_filename + '.jpeg to ' + output_path)
def export_seg_helper(rgb_frames, file_idx, output_path, dict_tracks, all_segments, all_segments_dict,
dict_colors, color_cat, cat_dict):
"""
export object segmentation for a single image - allows parallelization
Parameters
----------
scan_path :
rgb_frames :
file_idx :
output_path :
Returns
-------
"""
frame_filename = str(file_idx).zfill(6)
image_id = find_seg_id(frame_filename, all_segments)
fname_id = int(str.split(frame_filename, '.')[0])
segment = all_segments_dict[image_id]
track = dict_tracks[str(fname_id)]
output_filename = os.path.join(output_path, frame_filename + '.jpg')
img = cv2.imread(rgb_frames[file_idx])
img = img_seg_overlay(img, segment, track, dict_colors, color_cat, cat_dict)
cv2.imwrite(output_filename, img)
print('Saved object segmentation for ' + frame_filename + '.jpeg to ' + output_path)
def find_seg_id(image_name, test_data):
for item in test_data['images']:
if item['file_name'].find(image_name) != -1:
return item['id']
return -1
def find_seg_id_v2(image_name, test_data):
for img in test_data.keys():
if image_name in img:
return img
return -1
def img_seg_overlay(image, predictions, part_tracks, dict_colors, color_cat, cat_dict):
"""
overlays object segmentation from json file on the given image
Parameters
----------
img : rgb image
json_path : path to .json file
Returns
-------
img : rgb img with object segments overlay
"""
for part in part_tracks:
assigned = 0
for item in predictions:
box = item['bbox']
label = item['category_id']
segment = item['segmentation']
segment_id = item['id']
contours = []
length = len(segment)
if segment_id == int(part[1]):
for i in range(length):
id = 0
contour = segment[i]
cnt = len(contour)
c = np.zeros((int(cnt / 2), 1, 2), dtype=np.int32)
for j in range(0, cnt, 2):
c[id, 0, 0] = contour[j]
c[id, 0, 1] = contour[j + 1]
id = id + 1
contours.append(c)
cv2.drawContours(image, contours, -1, color_cat[label], -1)
x1, y1 = box[:2]
cv2.putText(image, cat_dict[label], (int(x1) - 10, int(y1) - 10), cv2.FONT_HERSHEY_SIMPLEX, .5, (0, 0, 0), 1)
rgb = dict_colors[part[0][-1]]
assigned = 1
image = cv2.rectangle(image, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), rgb, 3)
if assigned == 0:
rgb = dict_colors[part[0][-1]]
image = cv2.rectangle(image, (int(float(part[0][0])), int(float(part[0][1]))), (int(float(part[0][0]) + float(part[0][2])), int(float(part[0][1]) + float(part[0][3]))), rgb, 3)
return image
def img_seg_overlay_v2(image, predictions, color_cat, cat_dict, show_text=False):
"""
overlays object segmentation from json file on the given image
Parameters
----------
img : rgb image
json_path : path to .json file
Returns
-------
img : rgb img with object segments overlay
"""
for part in predictions:
contours = []
length = len(part['segmentation'])
bbox = part['bbox']
for i in range(length):
id = 0
contour = part['segmentation'][i]
cnt = len(contour)
c = np.zeros((int(cnt / 2), 1, 2), dtype=np.int32)
for j in range(0, cnt, 2):
c[id, 0, 0] = contour[j]
c[id, 0, 1] = contour[j + 1]
id = id + 1
if c.shape[0] != 0:
contours.append(c)
color = color_cat[part['category_id']]
cv2.drawContours(image, contours, -1, (color[0], color[1], color[2]), -1)
# if 'part_id' in part:
if show_text:
cv2.putText(image, cat_dict[part['category_id']],
(int(bbox[0] + bbox[2] // 2), int(bbox[1] + bbox[3] // 2)),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)
image = cv2.rectangle(image, (int(bbox[0]), int(bbox[1])),
(int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3])), (0, 0, 0),2)
return image
def img_pose_skeleton_overlay(img, pose_json_filename, show_numbers=False, anonimyze=False, skeleton_type='openpose'):
"""
overlays pose from json file on the given image
Parameters
----------
img : rgb image
json_path : path to .json file
Returns
-------
img : rgb img with pose overlay
"""
j2d = read_pose_json(pose_json_filename)
if skeleton_type == 'openpose':
skeleton_pairs = joint_ids.get_body25_connectivity()
skeleton_pairs = skeleton_pairs[0:19]
else:
skeleton_pairs = joint_ids.get_ikea_connectivity()
part_colors = joint_ids.get_pose_colors(mode='bgr')
if anonimyze:
# anonimize the img by plotting a black circle centered on the nose
nose = tuple(int(element) for element in j2d[0])
radius = 45
img = cv2.circle(img, nose, radius, (0, 0, 0), -1)
# plot the joints
bad_points_idx = []
for i, point in enumerate(j2d):
if not point[0] == 0 and not point[1] == 0:
cv2.circle(img, (int(point[0]), int(point[1])), 8, (0, 255, 255), thickness=-1, lineType=cv2.FILLED)
else:
bad_points_idx.append(i)
# plot the skeleton
for i, pair in enumerate(skeleton_pairs):
partA = pair[0]
partB = pair[1]
if partA not in bad_points_idx and partB not in bad_points_idx:
# if j2d[partA] and j2d[partB]:
line_color = part_colors[i]
img = cv2.line(img, tuple([int(el) for el in j2d[partA]]), tuple([int(el) for el in j2d[partB]]),
line_color, 3)
if show_numbers:
# add numbers to the joints
for i, point in enumerate(j2d):
if i not in bad_points_idx:
cv2.putText(img, "{}".format(i), (int(point[0]), int(point[1])), cv2.FONT_HERSHEY_SIMPLEX, 0.6,
(0, 0, 255), 2,
lineType=cv2.LINE_AA)
return img
def img_pose_mesh_overlay(img, pose_json_filename):
"""
overlays pose mesh (human SMPL model) from json file on the given image
Parameters
----------
img : rgb image
json_path : path to .json file
Returns
-------
img : rgb img with pose overlay
"""
data = read_pose_json(pose_json_filename)
vertices = data[0]['verts']
betas = data[0]['betas']
cam = data[0]['orig_cam']
mesh_color = [1.0, 1.0, 0.9]
renderer = Renderer(resolution=(img.shape[1], img.shape[0]), orig_img=True, wireframe=False)
img = renderer.render(img, vertices, cam=cam, color=mesh_color, mesh_filename=None)
return img
def read_pose_json(json_path):
"""
Parameters
----------
json_path : path to json file
Returns
-------
data: a list of dictionaries containing the pose information per video frame
"""
with open(json_path) as json_file:
json_data = json.load(json_file)
data = json_data['people']
if len(data) > 1:
data = get_active_person(data)
else:
data = | np.array(data[0]['pose_keypoints_2d']) | numpy.array |
# -*- coding: utf-8 -*-
#
# This file is part of the pyFDA project hosted at https://github.com/chipmuenk/pyfda
#
# Copyright © pyFDA Project Contributors
# Licensed under the terms of the MIT License
# (see file LICENSE in root directory for details)
"""
Create a popup window with FFT window information
"""
import logging
logger = logging.getLogger(__name__)
import numpy as np
from numpy.fft import fft, fftshift, fftfreq
from scipy.signal import argrelextrema
import matplotlib.patches as mpl_patches
from pyfda.libs.pyfda_lib import safe_eval, to_html, pprint_log
from pyfda.libs.pyfda_qt_lib import qwindow_stay_on_top
from pyfda.pyfda_rc import params
from pyfda.libs.pyfda_fft_windows_lib import calc_window_function
from pyfda.plot_widgets.mpl_widget import MplWidget
import pyfda.filterbroker as fb # importing filterbroker initializes all its globals
from pyfda.libs.compat import (Qt, pyqtSignal, QHBoxLayout, QVBoxLayout,
QDialog, QCheckBox, QLabel, QLineEdit, QFrame, QFont,
QTextBrowser, QSplitter,QTableWidget, QTableWidgetItem)
#------------------------------------------------------------------------------
class Plot_FFT_win(QDialog):
"""
Create a pop-up widget for displaying time and frequency view of an FFT
window.
Data is passed via the dictionary `win_dict` that is passed during construction.
"""
# incoming
sig_rx = pyqtSignal(object)
# outgoing
sig_tx = pyqtSignal(object)
def __init__(self, parent, win_dict=fb.fil[0]['win_fft'], sym=True, title='pyFDA Window Viewer'):
super(Plot_FFT_win, self).__init__(parent)
self.needs_calc = True
self.needs_draw = True
self.needs_redraw = True
self.bottom_f = -80 # min. value for dB display
self.bottom_t = -60
self.N = 32 # initial number of data points
self.N_auto = win_dict['win_len']
self.pad = 16 # amount of zero padding
self.win_dict = win_dict
self.sym = sym
self.tbl_rows = 2
self.tbl_cols = 6
# initial settings for checkboxes
self.tbl_sel = [True, True, False, False]
self.setAttribute(Qt.WA_DeleteOnClose)
self.setWindowTitle(title)
self._construct_UI()
qwindow_stay_on_top(self, True)
#------------------------------------------------------------------------------
def closeEvent(self, event):
"""
Catch closeEvent (user has tried to close the window) and send a
signal to parent where window closing is registered before actually
closing the window.
"""
self.sig_tx.emit({'sender':__name__, 'closeEvent':''})
event.accept()
#------------------------------------------------------------------------------
def process_sig_rx(self, dict_sig=None):
"""
Process signals coming from the navigation toolbar and from sig_rx
"""
logger.debug("PROCESS_SIG_RX - vis: {0}\n{1}"\
.format(self.isVisible(), pprint_log(dict_sig)))
if ('view_changed' in dict_sig and dict_sig['view_changed'] == 'win')\
or ('filt_changed' in dict_sig and dict_sig['filt_changed'] == 'firwin')\
or self.needs_calc:
# logger.warning("Auto: {0} - WinLen: {1}".format(self.N_auto, self.win_dict['win_len']))
self.N_auto = self.win_dict['win_len']
self.calc_N()
if self.isVisible():
self.draw()
self.needs_calc = False
else:
self.needs_calc = True
elif 'home' in dict_sig:
self.update_view()
else:
logger.error("Unknown content of dict_sig: {0}".format(dict_sig))
#------------------------------------------------------------------------------
def _construct_UI(self):
"""
Intitialize the widget, consisting of:
- Matplotlib widget with NavigationToolbar
- Frame with control elements
"""
self.bfont = QFont()
self.bfont.setBold(True)
self.chk_auto_N = QCheckBox(self)
self.chk_auto_N.setChecked(False)
self.chk_auto_N.setToolTip("Use number of points from calling routine.")
self.lbl_auto_N = QLabel("Auto " + to_html("N", frmt='i'))
self.led_N = QLineEdit(self)
self.led_N.setText(str(self.N))
self.led_N.setMaximumWidth(70)
self.led_N.setToolTip("<span>Number of window data points.</span>")
self.chk_log_t = QCheckBox("Log", self)
self.chk_log_t.setChecked(False)
self.chk_log_t.setToolTip("Display in dB")
self.led_log_bottom_t = QLineEdit(self)
self.led_log_bottom_t.setText(str(self.bottom_t))
self.led_log_bottom_t.setMaximumWidth(50)
self.led_log_bottom_t.setEnabled(self.chk_log_t.isChecked())
self.led_log_bottom_t.setToolTip("<span>Minimum display value for log. scale.</span>")
self.lbl_log_bottom_t = QLabel("dB", self)
self.lbl_log_bottom_t.setEnabled(self.chk_log_t.isChecked())
self.chk_norm_f = QCheckBox("Norm", self)
self.chk_norm_f.setChecked(True)
self.chk_norm_f.setToolTip("Normalize window spectrum for a maximum of 1.")
self.chk_half_f = QCheckBox("Half", self)
self.chk_half_f.setChecked(True)
self.chk_half_f.setToolTip("Display window spectrum in the range 0 ... 0.5 f_S.")
self.chk_log_f = QCheckBox("Log", self)
self.chk_log_f.setChecked(True)
self.chk_log_f.setToolTip("Display in dB")
self.led_log_bottom_f = QLineEdit(self)
self.led_log_bottom_f.setText(str(self.bottom_f))
self.led_log_bottom_f.setMaximumWidth(50)
self.led_log_bottom_f.setEnabled(self.chk_log_f.isChecked())
self.led_log_bottom_f.setToolTip("<span>Minimum display value for log. scale.</span>")
self.lbl_log_bottom_f = QLabel("dB", self)
self.lbl_log_bottom_f.setEnabled(self.chk_log_f.isChecked())
layHControls = QHBoxLayout()
layHControls.addWidget(self.chk_auto_N)
layHControls.addWidget(self.lbl_auto_N)
layHControls.addWidget(self.led_N)
layHControls.addStretch(1)
layHControls.addWidget(self.chk_log_t)
layHControls.addWidget(self.led_log_bottom_t)
layHControls.addWidget(self.lbl_log_bottom_t)
layHControls.addStretch(10)
layHControls.addWidget(self.chk_norm_f)
layHControls.addStretch(1)
layHControls.addWidget(self.chk_half_f)
layHControls.addStretch(1)
layHControls.addWidget(self.chk_log_f)
layHControls.addWidget(self.led_log_bottom_f)
layHControls.addWidget(self.lbl_log_bottom_f)
self.tblWinProperties = QTableWidget(self.tbl_rows, self.tbl_cols, self)
self.tblWinProperties.setAlternatingRowColors(True)
self.tblWinProperties.verticalHeader().setVisible(False)
self.tblWinProperties.horizontalHeader().setVisible(False)
self._init_table(self.tbl_rows, self.tbl_cols, " ")
self.txtInfoBox = QTextBrowser(self)
#----------------------------------------------------------------------
# ### frmControls ###
#
# This widget encompasses all control subwidgets
#----------------------------------------------------------------------
self.frmControls = QFrame(self)
self.frmControls.setObjectName("frmControls")
self.frmControls.setLayout(layHControls)
#----------------------------------------------------------------------
# ### mplwidget ###
#
# main widget: Layout layVMainMpl (VBox) is defined with MplWidget,
# additional widgets can be added (like self.frmControls)
# The widget encompasses all other widgets.
#----------------------------------------------------------------------
self.mplwidget = MplWidget(self)
self.mplwidget.layVMainMpl.addWidget(self.frmControls)
self.mplwidget.layVMainMpl.setContentsMargins(*params['wdg_margins'])
#----------------------------------------------------------------------
# ### frmInfo ###
#
# This widget encompasses the text info box and the table with window
# parameters.
#----------------------------------------------------------------------
layVInfo = QVBoxLayout(self)
layVInfo.addWidget(self.tblWinProperties)
layVInfo.addWidget(self.txtInfoBox)
self.frmInfo = QFrame(self)
self.frmInfo.setObjectName("frmInfo")
self.frmInfo.setLayout(layVInfo)
#----------------------------------------------------------------------
# ### splitter ###
#
# This widget encompasses all control subwidgets
#----------------------------------------------------------------------
splitter = QSplitter(self)
splitter.setOrientation(Qt.Vertical)
splitter.addWidget(self.mplwidget)
splitter.addWidget(self.frmInfo)
# setSizes uses absolute pixel values, but can be "misused" by specifying values
# that are way too large: in this case, the space is distributed according
# to the _ratio_ of the values:
splitter.setSizes([3000,1000])
layVMain = QVBoxLayout()
layVMain.addWidget(splitter)
self.setLayout(layVMain)
#----------------------------------------------------------------------
# Set subplots
#
self.ax = self.mplwidget.fig.subplots(nrows=1, ncols=2)
self.ax_t = self.ax[0]
self.ax_f = self.ax[1]
self.draw() # initial drawing
#----------------------------------------------------------------------
# GLOBAL SIGNALS & SLOTs
#----------------------------------------------------------------------
self.sig_rx.connect(self.process_sig_rx)
#----------------------------------------------------------------------
# LOCAL SIGNALS & SLOTs
#----------------------------------------------------------------------
self.chk_log_f.clicked.connect(self.update_view)
self.chk_log_t.clicked.connect(self.update_view)
self.led_log_bottom_t.editingFinished.connect(self.update_bottom)
self.led_log_bottom_f.editingFinished.connect(self.update_bottom)
self.chk_auto_N.clicked.connect(self.calc_N)
self.led_N.editingFinished.connect(self.draw)
self.chk_norm_f.clicked.connect(self.draw)
self.chk_half_f.clicked.connect(self.update_view)
self.mplwidget.mplToolbar.sig_tx.connect(self.process_sig_rx)
self.tblWinProperties.itemClicked.connect(self._handle_item_clicked)
#------------------------------------------------------------------------------
def _init_table(self, rows, cols, val):
for r in range(rows):
for c in range(cols):
item = QTableWidgetItem(val)
if c % 3 == 0:
item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
if self.tbl_sel[r * 2 + c % 3]:
item.setCheckState(Qt.Checked)
else:
item.setCheckState(Qt.Unchecked)
self.tblWinProperties.setItem(r,c,item)
# https://stackoverflow.com/questions/12366521/pyqt-checkbox-in-qtablewidget
#------------------------------------------------------------------------------
def _set_table_item(self, row, col, val, font=None, sel=None):
"""
Set the table item with the index `row, col` and the value val
"""
item = self.tblWinProperties.item(row, col)
item.setText(str(val))
if font:
self.tblWinProperties.item(row,col).setFont(font)
if sel == True:
item.setCheckState(Qt.Checked)
if sel == False:
item.setCheckState(Qt.Unchecked)
# when sel is not specified, don't change anything
#------------------------------------------------------------------------------
def _handle_item_clicked(self, item):
if item.column() % 3 == 0: # clicked on checkbox
num = item.row() * 2 + item.column() // 3
if item.checkState() == Qt.Checked:
self.tbl_sel[num] = True
logger.debug('"{0}:{1}" Checked'.format(item.text(), num))
else:
self.tbl_sel[num] = False
logger.debug('"{0}:{1}" Unchecked'.format(item.text(), num))
elif item.column() % 3 == 1: # clicked on value field
logger.info("{0:s} copied to clipboard.".format(item.text()))
fb.clipboard.setText(item.text())
self.update_view()
#------------------------------------------------------------------------------
def update_bottom(self):
"""
Update log bottom settings
"""
self.bottom_t = safe_eval(self.led_log_bottom_t.text(), self.bottom_t,
sign='neg', return_type='float')
self.led_log_bottom_t.setText(str(self.bottom_t))
self.bottom_f = safe_eval(self.led_log_bottom_f.text(), self.bottom_f,
sign='neg', return_type='float')
self.led_log_bottom_f.setText(str(self.bottom_f))
self.update_view()
#------------------------------------------------------------------------------
def calc_N(self):
"""
(Re-)Calculate the number of data points when Auto N chkbox has been
clicked or when the number of data points has been updated outside this
class
"""
if self.chk_auto_N.isChecked():
self.N = self.N_auto
self.draw()
#------------------------------------------------------------------------------
def calc_win(self):
"""
(Re-)Calculate the window and its FFT
"""
self.led_N.setEnabled(not self.chk_auto_N.isChecked())
if not self.chk_auto_N.isChecked():
self.N = safe_eval(self.led_N.text(), self.N, sign='pos', return_type='int')
# else:
#self.N = self.win_dict['win_len']
self.led_N.setText(str(self.N))
self.n = np.arange(self.N)
self.win = calc_window_function(self.win_dict, self.win_dict['name'], self.N, sym=self.sym)
self.nenbw = self.N * np.sum(np.square(self.win)) / (np.square(np.sum(self.win)))
self.scale = self.N / np.sum(self.win)
self.F = fftfreq(self.N * self.pad, d=1. / fb.fil[0]['f_S']) # use zero padding
self.Win = np.abs(fft(self.win, self.N * self.pad))
if self.chk_norm_f.isChecked():
self.Win /= (self.N / self.scale)# correct gain for periodic signals (coherent gain)
first_zero = argrelextrema(self.Win[:(self.N*self.pad)//2], np.less)
if | np.shape(first_zero) | numpy.shape |
"""
Created on Jan. 07, 2021
@author: Heng-Sheng (Hanson) Chang
"""
import numpy as np
from numba import njit
import multiprocessing as mp
from elastica._linalg import _batch_cross
from elastica._calculus import quadrature_kernel
from elastica.external_forces import inplace_addition, NoForces
from gym_softrobot.utils.actuation.actuations.actuation import ContinuousActuation, ApplyActuation
from gym_softrobot.utils.actuation.frame_tools import change_box_to_arrow_axes
class Muscle(ContinuousActuation):
def __init__(self, n_elements):
ContinuousActuation.__init__(self, n_elements)
self.n_elements = n_elements
self.activation = np.zeros(self.n_elements-1)
self.s = np.linspace(0, 1, self.n_elements+1)[1:-1]
def set_activation(self, activation):
self.activation[:] = activation
return
def get_activation(self):
raise NotImplementedError
class MuscleForce(Muscle):
def __init__(self, n_elements):
Muscle.__init__(self, n_elements)
self.distributed_activation = np.zeros(self.n_elements)
def get_activation(self):
redistribute_activation(self.activation, self.distributed_activation)
return self.distributed_activation
@njit(cache=True)
def redistribute_activation(activation, distributed_activation):
distributed_activation[0] = activation[0]/2
distributed_activation[-1] = activation[-1]/2
distributed_activation[1:-1] = (activation[1:] + activation[:-1])/2
return
class MuscleCouple(Muscle):
def __init__(self, n_elements):
Muscle.__init__(self, n_elements)
def get_activation(self):
return self.activation
class MuscleFibers(object):
def __init__(self, n_elements, control_numbers):
self.controls = np.zeros(control_numbers)
# self.G_activations = np.zeros((control_numbers, n_elements))
self.G_internal_forces = np.zeros((control_numbers, 3, n_elements))
self.G_internal_couples = | np.zeros((control_numbers, 3, n_elements-1)) | numpy.zeros |
import numpy as np
from PIL import Image
import jittor as jt
from jittor import nn
from jittor import transform
from jittor.lr_scheduler import CosineAnnealingLR
from data.jimm import resnet26
from data.feature_utils import *
model_dict_path = '/home/fengyuan/JittorModels/trained-models/restnet-14-0.98.pkl'
img_path = '/home/fengyuan/JittorModels/trainingSet/trainingSet/0/img_1.jpg'
def get_train_transforms():
return transform.Compose([
transform.RandomCropAndResize((448, 448)),
transform.RandomHorizontalFlip(),
transform.ToTensor(),
transform.ImageNormalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))
])
def get_valid_transforms():
return transform.Compose([
transform.Resize(448),
# transform.CenterCrop(448),
transform.ToTensor(),
transform.ImageNormalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))
])
class Extractor():
"""
Extract grad and output of a model
"""
def __init__(self, model):
self.model = model
self.model.eval()
self.model_output = None
self.conv_output = []
self.relu_output = []
self.conv_grads_out = []
self.relu_grads_out = []
self.conv_grads_in = []
def remove_hooks(self):
for module_pos, module in enumerate(unpack_children(self.model)):
if isinstance(module, jt.nn.ReLU):
module.remove_forward_hook()
module.remove_backward_hook()
elif isinstance(module, jt.nn.Conv2d):
module.remove_forward_hook()
module.remove_backward_hook()
def clear_cache(self):
self.conv_output = []
self.relu_output = []
self.conv_grads_out = []
self.relu_grads_out = []
self.conv_grads_in = []
def register_hooks(self, type="cam"):
self.remove_hooks()
self.clear_cache()
if type=="cam":
self.register_cam_hooks()
elif type=="gbp":
self.register_gbp_hooks()
elif type=="vbp":
self.register_vbp_hooks()
else:
print("wrong hook type")
def register_cam_hooks(self):
def relu_forward_hook(m, t_in, t_out):
self.relu_output.append(t_out)
def relu_backward_hook(m, g_in, g_out):
self.relu_grads_out.append(g_out[0])
def conv_forward_hook(m, t_in, t_out):
self.conv_output.append(t_out)
def conv_backward_hook(m, g_in, g_out):
self.conv_grads_out.append(g_out[0])
for module_pos, module in enumerate(unpack_children(self.model)):
if isinstance(module, jt.nn.ReLU):
module.register_forward_hook(relu_forward_hook)
module.register_backward_hook(relu_backward_hook)
elif isinstance(module, jt.nn.Conv2d):
module.register_forward_hook(conv_forward_hook)
module.register_backward_hook(conv_backward_hook)
def register_vbp_hooks(self):
def conv_backward_hook(m, g_in, g_out):
self.conv_grads_in.append(g_in[0])
def relu_backward_hook(m, g_in, g_out):
g_in[0].data
for module_pos, module in enumerate(unpack_children(self.model)):
if isinstance(module, jt.nn.ReLU):
module.register_backward_hook(relu_backward_hook)
elif isinstance(module, jt.nn.Conv2d):
module.register_backward_hook(conv_backward_hook)
def register_gbp_hooks(self):
def relu_backward_hook(module, grad_in, grad_out):
"""
If there is a negative gradient, change it to zero
"""
grad_in[0].data
corresponding_forward_output = self.relu_output[-1]
corresponding_forward_output.data[corresponding_forward_output.data > 0] = 1
modified_grad_out = corresponding_forward_output * jt.clamp(grad_in[0], min_v=0.0)
del self.relu_output[-1]
return (modified_grad_out,)
def relu_forward_hook(m, t_in, t_out):
self.relu_output.append(t_out)
def conv_backward_hook(m, g_in, g_out):
self.conv_grads_in.append(g_in[0])
for module_pos, module in enumerate(unpack_children(self.model)):
if isinstance(module, jt.nn.ReLU):
module.register_forward_hook(relu_forward_hook)
module.register_backward_hook(relu_backward_hook)
elif isinstance(module, jt.nn.Conv2d):
module.register_backward_hook(conv_backward_hook)
def forward_and_backward(self, model_input, target_class):
model_input.start_grad()
self.model_output = self.model(model_input)
if not target_class:
target_class = np.argmax(self.model_output.data)
one_hot_output = jt.float32([[0 for i in range(self.model_output.size()[-1])]])
one_hot_output.data[0][target_class] = 1
criterion = nn.CrossEntropyLoss()
loss = criterion(self.model_output, one_hot_output)
model_input_grad = jt.grad(loss, model_input)
model_input_grad.sync()
def generate_gradients(self, input_image, target_class):
# grad at first conv
self.clear_cache()
self.forward_and_backward(input_image, target_class)
gradients = self.conv_grads_in[-1]
self.clear_cache()
return gradients
# ------for integrated grad------------
def generate_images_on_linear_path(self, input_image, steps):
step_list = np.arange(steps+1)/steps
xbar_list = [input_image*step for step in step_list]
return xbar_list
def generate_integrated_gradients(self, model_input, target_class, steps=10):
xbar_list = self.generate_images_on_linear_path(model_input, steps)
integrated_grads = np.zeros(model_input.size())
for xbar_image in xbar_list:
single_integrated_grad = self.generate_gradients(xbar_image, target_class)
integrated_grads = integrated_grads + single_integrated_grad/steps
return integrated_grads[0]
class FeatureVis():
"""
Algorithms for feature visualization
(bp) vanilla_bp, guided_bp
(cam) grad_cam, layer_cam, guided_grad_cam
(grad) integrated_gradients
(gradximg) [(gbp/integ)_]grad_times_image,
"""
def __init__(self, model=None):
self.model = model
self.model.eval()
self.transform = get_valid_transforms()
self.ori_img = get_img(img_path)
self.model_input = self.transform(self.ori_img)
self.model_input = self.model_input.reshape((1,3,448,448))
self.model_input = jt.array(self.model_input)
self.target_class = extract_target_class(img_path)
def get_feature_vis(self, model_input=None, target_class=None, method='vanilla_bp'):
"""
model_input (numpy, [w, h, 3])
return numpy([w, h, 3])
"""
if model_input is not None:
if model_input.shape[2]==3: # if shape (w, h, 3)
img_input = model_input.transpose((2,0,1))
img_input = self.transform(model_input)
w, h = img_input.shape[1], img_input.shape[2]
img_input = img_input.reshape((1, 3, w, h))
img_input = jt.array(img_input)
print(img_input.shape, target_class)
if not 'cam' in method:
grads = eval("self.%s" % method)(img_input=img_input, target_class=target_class)
else:
ori_img = Image.fromarray(np.uint8(model_input))
grads = eval("self.%s" % method)(img_input=img_input, target_class=target_class, ori_img=ori_img)
grads = grads.transpose((1,2,0)) # change to (w, h, 3)
return grads
def vanilla_bp(self, img_input, target_class, file_name_to_export='vanilla_bp', save=False):
extractor = Extractor(self.model)
extractor.register_hooks(type="vbp")
first_conv_grad = extractor.generate_gradients(img_input, target_class)[0].data
vanilla_grads = first_conv_grad
if save:
save_gradient_images(vanilla_grads, file_name_to_export + '_Guided_BP_color')
grayscale_guided_grads = convert_to_grayscale(vanilla_grads)
save_gradient_images(grayscale_guided_grads, file_name_to_export + '_Guided_BP_gray')
pos_sal, neg_sal = get_positive_negative_saliency(vanilla_grads)
save_gradient_images(pos_sal, file_name_to_export + '_p_sal')
save_gradient_images(neg_sal, file_name_to_export + '_n_sal')
# grayscale_guided_grads = convert_to_grayscale(vanilla_grads)
# vanilla_grads = grayscale_guided_grads
print('vanilla_bp', type(vanilla_grads), vanilla_grads.shape)
vanilla_grads = normalize(vanilla_grads)
return vanilla_grads
def guided_bp(self, img_input, target_class, file_name_to_export='guided_bp', save=False):
extractor = Extractor(self.model)
extractor.register_hooks("gbp")
first_conv_grad = extractor.generate_gradients(img_input, target_class)[0].data
guided_grads = first_conv_grad
if save:
save_gradient_images(guided_grads, file_name_to_export + '_Guided_BP_color')
grayscale_guided_grads = convert_to_grayscale(guided_grads)
save_gradient_images(grayscale_guided_grads, file_name_to_export + '_Guided_BP_gray')
pos_sal, neg_sal = get_positive_negative_saliency(guided_grads)
save_gradient_images(pos_sal, file_name_to_export + '_p_sal')
save_gradient_images(neg_sal, file_name_to_export + '_n_sal')
print('guided_bp', type(guided_grads), guided_grads.shape)
return normalize(guided_grads)
def integrated_gradients(self, img_input, target_class, steps=10, file_name_to_export='integrated_gradients', save=False):
extractor = Extractor(self.model)
extractor.register_hooks("vbp")
integrated_grads = extractor.generate_integrated_gradients(img_input, target_class, steps)
integrated_grads = integrated_grads.data
if save:
grayscale_integrated_grads = convert_to_grayscale(integrated_grads)
save_gradient_images(grayscale_integrated_grads, file_name_to_export + '_Integrated_G_gray')
print('integrated_gradients', type(integrated_grads), integrated_grads.shape)
grayscale_integrated_grads = convert_to_grayscale(integrated_grads)
return normalize(grayscale_integrated_grads)
def grad_times_image(self, img_input, target_class, file_name_to_export='gradximg', save=False):
extractor = Extractor(self.model)
extractor.register_hooks("vbp")
first_conv_grad = extractor.generate_gradients(img_input, target_class)[0].data
vanilla_grads = first_conv_grad
grad_times_image = vanilla_grads * img_input.numpy()[0]
if save:
grayscale_vanilla_grads = convert_to_grayscale(grad_times_image)
save_gradient_images(grayscale_vanilla_grads, file_name_to_export + '_grad_times_image_gray')
print('grad_times_image', type(grad_times_image), grad_times_image.shape)
grayscale_vanilla_grads = convert_to_grayscale(grad_times_image)
return normalize(grayscale_vanilla_grads)
def gbp_grad_times_image(self, img_input, target_class, file_name_to_export='gbp_gradximg', save=False):
extractor = Extractor(self.model)
extractor.register_hooks("gbp")
first_conv_grad = extractor.generate_gradients(img_input, target_class)[0].data
gbp_grads = first_conv_grad
gbp_grad_times_image = gbp_grads * img_input.numpy()[0]
if save:
grayscale_vanilla_grads = convert_to_grayscale(gbp_grad_times_image)
save_gradient_images(grayscale_vanilla_grads, file_name_to_export + '_grad_times_image_gray')
print('gbp_grad_times_image', type(gbp_grad_times_image), gbp_grad_times_image.shape)
grayscale_vanilla_grads = convert_to_grayscale(gbp_grad_times_image)
return normalize(grayscale_vanilla_grads)
def integ_grad_times_image(self, img_input, target_class, file_name_to_export='integ_gradximg', save=False):
extractor = Extractor(self.model)
extractor.register_hooks("vbp")
integrated_grads = extractor.generate_integrated_gradients(img_input, target_class).data
integ_grad_times_image = integrated_grads * img_input.numpy()[0]
if save:
grayscale_vanilla_grads = convert_to_grayscale(integ_grad_times_image)
save_gradient_images(grayscale_vanilla_grads, file_name_to_export + '_grad_times_image_gray')
print('integ_grad_times_image', type(integ_grad_times_image), integ_grad_times_image.shape)
grayscale_vanilla_grads = convert_to_grayscale(integ_grad_times_image)
return normalize(grayscale_vanilla_grads)
def grad_cam(self, img_input, target_class, ori_img=None, file_name_to_export='grad_cam', save=False, cam_size=None, return_cam=False):
extractor = Extractor(self.model)
extractor.register_hooks("cam")
extractor.forward_and_backward(img_input, target_class)
last_conv_grad = extractor.conv_grads_out[0][0].data
last_conv_output = extractor.conv_output[-1][0].data
weights = np.mean(last_conv_grad, axis=(1, 2))
target = last_conv_output
cam = | np.ones(target.shape[1:], dtype=np.float32) | numpy.ones |
import os
import numpy as np
import torch
import shutil
import torchvision.transforms as transforms
from torch.autograd import Variable
class AvgrageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.avg = 0
self.sum = 0
self.cnt = 0
def update(self, val, n=1):
self.sum += val * n
self.cnt += n
self.avg = self.sum / self.cnt
def accuracy(output, target, topk=(1,)):
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0)
res.append(correct_k.mul_(100.0/batch_size))
return res
class Cutout(object):
def __init__(self, length):
self.length = length
def __call__(self, img):
h, w = img.size(1), img.size(2)
mask = np.ones((h, w), np.float32)
y = np.random.randint(h)
x = | np.random.randint(w) | numpy.random.randint |
"""Deep sea treasure envirnment
mostly compatible with OpenAI gym envs
"""
from __future__ import print_function
import sys
import math
import random
import itertools
import numpy as np
import scipy.stats
import gym
import pygame
print("Using pygame backend", file=sys.stderr)
from utils import truncated_mean, compute_angle, pareto_filter
SEA_MAP = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[18, 26, 31, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[-1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[-1, -1, -1, 44, 48.2, 0, 0, 0, 0, 0, 0, 0],
[-1, -1, -1, -1, -1, 56, 0, 0, 0, 0, 0, 0],
[-1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0],
[-1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0],
[-1, -1, -1, -1, -1, -1, 72, 76.3, 0, 0, 0, 0],
[-1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0],
[-1, -1, -1, -1, -1, -1, -1, -1, 90, 0, 0, 0],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, 100, 0, 0]]
HOME_POS = (0, 0)
SIZE_X = 12
SIZE_Y = 12
ACT_LEFT = 0
ACT_RIGHT = 1
ACT_UP = 2
ACT_DOWN = 3
ACTIONS = ["Left", "Right", "Up", "Down"]
ACTION_COUNT = len(ACTIONS)
# State space (whole map) vars
WIDTH = 480
HEIGHT = 480
BOX_WIDTH = int(WIDTH / SIZE_X)
BOX_HEIGHT = int(HEIGHT / SIZE_Y)
# Observation space vars
OBSERVE_WIDTH = int(WIDTH * 5 / 12)
OBSERVE_HEIGHT = int(HEIGHT * 5 / 12)
# Pre-calculated space vars for add margin
M_WIDTH = WIDTH + OBSERVE_WIDTH
M_HEIGHT = HEIGHT + OBSERVE_HEIGHT
W_MIN = int(OBSERVE_WIDTH/2)
W_MAX = int(OBSERVE_WIDTH/2 + WIDTH)
H_MIN = int(OBSERVE_HEIGHT/2)
H_MAX = int(OBSERVE_HEIGHT/2 + HEIGHT)
# Color definitions
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 51, 204)
YELLOW = (255, 212, 84)
GREY = (80, 80, 80)
FPS = 180
class DeepSeaTreasure():
"""Deep sea treasure environment
"""
def __init__(self, sea_map=SEA_MAP):
self.action_space = np.arange(ACTION_COUNT)
self.observation_space = np.zeros((OBSERVE_WIDTH, OBSERVE_HEIGHT, 3), dtype=np.uint8)
# Initialize graphics backend
pygame.init()
self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
self.clock = pygame.time.Clock()
# self.submarine_sprite = pygame.sprite.Sprite()
# self.submarine_sprites = pygame.sprite.Group()
# self.submarine_sprites.add(self.submarine_sprite)
self.submarine_pos = list(HOME_POS)
self.sea_map = sea_map
self.end = False
self.obj_cnt = 2
def step(self, action, frame_skip=1, incremental_frame_skip=True):
"""Perform the given action `frame_skip` times
["Left", "Right", "Up", "Down"]
Arguments:
action {int} -- Action to perform, ACT_MINE (0), ACT_LEFT (1), ACT_RIGHT (2), ACT_ACCEL (3), ACT_BRAKE (4) or ACT_NONE (5)
Keyword Arguments:
frame_skip {int} -- Repeat the action this many times (default: {1})
incremental_frame_skip {bool} -- If True, frame_skip actions are performed in succession, otherwise the repeated actions are performed simultaneously (e.g., 4 accelerations are performed and then the cart moves).
Returns:
tuple -- (observation, reward, terminal, info) tuple
"""
reward = np.zeros(self.obj_cnt)
if frame_skip < 1:
frame_skip = 1
reward[-1] = -1
move = (0, 0)
if action == ACT_LEFT:
move = (-1,0)
elif action == ACT_RIGHT:
move = (1,0)
elif action == ACT_UP:
move = (0,-1)
elif action == ACT_DOWN:
move = (0,1)
changed = self.move_submarine(move)
reward[0] = self.sea_map[self.submarine_pos[1]][self.submarine_pos[0]]
if not self.end and changed:
self.render()
info = self.get_state(True)
observation = self.observation_space
# observation (pixels), reward (list), done (boolean), info (dict)
return observation, reward, self.end, info
def move_submarine(self, move):
target_x = self.submarine_pos[0] + move[0]
target_y = self.submarine_pos[1] + move[1]
if 0 <= target_x < 12 and 0 <= target_y < 12:
if self.sea_map[target_y][target_x] != -1:
self.submarine_pos[0] = target_x
self.submarine_pos[1] = target_y
if self.sea_map[target_y][target_x] != 0:
self.end = True
return True
return False
def get_pixels(self, update=True):
"""Get the environment's image representation
Keyword Arguments:
update {bool} -- Whether to redraw the environment (default: {True})
Returns:
np.array -- array of pixels, with shape (width, height, channels)
"""
if update:
self.pixels = pygame.surfarray.array3d(self.screen)
self.get_observation()
return self.pixels
def get_state(self, update=True):
"""Returns the environment's full state, including the cart's position,
its speed, its orientation and its content, as well as the environment's
pixels
Keyword Arguments:
update {bool} -- Whether to update the representation (default: {True})
Returns:
dict -- dict containing the aforementioned elements
"""
return {
"position": self.submarine_pos,
"pixels": self.get_pixels(update)
}
def get_observation(self):
"""Create a partially observable observation with the given state.
Half size of state["pixels"] with origin of state["position"], and the
overflow part is black
Returns:
array: 3d array as the same type of state["pixels"]
"""
# original state pixels with margins
margin_state_pixels = | np.full((M_WIDTH, M_HEIGHT, 3), GREY[0], dtype=np.uint8) | numpy.full |
import numpy as np
from menpo.transform import ThinPlateSplines
from menpofit.differentiable import DL, DX
from .rbf import DifferentiableR2LogR2RBF
class DifferentiableThinPlateSplines(ThinPlateSplines, DL, DX):
r"""
The Thin Plate Splines (TPS) alignment between 2D `source` and `target`
landmarks. The transform can compute its own derivative with respect to
spatial changes, as well as anchor landmark changes.
Parameters
----------
source : ``(N, 2)`` `ndarray`
The source points to apply the tps from
target : ``(N, 2)`` `ndarray`
The target points to apply the tps to
kernel : `class` or ``None``, optional
The differentiable kernel to apply. Possible options are
:map:`DifferentiableR2LogRRBF` and :map:`DifferentiableR2LogR2RBF`. If
``None``, then :map:`DifferentiableR2LogR2RBF` is used.
"""
def __init__(self, source, target, kernel=None):
if kernel is None:
kernel = DifferentiableR2LogR2RBF(source.points)
ThinPlateSplines.__init__(self, source, target, kernel=kernel)
def d_dl(self, points):
"""
Calculates the Jacobian of the TPS warp wrt to the source landmarks
assuming that he target is equal to the source. This is a special
case of the Jacobian wrt to the source landmarks that is used in AAMs
to weight the relative importance of each pixel in the reference
frame wrt to each one of the source landmarks.
dW_dl = dOmega_dl * k(points)
= T * d_L**-1_dl * k(points)
= T * -L**-1 dL_dl L**-1 * k(points)
# per point
(c, d) = (d, c+3) (c+3, c+3) (c+3, c+3, c, d) (c+3, c+3) (c+3)
(c, d) = (d, c+3) (c+3, c+3, c, d) (c+3,)
(c, d) = (d, ) ( c, d)
(c, d) = ( ) ( c, d)
Parameters
----------
points : ``(n_points, n_dims)`` `ndarray`
The spatial points at which the derivative should be evaluated.
Returns
-------
dW/dl : (n_points, n_params, n_dims) ndarray
The Jacobian of the transform wrt to the source landmarks evaluated
at the previous points and assuming that the target is equal to
the source.
"""
n_centres = self.n_points
n_points = points.shape[0]
# TPS kernel (nonlinear + affine)
# for each input, evaluate the rbf
# (n_points, n_centres)
k_points = self.kernel.apply(points)
# k_points with (1, x, y) appended to each point
# (n_points, n_centres+3) - 3 is (1, x, y) for affine component
k = np.hstack([k_points, | np.ones([n_points, 1]) | numpy.ones |
#!/usr/bin/env python
"""
Extracts faces from images and recognize the persons inside each image
and returns the images the bounding boxes and the recognized faces
"""
# MIT License
#
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import os
import argparse
import tensorflow as tf
import numpy as np
import cv2
import random
from collections import Counter
from recognition.facenet.src import facenet
from detection.insightface.RetinaFace.retinaface import RetinaFace
def recognition_handler(args):
# define detector
gpuid = -1
model_path = args.fd_model.split(',')
detector = RetinaFace(model_path[0], int(model_path[1]), gpuid, 'net3')
# Making sure output directory exists
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
cap = cv2.VideoCapture(args.input_image)
# Check if video feed opened successfully
if not cap.isOpened():
print("Unable to read frames feed")
with tf.Graph().as_default():
with tf.Session() as sess:
emb_array = np.load(args.dataset+'features_data.npy') #load saved dataset features for KNN
labels = np.load(args.dataset+'labels.npy')
recognized_labels = []
facenet.load_model(args.fr_model)
# Get input and output tensors
images_placeholder = tf.get_default_graph().get_tensor_by_name("input:0")
embeddings = tf.get_default_graph().get_tensor_by_name("embeddings:0")
phase_train_placeholder = tf.get_default_graph().get_tensor_by_name("phase_train:0")
# embedding_size = embeddings.get_shape()[1]
counter = 0
while True: # place holder for the open connection
ret, frame = cap.read()
# if failed to read frame data
if ret:
detect_align(frame, detector)
else:
break
frame = cv2.rotate(frame,cv2.ROTATE_90_CLOCKWISE)
faces_bounding_boxes, landmarks = detect_align(frame, detector)
nrof_faces = faces_bounding_boxes.shape[0]
faces = np.zeros((nrof_faces, args.image_size, args.image_size, 3))
if nrof_faces > 0:
det = faces_bounding_boxes[:, 0:4]
det_arr = []
img_size = np.asarray(frame.shape)[0:2]
crop_margin = 20
for i in range(nrof_faces):
det_arr.append(np.squeeze(det[i]))
for i, det in enumerate(det_arr):
det = np.squeeze(det)
bb = | np.zeros(4, dtype=np.int32) | numpy.zeros |
# CIFAR - 10
# To decode the files
import pickle
# For array manipulations
import numpy as np
# To make one-hot vectors
from keras.utils import np_utils
# To plot graphs and display images
from matplotlib import pyplot as plt
import pandas as pd
#constants
path = "data/" # Path to data
# Height or width of the images (32 x 32)
size = 32
# 3 channels: Red, Green, Blue (RGB)
channels = 3
# Number of classes
num_classes = 10
# Each file contains 10000 images
image_batch = 10000
# 5 training files
num_files_train = 5
# Total number of training images
images_train = image_batch * num_files_train
# https://www.cs.toronto.edu/~kriz/cifar.html
def unpickle(file):
# Convert byte stream to object
with open(path + file,'rb') as fo:
print("Decoding file: %s" % (path+file))
dict = pickle.load(fo, encoding='bytes')
# Dictionary with images and labels
return dict
def convert_images(raw_images):
# Convert images to numpy arrays
# Convert raw images to numpy array and normalize it
raw = np.array(raw_images, dtype = float) / 255.0
# Reshape to 4-dimensions - [image_number, channel, height, width]
images = raw.reshape([-1, channels, size, size])
images = images.transpose([0, 2, 3, 1])
# 4D array - [image_number, height, width, channel]
return images
def load_data(file):
# Load file, unpickle it and return images with their labels
data = unpickle(file)
# Get raw images
images_array = data[b'data']
# Convert image
images = convert_images(images_array)
# Convert class number to numpy array
labels = np.array(data[b'labels'])
# Images and labels in np array form
return images, labels
def get_test_data():
# Load all test data
images, labels = load_data(file = "test_batch")
# Images, their labels and
# corresponding one-hot vectors in form of np arrays
return images, labels, np_utils.to_categorical(labels,num_classes)
def get_train_data():
# Load all training data in 5 files
# Pre-allocate arrays
images = np.zeros(shape = [images_train, size, size, channels], dtype = float)
labels = np.zeros(shape=[images_train],dtype = int)
# Starting index of training dataset
start = 0
# For all 5 files
for i in range(num_files_train):
# Load images and labels
images_batch, labels_batch = load_data(file = "data_batch_" + str(i+1))
# Calculate end index for current batch
end = start + image_batch
# Store data to corresponding arrays
images[start:end,:] = images_batch
labels[start:end] = labels_batch
# Update starting index of next batch
start = end
# Images, their labels and
# corresponding one-hot vectors in form of np arrays
return images, labels, np_utils.to_categorical(labels,num_classes)
def get_class_names():
# Load class names
raw = unpickle("batches.meta")[b'label_names']
# Convert from binary strings
names = [x.decode('utf-8') for x in raw]
# Class names
return names
def plot_image(image, label_true=None, class_names=None, label_pred=None):
plt.grid()
plt.imshow(image)
# Show true and predicted classes
if label_true is not None and class_names is not None:
labels_true_name = class_names[label_true]
if label_pred is None:
xlabel = "True: "+labels_true_name
else:
# Name of the predicted class
labels_pred_name = class_names[label_pred]
xlabel = "True: "+labels_true_name+"\nPredicted: "+ labels_pred_name
# Show the class on the x-axis
plt.xlabel(xlabel)
plt.xticks([]) # Remove ticks from the plot
plt.yticks([])
plt.show() # Show the plot
def plot_images(images, labels_true, class_names, labels_pred=None,
confidence=None, titles=None):
assert len(images) == len(labels_true)
# Create a figure with sub-plots
fig, axes = plt.subplots(3, 3, figsize = (10,10))
# Adjust the vertical spacing
hspace = 0.2
if labels_pred is not None:
hspace += 0.2
if titles is not None:
hspace += 0.2
fig.subplots_adjust(hspace=hspace, wspace=0.0)
for i, ax in enumerate(axes.flat):
# Fix crash when less than 9 images
if i < len(images):
# Plot the image
ax.imshow(images[i])
# Name of the true class
labels_true_name = class_names[labels_true[i]]
# Show true and predicted classes
if labels_pred is None:
xlabel = "True: "+labels_true_name
else:
# Name of the predicted class
labels_pred_name = class_names[labels_pred[i]]
xlabel = "True: "+labels_true_name+"\nPred: "+ labels_pred_name
if (confidence is not None):
xlabel += " (" + "{0:.1f}".format(confidence[i] * 100) + "%)"
# Show the class on the x-axis
ax.set_xlabel(xlabel)
if titles is not None:
ax.set_title(titles[i])
# Remove ticks from the plot
ax.set_xticks([])
ax.set_yticks([])
# Show the plot
plt.show()
def plot_model(model_details):
# Create sub-plots
fig, axs = plt.subplots(1,2,figsize=(15,5))
# Summarize history for accuracy
axs[0].plot(range(1,len(model_details.history['acc'])+1),model_details.history['acc'])
axs[0].plot(range(1,len(model_details.history['val_acc'])+1),model_details.history['val_acc'])
axs[0].set_title('Model Accuracy')
axs[0].set_ylabel('Accuracy')
axs[0].set_xlabel('Epoch')
axs[0].set_xticks(np.arange(1,len(model_details.history['acc'])+1),len(model_details.history['acc'])/10)
axs[0].legend(['train', 'val'], loc='best')
# Summarize history for loss
axs[1].plot(range(1,len(model_details.history['loss'])+1),model_details.history['loss'])
axs[1].plot(range(1,len(model_details.history['val_loss'])+1),model_details.history['val_loss'])
axs[1].set_title('Model Loss')
axs[1].set_ylabel('Loss')
axs[1].set_xlabel('Epoch')
axs[1].set_xticks(np.arange(1,len(model_details.history['loss'])+1),len(model_details.history['loss'])/10)
axs[1].legend(['train', 'val'], loc='best')
# Show the plot
plt.show()
def visualize_errors(images_test, labels_test, class_names, labels_pred, correct):
incorrect = (correct == False)
# Images of the test-set that have been incorrectly classified.
images_error = images_test[incorrect]
# Get predicted classes for those images
labels_error = labels_pred[incorrect]
# Get true classes for those images
labels_true = labels_test[incorrect]
# Plot the first 9 images.
plot_images(images=images_error[0:9],
labels_true=labels_true[0:9],
class_names=class_names,
labels_pred=labels_error[0:9])
def visualize_attack(df, class_names):
results = df[df.success].sample(9)
images = np.array(results.attack_image)
labels_true = | np.array(results.true) | numpy.array |
""""
Title : Wetted area wing
Written by: <NAME>
Date : 13/11/19
Language : Python
Aeronautical Institute of Technology
Inputs:
MTOW
Outputs:
Cap_Sal
FO_Sal
"""
########################################################################################
"""Importing Modules"""
########################################################################################
########################################################################################
"""Constants declaration"""
########################################################################################
import numpy as np
import pandas as pd
import os
from scipy import interpolate
from framework.Sizing.Geometry.area_triangle_3d import area_triangle_3d
from framework.Sizing.Geometry.airfoil_preprocessing import airfoil_preprocessing
def wetted_area_wing(vehicle, fileToRead1, fileToRead2, fileToRead3):
wing = vehicle['wing']
fuselage = vehicle['fuselage']
engine = vehicle['engine']
semispan = wing['span']/2
# Calcula area exposta ada asa
rad = np.pi/180
#
raio = fuselage['width']/2
tanaux = np.tan(rad*wing['sweep_leading_edge'] )
airfoil_names = [fileToRead1, fileToRead2, fileToRead3]
airfoil_chords = [wing['root_chord'], wing['kink_chord'], wing['tip_chord']]
########################################################################################
"""Pre-processing airfoils"""
########################################################################################
airfoils = {1: {},
2: {},
3: {}}
panel_number = 201
for i in range(len(airfoils)):
j = i+1
airfoils[j]['name'] = airfoil_names[i]
airfoils[j]['chord'] = airfoil_chords[i]
for i in airfoils:
airfoil = i
airfoil_name = airfoils[airfoil]['name']
airfoil_preprocessing(airfoil_name, panel_number)
########################################################################################
"""Importing Data"""
########################################################################################
# Load airfoil coordinates
df = pd.read_csv(
"" + airfoil_names[0] + '.dat', sep=',', delimiter=None, header=None, skiprows=[0])
df.columns = ['x', 'y']
df_head = df.head()
n_coordinates = len(df)
# Compute distance between consecutive points
dx = []
dy = []
ds = []
ds_vector = []
ds = np.zeros((n_coordinates, 1))
ds[0] = 0
for i in range(1, n_coordinates):
dx = df.x[i] - df.x[i-1]
dy = df.y[i] - df.y[i-1]
ds[i] = ds[i-1] + np.sqrt(dx*dx+dy*dy)
xa = df.x[0]
xb = df.x[1]
ind = 0
# Find leading edge index
while xb < xa:
ind = ind + 1
xa = df.x[ind]
xb = df.x[ind+1]
n_panels_x = 51
xp = np.linspace(0, 1, n_panels_x)
xp = np.flip((np.cos(xp*np.pi)/2+0.5))
# Interpolate upper skin
dsaux = ds[0:ind+1]
xaux = df.x[0:ind+1]
dsaux = np.reshape(dsaux, -1)
ds = np.reshape(ds, -1)
dsinterp = interpolate.interp1d(
xaux, dsaux, kind='slinear', fill_value='extrapolate')(xp)
yupp_root = interpolate.interp1d(ds, df.y, kind='slinear')(dsinterp)
# Interpolate lower skin
dsaux = []
dsaux = ds[ind:n_coordinates]
dsinterp = []
xaux = df.x[ind:n_coordinates]
dsinterp = interpolate.interp1d(
xaux, dsaux, kind='slinear', fill_value='extrapolate')(xp)
ylow_root = interpolate.interp1d(ds, df.y, kind='slinear')(dsinterp)
xproot = np.array([np.flip(xp), xp])
xproot = xproot.ravel()
yproot = np.array([np.flip(yupp_root), ylow_root])
yproot = yproot.ravel()
esspraiz = max(yupp_root)-min(ylow_root)
# plt.figure()
# plt.plot(xproot,yproot,'bo')
########################################################################################
# Load airfoil coordinates
df = pd.read_csv(
"" + airfoil_names[1] + '.dat', sep=',', delimiter=None, header=None, skiprows=[0])
df.columns = ['x', 'y']
df_head = df.head()
n_coordinates = len(df)
# Compute distance between consecutive points
dx = []
dy = []
ds = []
ds_vector = []
ds = np.zeros((n_coordinates, 1))
ds[0] = 0
for i in range(1, n_coordinates):
dx = df.x[i] - df.x[i-1]
dy = df.y[i] - df.y[i-1]
ds[i] = ds[i-1] + np.sqrt(dx*dx+dy*dy)
xa = df.x[0]
xb = df.x[1]
ind = 0
# Find leading edge index
while xb < xa:
ind = ind + 1
xa = df.x[ind]
xb = df.x[ind+1]
n_panels_x = 51
xp = np.linspace(0, 1, n_panels_x)
xp = np.flip((np.cos(xp*np.pi)/2+0.5))
# Interpolate upper skin
dsaux = ds[0:ind+1]
xaux = df.x[0:ind+1]
dsaux = np.reshape(dsaux, -1)
ds = np.reshape(ds, -1)
dsinterp = interpolate.interp1d(
xaux, dsaux, kind='slinear', fill_value='extrapolate')(xp)
yupp_kink = interpolate.interp1d(ds, df.y, kind='slinear')(dsinterp)
# Interpolate lower skin
dsaux = []
dsaux = ds[ind:n_coordinates]
dsinterp = []
xaux = df.x[ind:n_coordinates]
dsinterp = interpolate.interp1d(
xaux, dsaux, kind='slinear', fill_value='extrapolate')(xp)
ylow_kink = interpolate.interp1d(ds, df.y, kind='slinear')(dsinterp)
xpkink = np.array([np.flip(xp), xp])
xpkink = xpkink.ravel()
ypkink = np.array([np.flip(yupp_kink), ylow_kink])
ypkink = ypkink.ravel()
# plt.plot(xpkink,ypkink,'ro')
########################################################################################
# Load airfoil coordinates
df = pd.read_csv(
"" + airfoil_names[2] + '.dat', sep=',', delimiter=None, header=None, skiprows=[0])
df.columns = ['x', 'y']
df_head = df.head()
n_coordinates = len(df)
# Compute distance between consecutive points
dx = []
dy = []
ds = []
ds_vector = []
ds = np.zeros((n_coordinates, 1))
ds[0] = 0
for i in range(1, n_coordinates):
dx = df.x[i] - df.x[i-1]
dy = df.y[i] - df.y[i-1]
ds[i] = ds[i-1] + np.sqrt(dx*dx+dy*dy)
xa = df.x[0]
xb = df.x[1]
ind = 0
# Find leading edge index
while xb < xa:
ind = ind + 1
xa = df.x[ind]
xb = df.x[ind+1]
n_panels_x = 51
xp = np.linspace(0, 1, n_panels_x)
xp = np.flip((np.cos(xp*np.pi)/2+0.5))
# Interpolate upper skin
dsaux = ds[0:ind+1]
xaux = df.x[0:ind+1]
dsaux = np.reshape(dsaux, -1)
ds = np.reshape(ds, -1)
dsinterp = interpolate.interp1d(
xaux, dsaux, kind='slinear', fill_value='extrapolate')(xp)
yupp_tip = interpolate.interp1d(ds, df.y, kind='slinear')(dsinterp)
# Interpolate lower skin
dsaux = []
dsaux = ds[ind:n_coordinates]
dsinterp = []
xaux = df.x[ind:n_coordinates]
dsinterp = interpolate.interp1d(
xaux, dsaux, kind='slinear', fill_value='extrapolate')(xp)
ylow_tip = interpolate.interp1d(ds, df.y, kind='slinear')(dsinterp)
xptip = np.array([np.flip(xp), xp])
xptip = xptip.ravel()
yptip = np.array([np.flip(yupp_tip), ylow_tip])
yptip = yptip.ravel()
########################################################################################
########################################################################################
# =====> Wing
if wing['position'] == 1:
wingpos = -0.48*raio
engzpos = -0.485*raio
else:
wingpos = raio-wing['center_chord']*1.15*0.12/2
engzpos = wingpos-0.10*engine['fan_diameter']/2
# Rotate root section according to given incidence
teta = -wing['root_incidence'] # - points sky + points ground
tetar = teta*rad
xproot = xproot*np.cos(tetar)-yproot*np.sin(tetar)
yproot = xproot*np.sin(tetar)+yproot*np.cos(tetar)
# Rotates kink station airfoil
teta = -wing['kink_incidence']
tetar = teta*rad
xpkink = xpkink*np.cos(tetar)-ypkink*np.sin(tetar)
ypkink = xpkink*np.sin(tetar)+ypkink* | np.cos(tetar) | numpy.cos |
import os
import numpy as np
import flopy
import warnings
from io import StringIO
from struct import pack
from tempfile import TemporaryFile
from textwrap import dedent
from flopy.utils.util_array import Util2d, Util3d, Transient2d, Transient3d
from ci_framework import base_test_dir, FlopyTestSetup
base_dir = base_test_dir(__file__, rel_path="temp", verbose=True)
def test_load_txt_free():
a = np.ones((10,), dtype=np.float32) * 250.0
fp = StringIO("10*250.0")
fa = Util2d.load_txt(a.shape, fp, a.dtype, "(FREE)")
np.testing.assert_equal(fa, a)
assert fa.dtype == a.dtype
a = np.arange(10, dtype=np.int32).reshape((2, 5))
fp = StringIO(
dedent(
"""\
0 1,2,3, 4
5 6, 7, 8 9
"""
)
)
fa = Util2d.load_txt(a.shape, fp, a.dtype, "(FREE)")
np.testing.assert_equal(fa, a)
assert fa.dtype == a.dtype
a = np.ones((2, 5), dtype=np.float32)
a[1, 0] = 2.2
fp = StringIO(
dedent(
"""\
5*1.0
2.2 2*1.0, +1E-00 1.0
"""
)
)
fa = Util2d.load_txt(a.shape, fp, a.dtype, "(FREE)")
np.testing.assert_equal(fa, a)
assert fa.dtype == a.dtype
def test_load_txt_fixed():
a = np.arange(10, dtype=np.int32).reshape((2, 5))
fp = StringIO(
dedent(
"""\
01234X
56789
"""
)
)
fa = Util2d.load_txt(a.shape, fp, a.dtype, "(5I1)")
np.testing.assert_equal(fa, a)
assert fa.dtype == a.dtype
fp = StringIO(
dedent(
"""\
0123X
4
5678
9
"""
)
)
fa = Util2d.load_txt(a.shape, fp, a.dtype, "(4I1)")
np.testing.assert_equal(fa, a)
assert fa.dtype == a.dtype
a = np.array([[-1, 1, -2, 2, -3], [3, -4, 4, -5, 5]], np.int32)
fp = StringIO(
dedent(
"""\
-1 1-2 2-3
3 -44 -55
"""
)
)
fa = Util2d.load_txt(a.shape, fp, a.dtype, "(5I2)")
np.testing.assert_equal(fa, a)
assert fa.dtype == a.dtype
def test_load_block():
a = np.ones((2, 5), dtype=np.int32) * 4
fp = StringIO(
dedent(
"""\
1
1 2 1 5 4
"""
)
)
fa = Util2d.load_block(a.shape, fp, a.dtype)
np.testing.assert_equal(fa, a)
assert fa.dtype == a.dtype
a = np.ones((2, 5), dtype=np.float32) * 4
a[0:2, 1:2] = 9.0
a[0, 2:4] = 6.0
fp = StringIO(
dedent(
"""\
3
1 2 1 5 4.0
1 2 2 2 9.0
1 1 3 4 6.0
"""
)
)
fa = Util2d.load_block(a.shape, fp, a.dtype)
np.testing.assert_equal(fa, a)
assert fa.dtype == a.dtype
a = np.zeros((2, 5), dtype=np.int32)
a[0, 2:4] = 8
fp = StringIO(
dedent(
"""\
1
1 1 3 4 8
"""
)
)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
fa = Util2d.load_block(a.shape, fp, a.dtype)
assert len(w) == 1
assert "blocks do not cover full array" in str(w[-1].message)
np.testing.assert_equal(fa, a)
assert fa.dtype == a.dtype
def test_load_bin():
model_ws = f"{base_dir}_test_load_bin"
test_setup = FlopyTestSetup(test_dirs=model_ws)
def temp_file(data):
# writable file that is destroyed as soon as it is closed
f = TemporaryFile(dir=model_ws)
f.write(data)
f.seek(0)
return f
# INTEGER
a = np.arange(3 * 4, dtype=np.int32).reshape((3, 4)) - 1
fp = temp_file(a.tobytes())
fh, fa = Util2d.load_bin((3, 4), fp, np.int32)
assert fh is None # no header_dtype
np.testing.assert_equal(fa, a)
assert fa.dtype == a.dtype
# check warning if wrong integer type is used to read 4-byte integers
# e.g. on platforms where int -> int64
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
fp.seek(0)
fh, fa = Util2d.load_bin((3, 4), fp, np.int64)
fp.close()
assert len(w) == 1
assert a.dtype == np.int32
assert fh is None # no header_dtype
| np.testing.assert_equal(fa, a) | numpy.testing.assert_equal |
import numpy as np
from gym import spaces
import vrep
from envs.VrepEnv import catch_errors, VrepEnv
class SawyerEnv(VrepEnv):
"""
Abstract parent class encapsulating behaviour common to environments with a Sawyer arm.
"""
num_joints = 7
action_space = spaces.Box(np.array([-0.3] * num_joints), np.array([0.3] * num_joints),
dtype=np.float32)
curr_action = np.array([0.] * num_joints)
scale = 0.01
identity = scale * np.identity(num_joints)
def __init__(self, *args, random_joints=True):
super().__init__(*args)
self.random_joints = random_joints
self.np_random = np.random.RandomState()
# Get the initial configuration of the robot (needed to later reset the robot's pose)
self.init_config_tree, _, _, _ = self.call_lua_function('get_configuration_tree')
_, self.init_joint_angles, _, _ = self.call_lua_function('get_joint_angles')
self.joint_handles = np.array([None] * self.num_joints)
for i in range(self.num_joints):
handle = catch_errors(vrep.simxGetObjectHandle(self.cid, 'Sawyer_joint' + str(i + 1),
vrep.simx_opmode_blocking))
self.joint_handles[i] = handle
# Start the simulation (the "Play" button in V-Rep should now be in a "Pressed" state)
catch_errors(vrep.simxStartSimulation(self.cid, vrep.simx_opmode_blocking))
def seed(self, seed=None):
self.np_random.seed(seed)
def reset(self):
if self.random_joints:
initial_pose = self.np_random.multivariate_normal(self.init_joint_angles, self.identity)
else:
initial_pose = self.init_joint_angles
self.call_lua_function('set_joint_angles', ints=self.init_config_tree, floats=initial_pose)
self.curr_action = | np.array([0.] * 6) | numpy.array |
import pytest
import math
import numpy as np
import autograd.numpy as adnp
from autograd import grad
import cs107_salad.Forward.salad as ad
from cs107_salad.Forward.utils import check_list, compare_dicts, compare_dicts_multi
def test_add_radd():
x = ad.Variable(3)
y = x + 3
assert y.val == 6
assert list(y.der.values()) == np.array([1])
x = ad.Variable(3)
y = 3 + x
assert y.val == 6
assert list(y.der.values()) == np.array([1])
x = ad.Variable(3, {"x": 1})
y = ad.Variable(3, {"y": 1})
z = x + y
assert z.val == 6
assert z.der == {"x": 1, "y": 1}
x = ad.Variable(np.ones((5, 5)), label="x")
y = ad.Variable(np.ones((5, 5)), label="y")
z = x + y
assert np.array_equal(z.val, 2 * np.ones((5, 5)))
np.testing.assert_equal(z.der, {"x": np.ones((5, 5)), "y": np.ones((5, 5))})
z = x + x + y + y + 2
assert np.array_equal(z.val, 4 * np.ones((5, 5)) + 2)
np.testing.assert_equal(z.der, {"x": 2 * np.ones((5, 5)), "y": 2 * np.ones((5, 5))})
def test_sub_rsub():
x = ad.Variable(3)
y = x - 3
assert y.val == 0
assert list(y.der.values()) == np.array([1])
x = ad.Variable(3)
y = 3 - x
assert y.val == 0
assert list(y.der.values()) == np.array([-1])
x = ad.Variable(3, {"x": 1})
y = ad.Variable(3, {"y": 1})
z = x - y
assert z.val == 0
assert z.der == {"x": 1, "y": -1}
x = ad.Variable(np.ones((5, 5)), label="x")
y = ad.Variable(np.ones((5, 5)), label="y")
z = x - y
assert np.array_equal(z.val, np.zeros((5, 5)))
np.testing.assert_equal(z.der, {"x": np.ones((5, 5)), "y": -1 * np.ones((5, 5))})
z = x + x - y - y + 2
assert np.array_equal(z.val, 2 * np.ones((5, 5)))
np.testing.assert_equal(
z.der, {"x": 2 * np.ones((5, 5)), "y": -2 * np.ones((5, 5))}
)
def test_mul_rmul():
x = ad.Variable(3, label="x")
y = x * 2
assert y.val == 6
assert y.der == {"x": 2}
# y = 5x + x^2
y = x * 2 + 3 * x + x * x
assert y.val == 24
assert y.der == {"x": 11}
x = ad.Variable(3, label="x")
y = ad.Variable(2, label="y")
z = x * y
assert z.val == 6
assert z.der == {"x": 2, "y": 3}
z = 3 * z * 3
assert z.val == 54
assert z.der == {"x": 18, "y": 27}
x = ad.Variable(3, label="x")
y = ad.Variable(2, label="y")
z = x * y
z = y * z # y^2*x
assert z.val == 12
assert z.der == {"x": y.val ** 2, "y": 2 * y.val * x.val}
x = ad.Variable(2 * np.ones((5, 5)), label="x")
y = ad.Variable(3 * np.ones((5, 5)), label="y")
z = x * y
assert np.array_equal(z.val, 2 * 3 * np.ones((5, 5)))
np.testing.assert_equal(z.der, {"x": 3 * np.ones((5, 5)), "y": 2 * np.ones((5, 5))})
z = -1 * z * x # f = -(x^2) * y, dx = -2xy, dy = -x^2
assert np.array_equal(z.val, -12 * np.ones((5, 5)))
np.testing.assert_equal(
z.der, {"x": -2 * 2 * 3 * np.ones((5, 5)), "y": -1 * 2 * 2 * np.ones((5, 5))}
)
def test_truediv_rtruediv():
x = ad.Variable(3, label="x")
y = x / 2
assert y.val == 1.5
assert y.der == {"x": 1 / 2}
y = x / 2 + 3 / x + x / x
assert y.val == 3.5
assert y.der == {"x": 0.5 - 3 / 9}
x = ad.Variable(3, label="x")
y = ad.Variable(2, label="y")
z = x / y
assert z.val == 3 / 2
assert z.der == {"x": 1 / 2, "y": -3 / 4} # dx = 1/y, dy = -x/y^2
z = 2.4 / z / x / 8 # 2.4/(x/y)/x/8
assert z.val == 2.4 / (3 / 2) / 3 / 8
## Using this function because of rounding errors
assert compare_dicts(
z.der, {"x": (-0.6 * y.val) / (x.val ** 3), "y": (0.3 / (x.val ** 2))}
) # dx = -.6y/x^3 , dy = .3/x^2
x = ad.Variable(2 * np.ones((5, 5)), label="x")
y = ad.Variable(3 * np.ones((5, 5)), label="y")
z = x / y
assert np.array_equal(z.val, 2 / 3 * np.ones((5, 5)))
np.testing.assert_equal(z.der, {"x": 1 / y.val, "y": -1 * x.val / (y.val ** 2)})
z = -1 / z / x
assert np.array_equal(z.val, -1 / (2 / 3) / 2 * np.ones((5, 5)))
np.testing.assert_equal(
z.der, {"x": 2 * y.val / (x.val ** 3), "y": -1 / (x.val ** 2)}
)
def test_exp():
x = 3
ans = ad.exp(x)
sol = np.exp(x)
assert sol == ans
x = ad.Variable(3, label="x")
y = ad.exp(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = np.exp(3), np.exp(3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(3, label="x")
ans_val, ans_der = ad.exp(x).val, ad.exp(x).der["x"]
sol_val, sol_der = np.exp(3), np.exp(3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(3, label="x") + 3
y = ad.exp(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = np.exp(6), np.exp(6)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(3, label="x") + ad.Variable(4, label="y")
y = ad.exp(x)
ans_val, ans_der = y.val, [y.der["x"], y.der["y"]]
sol_val, sol_der = np.exp(7), [np.exp(7), np.exp(7)]
assert ans_val == sol_val
assert check_list(ans_der, sol_der)
x = ad.Variable([3, 4, 5], label="x")
y = ad.exp(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[np.exp(3), np.exp(4), np.exp(5)],
[np.exp(3), np.exp(4), np.exp(5),],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([3, 4, 5], label="x")
y = ad.exp(x) + ad.exp(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[2 * np.exp(3), 2 * np.exp(4), 2 * np.exp(5)],
[2 * np.exp(3), 2 * np.exp(4), 2 * np.exp(5),],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([3, 4, 5], label="x")
z = x + x
y = ad.exp(z)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[np.exp(2 * 3), np.exp(2 * 4), np.exp(2 * 5)],
[2 * np.exp(2 * 3), 2 * np.exp(2 * 4), 2 * np.exp(2 * 5),],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([3, 4, 5], label="x")
y = ad.Variable([6, 6, 6], label="y")
y = ad.exp(x + y)
ans_val, ans_der_x, ans_der_y = y.val, y.der["x"], y.der["y"]
sol_val, sol_der_x, sol_der_y = (
[np.exp(9), np.exp(10), np.exp(11)],
[
grad(lambda x, y: adnp.exp(x + y), 0)(3.0, 6.0),
grad(lambda x, y: adnp.exp(x + y), 0)(4.0, 6.0),
grad(lambda x, y: adnp.exp(x + y), 0)(5.0, 6.0),
],
[
grad(lambda x, y: adnp.exp(x + y), 1)(3.0, 6.0),
grad(lambda x, y: adnp.exp(x + y), 1)(4.0, 6.0),
grad(lambda x, y: adnp.exp(x + y), 1)(5.0, 6.0),
],
)
assert check_list(ans_val, sol_val)
assert check_list(sol_der_x, ans_der_x) & check_list(sol_der_y, ans_der_y)
def test_ln():
x = 3
ans = ad.ln(x)
sol = adnp.log(x)
assert sol == ans
x = ad.Variable(3, label="x")
y = ad.ln(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.log(3), grad(adnp.log)(3.0)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(3, label="x") + 3
y = ad.ln(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.log(6), grad(lambda x: adnp.log(x + 3.0))(3.0)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(3, label="x") + ad.Variable(4, label="y")
y = ad.ln(x)
ans_val, ans_der = y.val, [y.der["x"], y.der["y"]]
sol_val, sol_der = (
adnp.log(7),
[
grad(lambda x, y: adnp.log(x + y), 0)(3.0, 4.0),
grad(lambda x, y: adnp.log(x + y), 1)(3.0, 4.0),
],
)
assert ans_val == sol_val
assert check_list(ans_der, sol_der)
x = ad.Variable([3, 4, 5], label="x")
y = ad.ln(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[np.log(3), np.log(4), np.log(5)],
[
grad(lambda x: adnp.log(x))(3.0),
grad(lambda x: adnp.log(x))(4.0),
grad(lambda x: adnp.log(x))(5.0),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([3, 4, 5], label="x")
y = ad.ln(x + x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[adnp.log(3 * 2), adnp.log(4 * 2), adnp.log(5 * 2)],
[
grad(lambda x: adnp.log(x + x))(3.0),
grad(lambda x: adnp.log(x + x))(4.0),
grad(lambda x: adnp.log(x + x))(5.0),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([3, 4, 5], label="x")
y = ad.Variable([6, 6, 6], label="y")
y = ad.ln(x + y)
ans_val, ans_der_x, ans_der_y = y.val, y.der["x"], y.der["y"]
sol_val, sol_der_x, sol_der_y = (
[np.log(9), np.log(10), np.log(11)],
[
grad(lambda x, y: adnp.log(x + y), 0)(3.0, 6.0),
grad(lambda x, y: adnp.log(x + y), 0)(4.0, 6.0),
grad(lambda x, y: adnp.log(x + y), 0)(5.0, 6.0),
],
[
grad(lambda x, y: adnp.log(x + y), 1)(3.0, 6.0),
grad(lambda x, y: adnp.log(x + y), 1)(4.0, 6.0),
grad(lambda x, y: adnp.log(x + y), 1)(5.0, 6.0),
],
)
assert check_list(ans_val, sol_val)
assert check_list(sol_der_x, ans_der_x) & check_list(sol_der_y, ans_der_y)
def test_logistic():
def logistic(x):
return 1 / (1 + adnp.exp(-x))
x = 3
ans = ad.logistic(x)
sol = logistic(x)
assert sol == ans
x = ad.Variable(3, label="x")
y = ad.logistic(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = logistic(3), grad(logistic)(3.0)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(3, label="x") + 3
y = ad.logistic(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = logistic(6), grad(lambda x: logistic(x + 3.0))(3.0)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(3, label="x") + ad.Variable(4, label="y")
y = ad.logistic(x)
ans_val, ans_der = y.val, [y.der["x"], y.der["y"]]
sol_val, sol_der = (
logistic(7),
[
grad(lambda x, y: logistic(x + y), 0)(3.0, 4.0),
grad(lambda x, y: logistic(x + y), 1)(3.0, 4.0),
],
)
assert ans_val == sol_val
assert check_list(ans_der, sol_der)
x = ad.Variable([3, 4, 5], label="x")
y = ad.logistic(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[logistic(3), logistic(4), logistic(5)],
[
grad(lambda x: logistic(x))(3.0),
grad(lambda x: logistic(x))(4.0),
grad(lambda x: logistic(x))(5.0),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([3, 4, 5], label="x")
y = ad.logistic(x + x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[logistic(3 * 2), logistic(4 * 2), logistic(5 * 2)],
[
grad(lambda x: logistic(x + x))(3.0),
grad(lambda x: logistic(x + x))(4.0),
grad(lambda x: logistic(x + x))(5.0),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([3, 4, 5], label="x")
y = ad.Variable([6, 6, 6], label="y")
y = ad.logistic(x + y)
ans_val, ans_der_x, ans_der_y = y.val, y.der["x"], y.der["y"]
sol_val, sol_der_x, sol_der_y = (
[logistic(9), logistic(10), logistic(11)],
[
grad(lambda x, y: logistic(x + y), 0)(3.0, 6.0),
grad(lambda x, y: logistic(x + y), 0)(4.0, 6.0),
grad(lambda x, y: logistic(x + y), 0)(5.0, 6.0),
],
[
grad(lambda x, y: logistic(x + y), 1)(3.0, 6.0),
grad(lambda x, y: logistic(x + y), 1)(4.0, 6.0),
grad(lambda x, y: logistic(x + y), 1)(5.0, 6.0),
],
)
assert check_list(ans_val, sol_val)
assert check_list(sol_der_x, ans_der_x) & check_list(sol_der_y, ans_der_y)
def test_log10():
def log10(x):
return adnp.log(x) / adnp.log(10)
x = 3
ans = ad.log10(x)
sol = log10(x)
assert sol == ans
x = ad.Variable(3, label="x")
y = ad.log10(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = log10(3), grad(log10)(3.0)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(3, label="x") + 3
y = ad.log10(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = log10(6), grad(lambda x: log10(x + 3.0))(3.0)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(3, label="x") + ad.Variable(4, label="y")
y = ad.log10(x)
ans_val, ans_der = y.val, [y.der["x"], y.der["y"]]
sol_val, sol_der = (
log10(7),
[
grad(lambda x, y: log10(x + y), 0)(3.0, 4.0),
grad(lambda x, y: log10(x + y), 1)(3.0, 4.0),
],
)
assert ans_val == sol_val
assert check_list(ans_der, sol_der)
x = ad.Variable([3, 4, 5], label="x")
y = ad.log10(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[log10(3), log10(4), log10(5)],
[
grad(lambda x: log10(x))(3.0),
grad(lambda x: log10(x))(4.0),
grad(lambda x: log10(x))(5.0),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([3, 4, 5], label="x")
y = ad.log10(x + x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[log10(3 * 2), log10(4 * 2), log10(5 * 2)],
[
grad(lambda x: log10(x + x))(3.0),
grad(lambda x: log10(x + x))(4.0),
grad(lambda x: log10(x + x))(5.0),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([3, 4, 5], label="x")
y = ad.Variable([6, 6, 6], label="y")
y = ad.log10(x + y)
ans_val, ans_der_x, ans_der_y = y.val, y.der["x"], y.der["y"]
sol_val, sol_der_x, sol_der_y = (
[log10(9), log10(10), log10(11)],
[
grad(lambda x, y: log10(x + y), 0)(3.0, 6.0),
grad(lambda x, y: log10(x + y), 0)(4.0, 6.0),
grad(lambda x, y: log10(x + y), 0)(5.0, 6.0),
],
[
grad(lambda x, y: log10(x + y), 1)(3.0, 6.0),
grad(lambda x, y: log10(x + y), 1)(4.0, 6.0),
grad(lambda x, y: log10(x + y), 1)(5.0, 6.0),
],
)
assert check_list(ans_val, sol_val)
assert check_list(sol_der_x, ans_der_x) & check_list(sol_der_y, ans_der_y)
def test_sin():
x = 0.3
ans = ad.sin(x)
sol = adnp.sin(x)
assert sol == ans
x = ad.Variable(0.3, label="x")
y = ad.sin(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.sin(0.3), grad(adnp.sin)(0.3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(0.3, label="x") + 0.3
y = ad.sin(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.sin(0.6), grad(lambda x: adnp.sin(x + 0.3))(0.3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(0.3, label="x") + ad.Variable(0.4, label="y")
y = ad.sin(x)
ans_val, ans_der = y.val, [y.der["x"], y.der["y"]]
sol_val, sol_der = (
adnp.sin(0.7),
[
grad(lambda x, y: adnp.sin(x + y), 0)(0.3, 0.4),
grad(lambda x, y: adnp.sin(x + y), 1)(0.3, 0.4),
],
)
assert ans_val == sol_val
assert check_list(ans_der, sol_der)
x = ad.Variable([0.3, 0.4, 0.5], label="x")
y = ad.sin(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[adnp.sin(0.3), adnp.sin(0.4), adnp.sin(0.5)],
[
grad(lambda x: adnp.sin(x))(0.3),
grad(lambda x: adnp.sin(x))(0.4),
grad(lambda x: adnp.sin(x))(0.5),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([0.3, 0.4, 0.5], label="x")
y = ad.sin(x + x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[adnp.sin(0.3 * 2), adnp.sin(0.4 * 2), adnp.sin(0.5 * 2)],
[
grad(lambda x: adnp.sin(x + x))(0.3),
grad(lambda x: adnp.sin(x + x))(0.4),
grad(lambda x: adnp.sin(x + x))(0.5),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([0.03, 0.04, 0.05], label="x")
y = ad.Variable([0.06, 0.06, 0.06], label="y")
y = ad.sin(x + y)
ans_val, ans_der_x, ans_der_y = y.val, y.der["x"], y.der["y"]
sol_val, sol_der_x, sol_der_y = (
[adnp.sin(0.09), adnp.sin(0.10), adnp.sin(0.11)],
[
grad(lambda x, y: adnp.sin(x + y), 0)(0.030, 0.060),
grad(lambda x, y: adnp.sin(x + y), 0)(0.040, 0.060),
grad(lambda x, y: adnp.sin(x + y), 0)(0.050, 0.060),
],
[
grad(lambda x, y: adnp.sin(x + y), 1)(0.030, 0.060),
grad(lambda x, y: adnp.sin(x + y), 1)(0.040, 0.060),
grad(lambda x, y: adnp.sin(x + y), 1)(0.050, 0.060),
],
)
assert check_list(ans_val, sol_val)
assert check_list(sol_der_x, ans_der_x) & check_list(sol_der_y, ans_der_y)
def test_arcsin():
x = 0.3
ans = ad.arcsin(x)
sol = adnp.arcsin(x)
assert sol == ans
x = ad.Variable(0.3, label="x")
y = ad.arcsin(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.arcsin(0.3), grad(adnp.arcsin)(0.3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(0.3, label="x") + 0.3
y = ad.arcsin(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.arcsin(0.6), grad(lambda x: adnp.arcsin(x + 0.3))(0.3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(0.3, label="x") + ad.Variable(0.4, label="y")
y = ad.arcsin(x)
ans_val, ans_der = y.val, [y.der["x"], y.der["y"]]
sol_val, sol_der = (
adnp.arcsin(0.7),
[
grad(lambda x, y: adnp.arcsin(x + y), 0)(0.3, 0.4),
grad(lambda x, y: adnp.arcsin(x + y), 1)(0.3, 0.4),
],
)
assert ans_val == sol_val
assert check_list(ans_der, sol_der)
x = ad.Variable([0.3, 0.4, 0.5], label="x")
y = ad.arcsin(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[adnp.arcsin(0.3), adnp.arcsin(0.4), adnp.arcsin(0.5)],
[
grad(lambda x: adnp.arcsin(x))(0.3),
grad(lambda x: adnp.arcsin(x))(0.4),
grad(lambda x: adnp.arcsin(x))(0.5),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([0.3, 0.4, 0.5], label="x")
y = ad.arcsin(x + x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[adnp.arcsin(0.3 * 2), adnp.arcsin(0.4 * 2), adnp.arcsin(0.5 * 2)],
[
grad(lambda x: adnp.arcsin(x + x))(0.3),
grad(lambda x: adnp.arcsin(x + x))(0.4),
grad(lambda x: adnp.arcsin(x + x))(0.5),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([0.03, 0.04, 0.05], label="x")
y = ad.Variable([0.06, 0.06, 0.06], label="y")
y = ad.arcsin(x + y)
ans_val, ans_der_x, ans_der_y = y.val, y.der["x"], y.der["y"]
sol_val, sol_der_x, sol_der_y = (
[adnp.arcsin(0.09), adnp.arcsin(0.10), adnp.arcsin(0.11)],
[
grad(lambda x, y: adnp.arcsin(x + y), 0)(0.030, 0.060),
grad(lambda x, y: adnp.arcsin(x + y), 0)(0.040, 0.060),
grad(lambda x, y: adnp.arcsin(x + y), 0)(0.050, 0.060),
],
[
grad(lambda x, y: adnp.arcsin(x + y), 1)(0.030, 0.060),
grad(lambda x, y: adnp.arcsin(x + y), 1)(0.040, 0.060),
grad(lambda x, y: adnp.arcsin(x + y), 1)(0.050, 0.060),
],
)
assert check_list(ans_val, sol_val)
assert check_list(sol_der_x, ans_der_x) & check_list(sol_der_y, ans_der_y)
x = ad.Variable(2, label="x")
with pytest.raises(Exception):
y = ad.arcsin(x)
def test_sinh():
x = 0.3
ans = ad.sinh(x)
sol = adnp.sinh(x)
assert sol == ans
x = ad.Variable(0.3, label="x")
y = ad.sinh(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.sinh(0.3), grad(adnp.sinh)(0.3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(0.3, label="x") + 0.3
y = ad.sinh(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.sinh(0.6), grad(lambda x: adnp.sinh(x + 0.3))(0.3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(0.3, label="x") + ad.Variable(0.4, label="y")
y = ad.sinh(x)
ans_val, ans_der = y.val, [y.der["x"], y.der["y"]]
sol_val, sol_der = (
adnp.sinh(0.7),
[
grad(lambda x, y: adnp.sinh(x + y), 0)(0.3, 0.4),
grad(lambda x, y: adnp.sinh(x + y), 1)(0.3, 0.4),
],
)
assert ans_val == sol_val
assert check_list(ans_der, sol_der)
x = ad.Variable([0.3, 0.4, 0.5], label="x")
y = ad.sinh(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[adnp.sinh(0.3), adnp.sinh(0.4), adnp.sinh(0.5)],
[
grad(lambda x: adnp.sinh(x))(0.3),
grad(lambda x: adnp.sinh(x))(0.4),
grad(lambda x: adnp.sinh(x))(0.5),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([0.3, 0.4, 0.5], label="x")
y = ad.sinh(x + x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[adnp.sinh(0.3 * 2), adnp.sinh(0.4 * 2), adnp.sinh(0.5 * 2)],
[
grad(lambda x: adnp.sinh(x + x))(0.3),
grad(lambda x: adnp.sinh(x + x))(0.4),
grad(lambda x: adnp.sinh(x + x))(0.5),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([0.03, 0.04, 0.05], label="x")
y = ad.Variable([0.06, 0.06, 0.06], label="y")
y = ad.sinh(x + y)
ans_val, ans_der_x, ans_der_y = y.val, y.der["x"], y.der["y"]
sol_val, sol_der_x, sol_der_y = (
[adnp.sinh(0.09), adnp.sinh(0.10), adnp.sinh(0.11)],
[
grad(lambda x, y: adnp.sinh(x + y), 0)(0.030, 0.060),
grad(lambda x, y: adnp.sinh(x + y), 0)(0.040, 0.060),
grad(lambda x, y: adnp.sinh(x + y), 0)(0.050, 0.060),
],
[
grad(lambda x, y: adnp.sinh(x + y), 1)(0.030, 0.060),
grad(lambda x, y: adnp.sinh(x + y), 1)(0.040, 0.060),
grad(lambda x, y: adnp.sinh(x + y), 1)(0.050, 0.060),
],
)
assert check_list(ans_val, sol_val)
assert check_list(sol_der_x, ans_der_x) & check_list(sol_der_y, ans_der_y)
def test_cos():
x = 0.3
ans = ad.cos(x)
sol = adnp.cos(x)
assert sol == ans
x = ad.Variable(0.3, label="x")
y = ad.cos(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.cos(0.3), grad(adnp.cos)(0.3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(0.3, label="x") + 0.3
y = ad.cos(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.cos(0.6), grad(lambda x: adnp.cos(x + 0.3))(0.3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(0.3, label="x") + ad.Variable(0.4, label="y")
y = ad.cos(x)
ans_val, ans_der = y.val, [y.der["x"], y.der["y"]]
sol_val, sol_der = (
adnp.cos(0.7),
[
grad(lambda x, y: adnp.cos(x + y), 0)(0.3, 0.4),
grad(lambda x, y: adnp.cos(x + y), 1)(0.3, 0.4),
],
)
assert ans_val == sol_val
assert check_list(ans_der, sol_der)
x = ad.Variable([0.3, 0.4, 0.5], label="x")
y = ad.cos(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[adnp.cos(0.3), adnp.cos(0.4), adnp.cos(0.5)],
[
grad(lambda x: adnp.cos(x))(0.3),
grad(lambda x: adnp.cos(x))(0.4),
grad(lambda x: adnp.cos(x))(0.5),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([0.3, 0.4, 0.5], label="x")
y = ad.cos(x + x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[adnp.cos(0.3 * 2), adnp.cos(0.4 * 2), adnp.cos(0.5 * 2)],
[
grad(lambda x: adnp.cos(x + x))(0.3),
grad(lambda x: adnp.cos(x + x))(0.4),
grad(lambda x: adnp.cos(x + x))(0.5),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([0.03, 0.04, 0.05], label="x")
y = ad.Variable([0.06, 0.06, 0.06], label="y")
y = ad.cos(x + y)
ans_val, ans_der_x, ans_der_y = y.val, y.der["x"], y.der["y"]
sol_val, sol_der_x, sol_der_y = (
[adnp.cos(0.09), adnp.cos(0.10), adnp.cos(0.11)],
[
grad(lambda x, y: adnp.cos(x + y), 0)(0.030, 0.060),
grad(lambda x, y: adnp.cos(x + y), 0)(0.040, 0.060),
grad(lambda x, y: adnp.cos(x + y), 0)(0.050, 0.060),
],
[
grad(lambda x, y: adnp.cos(x + y), 1)(0.030, 0.060),
grad(lambda x, y: adnp.cos(x + y), 1)(0.040, 0.060),
grad(lambda x, y: adnp.cos(x + y), 1)(0.050, 0.060),
],
)
assert check_list(ans_val, sol_val)
assert check_list(sol_der_x, ans_der_x) & check_list(sol_der_y, ans_der_y)
def test_arccos():
x = 0.3
ans = ad.arccos(x)
sol = adnp.arccos(x)
assert sol == ans
x = ad.Variable(0.3, label="x")
y = ad.arccos(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.arccos(0.3), grad(adnp.arccos)(0.3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(0.3, label="x") + 0.3
y = ad.arccos(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.arccos(0.6), grad(lambda x: adnp.arccos(x + 0.3))(0.3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(0.3, label="x") + ad.Variable(0.4, label="y")
y = ad.arccos(x)
ans_val, ans_der = y.val, [y.der["x"], y.der["y"]]
sol_val, sol_der = (
adnp.arccos(0.7),
[
grad(lambda x, y: adnp.arccos(x + y), 0)(0.3, 0.4),
grad(lambda x, y: adnp.arccos(x + y), 1)(0.3, 0.4),
],
)
assert ans_val == sol_val
assert check_list(ans_der, sol_der)
x = ad.Variable([0.3, 0.4, 0.5], label="x")
y = ad.arccos(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[adnp.arccos(0.3), adnp.arccos(0.4), adnp.arccos(0.5)],
[
grad(lambda x: adnp.arccos(x))(0.3),
grad(lambda x: adnp.arccos(x))(0.4),
grad(lambda x: adnp.arccos(x))(0.5),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([0.3, 0.4, 0.5], label="x")
y = ad.arccos(x + x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[adnp.arccos(0.3 * 2), adnp.arccos(0.4 * 2), adnp.arccos(0.5 * 2)],
[
grad(lambda x: adnp.arccos(x + x))(0.3),
grad(lambda x: adnp.arccos(x + x))(0.4),
grad(lambda x: adnp.arccos(x + x))(0.5),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([0.03, 0.04, 0.05], label="x")
y = ad.Variable([0.06, 0.06, 0.06], label="y")
y = ad.arccos(x + y)
ans_val, ans_der_x, ans_der_y = y.val, y.der["x"], y.der["y"]
sol_val, sol_der_x, sol_der_y = (
[adnp.arccos(0.09), adnp.arccos(0.10), adnp.arccos(0.11)],
[
grad(lambda x, y: adnp.arccos(x + y), 0)(0.030, 0.060),
grad(lambda x, y: adnp.arccos(x + y), 0)(0.040, 0.060),
grad(lambda x, y: adnp.arccos(x + y), 0)(0.050, 0.060),
],
[
grad(lambda x, y: adnp.arccos(x + y), 1)(0.030, 0.060),
grad(lambda x, y: adnp.arccos(x + y), 1)(0.040, 0.060),
grad(lambda x, y: adnp.arccos(x + y), 1)(0.050, 0.060),
],
)
assert check_list(ans_val, sol_val)
assert check_list(sol_der_x, ans_der_x) & check_list(sol_der_y, ans_der_y)
x = ad.Variable(2, label="x")
with pytest.raises(Exception):
y = ad.arccos(x)
def test_cosh():
x = 0.3
ans = ad.cosh(x)
sol = adnp.cosh(x)
assert sol == ans
x = ad.Variable(0.3, label="x")
y = ad.cosh(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.cosh(0.3), grad(adnp.cosh)(0.3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(0.3, label="x") + 0.3
y = ad.cosh(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.cosh(0.6), grad(lambda x: adnp.cosh(x + 0.3))(0.3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(0.3, label="x") + ad.Variable(0.4, label="y")
y = ad.cosh(x)
ans_val, ans_der = y.val, [y.der["x"], y.der["y"]]
sol_val, sol_der = (
adnp.cosh(0.7),
[
grad(lambda x, y: adnp.cosh(x + y), 0)(0.3, 0.4),
grad(lambda x, y: adnp.cosh(x + y), 1)(0.3, 0.4),
],
)
assert ans_val == sol_val
assert check_list(ans_der, sol_der)
x = ad.Variable([0.3, 0.4, 0.5], label="x")
y = ad.cosh(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[adnp.cosh(0.3), adnp.cosh(0.4), adnp.cosh(0.5)],
[
grad(lambda x: adnp.cosh(x))(0.3),
grad(lambda x: adnp.cosh(x))(0.4),
grad(lambda x: adnp.cosh(x))(0.5),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([0.3, 0.4, 0.5], label="x")
y = ad.cosh(x + x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[adnp.cosh(0.3 * 2), adnp.cosh(0.4 * 2), adnp.cosh(0.5 * 2)],
[
grad(lambda x: adnp.cosh(x + x))(0.3),
grad(lambda x: adnp.cosh(x + x))(0.4),
grad(lambda x: adnp.cosh(x + x))(0.5),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([0.03, 0.04, 0.05], label="x")
y = ad.Variable([0.06, 0.06, 0.06], label="y")
y = ad.cosh(x + y)
ans_val, ans_der_x, ans_der_y = y.val, y.der["x"], y.der["y"]
sol_val, sol_der_x, sol_der_y = (
[adnp.cosh(0.09), adnp.cosh(0.10), adnp.cosh(0.11)],
[
grad(lambda x, y: adnp.cosh(x + y), 0)(0.030, 0.060),
grad(lambda x, y: adnp.cosh(x + y), 0)(0.040, 0.060),
grad(lambda x, y: adnp.cosh(x + y), 0)(0.050, 0.060),
],
[
grad(lambda x, y: adnp.cosh(x + y), 1)(0.030, 0.060),
grad(lambda x, y: adnp.cosh(x + y), 1)(0.040, 0.060),
grad(lambda x, y: adnp.cosh(x + y), 1)(0.050, 0.060),
],
)
assert check_list(ans_val, sol_val)
assert check_list(sol_der_x, ans_der_x) & check_list(sol_der_y, ans_der_y)
def test_tan():
x = 0.3
ans = ad.tan(x)
sol = adnp.tan(x)
assert sol == ans
x = ad.Variable(0.3, label="x")
y = ad.tan(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.tan(0.3), grad(adnp.tan)(0.3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(0.3, label="x") + 0.3
y = ad.tan(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.tan(0.6), grad(lambda x: adnp.tan(x + 0.3))(0.3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(0.3, label="x") + ad.Variable(0.4, label="y")
y = ad.tan(x)
ans_val, ans_der = y.val, [y.der["x"], y.der["y"]]
sol_val, sol_der = (
adnp.tan(0.7),
[
grad(lambda x, y: adnp.tan(x + y), 0)(0.3, 0.4),
grad(lambda x, y: adnp.tan(x + y), 1)(0.3, 0.4),
],
)
assert ans_val == sol_val
assert check_list(ans_der, sol_der)
x = ad.Variable([0.3, 0.4, 0.5], label="x")
y = ad.tan(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[adnp.tan(0.3), adnp.tan(0.4), adnp.tan(0.5)],
[
grad(lambda x: adnp.tan(x))(0.3),
grad(lambda x: adnp.tan(x))(0.4),
grad(lambda x: adnp.tan(x))(0.5),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([0.3, 0.4, 0.5], label="x")
y = ad.tan(x + x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[adnp.tan(0.3 * 2), adnp.tan(0.4 * 2), adnp.tan(0.5 * 2)],
[
grad(lambda x: adnp.tan(x + x))(0.3),
grad(lambda x: adnp.tan(x + x))(0.4),
grad(lambda x: adnp.tan(x + x))(0.5),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([0.03, 0.04, 0.05], label="x")
y = ad.Variable([0.06, 0.06, 0.06], label="y")
y = ad.tan(x + y)
ans_val, ans_der_x, ans_der_y = y.val, y.der["x"], y.der["y"]
sol_val, sol_der_x, sol_der_y = (
[adnp.tan(0.09), adnp.tan(0.10), adnp.tan(0.11)],
[
grad(lambda x, y: adnp.tan(x + y), 0)(0.030, 0.060),
grad(lambda x, y: adnp.tan(x + y), 0)(0.040, 0.060),
grad(lambda x, y: adnp.tan(x + y), 0)(0.050, 0.060),
],
[
grad(lambda x, y: adnp.tan(x + y), 1)(0.030, 0.060),
grad(lambda x, y: adnp.tan(x + y), 1)(0.040, 0.060),
grad(lambda x, y: adnp.tan(x + y), 1)(0.050, 0.060),
],
)
assert check_list(ans_val, sol_val)
assert check_list(sol_der_x, ans_der_x) & check_list(sol_der_y, ans_der_y)
def test_arctan():
x = 0.3
ans = ad.arctan(x)
sol = adnp.arctan(x)
assert sol == ans
x = ad.Variable(0.3, label="x")
y = ad.arctan(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.arctan(0.3), grad(adnp.arctan)(0.3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(0.3, label="x") + 0.3
y = ad.arctan(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.arctan(0.6), grad(lambda x: adnp.arctan(x + 0.3))(0.3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(0.3, label="x") + ad.Variable(0.4, label="y")
y = ad.arctan(x)
ans_val, ans_der = y.val, [y.der["x"], y.der["y"]]
sol_val, sol_der = (
adnp.arctan(0.7),
[
grad(lambda x, y: adnp.arctan(x + y), 0)(0.3, 0.4),
grad(lambda x, y: adnp.arctan(x + y), 1)(0.3, 0.4),
],
)
assert ans_val == sol_val
assert check_list(ans_der, sol_der)
x = ad.Variable([0.3, 0.4, 0.5], label="x")
y = ad.arctan(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[adnp.arctan(0.3), adnp.arctan(0.4), adnp.arctan(0.5)],
[
grad(lambda x: adnp.arctan(x))(0.3),
grad(lambda x: adnp.arctan(x))(0.4),
grad(lambda x: adnp.arctan(x))(0.5),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([0.3, 0.4, 0.5], label="x")
y = ad.arctan(x + x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[adnp.arctan(0.3 * 2), adnp.arctan(0.4 * 2), adnp.arctan(0.5 * 2)],
[
grad(lambda x: adnp.arctan(x + x))(0.3),
grad(lambda x: adnp.arctan(x + x))(0.4),
grad(lambda x: adnp.arctan(x + x))(0.5),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([0.03, 0.04, 0.05], label="x")
y = ad.Variable([0.06, 0.06, 0.06], label="y")
y = ad.arctan(x + y)
ans_val, ans_der_x, ans_der_y = y.val, y.der["x"], y.der["y"]
sol_val, sol_der_x, sol_der_y = (
[adnp.arctan(0.09), adnp.arctan(0.10), adnp.arctan(0.11)],
[
grad(lambda x, y: adnp.arctan(x + y), 0)(0.030, 0.060),
grad(lambda x, y: adnp.arctan(x + y), 0)(0.040, 0.060),
grad(lambda x, y: adnp.arctan(x + y), 0)(0.050, 0.060),
],
[
grad(lambda x, y: adnp.arctan(x + y), 1)(0.030, 0.060),
grad(lambda x, y: adnp.arctan(x + y), 1)(0.040, 0.060),
grad(lambda x, y: adnp.arctan(x + y), 1)(0.050, 0.060),
],
)
assert check_list(ans_val, sol_val)
assert check_list(sol_der_x, ans_der_x) & check_list(sol_der_y, ans_der_y)
def test_tanh():
x = 0.3
ans = ad.tanh(x)
sol = adnp.tanh(x)
assert sol == ans
x = ad.Variable(0.3, label="x")
y = ad.tanh(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.tanh(0.3), grad(adnp.tanh)(0.3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(0.3, label="x") + 0.3
y = ad.tanh(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = adnp.tanh(0.6), grad(lambda x: adnp.tanh(x + 0.3))(0.3)
assert ans_val == sol_val
assert math.isclose(ans_der, sol_der)
x = ad.Variable(0.3, label="x") + ad.Variable(0.4, label="y")
y = ad.tanh(x)
ans_val, ans_der = y.val, [y.der["x"], y.der["y"]]
sol_val, sol_der = (
adnp.tanh(0.7),
[
grad(lambda x, y: adnp.tanh(x + y), 0)(0.3, 0.4),
grad(lambda x, y: adnp.tanh(x + y), 1)(0.3, 0.4),
],
)
assert ans_val == sol_val
assert check_list(ans_der, sol_der)
x = ad.Variable([0.3, 0.4, 0.5], label="x")
y = ad.tanh(x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[adnp.tanh(0.3), adnp.tanh(0.4), adnp.tanh(0.5)],
[
grad(lambda x: adnp.tanh(x))(0.3),
grad(lambda x: adnp.tanh(x))(0.4),
grad(lambda x: adnp.tanh(x))(0.5),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([0.3, 0.4, 0.5], label="x")
y = ad.tanh(x + x)
ans_val, ans_der = y.val, y.der["x"]
sol_val, sol_der = (
[adnp.tanh(0.3 * 2), adnp.tanh(0.4 * 2), adnp.tanh(0.5 * 2)],
[
grad(lambda x: adnp.tanh(x + x))(0.3),
grad(lambda x: adnp.tanh(x + x))(0.4),
grad(lambda x: adnp.tanh(x + x))(0.5),
],
)
assert check_list(ans_val, sol_val)
assert check_list(ans_der, sol_der)
x = ad.Variable([0.03, 0.04, 0.05], label="x")
y = ad.Variable([0.06, 0.06, 0.06], label="y")
y = ad.tanh(x + y)
ans_val, ans_der_x, ans_der_y = y.val, y.der["x"], y.der["y"]
sol_val, sol_der_x, sol_der_y = (
[adnp.tanh(0.09), adnp.tanh(0.10), adnp.tanh(0.11)],
[
grad(lambda x, y: adnp.tanh(x + y), 0)(0.030, 0.060),
grad(lambda x, y: adnp.tanh(x + y), 0)(0.040, 0.060),
grad(lambda x, y: adnp.tanh(x + y), 0)(0.050, 0.060),
],
[
grad(lambda x, y: adnp.tanh(x + y), 1)(0.030, 0.060),
grad(lambda x, y: adnp.tanh(x + y), 1)(0.040, 0.060),
grad(lambda x, y: adnp.tanh(x + y), 1)(0.050, 0.060),
],
)
assert check_list(ans_val, sol_val)
assert check_list(sol_der_x, ans_der_x) & check_list(sol_der_y, ans_der_y)
def test_neg():
x = ad.Variable(3, label="x")
y = -x
assert y.val == -3
assert y.der == {"x": -1}
x = ad.Variable(3, label="x", der={"x": 2})
y = -x
assert y.val == -3
assert y.der == {"x": -2}
x = ad.Variable(np.arange(3), label="x")
y = -x
assert np.all(y.val == [0, -1, -2])
assert y.der == {"x": [-1, -1, -1]}
x = ad.Variable(0, label="x")
y = ad.Variable(3, label="y")
z = x + 2 * y
z2 = -z
assert z2.val == -6
assert z2.der == {"x": -1, "y": -2}
x = ad.Variable(np.arange(3), label="x")
y = ad.Variable(3 + np.arange(3), label="y")
z = x + 2 * y
z2 = -z
assert np.all(z2.val == [-6, -9, -12])
assert z2.der == {"x": [-1, -1, -1], "y": [-2, -2, -2]}
def test_pow():
x = ad.Variable(3, label="x")
z = x ** 2
assert z.val == 9
assert z.der == {"x": 6}
x = ad.Variable(0, label="x")
z = x ** 2
assert z.val == 0
assert z.der == {"x": 0}
x = ad.Variable([3, 2], label="x")
z = x ** 2
assert np.all(z.val == [9, 4])
assert np.all(z.der == {"x": [6, 4]})
x = ad.Variable(3, label="x")
y = ad.Variable(2, label="y")
z = x ** y
assert z.val == 9
assert z.der == {"x": 6, "y": 9 * np.log(3)}
x = ad.Variable([3, 2], label="x")
y = ad.Variable([2, 3], label="y")
z = x ** y
assert np.all(z.val == [9, 8])
assert (
compare_dicts_multi(z.der, {"x": [6, 12], "y": [9 * np.log(3), 8 * np.log(2)]})
== True
)
x = ad.Variable([np.e - 1, np.e - 1], label="x")
y = ad.Variable([1, 1], label="y")
z = x + y
z2 = z ** y
assert np.all(z2.val == [np.e, np.e])
assert compare_dicts_multi(z2.der, {"x": [1, 1], "y": [np.e + 1, np.e + 1]}) == True
x = ad.Variable([0, 0], label="x")
y = ad.Variable([1, 2], label="y")
z = x ** y
assert np.all(z.val == [0, 0])
assert compare_dicts_multi(z.der, {"x": [1, 0], "y": [0, 0]}) == True
def test_rpow():
x = ad.Variable(1, label="x")
z = np.e ** x
assert z.val == np.e
assert z.der == {"x": np.e}
x = ad.Variable(1, label="x")
z = 0 ** x
assert z.val == 0
assert z.der == {"x": 0}
x = ad.Variable([1, 2], label="x")
z = np.e ** x
assert np.all(z.val == [np.e, np.e ** 2])
assert np.all(z.der == {"x": [np.e, np.e ** 2]})
x = ad.Variable(2, label="x")
y = ad.Variable(-1, label="y")
z = np.e ** (x + 2 * y)
assert z.val == 1
assert z.der == {"x": 1, "y": 2}
x = ad.Variable([2, -2], label="x")
y = ad.Variable([-1, 1], label="y")
z = np.e ** (x + 2 * y)
assert np.all(z.val == [1, 1])
assert np.all(z.der == {"x": [1, 1], "y": [2, 2]})
def test_ne():
x = ad.Variable(1, label="x")
y = ad.Variable(1, label="y")
assert (x != x) == False
assert (x != y) == True
z1 = ad.Variable([1, 2], der={"x": [1, 2], "y": [1, 2]}, label="z1")
z2 = ad.Variable([1, 2], der={"x": [1, 2], "y": [1, 2]}, label="z2")
assert (z1 != z2) == False
z1 = ad.Variable(1, der={"x": 2, "y": 3}, label="z1")
z2 = ad.Variable(1, der={"x": 2, "y": 3}, label="z2")
assert (z1 != z2) == False
z1 = ad.Variable([1, 2], der={"x": [1, 2], "y": [1, 2]}, label="z1")
z2 = ad.Variable([1, 2], der={"x": [1, 2], "y": [1, 3]}, label="z2")
assert (z1 != z2) == True
x = ad.Variable(1, label="x")
y = ad.Variable(1, label="y")
z1 = ad.exp(x) + np.e * y
z2 = ad.exp(y) + np.e * x
assert (z1 != z2) == False
x = ad.Variable([1, 2, 3], label="x")
y = ad.Variable([2, 3], label="y")
assert (x != y) == True
z = 1
assert (x != z) == True
def test_lt():
x = ad.Variable(1, label="x")
y = ad.Variable(2, label="y")
assert (x < y) == True
x = ad.Variable([1, 2], label="x")
y = ad.Variable([2, 2], label="y")
assert np.all((x < y) == [True, False])
x = ad.Variable([1, 1, 1], label="x")
y = ad.Variable([2, 2], label="y")
with pytest.raises(Exception):
print(x < y)
def test_le():
x = ad.Variable(1, label="x")
y = ad.Variable(2, label="y")
assert (x <= y) == True
x = ad.Variable([1, 2], label="x")
y = ad.Variable([2, 2], label="y")
assert np.all((x <= y) == [True, True])
x = ad.Variable([1, 1, 1], label="x")
y = ad.Variable([2, 2], label="y")
with pytest.raises(Exception):
print(x <= y)
def test_gt():
x = ad.Variable(3, label="x")
y = ad.Variable(2, label="y")
assert (x > y) == True
x = ad.Variable([3, 2], label="x")
y = ad.Variable([2, 2], label="y")
assert np.all((x > y) == [True, False])
x = ad.Variable([1, 1, 1], label="x")
y = ad.Variable([2, 2], label="y")
with pytest.raises(Exception):
print(x > y)
def test_ge():
x = ad.Variable(3, label="x")
y = ad.Variable(2, label="y")
assert (x >= y) == True
x = ad.Variable([3, 2], label="x")
y = ad.Variable([2, 2], label="y")
assert np.all((x >= y) == [True, True])
x = ad.Variable([1, 1, 1], label="x")
y = ad.Variable([2, 2], label="y")
with pytest.raises(Exception):
print(x >= y)
def test_complicated_functions():
## Function 1
## sin(x) + cos(x) * 3*y - x^4 + ln(x*y)
x = np.random.rand(5, 4)
x_var = ad.Variable(x, label="x")
y = np.random.rand(5, 4)
y_var = ad.Variable(y, label="y")
f_ad = ad.sin(x_var) + ad.cos(x_var) * 3 * y_var - x_var ** 4 + ad.ln(x_var * y_var)
f_ad_val = f_ad.val
f_ad_grad = f_ad.der
f_np_val = np.sin(x) + np.cos(x) * 3 * y - x ** 4 + np.log(x * y)
dx = -4 * x ** 3 - 3 * y * np.sin(x) + 1 / x + np.cos(x)
dy = 3 * np.cos(x) + 1 / y
assert np.array_equal(f_ad_val, f_np_val)
assert np.array_equal(np.around(f_ad_grad["x"], 4), np.around(dx, 4))
assert np.array_equal(np.around(f_ad_grad["y"], 4), np.around(dy, 4))
## Function 2
## cos(x*y^2) + exp(x*y*3x)
x = np.random.rand(3, 8)
x_var = ad.Variable(x, label="x")
y = np.random.rand(3, 8)
y_var = ad.Variable(y, label="y")
f_ad = ad.cos(x_var * y_var ** 2) + ad.exp(x_var * y_var * 3 * x_var)
f_ad_val = f_ad.val
f_ad_grad = f_ad.der
f_np_val = np.cos(x * y ** 2) + np.exp(x * y * 3 * x)
dx = y * (6 * x * np.exp(3 * x ** 2 * y) - y * np.sin(x * y ** 2))
dy = x * (3 * x * | np.exp(3 * x ** 2 * y) | numpy.exp |
# 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])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, 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,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(221, 'P m -3 m', transformations)
space_groups[221] = sg
space_groups['P m -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,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([0,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([0,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,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([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,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([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([0,0,1,0,-1,0,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,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,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,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,0,1,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([-1,0,0,0,0,-1,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,0,-1,0,-1,0,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([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([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,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([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([0,0,-1,0,1,0,-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,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,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,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(222, 'P n -3 n :2', transformations)
space_groups[222] = sg
space_groups['P n -3 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,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))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([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(223, 'P m -3 n', transformations)
space_groups[223] = sg
space_groups['P m -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,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,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([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([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,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([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([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([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,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,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([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,-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,-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([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([-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,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([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([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([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,-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,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(224, 'P n -3 m :2', transformations)
space_groups[224] = sg
space_groups['P n -3 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,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,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([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,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))
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(225, 'F m -3 m', transformations)
space_groups[225] = sg
space_groups['F m -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,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,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([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,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([0,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([0,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([0,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([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([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([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,0,-1,0,1,0,-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([0,0,1,0,1,0,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,0,-1,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([1,0,0,0,0,1,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([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))
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([0,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([0,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([0,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([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([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([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,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([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([0,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([0,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([0,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([0,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([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(226, 'F m -3 c', transformations)
space_groups[226] = sg
space_groups['F m -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,0,1])
trans_den = N.array([4,1,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,0])
trans_den = N.array([4,4,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([4,4,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,1,1])
trans_den = N.array([1,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([0,1,1])
trans_den = N.array([1,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,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([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([0,1,0,1,0,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([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([1,0,1])
trans_den = N.array([4,1,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([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,1,1])
trans_den = N.array([1,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([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([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,-1])
trans_den = N.array([4,1,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,0])
trans_den = N.array([4,4,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([4,4,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,-1,-1])
trans_den = N.array([1,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([0,-1,-1])
trans_den = N.array([1,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,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([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([0,-1,0,-1,0,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([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([-1,0,-1])
trans_den = N.array([4,1,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([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,-1,-1])
trans_den = N.array([1,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([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_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,3])
trans_den = N.array([4,2,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,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,3,1])
trans_den = N.array([4,4,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,3,3])
trans_den = N.array([1,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([0,3,3])
trans_den = N.array([1,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,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([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([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,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([1,1,3])
trans_den = N.array([4,2,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([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,3,3])
trans_den = N.array([1,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([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,0,1,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([-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,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([4,4,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,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([0,1,1])
trans_den = N.array([1,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,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([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([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,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([-1,1,1])
trans_den = N.array([4,2,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([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,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([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([3,0,3])
trans_den = N.array([4,1,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,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([3,1,1])
trans_den = N.array([4,4,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,3])
trans_den = N.array([2,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([2,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,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([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([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,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([3,0,3])
trans_den = N.array([4,1,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,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,1,3])
trans_den = N.array([2,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,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,0,1,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([-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,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([4,4,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,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([2,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,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,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([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,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([4,1,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,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,-1,1])
trans_den = N.array([2,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,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([3,1,1])
trans_den = N.array([4,2,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,0])
trans_den = N.array([4,4,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([3,3,0])
trans_den = N.array([4,4,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,3,1])
trans_den = N.array([2,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([2,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,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([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([0,1,0,1,0,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([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([3,1,1])
trans_den = N.array([4,2,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,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,3,1])
trans_den = N.array([2,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,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,0,1,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([-1,0,0,0,0,-1,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,0,-1,0,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,0,-1,0,-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([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,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,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([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))
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([4,4,1])
transformations.append((rot, trans_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,-1])
trans_den = N.array([4,2,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,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,-1])
trans_den = N.array([2,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,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(227, 'F d -3 m :2', transformations)
space_groups[227] = sg
space_groups['F d -3 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,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([4,1,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,0])
trans_den = N.array([4,4,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,3,0])
trans_den = N.array([4,4,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,1,3])
trans_den = N.array([1,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([0,1,3])
trans_den = N.array([1,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,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([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([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_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,3])
trans_den = N.array([4,1,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,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([0,1,3])
trans_den = N.array([1,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,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,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-3])
trans_den = N.array([4,1,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,0])
trans_den = N.array([4,4,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,-3,0])
trans_den = N.array([4,4,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,-1,-3])
trans_den = N.array([1,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([0,-1,-3])
trans_den = N.array([1,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,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([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([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_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,-3])
trans_den = N.array([4,1,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,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([0,-1,-3])
trans_den = N.array([1,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,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,5])
trans_den = N.array([4,2,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,5,1])
trans_den = N.array([4,4,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,5,1])
trans_den = N.array([4,4,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,3,5])
trans_den = N.array([1,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([0,3,5])
trans_den = N.array([1,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,5])
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([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]) | numpy.array |
# -*- coding: utf-8 -*-
"""
pyDIS: A simple one dimensional spectra reduction and analysis package
Created with the Apache Point Observatory (APO) 3.5-m telescope's
Dual Imaging Spectrograph (DIS) in mind. YMMV
e.g. DIS specifics:
- have BLUE/RED channels
- hand-code in that the RED channel wavelength is backwards
- dispersion along the X, spatial along the Y axis
"""
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.widgets import Cursor
import os
import numpy as np
from astropy.io import fits
from astropy.convolution import convolve, Box1DKernel
from scipy.optimize import curve_fit
import scipy.signal
from scipy.interpolate import UnivariateSpline
from scipy.interpolate import SmoothBivariateSpline
import warnings
# import datetime
# from matplotlib.widgets import SpanSelector
__all__ = ['OpenImg', 'ap_trace', 'ap_extract', 'HeNeAr_fit', 'mapwavelength',
'biascombine', 'flatcombine', 'line_trace', 'find_peaks',
'lines_to_surface', 'normalize', 'DefFluxCal', 'ApplyFluxCal',
'AirmassCor']
def _mag2flux(wave, mag, zeropt=48.60):
'''
Convert magnitudes to flux units. This is important for dealing with standards
and files from IRAF, which are stored in AB mag units. To be clear, this converts
to "PHOTFLAM" units in IRAF-speak. Assumes the common flux zeropoint used in IRAF
Parameters
----------
wave : 1d numpy array
The wavelength of the data points
mag : 1d numpy array
The magnitudes of the data
zeropt : float, optional
Conversion factor for mag->flux. (Default is 48.60)
Returns
-------
Flux values!
'''
c = 2.99792458e18 # speed of light, in A/s
flux = 10.0**( (mag + zeropt) / (-2.5) )
return flux * (c / wave**2.0)
def _gaus(x, a, b, x0, sigma):
"""
Simple Gaussian function, for internal use only
Parameters
----------
x : float or 1-d numpy array
The data to evaluate the Gaussian over
a : float
the amplitude
b : float
the constant offset
x0 : float
the center of the Gaussian
sigma : float
the width of the Gaussian
Returns
-------
Array or float of same type as input (x).
"""
return a * np.exp(-(x - x0)**2 / (2 * sigma**2)) + b
def _WriteSpec(spec, wfinal, ffinal, efinal, trace):
# write file with the trace (y positions)
tout = open(spec+'.trace','w')
tout.write('# This file contains the x,y coordinates of the trace \n')
for k in range(len(trace)):
tout.write(str(k)+', '+str(trace[k]) + '\n')
tout.close()
# write the final spectrum out
fout = open(spec+'.spec','w')
fout.write('# This file contains the final extracted (wavelength,flux,err) data \n')
for k in range(len(wfinal)):
fout.write(str(wfinal[k]) + ' ' + str(ffinal[k]) + ' ' + str(efinal[k]) + '\n')
fout.close()
return
def _CheckMono(wave):
'''
Check if the wavelength array is monotonically increasing. Return a
warning if not. NOTE: because RED/BLUE wavelength direction is flipped
it has to check both increasing and decreasing. It must satisfy one!
Method adopted from here:
http://stackoverflow.com/a/4983359/4842871
'''
# increasing
up = all(x<y for x, y in zip(wave, wave[1:]))
# decreasing
dn = all(x>y for x, y in zip(wave, wave[1:]))
if (up is False) and (dn is False):
print("WARNING: Wavelength array is not monotonically increasing!")
return
class OpenImg(object):
"""
A simple wrapper for astropy.io.fits (pyfits) to open and extract
the data we want from images and headers.
Parameters
----------
file : string
The path to the image to open
trim : bool, optional
Trim the image using the DATASEC keyword in the header, assuming
has format of [0:1024,0:512] (Default is True)
Returns
-------
image object
"""
def __init__(self, file, trim=True):
self.file = file
self.trim = trim
hdu = fits.open(file)
if trim is True:
self.datasec = hdu[0].header['DATASEC'][1:-1].replace(':',',').split(',')
d = list(map(int, self.datasec))
self.data = hdu[0].data[d[2]-1:d[3],d[0]-1:d[1]]
else:
self.data = hdu[0].data
if 'AIRMASS' in hdu[0].header:
self.airmass = hdu[0].header['AIRMASS']
elif 'ZD' in hdu[0].header:
# try using the Zenith Distance (assume in degrees)
ZD = hdu[0].header['ZD'] / 180.0 * np.pi
self.airmass = 1.0/np.cos(ZD) # approximate airmass
else:
self.airmass = 1.0
# compute the approximate wavelength solution
try:
self.disp_approx = hdu[0].header['DISPDW']
self.wcen_approx = hdu[0].header['DISPWC']
# the red chip wavelength is backwards (DIS specific)
clr = hdu[0].header['DETECTOR']
if (clr.lower()=='red'):
sign = -1.0
else:
sign = 1.0
self.wavelength = (np.arange(self.data.shape[1]) -
(self.data.shape[1])/2.0) * \
self.disp_approx * sign + self.wcen_approx
except KeyError:
# if these keywords aren't in the header, just return pixel #
self.wavelength = np.arange(self.data.shape[1])
self.exptime = hdu[0].header['EXPTIME']
hdu.close(closed=True)
# return raw, exptime, airmass, wapprox
def biascombine(biaslist, output='BIAS.fits', trim=True, silent=True):
"""
Combine the bias frames in to a master bias image. Currently only
supports median combine.
Parameters
----------
biaslist : str
Path to file containing list of bias images.
output: str, optional
Name of the master bias image to write. (Default is "BIAS.fits")
trim : bool, optional
Trim the image using the DATASEC keyword in the header, assuming
has format of [0:1024,0:512] (Default is True)
silent : bool, optional
If False, print details about the biascombine. (Default is True)
Returns
-------
bias : 2-d array
The median combined master bias image
"""
# assume biaslist is a simple text file with image names
# e.g. ls flat.00*b.fits > bflat.lis
files = np.genfromtxt(biaslist,dtype=np.str)
if silent is False:
print('biascombine: combining ' + str(len(files)) + ' files in ' + biaslist)
for i in range(0,len(files)):
hdu_i = fits.open(files[i])
if trim is False:
im_i = hdu_i[0].data
if trim is True:
datasec = hdu_i[0].header['DATASEC'][1:-1].replace(':',',').split(',')
d = list(map(int, datasec))
im_i = hdu_i[0].data[d[2]-1:d[3],d[0]-1:d[1]]
# create image stack
if (i==0):
all_data = im_i
elif (i>0):
all_data = np.dstack( (all_data, im_i) )
hdu_i.close(closed=True)
# do median across whole stack
bias = np.nanmedian(all_data, axis=2)
# write output to disk for later use
hduOut = fits.PrimaryHDU(bias)
hduOut.writeto(output, overwrite=True)
return bias
def overscanbias(img, cols=(1,), rows=(1,)):
'''
Generate a bias frame based on overscan region.
Can work with rows or columns, pass either kwarg the limits:
>>> bias = overscanbias(imagedata, cols=(1024,1050)) # doctest: +SKIP
'''
bias = np.zeros_like(img)
if len(cols) > 1:
bcol = np.nanmean(img[:, cols[0]:cols[1]], axis=0)
for j in range(img.shape()[1]):
img[j,:] = bcol
elif len(rows) > 1:
brow = np.nanmean(img[rows[0]:rows[1], :], axis=1)
for j in range(img.shape()[0]):
img[j,:] = brow
else:
print('OVERSCANBIAS ERROR: need to pass either cols=(a,b) or rows=(a,b),')
print('setting bias = zero as result!')
return bias
def smooth(y, box_pts):
box = np.ones(box_pts)/box_pts
y_smooth = np.convolve(y, box, mode='same')
return y_smooth
def flatcombine(flatlist, bias, output='FLAT.fits', trim=True, mode='spline',
display=True, flat_poly=5, response=True, Saxis=1):
"""
Combine the flat frames in to a master flat image. Subtracts the
master bias image first from each flat image. Currently only
supports median combining the images.
Parameters
----------
flatlist : str
Path to file containing list of flat images.
bias : str or 2-d array
Either the path to the master bias image (str) or
the output from 2-d array output from biascombine
output : str, optional
Name of the master flat image to write. (Default is "FLAT.fits")
response : bool, optional
If set to True, first combines the median image stack along the
spatial (Y) direction, then fits polynomial to 1D curve, then
divides each row in flat by this structure. This nominally divides
out the spectrum of the flat field lamp. (Default is True)
trim : bool, optional
Trim the image using the DATASEC keyword in the header, assuming
has format of [0:1024,0:512] (Default is True)
display : bool, optional
Set to True to show 1d flat, and final flat (Default is False)
flat_poly : int, optional
Polynomial order to fit 1d flat curve with. Only used if
response is set to True. (Default is 5)
Saxis : int, optional
Set which axis the spatial dimension is along. 1 = Y axis, 0 = X.
(Default is 1)
Returns
-------
flat : 2-d array
The median combined master flat
"""
# read the bias in, BUT we don't know if it's the numpy array or file name
if isinstance(bias, str):
# read in file if a string
bias_im = fits.open(bias)[0].data
else:
# assume is proper array from biascombine function
bias_im = bias
# assume flatlist is a simple text file with image names
# e.g. ls flat.00*b.fits > bflat.lis
files = np.genfromtxt(flatlist,dtype=np.str)
for i in range(0,len(files)):
hdu_i = fits.open(files[i])
if trim is False:
im_i = hdu_i[0].data - bias_im
if trim is True:
datasec = hdu_i[0].header['DATASEC'][1:-1].replace(':',',').split(',')
d = list(map(int, datasec))
im_i = hdu_i[0].data[d[2]-1:d[3],d[0]-1:d[1]] - bias_im
# check for bad regions (not illuminated) in the spatial direction
ycomp = im_i.sum(axis=Saxis) # compress to spatial axis only
illum_thresh = 0.8 # value compressed data must reach to be used for flat normalization
ok = np.where( (ycomp>= np.nanmedian(ycomp)*illum_thresh) )
# assume a median scaling for each flat to account for possible different exposure times
if (i==0):
all_data = im_i / np.nanmedian(im_i[ok,:])
elif (i>0):
all_data = np.dstack( (all_data, im_i / np.nanmedian(im_i[ok,:])) )
hdu_i.close(closed=True)
# do median across whole stack of flat images
flat_stack = np.nanmedian(all_data, axis=2)
# print(flat_stack.shape)
# print(flat_stack[ok,:].shape)
# print(ok)
if display:
plt.figure()
plt.imshow(flat_stack)
plt.show()
# define the wavelength axis
Waxis = 0
# add a switch in case the spatial/wavelength axis is swapped
if Saxis is 0:
Waxis = 1
if response is True:
xdata = np.arange(all_data.shape[1]) # x pixels
# sum along spatial axis, smooth w/ 5pixel boxcar, take log of summed flux
flat_1d = np.log10(smooth(flat_stack[ok[0],:].mean(axis=Waxis), 5))
if mode=='spline':
spl = UnivariateSpline(xdata, flat_1d, ext=0, k=2 ,s=0.001)
flat_curve = 10.0**spl(xdata)
elif mode=='poly':
# fit log flux with polynomial
flat_fit = np.polyfit(xdata, flat_1d, flat_poly)
# get rid of log
flat_curve = 10.0**np.polyval(flat_fit, xdata)
if display is True:
plt.figure()
plt.plot(10.0**flat_1d)
plt.plot(xdata, flat_curve,'r')
plt.show()
# divide median stacked flat by this RESPONSE curve
flat = np.zeros_like(flat_stack)
if Saxis is 1:
for i in range(flat_stack.shape[Waxis]):
flat[i,:] = flat_stack[i,:] / flat_curve
else:
for i in range(flat_stack.shape[Waxis]):
flat[:,i] = flat_stack[:,i] / flat_curve
else:
flat = flat_stack
if display is True:
plt.figure()
plt.imshow(flat, origin='lower',aspect='auto')
plt.show()
# write output to disk for later use
hduOut = fits.PrimaryHDU(flat)
hduOut.writeto(output, overwrite=True)
return flat ,ok[0]
def ap_trace(img, fmask=(1,), nsteps=20, interac=False,
recenter=False, prevtrace=(0,), bigbox=15,
Saxis=1, display=False, peak_guess = None, plot_ind = False):
"""
Trace the spectrum aperture in an image
Assumes wavelength axis is along the X, spatial axis along the Y.
Chops image up in bins along the wavelength direction, fits a Gaussian
within each bin to determine the spatial center of the trace. Finally,
draws a cubic spline through the bins to up-sample the trace.
Parameters
----------
img : 2d numpy array
This is the image, stored as a normal numpy array. Can be read in
using astropy.io.fits like so:
>>> hdu = fits.open('file.fits') # doctest: +SKIP
>>> img = hdu[0].data # doctest: +SKIP
nsteps : int, optional
Keyword, number of bins in X direction to chop image into. Use
fewer bins if ap_trace is having difficulty, such as with faint
targets (default is 50, minimum is 4)
fmask : array-like, optional
A list of illuminated rows in the spatial direction (Y), as
returned by flatcombine.
interac : bool, optional
Set to True to have user click on the y-coord peak. (Default is
False)
recenter : bool, optional
Set to True to use previous trace, but allow small shift in
position. Currently only allows linear shift (Default is False)
bigbox : float, optional
The number of sigma away from the main aperture to allow to trace
display : bool, optional
If set to true display the trace over-plotted on the image
Saxis : int, optional
Set which axis the spatial dimension is along. 1 = Y axis, 0 = X.
(Default is 1)
Returns
-------
my : array
The spatial (Y) positions of the trace, interpolated over the
entire wavelength (X) axis
"""
# define the wavelength axis
Waxis = 0
# add a switch in case the spatial/wavelength axis is swapped
if Saxis is 0:
Waxis = 1
print('Tracing Aperture using nsteps='+str(nsteps))
# the valid y-range of the chip
if (len(fmask)>1):
ydata = np.arange(img.shape[Waxis])[fmask]
else:
ydata = np.arange(img.shape[Waxis])
# need at least 4 samples along the trace. sometimes can get away with very few
if (nsteps<4):
nsteps = 4
# median smooth to crudely remove cosmic rays
img_sm = scipy.signal.medfilt2d(img, kernel_size=(5,5))
#--- Pick the strongest source, good if only 1 obj on slit
ztot = img_sm.sum(axis=Saxis)[ydata]
yi = np.arange(img.shape[Waxis])[ydata]
peak_y = yi[np.nanargmax(ztot)]
if peak_guess is None:
peak_guess = [np.nanmax(ztot), np.nanmedian(ztot), peak_y, 2.]
else:
peak_guess = [ztot[peak_guess], np.nanmedian(ztot), peak_guess, 2.] # IF user supplies peak guess.
#-- allow interactive mode, if mult obj on slit
if interac is True and recenter is False:
class InteracTrace(object):
def __init__(self):
self.fig = plt.figure()
self.ax = self.fig.add_subplot(111)
self.ax.plot(yi, ztot)
plt.ylabel('Counts (Image summed in X direction)')
plt.xlabel('Y Pixel')
plt.title('Click on object!')
self.cursor = Cursor(self.ax, useblit=False, horizOn=False,
color='red', linewidth=1 )
self.connect = self.fig.canvas.mpl_connect
self.disconnect = self.fig.canvas.mpl_disconnect
self.ClickID = self.connect('button_press_event', self.__onclick__)
return
def __onclick__(self,click):
if self.fig.canvas.manager.toolbar._active is None:
self.xpoint = click.xdata
self.ypoint = click.ydata
self.disconnect(self.ClickID) # disconnect from event
self.cursor.disconnect_events()
self.cursor._update()
plt.close() # close window when clicked
return self.xpoint, self.ypoint
else:
pass
theclick = InteracTrace()
plt.show()
xcl = theclick.xpoint
# ycl = theclick.ypoint
peak_guess[2] = xcl
#-- use middle of previous trace as starting guess
if (recenter is True) and (len(prevtrace)>10):
peak_guess[2] = np.nanmedian(prevtrace)
#-- fit a Gaussian to peak
popt_tot, pcov = curve_fit(_gaus, yi[np.isfinite(ztot)], ztot[np.isfinite(ztot)], p0=peak_guess)
ydata2 = ydata
ztot = img_sm.sum(axis=Saxis)[ydata2]
yi = np.arange(img.shape[Waxis])[ydata2]
# define the X-bin edges
xbins = np.linspace(0, img.shape[Saxis], nsteps, dtype='int')
ybins = np.zeros_like(xbins, dtype='int')
for i in range(0,len(xbins)-1):
#-- fit gaussian w/i each window
if Saxis is 1:
zi = np.sum(img_sm[ydata2, xbins[i]:xbins[i+1]], axis=Saxis)
else:
zi = img_sm[xbins[i]:xbins[i+1], ydata2].sum(axis=Saxis)
zifilt = scipy.signal.medfilt(zi, 3) # remove random noise when fitting trace
pguess = [np.nanmax(zi), np.nanmedian(zi), yi[np.nanargmax(zifilt)], 3.]
print(pguess)
popt,pcov = curve_fit(_gaus, yi[np.isfinite(ztot)], zi[np.isfinite(ztot)], p0=pguess, maxfev = 10000)
if plot_ind:
plt.figure()
plt.plot(yi[np.isfinite(ztot)], zi[np.isfinite(ztot)])
plt.plot(yi[np.isfinite(ztot)], _gaus(yi[np.isfinite(ztot)], *popt))
plt.axvline(popt[2])
plt.show()
# if gaussian fits off chip, then use chip-integrated answer
if (popt[2] <= min(ydata2)+25) or (popt[2] >= max(ydata2)-25):
ybins[i] = popt_tot[2]
popt = popt_tot
print('failed. using chip answer')
else:
ybins[i] = popt[2]
# update the box it can search over, in case a big bend in the order
# ydata2 = ydata[np.where((ydata>= popt[2] - popt[3]*bigbox) &
# (ydata<= popt[2] + popt[3]*bigbox))]
# recenter the bin positions, trim the unused bin off in Y
mxbins = (xbins[:-1]+xbins[1:]) / 2.
mybins = ybins[:-1]
# run a cubic spline thru the bins
ap_spl = UnivariateSpline(mxbins, mybins, ext=0, k=3, s=0)
# interpolate the spline to 1 position per column
mx = np.arange(0, img.shape[Saxis])
my = ap_spl(mx)
if display is True:
plt.figure()
plt.imshow(np.log10(img),origin='lower',aspect='auto',cmap=cm.Greys_r)
plt.autoscale(False)
plt.plot(mx,my,'b',lw=1)
# plt.plot(mx,my+popt_tot[3]*bigbox,'y')
# plt.plot(mx,my-popt_tot[3]*bigbox,'y')
plt.show()
print("> Trace gaussian width = "+str(popt_tot[3])+' pixels')
return my
def line_trace(img, pcent, wcent, fmask=(1,), maxbend=10, display=False):
'''
Trace the lines of constant wavelength along the spatial dimension.
To be run after peaks found in the HeNeAr lamp. Usually run internally
to HeNeAr_fit()
Method works by tracing up and down from the image center (slice) along
each HeNeAr line by 1 pixel, fitting a gaussian to find the center.
Parameters
----------
img : 2d float
the HeNeAr data
pcent : float array
the pixel center along the image slice of each HeNeAr line to trace
wcent : float array
the identified wavelength that corresponds to each peak's pixel center (pcent)
fmask : float array, optional
the illumination section to trace trace over in spatial dimension
maxbend : int, optional
How big of a width (in pixel units) to allow the bend in the HeNeAr
line to search over (Default is 10). Probably doesn't need to be
modified much.
display : bool, optional
should we display plot after? (Default is False)
Returns
-------
xcent, ycent, wcent
These are the arrays of X pixel (wavelength dimension), Y pixel
(spatial dimension), and corresponding wavelengths of each HeNeAr line.
'''
xcent_big = []
ycent_big = []
wcent_big = []
# the valid y-range of the chip
if (len(fmask)>1):
ydata = np.arange(img.shape[0])[fmask]
else:
ydata = np.arange(img.shape[0])
ybuf = 10
# split the chip in to 2 parts, above and below the center
ydata1 = ydata[np.where((ydata>=img.shape[0]/2) &
(ydata<img.shape[0]-ybuf))]
ydata2 = ydata[np.where((ydata<img.shape[0]/2) &
(ydata>ybuf))][::-1]
# plt.figure()
# plt.plot(img[img.shape[0]/2,:])
# plt.scatter(pcent, pcent*0.+np.mean(img))
# plt.show()
img_med = np.nanmedian(img)
# loop over every HeNeAr peak that had a good fit
for i in range(len(pcent)):
xline = np.arange(int(pcent[i])-maxbend,int(pcent[i])+maxbend)
# above center line (where fit was done)
for j in ydata1:
yline = img[j-ybuf:j+ybuf, int(pcent[i])-maxbend:int(pcent[i])+maxbend].sum(axis=0)
# fit gaussian, assume center at 0, width of 2
if j==ydata1[0]:
cguess = pcent[i] # xline[np.argmax(yline)]
pguess = [np.nanmax(yline), img_med, cguess, 2.]
try:
popt,pcov = curve_fit(_gaus, xline, yline, p0=pguess)
if popt[2]>0 and popt[2]<img.shape[1]:
cguess = popt[2] # update center pixel
xcent_big = np.append(xcent_big, popt[2])
ycent_big = np.append(ycent_big, j)
wcent_big = np.append(wcent_big, wcent[i])
except RuntimeError:
popt = pguess
# below center line, from middle down
for j in ydata2:
yline = img[j-ybuf:j+ybuf, int(pcent[i])-maxbend:int(pcent[i])+maxbend].sum(axis=0)
# fit gaussian, assume center at 0, width of 2
if j==ydata2[0]:
cguess = pcent[i] # xline[np.argmax(yline)]
pguess = [np.nanmax(yline), img_med, cguess, 2.]
try:
popt,pcov = curve_fit(_gaus, xline, yline, p0=pguess)
if popt[2]>0 and popt[2]<img.shape[1]:
cguess = popt[2] # update center pixel
xcent_big = np.append(xcent_big, popt[2])
ycent_big = np.append(ycent_big, j)
wcent_big = np.append(wcent_big, wcent[i])
except RuntimeError:
popt = pguess
if display is True:
plt.figure()
plt.imshow(np.log10(img), origin = 'lower',aspect='auto',cmap=cm.Greys_r)
plt.colorbar()
plt.scatter(xcent_big,ycent_big,marker='|',c='r')
plt.show()
return xcent_big, ycent_big, wcent_big
def find_peaks(wave, flux, pwidth=10, pthreshold=97, minsep=1):
'''
Given a slice thru a HeNeAr image, find the significant peaks.
Parameters
----------
wave : `~numpy.ndarray`
Wavelength
flux : `~numpy.ndarray`
Flux
pwidth : float
the number of pixels around the "peak" to fit over
pthreshold : float
Peak threshold
minsep : float
Minimum separation
Returns
-------
Peak Pixels, Peak Wavelengths
'''
# sort data, cut top x% of flux data as peak threshold
flux_thresh = np.percentile(flux, pthreshold)
# find flux above threshold
high = np.where((flux >= flux_thresh))
# find individual peaks (separated by > 1 pixel)
pk = high[0][1:][ ( (high[0][1:]-high[0][:-1]) > minsep ) ]
# offset from start/end of array by at least same # of pixels
pk = pk[pk > pwidth]
pk = pk[pk < (len(flux) - pwidth)]
# print('Found '+str(len(pk))+' peaks in HeNeAr to fit Gaussians to')
pcent_pix = np.zeros_like(pk,dtype='float')
wcent_pix = np.zeros_like(pk,dtype='float') # wtemp[pk]
# for each peak, fit a gaussian to find center
for i in range(len(pk)):
xi = wave[pk[i] - pwidth:pk[i] + pwidth]
yi = flux[pk[i] - pwidth:pk[i] + pwidth]
pguess = (np.nanmax(yi), np.nanmedian(flux), float(np.nanargmax(yi)), 2.)
try:
popt,pcov = curve_fit(_gaus, np.arange(len(xi),dtype='float'), yi,
p0=pguess)
# the gaussian center of the line in pixel units
pcent_pix[i] = (pk[i]-pwidth) + popt[2]
# and the peak in wavelength units
wcent_pix[i] = xi[np.nanargmax(yi)]
except RuntimeError:
pcent_pix[i] = float('nan')
wcent_pix[i] = float('nan')
wcent_pix, ss = np.unique(wcent_pix, return_index=True)
pcent_pix = pcent_pix[ss]
okcent = np.where((np.isfinite(pcent_pix)))
return pcent_pix[okcent], wcent_pix[okcent]
def lines_to_surface(img, xcent, ycent, wcent,
mode='spline2d', fit_order=2, display=False):
'''
Turn traced arc lines into a wavelength solution across the entire chip
Requires inputs from line_trace(). Outputs are a 2d wavelength solution
Parameters
----------
img : 2d array
the HeNeAr data
xcent : 1d array
the X (spatial) pixel positions of the HeNeAr lines
ycent : 1d array
the Y (wavelength) pixel positions of the HeNeAr lines
wcent : 1d array
the wavelength values of the HeNeAr lines
mode : str, {'poly', 'spline', 'spline2d'}
what mode of interpolation to use to go from traces along the
HeNeAr lines to a wavelength value for every (x,y) pixel?
Options include (1) poly: along 1-pixel wide slices in the spatial
dimension, fit a polynomial between the HeNeAr lines. Uses fit_order;
(2) spline: along 1-pixel wide slices in the spatial dimension,
fit a quadratic spline; (3) spline2d: fit a full 2d surface using a
cubic spline. This is the best option, in principle.
Returns
-------
the 2d wavelenth solution. Output depends on mode parameter.
'''
xsz = img.shape[1]
# fit the wavelength solution for the entire chip w/ a 2d spline
if (mode=='spline2d'):
xfitd = 5 # the spline dimension in the wavelength space
print('Fitting Spline2d - NOTE: this mode doesnt work well')
wfit = SmoothBivariateSpline(xcent, ycent, wcent, kx=xfitd, ky=3,
bbox=[0,img.shape[1],0,img.shape[0]], s=0)
#elif mode=='poly2d':
## using 2d polyfit
# wfit = polyfit2d(xcent_big, ycent_big, wcent_big, order=3)
elif mode=='spline':
wfit = np.zeros_like(img)
xpix = np.arange(xsz)
for i in np.arange(ycent.min(), ycent.max()):
x = np.where((ycent == i))[0]
x_u, ind_u = np.unique(xcent[x], return_index=True)
# this smoothing parameter is absurd...
spl = UnivariateSpline(x_u, wcent[x][ind_u], ext=0, k=3, s=5e7)
if display is True:
plt.figure()
plt.scatter(xcent[x][ind_u], wcent[x][ind_u])
plt.plot(xpix, spl(xpix))
plt.show()
wfit[int(i),:] = spl(xpix)
elif mode=='poly':
wfit = np.zeros_like(img).astype(np.float64)
xpix = np.arange(xsz)
# print(xcent)
# print(ycent)
# print(wcent)
# print(ycent.min(), ycent.max(), ycent)
for i in np.arange(ycent.min(), ycent.max()):
x = np.where((ycent == i))[0]
if len(x) == 0:
wfit[int(i),:] = 0.0
print('x has length 0')
continue
coeff = np.polyfit(xcent[x], wcent[x], fit_order)
wfit[int(i),:] = np.polyval(coeff, xpix)
return wfit
def ap_extract(img, trace, apwidth=8, skysep=3, skywidth=7, skydeg=0,
coaddN=1):
"""
1. Extract the spectrum using the trace. Simply add up all the flux
around the aperture within a specified +/- width.
Note: implicitly assumes wavelength axis is perfectly vertical within
the trace. An major simplification at present. To be changed!
2. Fits a polynomial to the sky at each column
Note: implicitly assumes wavelength axis is perfectly vertical within
the trace. An important simplification.
3. Computes the uncertainty in each pixel
Parameters
----------
img : 2d numpy array
This is the image, stored as a normal numpy array. Can be read in
using astropy.io.fits like so:
>>> hdu = fits.open('file.fits') # doctest: +SKIP
>>> img = hdu[0].data # doctest: +SKIP
trace : 1-d array
The spatial positions (Y axis) corresponding to the center of the
trace for every wavelength (X axis), as returned from ap_trace
apwidth : int, optional
The width along the Y axis on either side of the trace to extract.
Note: a fixed width is used along the whole trace.
(default is 8 pixels)
skysep : int, optional
The separation in pixels from the aperture to the sky window.
(Default is 3)
skywidth : int, optional
The width in pixels of the sky windows on either side of the
aperture. (Default is 7)
skydeg : int, optional
The polynomial order to fit between the sky windows.
(Default is 0)
Returns
-------
onedspec : 1-d array
The summed flux at each column about the trace. Note: is not
sky subtracted!
skysubflux : 1-d array
The integrated sky values along each column, suitable for
subtracting from the output of ap_extract
fluxerr : 1-d array
the uncertainties of the flux values
"""
onedspec = np.zeros_like(trace)
skysubflux = np.zeros_like(trace)
fluxerr = np.zeros_like(trace)
for i in range(0,len(trace)):
#-- first do the aperture flux
# juuuust in case the trace gets too close to the edge
widthup = apwidth
widthdn = apwidth
if (trace[i]+widthup > img.shape[0]):
widthup = img.shape[0]-trace[i] - 1
if (trace[i]-widthdn < 0):
widthdn = trace[i] - 1
# simply add up the total flux around the trace +/- width
onedspec[i] = img[int(trace[i]-widthdn):int(trace[i]+widthup+1), i].sum()
#-- now do the sky fit
itrace = int(trace[i])
y = np.append(np.arange(itrace-apwidth-skysep-skywidth, itrace-apwidth-skysep),
np.arange(itrace+apwidth+skysep+1, itrace+apwidth+skysep+skywidth+1))
z = img[y,i]
if (skydeg>0):
# fit a polynomial to the sky in this column
pfit = np.polyfit(y,z,skydeg)
# define the aperture in this column
ap = np.arange(trace[i]-apwidth, trace[i]+apwidth+1)
# evaluate the polynomial across the aperture, and sum
skysubflux[i] = np.sum(np.polyval(pfit, ap))
elif (skydeg==0):
skysubflux[i] = np.nanmean(z)*(apwidth*2.0 + 1)
#-- finally, compute the error in this pixel
sigB = (np.quantile(z, 0.84) - np.quantile(z, 0.16)) / 2 # stddev in the background data
N_B = len(y) # number of bkgd pixels
N_A = apwidth*2. + 1 # number of aperture pixels
# based on aperture phot err description by <NAME>, Caltech:
# http://wise2.ipac.caltech.edu/staff/fmasci/ApPhotUncert.pdf
fluxerr[i] = np.sqrt(np.sum((onedspec[i]-(skysubflux[i]))/coaddN) +
(N_A + N_A**2. / N_B) * (sigB**2.))
return onedspec, skysubflux, fluxerr
def HeNeAr_fit(calimage, linelist='apohenear.dat', interac=True,
trim=True, fmask=(1,), display=False,
tol=10, fit_order=2, previous='',mode='poly',
second_pass=True):
"""
Determine the wavelength solution to be used for the science images.
Can be done either automatically (buyer beware) or manually. Both the
manual and auto modes use a "slice" through the chip center to learn
the wavelengths of specific HeNeAr lines. Emulates the IDENTIFY
function in IRAF.
If the automatic mode is selected (interac=False), program tries to
first find significant peaks in the "slice", then uses a brute-force
guess scheme based on the grating information in the header. While
easy, your mileage may vary with this method.
If the interactive mode is selected (interac=True), you click on
features in the "slice" and identify their wavelengths.
Parameters
----------
calimage : str
Path to the HeNeAr calibration image
linelist : str, optional
The linelist file to use in the resources/linelists/ directory.
Only used in automatic mode. (Default is apohenear.dat)
interac : bool, optional
Should the HeNeAr identification be done interactively (manually)?
(Default is True)
trim : bool, optional
Trim the image using the DATASEC keyword in the header, assuming
has format of [0:1024,0:512] (Default is True)
fmask : array-like, optional
A list of illuminated rows in the spatial direction (Y), as
returned by flatcombine.
display : bool, optional
tol : int, optional
When in automatic mode, the tolerance in pixel units between
linelist entries and estimated wavelengths for the first few
lines matched... use carefully. (Default is 10)
mode : str, optional
What type of function to use to fit the entire 2D wavelength
solution? Options include (poly, spline2d). (Default is poly)
fit_order : int, optional
The polynomial order to use to interpolate between identified
peaks in the HeNeAr (Default is 2)
previous : string, optional
name of file containing previously identified peaks. Still has to
do the fitting.
Returns
-------
wfit : bivariate spline object or 2d polynomial
The wavelength solution at every pixel. Output type depends on the
mode keyword above (poly is recommended)
"""
print('Running HeNeAr_fit function on file '+calimage)
# silence the polyfit warnings
warnings.simplefilter('ignore', np.RankWarning)
hdu = fits.open(calimage)
if trim is False:
img = hdu[0].data
if trim is True:
datasec = hdu[0].header['DATASEC'][1:-1].replace(':',',').split(',')
d = list(map(int, datasec))
img = hdu[0].data[d[2]-1:d[3],d[0]-1:d[1]]
# this approach will be very DIS specific
try:
disp_approx = hdu[0].header['DISPDW']
wcen_approx = hdu[0].header['DISPWC']
except KeyError:
disp_approx = 0.
wcen_approx = 1.
try:
# the red chip wavelength is backwards (DIS specific)
clr = hdu[0].header['DETECTOR']
if (clr.lower() == 'red'):
sign = -1.0
else:
sign = 1.0
except KeyError:
sign = 1.0
hdu.close(closed=True)
#-- this is how I *want* to do this. Need to header values later though...
# img, _, _, wtemp = OpenImg(calimage, trim=trim)
# take a slice thru the data (+/- 10 pixels) in center row of chip
slice = img[int(img.shape[0]/2-10):int(img.shape[0]/2+10),:].sum(axis=0)
# use the header info to do rough solution (linear guess)
wtemp = (np.arange(len(slice))-len(slice)/2) * disp_approx * sign + wcen_approx
###### IDENTIFY (auto and interac modes)
# = = = = = = = = = = = = = = = =
#-- automatic mode
if (interac is False):
if (len(previous)==0):
print("Doing automatic wavelength calibration on HeNeAr.")
print("Note, this is not very robust. Suggest you re-run with interac=True")
# find the linelist of choice
linelists_dir = os.path.dirname(os.path.realpath(__file__))+ '/resources/linelists/'
# if (len(linelist)==0):
# linelist = os.path.join(linelists_dir, linelist)
# import the linelist
linewave = np.genfromtxt(os.path.join(linelists_dir, linelist), dtype='float',
skip_header=1,usecols=(0,),unpack=True)
pcent_pix, wcent_pix = find_peaks(wtemp, slice, pwidth=10, pthreshold=97)
# loop thru each peak, from center outwards. a greedy solution
# find nearest list line. if not line within tolerance, then skip peak
pcent = []
wcent = []
# find center-most lines, sort by dist from center pixels
ss = np.argsort(np.abs(wcent_pix-wcen_approx))
#coeff = [0.0, 0.0, disp_approx*sign, wcen_approx]
coeff = np.append(np.zeros(fit_order-1),(disp_approx*sign, wcen_approx))
for i in range(len(pcent_pix)):
xx = pcent_pix-len(slice)/2
#wcent_pix = coeff[3] + xx * coeff[2] + coeff[1] * (xx*xx) + coeff[0] * (xx*xx*xx)
wcent_pix = np.polyval(coeff, xx)
if display is True:
plt.figure()
plt.plot(wtemp, slice, 'b')
plt.scatter(linewave,np.ones_like(linewave)*np.nanmax(slice),marker='o',c='cyan')
plt.scatter(wcent_pix,np.ones_like(wcent_pix)*np.nanmax(slice)/2.,marker='*',c='green')
plt.scatter(wcent_pix[ss[i]],np.nanmax(slice)/2., marker='o',c='orange')
# if there is a match w/i the linear tolerance
if (min((np.abs(wcent_pix[ss][i] - linewave))) < tol):
# add corresponding pixel and *actual* wavelength to output vectors
pcent = np.append(pcent,pcent_pix[ss[i]])
wcent = np.append(wcent, linewave[np.argmin(np.abs(wcent_pix[ss[i]] - linewave))] )
if display is True:
plt.scatter(wcent,np.ones_like(wcent)*np.nanmax(slice),marker='o',c='red')
if (len(pcent)>fit_order):
coeff = np.polyfit(pcent-len(slice)/2, wcent, fit_order)
if display is True:
plt.xlim((min(wtemp),max(wtemp)))
plt.show()
lout = open(calimage+'.lines', 'w')
lout.write("# This file contains the HeNeAr lines identified [auto] Columns: (pixel, wavelength) \n")
for l in range(len(pcent)):
lout.write(str(pcent[l]) + ', ' + str(wcent[l])+'\n')
lout.close()
# the end result is the vector "coeff" has the wavelength solution for "slice"
# update the "wtemp" vector that goes with "slice" (fluxes)
wtemp = np.polyval(coeff, (np.arange(len(slice))-len(slice)/2))
if (len(previous) > 0):
pcent, wcent = np.genfromtxt(previous, dtype='float',
unpack=True, skip_header=1, delimiter=',')
# = = = = = = = = = = = = = = = =
#-- manual (interactive) mode
elif (interac is True):
if (len(previous)==0):
print('')
print('Using INTERACTIVE HeNeAr_fit mode:')
print('1) Click on HeNeAr lines in plot window')
print('2) Enter corresponding wavelength in terminal and press <return>')
print(' If mis-click or unsure, just press leave blank and press <return>')
print('3) To delete an entry, click on label, enter "d" in terminal, press <return>')
print('4) Close plot window when finished')
xraw = np.arange(len(slice))
class InteracWave(object):
# http://stackoverflow.com/questions/21688420/callbacks-for-graphical-mouse-input-how-to-refresh-graphics-how-to-tell-matpl
def __init__(self):
self.fig = plt.figure()
self.ax = self.fig.add_subplot(111)
self.ax.plot(wtemp, slice, 'b')
plt.xlabel('Wavelength')
plt.ylabel('Counts')
self.pcent = [] # the pixel centers of the identified lines
self.wcent = [] # the labeled wavelengths of the lines
self.ixlib = [] # library of click points
self.cursor = Cursor(self.ax, useblit=False,horizOn=False,
color='red', linewidth=1 )
self.connect = self.fig.canvas.mpl_connect
self.disconnect = self.fig.canvas.mpl_disconnect
self.clickCid = self.connect("button_press_event",self.OnClick)
def OnClick(self, event):
# only do stuff if toolbar not being used
# NOTE: this subject to change API, so if breaks, this probably why
# http://stackoverflow.com/questions/20711148/ignore-matplotlib-cursor-widget-when-toolbar-widget-selected
if self.fig.canvas.manager.toolbar._active is None:
ix = event.xdata
# if the click is in good space, proceed
if (ix is not None) and (ix > np.nanmin(slice)) and (ix < np.nanmax(slice)):
# disable button event connection
self.disconnect(self.clickCid)
# disconnect cursor, and remove from plot
self.cursor.disconnect_events()
self.cursor._update()
# get points nearby to the click
nearby = np.where((wtemp > ix-10*disp_approx) &
(wtemp < ix+10*disp_approx) )
# find if click is too close to an existing click (overlap)
kill = None
if len(self.pcent)>0:
for k in range(len(self.pcent)):
if np.abs(self.ixlib[k]-ix)<tol:
kill_d = input('> WARNING: Click too close to existing point. To delete existing point, enter "d"')
if kill_d=='d':
kill = k
if kill is not None:
del(self.pcent[kill])
del(self.wcent[kill])
del(self.ixlib[kill])
# If there are enough valid points to possibly fit a peak too...
if (len(nearby[0]) > 4) and (kill is None):
imax = np.nanargmax(slice[nearby])
pguess = (np.nanmax(slice[nearby]), np.nanmedian(slice), xraw[nearby][imax], 3.)
try:
popt,pcov = curve_fit(_gaus, xraw[nearby], slice[nearby], p0=pguess)
self.ax.plot(wtemp[int(popt[2])], popt[0], 'r|')
except ValueError:
print('> WARNING: Bad data near this click, cannot centroid line with Gaussian. I suggest you skip this one')
popt = pguess
except RuntimeError:
print('> WARNING: Gaussian centroid on line could not converge. I suggest you skip this one')
popt = pguess
# using raw_input sucks b/c doesn't raise terminal, but works for now
try:
number=float(input('> Enter Wavelength: '))
self.pcent.append(popt[2])
self.wcent.append(number)
self.ixlib.append((ix))
self.ax.plot(wtemp[int(popt[2])], popt[0], 'ro')
print(' Saving '+str(number))
except ValueError:
print("> Warning: Not a valid wavelength float!")
elif (kill is None):
print('> Error: No valid data near click!')
# reconnect to cursor and button event
self.clickCid = self.connect("button_press_event",self.OnClick)
self.cursor = Cursor(self.ax, useblit=False,horizOn=False,
color='red', linewidth=1 )
else:
pass
# run the interactive program
wavefit = InteracWave()
plt.show() #activate the display - GO!
# how I would LIKE to do this interactively:
# inside the interac mode, do a split panel, live-updated with
# the wavelength solution, and where user can edit the fit_order
# how I WILL do it instead
# a crude while loop here, just to get things moving
# after interactive fitting done, get results fit peaks
pcent = np.array(wavefit.pcent,dtype='float')
wcent = np.array(wavefit.wcent, dtype='float')
print('> You have identified '+str(len(pcent))+' lines')
lout = open(calimage+'.lines', 'w')
lout.write("# This file contains the HeNeAr lines identified [manual] Columns: (pixel, wavelength) \n")
for l in range(len(pcent)):
lout.write(str(pcent[l]) + ', ' + str(wcent[l])+'\n')
lout.close()
if (len(previous)>0):
pcent, wcent = np.genfromtxt(previous, dtype='float',
unpack=True, skip_header=1,delimiter=',')
#--- FIT SMOOTH FUNCTION ---
# fit polynomial thru the peak wavelengths
# xpix = (np.arange(len(slice))-len(slice)/2)
# coeff = np.polyfit(pcent-len(slice)/2, wcent, fit_order)
xpix = np.arange(len(slice))
coeff = np.polyfit(pcent, wcent, fit_order)
wtemp = np.polyval(coeff, xpix)
done = str(fit_order)
while (done != 'd'):
fit_order = int(done)
coeff = np.polyfit(pcent, wcent, fit_order)
wtemp = np.polyval(coeff, xpix)
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax1.plot(pcent, wcent, 'bo')
ax1.plot(xpix, wtemp, 'r')
ax2.plot(pcent, wcent - np.polyval(coeff, pcent),'ro')
ax2.set_xlabel('pixel')
ax1.set_ylabel('wavelength')
ax2.set_ylabel('residual')
ax1.set_title('fit_order = '+str(fit_order))
# ylabel('wavelength')
print(" ")
print('> How does this look? Enter "d" to be done (accept), ')
print(' or a number to change the polynomial order and re-fit')
print('> Currently fit_order = '+str(fit_order))
print(" ")
plt.show()
_CheckMono(wtemp)
print(' ')
done = str(input('ENTER: "d" (done) or a # (poly order): '))
# = = = = = = = = = = = = = = = = = =
# now rough wavelength is found, either via interactive or auto mode!
#-- SECOND PASS
if second_pass is True:
linelists_dir = os.path.dirname(os.path.realpath(__file__))+ '/resources/linelists/'
hireslinelist = 'henear.dat'
linewave2 = np.genfromtxt(os.path.join(linelists_dir, hireslinelist), dtype='float',
skip_header=1, usecols=(0,), unpack=True)
tol2 = tol # / 2.0
pcent_pix2, wcent_pix2 = find_peaks(wtemp, slice, pwidth=10, pthreshold=80)
pcent2 = []
wcent2 = []
# sort from center wavelength out
ss = np.argsort(np.abs(wcent_pix2-wcen_approx))
# coeff should already be set by manual or interac mode above
# coeff = np.append(np.zeros(fit_order-1),(disp_approx*sign, wcen_approx))
for i in range(len(pcent_pix2)):
xx = pcent_pix2-len(slice)/2
wcent_pix2 = np.polyval(coeff, xx)
if (min((np.abs(wcent_pix2[ss][i] - linewave2))) < tol2):
# add corresponding pixel and *actual* wavelength to output vectors
pcent2 = np.append(pcent2, pcent_pix2[ss[i]])
wcent2 = np.append(wcent2, linewave2[np.argmin(np.abs(wcent_pix2[ss[i]] - linewave2))] )
#-- update in real time. maybe not good for 2nd pass
# if (len(pcent2)>fit_order):
# coeff = np.polyfit(pcent2-len(slice)/2, wcent2, fit_order)
if display is True:
plt.figure()
plt.plot(wtemp, slice, 'b')
plt.scatter(linewave2,np.ones_like(linewave2)*np.nanmax(slice),
marker='o',c='cyan')
plt.scatter(wcent_pix2,np.ones_like(wcent_pix2)*np.nanmax(slice)/2.,
marker='*',c='green')
plt.scatter(wcent_pix2[ss[i]],np.nanmax(slice)/2.,
marker='o',c='orange')
plt.text(np.nanmin(wcent_pix2), np.nanmax(slice)*0.95, hireslinelist)
plt.text(np.nanmin(wcent_pix2), np.nanmax(slice)/2.*1.1, 'detected lines')
plt.scatter(wcent2,np.ones_like(wcent2)*np.nanmax(slice)*1.05,marker='o',c='red')
plt.text(np.nanmin(wcent_pix2), np.nanmax(slice)*1.1, 'matched lines')
plt.ylim((np.nanmin(slice), np.nanmax(slice)*1.2))
plt.xlim((min(wtemp),max(wtemp)))
plt.show()
wtemp = np.polyval(coeff, (np.arange(len(slice))-len(slice)/2))
lout = open(calimage+'.lines2', 'w')
lout.write("# This file contains the HeNeAr lines identified [2nd pass] Columns: (pixel, wavelength) \n")
for l in range(len(pcent2)):
lout.write(str(pcent2[l]) + ', ' + str(wcent2[l])+'\n')
lout.close()
xpix = np.arange(len(slice))
coeff = np.polyfit(pcent2, wcent2, fit_order)
wtemp = np.polyval(coeff, xpix)
#--- FIT SMOOTH FUNCTION ---
if interac is True:
done = str(fit_order)
while (done != 'd'):
fit_order = int(done)
coeff = np.polyfit(pcent2, wcent2, fit_order)
wtemp = np.polyval(coeff, xpix)
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax1.plot(pcent2, wcent2, 'bo')
ax1.plot(xpix, wtemp, 'r')
ax2.plot(pcent2, wcent2 - np.polyval(coeff, pcent2),'ro')
ax2.set_xlabel('pixel')
ax1.set_ylabel('wavelength')
ax2.set_ylabel('residual')
ax1.set_title('2nd pass, fit_order = '+str(fit_order))
# ylabel('wavelength')
print(" ")
print('> How does this look? Enter "d" to be done (accept), ')
print(' or a number to change the polynomial order and re-fit')
print('> Currently fit_order = '+str(fit_order))
print(" ")
plt.show()
_CheckMono(wtemp)
print(' ')
done = str(input('ENTER: "d" (done) or a # (poly order): '))
#-- trace the peaks vertically --
xcent_big, ycent_big, wcent_big = line_trace(img, pcent, wcent,
fmask=fmask, display=display)
plt.figure()
plt.imshow(img)
plt.show()
#-- turn these vertical traces in to a whole chip wavelength solution
wfit = lines_to_surface(img, xcent_big, ycent_big, wcent_big,
mode=mode, fit_order=fit_order)
return wfit
def mapwavelength(trace, wavemap, mode='spline2d'):
"""
Compute the wavelength along the center of the trace, to be run after
the HeNeAr_fit routine.
Parameters
----------
trace : 1-d array
The spatial positions (Y axis) corresponding to the center of the
trace for every wavelength (X axis), as returned from ap_trace
wavemap : bivariate spline object or image-like wavelength map
The wavelength evaluated at every pixel, output from HeNeAr_fit
Type depends on mode parameter.
mode : str, optional
Which mode was used to generate the 2D wavelength solution in
HeNeAr_fit(), and specifically in lines_to_surface()?
Options include: poly, spline, spline2d (Default is 'spline2d')
Returns
-------
trace_wave : 1d array
The wavelength vector evaluated at each position along the trace
"""
# use the wavemap from the HeNeAr_fit routine to determine the wavelength along the trace
if mode=='spline2d':
trace_wave = wavemap.ev(np.arange(len(trace)), trace)
elif mode=='poly' or mode=='spline':
trace_wave = np.zeros_like(trace)
for i in range(len(trace)):
wli = np.interp(trace[i], np.arange(wavemap.shape[0]), wavemap[:,i])
trace_wave[i] = wli
## using 2d polyfit
# trace_wave = polyval2d(np.arange(len(trace)), trace, wavemap)
return trace_wave
def normalize(wave, flux, mode='poly', order=5):
'''
Return a flattened, normalized spectrum. A model spectrum is made of
the continuum by fitting either a polynomial or spline to the data,
and then the data is normalized with the equation:
>>> norm = (flux - model) / model # doctest: +SKIP
Parameters
----------
wave : 1-d array
The object's wavelength array
flux : 1-d array
The object's flux array
mode : str, optional
Decides which mode should be used to flatten the spectrum.
Options are 'poly' (Default), 'spline', 'interac'.
order : int, optional
The polynomial order to use for mode='poly'. (Default is 3)
Returns
-------
Flux normalized spectrum at same wavelength points as the input
'''
if (mode != 'interac') and (mode != 'spline') and (mode != 'poly'):
mode = 'poly'
print("WARNING: invalid mode set in normalize. Changing to 'poly'")
if mode=='interac':
print('interac mode not built yet. sorry...')
mode = 'poly'
if mode=='poly':
fit = np.polyfit(wave, flux, order)
model = np.polyval(fit, wave)
if mode=='spline':
spl = UnivariateSpline(wave, flux, ext=0, k=2 ,s=0.0025)
model = spl(wave)
norm = (flux - model) / model
return norm
def AirmassCor(obj_wave, obj_flux, airmass, airmass_file='apoextinct.dat'):
"""
Correct the spectrum based on the airmass
Parameters
----------
obj_wave : 1-d array
The 1-d wavelength array of the spectrum
obj_flux : 1-d or 2-d array
The 1-d or 2-d flux array of the spectrum
airmass : float
The value of the airmass, not the header keyword.
airmass_file : str, {'apoextinct.dat', 'ctioextinct.dat', 'kpnoextinct.dat', 'ormextinct.dat'}
The name of the airmass extinction file. This routine assumes
the file is stored in the resources/extinction/ subdirectory.
Available files are (Default is apoextinct.dat)
Returns
-------
The flux array
"""
# read in the airmass extinction curve
extinction_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)),
'resources/extinction')
if len(airmass_file)==0:
air_wave, air_cor = np.genfromtxt(os.path.join(extinction_dir, airmass_file),
unpack=True,skip_header=2)
else:
print('> Loading airmass library file: '+airmass_file)
# print(' Note: first 2 rows are skipped, assuming header')
air_wave, air_cor = np.genfromtxt(os.path.join(extinction_dir, airmass_file),
unpack=True,skip_header=2)
# air_cor in units of mag/airmass
airmass_ext = 10.0**(0.4 * airmass *
np.interp(obj_wave, air_wave, air_cor))
# arimas_ext is broadcast to obj_flux if it is a 2-d array
return obj_flux * airmass_ext
def DefFluxCal(obj_wave, obj_flux, std_wave, std_mag, std_wth, std_stdstar='', mode='spline', polydeg=9,
display=False):
"""
Parameters
----------
obj_wave : 1-d array
The 1-d wavelength array of the spectrum
obj_flux : 1-d array
The 1-d flux array of the spectrum
stdstar : str
Name of the standard star file to use for flux calibration. You
must give the subdirectory and file name, for example:
>>> sensfunc = DefFluxCal(wave, flux, mode='spline', stdstar='spec50cal/feige34.dat') # doctest: +SKIP
If no standard is set, or an invalid standard is selected, will
return array of 1's and a warning. A list of all available
subdirectories and objects is available on the wiki, or look in
pydis/resources/onedstds/
mode : str, optional
either "linear", "spline", or "poly" (Default is spline)
polydeg : float, optional
set the order of the polynomial to fit through (Default is 9)
display : bool, optional
If True, plot the down-sampled sensfunc and fit to screen (Default
is False)
Returns
-------
sensfunc : 1-d array
The sensitivity function for the standard star
"""
# standard star spectrum is stored in magnitude units
std_flux = _mag2flux(std_wave, std_mag)
# Automatically exclude these obnoxious lines...
balmer = np.array([6563, 4861, 4341], dtype='float')
# down-sample (ds) the observed flux to the standard's bins
obj_flux_ds = []
obj_wave_ds = []
std_flux_ds = []
for i in range(len(std_wave)):
rng = np.where((obj_wave >= std_wave[i] - std_wth[i] / 2.0) &
(obj_wave < std_wave[i] + std_wth[i] / 2.0))
IsH = np.where((balmer >= std_wave[i] - std_wth[i] / 2.0) &
(balmer < std_wave[i] + std_wth[i] / 2.0))
# does this bin contain observed spectra, and no Balmer line?
if (len(rng[0]) > 1) and (len(IsH[0]) == 0):
# obj_flux_ds.append(np.sum(obj_flux[rng]) / std_wth[i])
obj_flux_ds.append( np.nanmean(obj_flux[rng]) )
obj_wave_ds.append(std_wave[i])
std_flux_ds.append(std_flux[i])
# the ratio between the standard star flux and observed flux
# has units like erg / counts
ratio = np.abs(np.array(std_flux_ds, dtype='float') /
np.array(obj_flux_ds, dtype='float'))
# interp calibration (sensfunc) on to object's wave grid
# can use 3 types of interpolations: linear, cubic spline, polynomial
# if invalid mode selected, make it spline
if mode not in ('linear', 'spline', 'poly'):
mode = 'spline'
print("WARNING: invalid mode set in DefFluxCal. Changing to spline")
# actually fit the log of this sensfunc ratio
# since IRAF does the 2.5*log(ratio), everything in mag units!
LogSensfunc = np.log10(ratio)
# interpolate back on to observed wavelength grid
if mode=='linear':
sensfunc2 = np.interp(obj_wave, obj_wave_ds, LogSensfunc)
elif mode=='spline':
spl = UnivariateSpline(obj_wave_ds, LogSensfunc, ext=0, k=2 ,s=0.0025)
sensfunc2 = spl(obj_wave)
elif mode=='poly':
fit = np.polyfit(obj_wave_ds, LogSensfunc, polydeg)
sensfunc2 = np.polyval(fit, obj_wave)
if display is True:
plt.figure()
plt.plot(std_wave, std_flux, 'r', alpha=0.5, label='standard flux')
plt.xlabel('Wavelength')
plt.ylabel('Standard Star Flux')
plt.legend()
plt.show()
plt.figure()
plt.plot(obj_wave, obj_flux, 'k', label='observed counts')
plt.plot(obj_wave_ds, obj_flux_ds, 'bo',
label='downsample observed')
plt.xlabel('Wavelength')
plt.ylabel('Observed Counts/S')
plt.legend()
plt.show()
plt.figure()
plt.plot(obj_wave_ds, LogSensfunc, 'ko', label='sensfunc')
plt.plot(obj_wave, sensfunc2, label='interpolated sensfunc')
plt.xlabel('Wavelength')
plt.ylabel('log Sensfunc')
plt.legend()
plt.show()
plt.figure()
plt.plot(obj_wave, obj_flux*(10**sensfunc2),'k',
label='applied sensfunc')
plt.plot(std_wave, std_flux, 'ro', alpha=0.5, label='standard flux')
plt.xlabel('Wavelength')
plt.ylabel('Standard Star Flux')
plt.legend()
plt.show()
return 10**sensfunc2
def ApplyFluxCal(obj_wave, obj_flux, obj_err, cal_wave, sensfunc):
# the sensfunc should already be BASICALLY at the same wavelenths as the targets
# BUT, just in case, we linearly resample it:
# ensure input array is sorted!
ss = np.argsort(cal_wave)
sensfunc2 = | np.interp(obj_wave, cal_wave[ss], sensfunc[ss]) | numpy.interp |
#!/usr/bin/env python
# -*- coding: latin-1 -*-
#
# Copyright 2016-2021 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
import bisect
import copy
import gc
import logging
import multiprocessing as mp
import os
import platform
import warnings
import numpy as np
from matplotlib.pyplot import figure, plot, show
from nilearn import masking
from scipy import ndimage
from sklearn.decomposition import PCA
import rapidtide.calccoherence as tide_calccoherence
import rapidtide.calcnullsimfunc as tide_nullsimfunc
import rapidtide.calcsimfunc as tide_calcsimfunc
import rapidtide.correlate as tide_corr
import rapidtide.filter as tide_filt
import rapidtide.fit as tide_fit
import rapidtide.glmpass as tide_glmpass
import rapidtide.helper_classes as tide_classes
import rapidtide.io as tide_io
import rapidtide.miscmath as tide_math
import rapidtide.multiproc as tide_multiproc
import rapidtide.peakeval as tide_peakeval
import rapidtide.refine as tide_refine
import rapidtide.resample as tide_resample
import rapidtide.simfuncfit as tide_simfuncfit
import rapidtide.stats as tide_stats
import rapidtide.util as tide_util
import rapidtide.wiener as tide_wiener
from rapidtide.tests.utils import mse
from .utils import setup_logger
try:
import mkl
mklexists = True
except ImportError:
mklexists = False
print("mklexists:", mklexists)
try:
from memory_profiler import profile
memprofilerexists = True
except ImportError:
memprofilerexists = False
LGR = logging.getLogger("GENERAL")
TimingLGR = logging.getLogger("TIMING")
def conditionalprofile():
def resdec(f):
if memprofilerexists:
return profile(f)
return f
return resdec
@conditionalprofile()
def memcheckpoint(message):
print(message)
def maketmask(filename, timeaxis, maskvector, debug=False):
inputdata = tide_io.readvecs(filename)
theshape = np.shape(inputdata)
if theshape[0] == 1:
# this is simply a vector, one per TR. If the value is nonzero, include the point, otherwise don't
if theshape[1] == len(timeaxis):
maskvector = np.where(inputdata[0, :] > 0.0, 1.0, 0.0)
else:
raise ValueError("tmask length does not match fmri data")
else:
maskvector *= 0.0
for idx in range(0, theshape[1]):
starttime = inputdata[0, idx]
endtime = starttime + inputdata[1, idx]
startindex = np.max((bisect.bisect_left(timeaxis, starttime), 0))
endindex = np.min((bisect.bisect_right(timeaxis, endtime), len(maskvector) - 1))
maskvector[startindex:endindex] = 1.0
LGR.info(f"{starttime}, {startindex}, {endtime}, {endindex}")
return maskvector
def numpy2shared(inarray, thetype):
thesize = inarray.size
theshape = inarray.shape
if thetype == np.float64:
inarray_shared = mp.RawArray("d", inarray.reshape(thesize))
else:
inarray_shared = mp.RawArray("f", inarray.reshape(thesize))
inarray = np.frombuffer(inarray_shared, dtype=thetype, count=thesize)
inarray.shape = theshape
return inarray
def allocshared(theshape, thetype):
thesize = int(1)
if not isinstance(theshape, (list, tuple)):
thesize = theshape
else:
for element in theshape:
thesize *= int(element)
if thetype == np.float64:
outarray_shared = mp.RawArray("d", thesize)
else:
outarray_shared = mp.RawArray("f", thesize)
outarray = np.frombuffer(outarray_shared, dtype=thetype, count=thesize)
outarray.shape = theshape
return outarray, outarray_shared, theshape
def readamask(maskfilename, nim_hdr, xsize, istext=False, valslist=None, maskname="the"):
LGR.verbose(f"readamask called with filename: {maskfilename} vals: {valslist}")
if istext:
maskarray = tide_io.readvecs(maskfilename).astype("int16")
theshape = np.shape(maskarray)
theincludexsize = theshape[0]
if not theincludexsize == xsize:
raise ValueError(
f"Dimensions of {maskname} mask do not match the input data - exiting"
)
else:
themask, maskarray, mask_hdr, maskdims, masksizes = tide_io.readfromnifti(maskfilename)
maskarray = np.round(maskarray, 0).astype("int16")
if not tide_io.checkspacematch(mask_hdr, nim_hdr):
raise ValueError(f"Dimensions of {maskname} mask do not match the fmri data - exiting")
if valslist is not None:
tempmask = (0 * maskarray).astype("int16")
for theval in valslist:
LGR.verbose(f"looking for voxels matching {theval}")
tempmask[np.where(np.fabs(maskarray - theval) < 0.1)] += 1
maskarray = np.where(tempmask > 0, 1, 0)
return maskarray
def getglobalsignal(indata, optiondict, includemask=None, excludemask=None, pcacomponents=0.8):
# Start with all voxels
themask = indata[:, 0] * 0 + 1
# modify the mask if needed
if includemask is not None:
themask = themask * includemask
if excludemask is not None:
themask = themask * (1 - excludemask)
# combine all the voxels using one of the three methods
global rt_floatset, rt_floattype
globalmean = rt_floatset(indata[0, :])
thesize = np.shape(themask)
numvoxelsused = int(np.sum(np.where(themask > 0.0, 1, 0)))
selectedvoxels = indata[np.where(themask > 0.0), :][0]
LGR.info(f"constructing global mean signal using {optiondict['globalsignalmethod']}")
if optiondict["globalsignalmethod"] == "sum":
globalmean = np.sum(selectedvoxels, axis=0)
elif optiondict["globalsignalmethod"] == "meanscale":
themean = np.mean(indata, axis=1)
for vox in range(0, thesize[0]):
if themask[vox] > 0.0:
if themean[vox] != 0.0:
globalmean += indata[vox, :] / themean[vox] - 1.0
elif optiondict["globalsignalmethod"] == "pca":
try:
thefit = PCA(n_components=pcacomponents).fit(selectedvoxels)
except ValueError:
if pcacomponents == "mle":
LGR.warning("mle estimation failed - falling back to pcacomponents=0.8")
thefit = PCA(n_components=0.8).fit(selectedvoxels)
else:
raise ValueError("unhandled math exception in PCA refinement - exiting")
varex = 100.0 * np.cumsum(thefit.explained_variance_ratio_)[len(thefit.components_) - 1]
LGR.info(
f"Using {len(thefit.components_)} component(s), accounting for "
f"{varex:.2f}% of the variance"
)
else:
dummy = optiondict["globalsignalmethod"]
raise ValueError(f"illegal globalsignalmethod: {dummy}")
LGR.info(f"used {numvoxelsused} voxels to calculate global mean signal")
return tide_math.stdnormalize(globalmean), themask
def addmemprofiling(thefunc, memprofile, themessage):
if memprofile:
return profile(thefunc, precision=2)
else:
tide_util.logmem(themessage)
return thefunc
def checkforzeromean(thedataset):
themean = np.mean(thedataset, axis=1)
thestd = np.std(thedataset, axis=1)
if np.mean(thestd) > np.mean(themean):
return True
else:
return False
def echocancel(thetimecourse, echooffset, thetimestep, outputname, padtimepoints):
tide_io.writebidstsv(
f"{outputname}_desc-echocancellation_timeseries",
thetimecourse,
1.0 / thetimestep,
columns=["original"],
append=False,
)
shifttr = echooffset / thetimestep # lagtime is in seconds
echotc, dummy, dummy, dummy = tide_resample.timeshift(thetimecourse, shifttr, padtimepoints)
echotc[0 : int(np.ceil(shifttr))] = 0.0
echofit, echoR = tide_fit.mlregress(echotc, thetimecourse)
fitcoeff = echofit[0, 1]
outputtimecourse = thetimecourse - fitcoeff * echotc
tide_io.writebidstsv(
f"{outputname}_desc-echocancellation_timeseries",
echotc,
1.0 / thetimestep,
columns=["echo"],
append=True,
)
tide_io.writebidstsv(
f"{outputname}_desc-echocancellation_timeseries",
outputtimecourse,
1.0 / thetimestep,
columns=["filtered"],
append=True,
)
return outputtimecourse, echofit, echoR
def rapidtide_main(argparsingfunc):
optiondict, theprefilter = argparsingfunc
optiondict["nodename"] = platform.node()
fmrifilename = optiondict["in_file"]
outputname = optiondict["outputname"]
filename = optiondict["regressorfile"]
# Set up loggers for workflow
setup_logger(
logger_filename=f"{outputname}_log.txt",
timing_filename=f"{outputname}_runtimings.tsv",
memory_filename=f"{outputname}_memusage.tsv",
verbose=optiondict["verbose"],
debug=optiondict["debug"],
)
TimingLGR.info("Start")
# construct the BIDS base dictionary
outputpath = os.path.dirname(optiondict["outputname"])
rawsources = [os.path.relpath(optiondict["in_file"], start=outputpath)]
if optiondict["regressorfile"] is not None:
rawsources.append(os.path.relpath(optiondict["regressorfile"], start=outputpath))
bidsbasedict = {
"RawSources": rawsources,
"Units": "arbitrary",
"CommandLineArgs": optiondict["commandlineargs"],
}
TimingLGR.info("Argument parsing done")
# don't use shared memory if there is only one process
if (optiondict["nprocs"] == 1) and not optiondict["alwaysmultiproc"]:
optiondict["sharedmem"] = False
LGR.info("running single process - disabled shared memory use")
# disable numba now if we're going to do it (before any jits)
if optiondict["nonumba"]:
tide_util.disablenumba()
# set the internal precision
global rt_floatset, rt_floattype
if optiondict["internalprecision"] == "double":
LGR.info("setting internal precision to double")
rt_floattype = "float64"
rt_floatset = np.float64
else:
LGR.info("setting internal precision to single")
rt_floattype = "float32"
rt_floatset = np.float32
# set the output precision
if optiondict["outputprecision"] == "double":
LGR.info("setting output precision to double")
rt_outfloattype = "float64"
rt_outfloatset = np.float64
else:
LGR.info("setting output precision to single")
rt_outfloattype = "float32"
rt_outfloatset = np.float32
# set set the number of worker processes if multiprocessing
if optiondict["nprocs"] < 1:
optiondict["nprocs"] = tide_multiproc.maxcpus()
if optiondict["singleproc_getNullDist"]:
optiondict["nprocs_getNullDist"] = 1
else:
optiondict["nprocs_getNullDist"] = optiondict["nprocs"]
if optiondict["singleproc_calcsimilarity"]:
optiondict["nprocs_calcsimilarity"] = 1
else:
optiondict["nprocs_calcsimilarity"] = optiondict["nprocs"]
if optiondict["singleproc_peakeval"]:
optiondict["nprocs_peakeval"] = 1
else:
optiondict["nprocs_peakeval"] = optiondict["nprocs"]
if optiondict["singleproc_fitcorr"]:
optiondict["nprocs_fitcorr"] = 1
else:
optiondict["nprocs_fitcorr"] = optiondict["nprocs"]
if optiondict["singleproc_glm"]:
optiondict["nprocs_glm"] = 1
else:
optiondict["nprocs_glm"] = optiondict["nprocs"]
# set the number of MKL threads to use
if mklexists:
mklmaxthreads = mkl.get_max_threads()
if not (1 <= optiondict["mklthreads"] <= mklmaxthreads):
optiondict["mklthreads"] = mklmaxthreads
mkl.set_num_threads(optiondict["mklthreads"])
print(f"using {optiondict['mklthreads']} MKL threads")
# Generate MemoryLGR output file with column names
if not optiondict["memprofile"]:
tide_util.logmem()
# open the fmri datafile
tide_util.logmem("before reading in fmri data")
if tide_io.checkiftext(fmrifilename):
LGR.info("input file is text - all I/O will be to text files")
optiondict["textio"] = True
if optiondict["gausssigma"] > 0.0:
optiondict["gausssigma"] = 0.0
LGR.info("gaussian spatial filter disabled for text input files")
else:
optiondict["textio"] = False
if optiondict["textio"]:
nim_data = tide_io.readvecs(fmrifilename)
nim_hdr = None
theshape = np.shape(nim_data)
xsize = theshape[0]
ysize = 1
numslices = 1
fileiscifti = False
timepoints = theshape[1]
thesizes = [0, int(xsize), 1, 1, int(timepoints)]
numspatiallocs = int(xsize)
else:
fileiscifti = tide_io.checkifcifti(fmrifilename)
if fileiscifti:
LGR.info("input file is CIFTI")
(
cifti,
cifti_hdr,
nim_data,
nim_hdr,
thedims,
thesizes,
dummy,
) = tide_io.readfromcifti(fmrifilename)
optiondict["isgrayordinate"] = True
timepoints = nim_data.shape[1]
numspatiallocs = nim_data.shape[0]
LGR.info(f"cifti file has {timepoints} timepoints, {numspatiallocs} numspatiallocs")
slicesize = numspatiallocs
else:
LGR.info("input file is NIFTI")
nim, nim_data, nim_hdr, thedims, thesizes = tide_io.readfromnifti(fmrifilename)
optiondict["isgrayordinate"] = False
xsize, ysize, numslices, timepoints = tide_io.parseniftidims(thedims)
numspatiallocs = int(xsize) * int(ysize) * int(numslices)
xdim, ydim, slicethickness, tr = tide_io.parseniftisizes(thesizes)
tide_util.logmem("after reading in fmri data")
# correct some fields if necessary
if fileiscifti:
fmritr = 0.72 # this is wrong and is a hack until I can parse CIFTI XML
else:
if optiondict["textio"]:
if optiondict["realtr"] <= 0.0:
raise ValueError(
"for text file data input, you must use the -t option to set the timestep"
)
else:
if nim_hdr.get_xyzt_units()[1] == "msec":
fmritr = thesizes[4] / 1000.0
else:
fmritr = thesizes[4]
if optiondict["realtr"] > 0.0:
fmritr = optiondict["realtr"]
# check to see if we need to adjust the oversample factor
if optiondict["oversampfactor"] < 0:
optiondict["oversampfactor"] = int(np.max([np.ceil(fmritr / 0.5), 1]))
LGR.info(f"oversample factor set to {optiondict['oversampfactor']}")
oversamptr = fmritr / optiondict["oversampfactor"]
LGR.verbose(f"fmri data: {timepoints} timepoints, tr = {fmritr}, oversamptr = {oversamptr}")
LGR.info(f"{numspatiallocs} spatial locations, {timepoints} timepoints")
TimingLGR.info("Finish reading fmrifile")
# if the user has specified start and stop points, limit check, then use these numbers
validstart, validend = tide_util.startendcheck(
timepoints, optiondict["startpoint"], optiondict["endpoint"]
)
if abs(optiondict["lagmin"]) > (validend - validstart + 1) * fmritr / 2.0:
raise ValueError(
f"magnitude of lagmin exceeds {(validend - validstart + 1) * fmritr / 2.0} - invalid"
)
if abs(optiondict["lagmax"]) > (validend - validstart + 1) * fmritr / 2.0:
raise ValueError(
f"magnitude of lagmax exceeds {(validend - validstart + 1) * fmritr / 2.0} - invalid"
)
# do spatial filtering if requested
if optiondict["gausssigma"] < 0.0 and not optiondict["textio"]:
# set gausssigma automatically
optiondict["gausssigma"] = np.mean([xdim, ydim, slicethickness]) / 2.0
if optiondict["gausssigma"] > 0.0:
LGR.info(
f"applying gaussian spatial filter to timepoints {validstart} "
f"to {validend} with sigma={optiondict['gausssigma']}"
)
reportstep = 10
for i in range(validstart, validend + 1):
if (i % reportstep == 0 or i == validend) and optiondict["showprogressbar"]:
tide_util.progressbar(
i - validstart + 1,
validend - validstart + 1,
label="Percent complete",
)
nim_data[:, :, :, i] = tide_filt.ssmooth(
xdim,
ydim,
slicethickness,
optiondict["gausssigma"],
nim_data[:, :, :, i],
)
print()
TimingLGR.info("End 3D smoothing")
# reshape the data and trim to a time range, if specified. Check for special case of no trimming to save RAM
fmri_data = nim_data.reshape((numspatiallocs, timepoints))[:, validstart : validend + 1]
validtimepoints = validend - validstart + 1
# detect zero mean data
optiondict["dataiszeromean"] = checkforzeromean(fmri_data)
if optiondict["dataiszeromean"]:
LGR.warning(
"WARNING: dataset is zero mean - forcing variance masking and no refine prenormalization. "
"Consider specifying a global mean and correlation mask."
)
optiondict["refineprenorm"] = "None"
optiondict["globalmaskmethod"] = "variance"
# read in the optional masks
tide_util.logmem("before setting masks")
internalglobalmeanincludemask = None
internalglobalmeanexcludemask = None
internalrefineincludemask = None
internalrefineexcludemask = None
if optiondict["globalmeanincludename"] is not None:
LGR.info("constructing global mean include mask")
theglobalmeanincludemask = readamask(
optiondict["globalmeanincludename"],
nim_hdr,
xsize,
istext=optiondict["textio"],
valslist=optiondict["globalmeanincludevals"],
maskname="global mean include",
)
internalglobalmeanincludemask = theglobalmeanincludemask.reshape(numspatiallocs)
if tide_stats.getmasksize(internalglobalmeanincludemask) == 0:
raise ValueError(
"ERROR: there are no voxels in the global mean include mask - exiting"
)
if optiondict["globalmeanexcludename"] is not None:
LGR.info("constructing global mean exclude mask")
theglobalmeanexcludemask = readamask(
optiondict["globalmeanexcludename"],
nim_hdr,
xsize,
istext=optiondict["textio"],
valslist=optiondict["globalmeanexcludevals"],
maskname="global mean exclude",
)
internalglobalmeanexcludemask = theglobalmeanexcludemask.reshape(numspatiallocs)
if tide_stats.getmasksize(internalglobalmeanexcludemask) == numspatiallocs:
raise ValueError(
"ERROR: the global mean exclude mask does not leave any voxels - exiting"
)
if (internalglobalmeanincludemask is not None) and (internalglobalmeanexcludemask is not None):
if (
tide_stats.getmasksize(
internalglobalmeanincludemask * (1 - internalglobalmeanexcludemask)
)
== 0
):
raise ValueError(
"ERROR: the global mean include and exclude masks not leave any voxels between them - exiting"
)
if optiondict["refineincludename"] is not None:
LGR.info("constructing refine include mask")
therefineincludemask = readamask(
optiondict["refineincludename"],
nim_hdr,
xsize,
istext=optiondict["textio"],
valslist=optiondict["refineincludevals"],
maskname="refine include",
)
internalrefineincludemask = therefineincludemask.reshape(numspatiallocs)
if tide_stats.getmasksize(internalrefineincludemask) == 0:
raise ValueError("ERROR: there are no voxels in the refine include mask - exiting")
if optiondict["refineexcludename"] is not None:
LGR.info("constructing refine exclude mask")
therefineexcludemask = readamask(
optiondict["refineexcludename"],
nim_hdr,
xsize,
istext=optiondict["textio"],
valslist=optiondict["refineexcludevals"],
maskname="refine exclude",
)
internalrefineexcludemask = therefineexcludemask.reshape(numspatiallocs)
if tide_stats.getmasksize(internalrefineexcludemask) == numspatiallocs:
raise ValueError("ERROR: the refine exclude mask does not leave any voxels - exiting")
tide_util.logmem("after setting masks")
# read or make a mask of where to calculate the correlations
tide_util.logmem("before selecting valid voxels")
threshval = tide_stats.getfracvals(fmri_data[:, :], [0.98])[0] / 25.0
LGR.info("constructing correlation mask")
if optiondict["corrmaskincludename"] is not None:
thecorrmask = readamask(
optiondict["corrmaskincludename"],
nim_hdr,
xsize,
istext=optiondict["textio"],
valslist=optiondict["corrmaskincludevals"],
maskname="correlation",
)
corrmask = np.uint16(np.where(thecorrmask > 0, 1, 0).reshape(numspatiallocs))
else:
# check to see if the data has been demeaned
meanim = np.mean(fmri_data, axis=1)
stdim = np.std(fmri_data, axis=1)
if fileiscifti:
corrmask = np.uint(nim_data[:, 0] * 0 + 1)
else:
if np.mean(stdim) < np.mean(meanim):
LGR.info("generating correlation mask from mean image")
corrmask = np.uint16(masking.compute_epi_mask(nim).dataobj.reshape(numspatiallocs))
else:
LGR.info("generating correlation mask from std image")
corrmask = np.uint16(
tide_stats.makemask(stdim, threshpct=optiondict["corrmaskthreshpct"])
)
if tide_stats.getmasksize(corrmask) == 0:
raise ValueError("ERROR: there are no voxels in the correlation mask - exiting")
optiondict["corrmasksize"] = tide_stats.getmasksize(corrmask)
if internalrefineincludemask is not None:
if internalrefineexcludemask is not None:
if (
tide_stats.getmasksize(
corrmask * internalrefineincludemask * (1 - internalrefineexcludemask)
)
== 0
):
raise ValueError(
"ERROR: the refine include and exclude masks not leave any voxels in the corrmask - exiting"
)
else:
if tide_stats.getmasksize(corrmask * internalrefineincludemask) == 0:
raise ValueError(
"ERROR: the refine include mask does not leave any voxels in the corrmask - exiting"
)
else:
if internalrefineexcludemask is not None:
if tide_stats.getmasksize(corrmask * (1 - internalrefineexcludemask)) == 0:
raise ValueError(
"ERROR: the refine exclude mask does not leave any voxels in the corrmask - exiting"
)
if optiondict["nothresh"]:
corrmask *= 0
corrmask += 1
threshval = -10000000.0
if optiondict["savecorrmask"] and not (fileiscifti or optiondict["textio"]):
theheader = copy.deepcopy(nim_hdr)
theheader["dim"][0] = 3
theheader["dim"][4] = 1
if optiondict["bidsoutput"]:
savename = f"{outputname}_desc-processed_mask"
else:
savename = f"{outputname}_corrmask"
tide_io.savetonifti(corrmask.reshape(xsize, ysize, numslices), theheader, savename)
LGR.verbose(f"image threshval = {threshval}")
validvoxels = np.where(corrmask > 0)[0]
numvalidspatiallocs = np.shape(validvoxels)[0]
LGR.info(f"validvoxels shape = {numvalidspatiallocs}")
fmri_data_valid = fmri_data[validvoxels, :] + 0.0
LGR.info(f"original size = {np.shape(fmri_data)}, trimmed size = {np.shape(fmri_data_valid)}")
if internalglobalmeanincludemask is not None:
internalglobalmeanincludemask_valid = 1.0 * internalglobalmeanincludemask[validvoxels]
del internalglobalmeanincludemask
LGR.info(
"internalglobalmeanincludemask_valid has size: "
f"{internalglobalmeanincludemask_valid.size}"
)
else:
internalglobalmeanincludemask_valid = None
if internalglobalmeanexcludemask is not None:
internalglobalmeanexcludemask_valid = 1.0 * internalglobalmeanexcludemask[validvoxels]
del internalglobalmeanexcludemask
LGR.info(
"internalglobalmeanexcludemask_valid has size: "
f"{internalglobalmeanexcludemask_valid.size}"
)
else:
internalglobalmeanexcludemask_valid = None
if internalrefineincludemask is not None:
internalrefineincludemask_valid = 1.0 * internalrefineincludemask[validvoxels]
del internalrefineincludemask
LGR.info(
"internalrefineincludemask_valid has size: " f"{internalrefineincludemask_valid.size}"
)
else:
internalrefineincludemask_valid = None
if internalrefineexcludemask is not None:
internalrefineexcludemask_valid = 1.0 * internalrefineexcludemask[validvoxels]
del internalrefineexcludemask
LGR.info(
"internalrefineexcludemask_valid has size: " f"{internalrefineexcludemask_valid.size}"
)
else:
internalrefineexcludemask_valid = None
tide_util.logmem("after selecting valid voxels")
# move fmri_data_valid into shared memory
if optiondict["sharedmem"]:
LGR.info("moving fmri data to shared memory")
TimingLGR.info("Start moving fmri_data to shared memory")
numpy2shared_func = addmemprofiling(
numpy2shared, optiondict["memprofile"], "before fmri data move"
)
fmri_data_valid = numpy2shared_func(fmri_data_valid, rt_floatset)
TimingLGR.info("End moving fmri_data to shared memory")
# get rid of memory we aren't using
tide_util.logmem("before purging full sized fmri data")
meanvalue = np.mean(
nim_data.reshape((numspatiallocs, timepoints))[:, validstart : validend + 1],
axis=1,
)
del fmri_data
del nim_data
gc.collect()
tide_util.logmem("after purging full sized fmri data")
# filter out motion regressors here
if optiondict["motionfilename"] is not None:
LGR.info("regressing out motion")
TimingLGR.info("Motion filtering start")
(motionregressors, motionregressorlabels, fmri_data_valid,) = tide_glmpass.motionregress(
optiondict["motionfilename"],
fmri_data_valid,
fmritr,
motstart=validstart,
motend=validend + 1,
position=optiondict["mot_pos"],
deriv=optiondict["mot_deriv"],
derivdelayed=optiondict["mot_delayderiv"],
)
TimingLGR.info(
"Motion filtering end",
{
"message2": fmri_data_valid.shape[0],
"message3": "voxels",
},
)
if optiondict["bidsoutput"]:
tide_io.writebidstsv(
f"{outputname}_desc-orthogonalizedmotion_timeseries",
motionregressors,
1.0 / fmritr,
columns=motionregressorlabels,
append=True,
)
else:
tide_io.writenpvecs(motionregressors, f"{outputname}_orthogonalizedmotion.txt")
if optiondict["memprofile"]:
memcheckpoint("...done")
else:
tide_util.logmem("after motion glm filter")
if optiondict["savemotionfiltered"]:
outfmriarray = np.zeros((numspatiallocs, validtimepoints), dtype=rt_floattype)
outfmriarray[validvoxels, :] = fmri_data_valid[:, :]
if optiondict["textio"]:
tide_io.writenpvecs(
outfmriarray.reshape((numspatiallocs, validtimepoints)),
f"{outputname}_motionfiltered.txt",
)
else:
if optiondict["bidsoutput"]:
savename = f"{outputname}_desc-motionfiltered"
else:
savename = f"{outputname}_motionfiltered"
tide_io.savetonifti(
outfmriarray.reshape((xsize, ysize, numslices, validtimepoints)),
nim_hdr,
savename,
)
# read in the timecourse to resample
TimingLGR.info("Start of reference prep")
if filename is None:
LGR.info("no regressor file specified - will use the global mean regressor")
optiondict["useglobalref"] = True
else:
optiondict["useglobalref"] = False
# calculate the global mean whether we intend to use it or not
meanfreq = 1.0 / fmritr
meanperiod = 1.0 * fmritr
meanstarttime = 0.0
meanvec, meanmask = getglobalsignal(
fmri_data_valid,
optiondict,
includemask=internalglobalmeanincludemask_valid,
excludemask=internalglobalmeanexcludemask_valid,
pcacomponents=optiondict["globalpcacomponents"],
)
# now set the regressor that we'll use
if optiondict["useglobalref"]:
LGR.info("using global mean as probe regressor")
inputfreq = meanfreq
inputperiod = meanperiod
inputstarttime = meanstarttime
inputvec = meanvec
fullmeanmask = np.zeros(numspatiallocs, dtype=rt_floattype)
fullmeanmask[validvoxels] = meanmask[:]
if optiondict["bidsoutput"]:
savename = f"{outputname}_desc-globalmean_mask"
else:
savename = f"{outputname}_meanmask"
if fileiscifti:
theheader = copy.deepcopy(nim_hdr)
timeindex = theheader["dim"][0] - 1
spaceindex = theheader["dim"][0]
theheader["dim"][timeindex] = 1
theheader["dim"][spaceindex] = numspatiallocs
tide_io.savetocifti(
fullmeanmask,
cifti_hdr,
theheader,
savename,
isseries=False,
names=["meanmask"],
)
elif optiondict["textio"]:
tide_io.writenpvecs(
fullmeanmask,
savename + ".txt",
)
else:
theheader = copy.deepcopy(nim_hdr)
theheader["dim"][0] = 3
theheader["dim"][4] = 1
tide_io.savetonifti(
fullmeanmask.reshape((xsize, ysize, numslices)), theheader, savename
)
optiondict["preprocskip"] = 0
else:
LGR.info(f"using externally supplied probe regressor {filename}")
(
fileinputfreq,
filestarttime,
dummy,
inputvec,
dummy,
dummy,
) = tide_io.readvectorsfromtextfile(filename, onecol=True)
inputfreq = optiondict["inputfreq"]
inputstarttime = optiondict["inputstarttime"]
if inputfreq is None:
if fileinputfreq is not None:
inputfreq = fileinputfreq
else:
inputfreq = 1.0 / fmritr
LGR.warning(f"no regressor frequency specified - defaulting to {inputfreq} (1/tr)")
if inputstarttime is None:
if filestarttime is not None:
inputstarttime = filestarttime
else:
LGR.warning("no regressor start time specified - defaulting to 0.0")
inputstarttime = 0.0
inputperiod = 1.0 / inputfreq
# inputvec = tide_io.readvec(filename)
numreference = len(inputvec)
optiondict["inputfreq"] = inputfreq
optiondict["inputstarttime"] = inputstarttime
LGR.info(
"Regressor start time, end time, and step: {:.3f}, {:.3f}, {:.3f}".format(
-inputstarttime, inputstarttime + numreference * inputperiod, inputperiod
)
)
LGR.verbose("Input vector")
LGR.verbose(f"length: {len(inputvec)}")
LGR.verbose(f"input freq: {inputfreq}")
LGR.verbose(f"input start time: {inputstarttime:.3f}")
if not optiondict["useglobalref"]:
globalcorrx, globalcorry, dummy, dummy = tide_corr.arbcorr(
meanvec, meanfreq, inputvec, inputfreq, start2=inputstarttime
)
synctime = globalcorrx[np.argmax(globalcorry)]
if optiondict["autosync"]:
optiondict["offsettime"] = -synctime
optiondict["offsettime_total"] = synctime
else:
synctime = 0.0
LGR.info(f"synctime is {synctime}")
reference_x = np.arange(0.0, numreference) * inputperiod - (
inputstarttime - optiondict["offsettime"]
)
LGR.info(f"total probe regressor offset is {inputstarttime + optiondict['offsettime']}")
# Print out initial information
LGR.verbose(f"there are {numreference} points in the original regressor")
LGR.verbose(f"the timepoint spacing is {1.0 / inputfreq}")
LGR.verbose(f"the input timecourse start time is {inputstarttime}")
# generate the time axes
fmrifreq = 1.0 / fmritr
optiondict["fmrifreq"] = fmrifreq
skiptime = fmritr * (optiondict["preprocskip"])
LGR.info(f"first fMRI point is at {skiptime} seconds relative to time origin")
initial_fmri_x = np.arange(0.0, validtimepoints) * fmritr + skiptime
os_fmri_x = (
np.arange(
0.0,
validtimepoints * optiondict["oversampfactor"] - (optiondict["oversampfactor"] - 1),
)
* oversamptr
+ skiptime
)
LGR.verbose(f"os_fmri_x dim-0 shape: {np.shape(os_fmri_x)[0]}")
LGR.verbose(f"initial_fmri_x dim-0 shape: {np.shape(initial_fmri_x)[0]}")
# generate the comparison regressor from the input timecourse
# correct the output time points
# check for extrapolation
if os_fmri_x[0] < reference_x[0]:
LGR.warning(
f"WARNING: extrapolating {os_fmri_x[0] - reference_x[0]} "
"seconds of data at beginning of timecourse"
)
if os_fmri_x[-1] > reference_x[-1]:
LGR.warning(
f"WARNING: extrapolating {os_fmri_x[-1] - reference_x[-1]} "
"seconds of data at end of timecourse"
)
# invert the regressor if necessary
if optiondict["invertregressor"]:
invertfac = -1.0
else:
invertfac = 1.0
# detrend the regressor if necessary
if optiondict["detrendorder"] > 0:
reference_y = invertfac * tide_fit.detrend(
inputvec[0:numreference],
order=optiondict["detrendorder"],
demean=optiondict["dodemean"],
)
else:
reference_y = invertfac * (inputvec[0:numreference] - np.mean(inputvec[0:numreference]))
# write out the reference regressor prior to filtering
if optiondict["bidsoutput"]:
tide_io.writebidstsv(
f"{outputname}_desc-initialmovingregressor_timeseries",
reference_y,
inputfreq,
starttime=inputstarttime,
columns=["prefilt"],
append=False,
)
else:
tide_io.writenpvecs(reference_y, f"{outputname}_reference_origres_prefilt.txt")
# band limit the regressor if that is needed
LGR.info(f"filtering to {theprefilter.gettype()} band")
(
optiondict["lowerstop"],
optiondict["lowerpass"],
optiondict["upperpass"],
optiondict["upperstop"],
) = theprefilter.getfreqs()
reference_y_classfilter = theprefilter.apply(inputfreq, reference_y)
if optiondict["negativegradregressor"]:
reference_y = -np.gradient(reference_y_classfilter)
else:
reference_y = reference_y_classfilter
# write out the reference regressor used
if optiondict["bidsoutput"]:
tide_io.writebidstsv(
f"{outputname}_desc-initialmovingregressor_timeseries",
tide_math.stdnormalize(reference_y),
inputfreq,
starttime=inputstarttime,
columns=["postfilt"],
append=True,
)
else:
tide_io.writenpvecs(
tide_math.stdnormalize(reference_y), f"{outputname}_reference_origres.txt"
)
# filter the input data for antialiasing
if optiondict["antialias"]:
LGR.debug("applying trapezoidal antialiasing filter")
reference_y_filt = tide_filt.dolptrapfftfilt(
inputfreq,
0.25 * fmrifreq,
0.5 * fmrifreq,
reference_y,
padlen=int(inputfreq * optiondict["padseconds"]),
debug=optiondict["debug"],
)
reference_y = rt_floatset(reference_y_filt.real)
warnings.filterwarnings("ignore", "Casting*")
if optiondict["fakerun"]:
return
# generate the resampled reference regressors
oversampfreq = optiondict["oversampfactor"] / fmritr
if optiondict["detrendorder"] > 0:
resampnonosref_y = tide_fit.detrend(
tide_resample.doresample(
reference_x,
reference_y,
initial_fmri_x,
padlen=int(inputfreq * optiondict["padseconds"]),
method=optiondict["interptype"],
debug=optiondict["debug"],
),
order=optiondict["detrendorder"],
demean=optiondict["dodemean"],
)
resampref_y = tide_fit.detrend(
tide_resample.doresample(
reference_x,
reference_y,
os_fmri_x,
padlen=int(oversampfreq * optiondict["padseconds"]),
method=optiondict["interptype"],
debug=optiondict["debug"],
),
order=optiondict["detrendorder"],
demean=optiondict["dodemean"],
)
else:
resampnonosref_y = tide_resample.doresample(
reference_x,
reference_y,
initial_fmri_x,
padlen=int(inputfreq * optiondict["padseconds"]),
method=optiondict["interptype"],
)
resampref_y = tide_resample.doresample(
reference_x,
reference_y,
os_fmri_x,
padlen=int(oversampfreq * optiondict["padseconds"]),
method=optiondict["interptype"],
)
LGR.info(
f"{len(os_fmri_x)} "
f"{len(resampref_y)} "
f"{len(initial_fmri_x)} "
f"{len(resampnonosref_y)}"
)
previousnormoutputdata = resampnonosref_y + 0.0
# prepare the temporal mask
if optiondict["tmaskname"] is not None:
tmask_y = maketmask(optiondict["tmaskname"], reference_x, rt_floatset(reference_y))
tmaskos_y = tide_resample.doresample(
reference_x, tmask_y, os_fmri_x, method=optiondict["interptype"]
)
if optiondict["bidsoutput"]:
tide_io.writenpvecs(tmask_y, f"{outputname}_temporalmask.txt")
else:
tide_io.writenpvecs(tmask_y, f"{outputname}_temporalmask.txt")
resampnonosref_y *= tmask_y
thefit, R = tide_fit.mlregress(tmask_y, resampnonosref_y)
resampnonosref_y -= thefit[0, 1] * tmask_y
resampref_y *= tmaskos_y
thefit, R = tide_fit.mlregress(tmaskos_y, resampref_y)
resampref_y -= thefit[0, 1] * tmaskos_y
nonosrefname = "_reference_fmrires_pass1.txt"
osrefname = "_reference_resampres_pass1.txt"
(
optiondict["kurtosis_reference_pass1"],
optiondict["kurtosisz_reference_pass1"],
optiondict["kurtosisp_reference_pass1"],
) = tide_stats.kurtosisstats(resampref_y)
if optiondict["bidsoutput"]:
if optiondict["bidsoutput"]:
tide_io.writebidstsv(
f"{outputname}_desc-movingregressor_timeseries",
tide_math.stdnormalize(resampnonosref_y),
1.0 / fmritr,
columns=["pass1"],
append=False,
)
tide_io.writebidstsv(
f"{outputname}_desc-oversampledmovingregressor_timeseries",
tide_math.stdnormalize(resampref_y),
oversampfreq,
columns=["pass1"],
append=False,
)
else:
tide_io.writenpvecs(tide_math.stdnormalize(resampnonosref_y), outputname + nonosrefname)
tide_io.writenpvecs(tide_math.stdnormalize(resampref_y), outputname + osrefname)
TimingLGR.info("End of reference prep")
corrtr = oversamptr
LGR.verbose(f"corrtr={corrtr}")
# initialize the Correlator
theCorrelator = tide_classes.Correlator(
Fs=oversampfreq,
ncprefilter=theprefilter,
negativegradient=optiondict["negativegradient"],
detrendorder=optiondict["detrendorder"],
windowfunc=optiondict["windowfunc"],
corrweighting=optiondict["corrweighting"],
corrpadding=optiondict["zeropadding"],
)
theCorrelator.setreftc(
np.zeros((optiondict["oversampfactor"] * validtimepoints), dtype=np.float64)
)
corrorigin = theCorrelator.similarityfuncorigin
dummy, corrscale, dummy = theCorrelator.getfunction(trim=False)
lagmininpts = int((-optiondict["lagmin"] / corrtr) - 0.5)
lagmaxinpts = int((optiondict["lagmax"] / corrtr) + 0.5)
if (lagmaxinpts + lagmininpts) < 3:
raise ValueError(
"correlation search range is too narrow - decrease lagmin, increase lagmax, or increase oversample factor"
)
theCorrelator.setlimits(lagmininpts, lagmaxinpts)
dummy, trimmedcorrscale, dummy = theCorrelator.getfunction()
# initialize the MutualInformationator
theMutualInformationator = tide_classes.MutualInformationator(
Fs=oversampfreq,
smoothingtime=optiondict["smoothingtime"],
ncprefilter=theprefilter,
negativegradient=optiondict["negativegradient"],
detrendorder=optiondict["detrendorder"],
windowfunc=optiondict["windowfunc"],
madnorm=False,
lagmininpts=lagmininpts,
lagmaxinpts=lagmaxinpts,
debug=optiondict["debug"],
)
theMutualInformationator.setreftc(
np.zeros((optiondict["oversampfactor"] * validtimepoints), dtype=np.float64)
)
nummilags = theMutualInformationator.similarityfunclen
theMutualInformationator.setlimits(lagmininpts, lagmaxinpts)
dummy, trimmedmiscale, dummy = theMutualInformationator.getfunction()
LGR.verbose(f"trimmedcorrscale length: {len(trimmedcorrscale)}")
LGR.verbose(f"trimmedmiscale length: {len(trimmedmiscale)} {nummilags}")
LGR.verbose(f"corrorigin at point {corrorigin} {corrscale[corrorigin]}")
LGR.verbose(
f"corr range from {corrorigin - lagmininpts} ({corrscale[corrorigin - lagmininpts]}) "
f"to {corrorigin + lagmaxinpts} ({corrscale[corrorigin + lagmaxinpts]})"
)
if optiondict["savecorrtimes"]:
if optiondict["bidsoutput"]:
tide_io.writenpvecs(trimmedcorrscale, f"{outputname}_corrtimes.txt")
tide_io.writenpvecs(trimmedmiscale, f"{outputname}_mitimes.txt")
else:
tide_io.writenpvecs(trimmedcorrscale, f"{outputname}_corrtimes.txt")
tide_io.writenpvecs(trimmedmiscale, f"{outputname}_mitimes.txt")
# allocate all of the data arrays
tide_util.logmem("before main array allocation")
if optiondict["textio"]:
nativespaceshape = xsize
else:
if fileiscifti:
nativespaceshape = (1, 1, 1, 1, numspatiallocs)
else:
nativespaceshape = (xsize, ysize, numslices)
internalspaceshape = numspatiallocs
internalvalidspaceshape = numvalidspatiallocs
meanval = np.zeros(internalvalidspaceshape, dtype=rt_floattype)
lagtimes = np.zeros(internalvalidspaceshape, dtype=rt_floattype)
lagstrengths = np.zeros(internalvalidspaceshape, dtype=rt_floattype)
lagsigma = np.zeros(internalvalidspaceshape, dtype=rt_floattype)
fitmask = np.zeros(internalvalidspaceshape, dtype="uint16")
failreason = np.zeros(internalvalidspaceshape, dtype="uint32")
R2 = np.zeros(internalvalidspaceshape, dtype=rt_floattype)
outmaparray = np.zeros(internalspaceshape, dtype=rt_floattype)
tide_util.logmem("after main array allocation")
corroutlen = np.shape(trimmedcorrscale)[0]
if optiondict["textio"]:
nativecorrshape = (xsize, corroutlen)
else:
if fileiscifti:
nativecorrshape = (1, 1, 1, corroutlen, numspatiallocs)
else:
nativecorrshape = (xsize, ysize, numslices, corroutlen)
internalcorrshape = (numspatiallocs, corroutlen)
internalvalidcorrshape = (numvalidspatiallocs, corroutlen)
LGR.info(
f"allocating memory for correlation arrays {internalcorrshape} {internalvalidcorrshape}"
)
if optiondict["sharedmem"]:
corrout, dummy, dummy = allocshared(internalvalidcorrshape, rt_floatset)
gaussout, dummy, dummy = allocshared(internalvalidcorrshape, rt_floatset)
windowout, dummy, dummy = allocshared(internalvalidcorrshape, rt_floatset)
outcorrarray, dummy, dummy = allocshared(internalcorrshape, rt_floatset)
else:
corrout = np.zeros(internalvalidcorrshape, dtype=rt_floattype)
gaussout = np.zeros(internalvalidcorrshape, dtype=rt_floattype)
windowout = np.zeros(internalvalidcorrshape, dtype=rt_floattype)
outcorrarray = np.zeros(internalcorrshape, dtype=rt_floattype)
tide_util.logmem("after correlation array allocation")
if optiondict["textio"]:
nativefmrishape = (xsize, np.shape(initial_fmri_x)[0])
else:
if fileiscifti:
nativefmrishape = (1, 1, 1, np.shape(initial_fmri_x)[0], numspatiallocs)
else:
nativefmrishape = (xsize, ysize, numslices, np.shape(initial_fmri_x)[0])
internalfmrishape = (numspatiallocs, np.shape(initial_fmri_x)[0])
internalvalidfmrishape = (numvalidspatiallocs, np.shape(initial_fmri_x)[0])
if optiondict["sharedmem"]:
lagtc, dummy, dummy = allocshared(internalvalidfmrishape, rt_floatset)
else:
lagtc = np.zeros(internalvalidfmrishape, dtype=rt_floattype)
tide_util.logmem("after lagtc array allocation")
if optiondict["passes"] > 1 or optiondict["convergencethresh"] is not None:
if optiondict["sharedmem"]:
shiftedtcs, dummy, dummy = allocshared(internalvalidfmrishape, rt_floatset)
weights, dummy, dummy = allocshared(internalvalidfmrishape, rt_floatset)
else:
shiftedtcs = np.zeros(internalvalidfmrishape, dtype=rt_floattype)
weights = np.zeros(internalvalidfmrishape, dtype=rt_floattype)
tide_util.logmem("after refinement array allocation")
if optiondict["sharedmem"]:
outfmriarray, dummy, dummy = allocshared(internalfmrishape, rt_floatset)
else:
outfmriarray = np.zeros(internalfmrishape, dtype=rt_floattype)
# prepare for fast resampling
padtime = (
max((-optiondict["lagmin"], optiondict["lagmax"]))
+ 30.0
+ np.abs(optiondict["offsettime"])
)
LGR.info(f"setting up fast resampling with padtime = {padtime}")
numpadtrs = int(padtime // fmritr)
padtime = fmritr * numpadtrs
genlagtc = tide_resample.FastResampler(reference_x, reference_y, padtime=padtime)
# cycle over all voxels
refine = True
LGR.verbose(f"refine is set to {refine}")
optiondict["edgebufferfrac"] = max(
[optiondict["edgebufferfrac"], 2.0 / np.shape(corrscale)[0]]
)
LGR.verbose(f"edgebufferfrac set to {optiondict['edgebufferfrac']}")
# intitialize the correlation fitter
thefitter = tide_classes.SimilarityFunctionFitter(
lagmod=optiondict["lagmod"],
lthreshval=optiondict["lthreshval"],
uthreshval=optiondict["uthreshval"],
bipolar=optiondict["bipolar"],
lagmin=optiondict["lagmin"],
lagmax=optiondict["lagmax"],
absmaxsigma=optiondict["absmaxsigma"],
absminsigma=optiondict["absminsigma"],
debug=optiondict["debug"],
peakfittype=optiondict["peakfittype"],
searchfrac=optiondict["searchfrac"],
enforcethresh=optiondict["enforcethresh"],
hardlimit=optiondict["hardlimit"],
)
# Preprocessing - echo cancellation
if optiondict["echocancel"]:
LGR.info("\n\nEcho cancellation")
TimingLGR.info("Echo cancellation start")
calcsimilaritypass_func = addmemprofiling(
tide_calcsimfunc.correlationpass,
optiondict["memprofile"],
"before correlationpass",
)
referencetc = tide_math.corrnormalize(
resampref_y,
detrendorder=optiondict["detrendorder"],
windowfunc=optiondict["windowfunc"],
)
(voxelsprocessed_echo, theglobalmaxlist, trimmedcorrscale,) = calcsimilaritypass_func(
fmri_data_valid[:, :],
referencetc,
theCorrelator,
initial_fmri_x,
os_fmri_x,
lagmininpts,
lagmaxinpts,
corrout,
meanval,
nprocs=optiondict["nprocs_calcsimilarity"],
alwaysmultiproc=optiondict["alwaysmultiproc"],
oversampfactor=optiondict["oversampfactor"],
interptype=optiondict["interptype"],
showprogressbar=optiondict["showprogressbar"],
chunksize=optiondict["mp_chunksize"],
rt_floatset=rt_floatset,
rt_floattype=rt_floattype,
)
for i in range(len(theglobalmaxlist)):
theglobalmaxlist[i] = corrscale[theglobalmaxlist[i]]
if optiondict["bidsoutput"]:
namesuffix = "_desc-globallag_hist"
else:
namesuffix = "_globallaghist_echocancel"
tide_stats.makeandsavehistogram(
np.asarray(theglobalmaxlist),
len(corrscale),
0,
outputname + namesuffix,
displaytitle="lagtime histogram",
therange=(corrscale[0], corrscale[-1]),
refine=False,
dictvarname="globallaghist_preechocancel",
saveasbids=optiondict["bidsoutput"],
append=False,
thedict=optiondict,
)
# Now find and regress out the echo
echooffset, echoratio = tide_stats.echoloc(np.asarray(theglobalmaxlist), len(corrscale))
LGR.info(f"Echooffset, echoratio: {echooffset} {echoratio}")
echoremovedtc, echofit, echoR = echocancel(
resampref_y, echooffset, oversamptr, outputname, numpadtrs
)
optiondict["echooffset"] = echooffset
optiondict["echoratio"] = echoratio
optiondict["echofit"] = [echofit[0, 0], echofit[0, 1]]
optiondict["echofitR"] = echoR
resampref_y = echoremovedtc
TimingLGR.info(
"Echo cancellation calculation end",
{
"message2": voxelsprocessed_echo,
"message3": "voxels",
},
)
# --------------------- Main pass loop ---------------------
# loop over all passes
stoprefining = False
refinestopreason = "passesreached"
if optiondict["convergencethresh"] is None:
numpasses = optiondict["passes"]
else:
numpasses = np.max([optiondict["passes"], optiondict["maxpasses"]])
for thepass in range(1, numpasses + 1):
if stoprefining:
break
# initialize the pass
if optiondict["passes"] > 1:
LGR.info("\n\n*********************")
LGR.info(f"Pass number {thepass}")
referencetc = tide_math.corrnormalize(
resampref_y,
detrendorder=optiondict["detrendorder"],
windowfunc=optiondict["windowfunc"],
)
# Step -1 - check the regressor for periodic components in the passband
dolagmod = True
doreferencenotch = True
if optiondict["respdelete"]:
resptracker = tide_classes.FrequencyTracker(nperseg=64)
thetimes, thefreqs = resptracker.track(resampref_y, 1.0 / oversamptr)
if optiondict["bidsoutput"]:
tide_io.writevec(thefreqs, f"{outputname}_peakfreaks_pass{thepass}.txt")
else:
tide_io.writevec(thefreqs, f"{outputname}_peakfreaks_pass{thepass}.txt")
resampref_y = resptracker.clean(resampref_y, 1.0 / oversamptr, thetimes, thefreqs)
if optiondict["bidsoutput"]:
tide_io.writevec(resampref_y, f"{outputname}_respfilt_pass{thepass}.txt")
else:
tide_io.writevec(resampref_y, f"{outputname}_respfilt_pass{thepass}.txt")
referencetc = tide_math.corrnormalize(
resampref_y,
detrendorder=optiondict["detrendorder"],
windowfunc=optiondict["windowfunc"],
)
if optiondict["check_autocorrelation"]:
LGR.info("checking reference regressor autocorrelation properties")
optiondict["lagmod"] = 1000.0
lagindpad = corrorigin - 2 * np.max((lagmininpts, lagmaxinpts))
acmininpts = lagmininpts + lagindpad
acmaxinpts = lagmaxinpts + lagindpad
theCorrelator.setreftc(referencetc)
theCorrelator.setlimits(acmininpts, acmaxinpts)
thexcorr, accheckcorrscale, dummy = theCorrelator.run(resampref_y)
thefitter.setcorrtimeaxis(accheckcorrscale)
(
maxindex,
maxlag,
maxval,
acwidth,
maskval,
peakstart,
peakend,
thisfailreason,
) = tide_simfuncfit.onesimfuncfit(
thexcorr,
thefitter,
despeckle_thresh=optiondict["despeckle_thresh"],
lthreshval=optiondict["lthreshval"],
fixdelay=optiondict["fixdelay"],
rt_floatset=rt_floatset,
rt_floattype=rt_floattype,
)
outputarray = np.asarray([accheckcorrscale, thexcorr])
if optiondict["bidsoutput"]:
tide_io.writebidstsv(
f"{outputname}_desc-autocorr_timeseries",
thexcorr,
1.0 / (accheckcorrscale[1] - accheckcorrscale[0]),
starttime=accheckcorrscale[0],
columns=[f"pass{thepass}"],
append=(thepass > 1),
)
else:
tide_io.writenpvecs(
outputarray,
f"{outputname}_referenceautocorr_pass" + str(thepass) + ".txt",
)
thelagthresh = np.max((abs(optiondict["lagmin"]), abs(optiondict["lagmax"])))
theampthresh = 0.1
LGR.info(
f"searching for sidelobes with amplitude > {theampthresh} "
f"with abs(lag) < {thelagthresh} s"
)
sidelobetime, sidelobeamp = tide_corr.check_autocorrelation(
accheckcorrscale,
thexcorr,
acampthresh=theampthresh,
aclagthresh=thelagthresh,
detrendorder=optiondict["detrendorder"],
)
optiondict["acwidth"] = acwidth + 0.0
optiondict["absmaxsigma"] = acwidth * 10.0
passsuffix = "_pass" + str(thepass)
if sidelobetime is not None:
optiondict["acsidelobelag" + passsuffix] = sidelobetime
optiondict["despeckle_thresh"] = np.max(
[optiondict["despeckle_thresh"], sidelobetime / 2.0]
)
optiondict["acsidelobeamp" + passsuffix] = sidelobeamp
LGR.warning(
f"\n\nWARNING: check_autocorrelation found bad sidelobe at {sidelobetime} "
f"seconds ({1.0 / sidelobetime} Hz)..."
)
if optiondict["bidsoutput"]:
tide_io.writenpvecs(
np.array([sidelobetime]),
f"{outputname}_autocorr_sidelobetime" + passsuffix + ".txt",
)
else:
tide_io.writenpvecs(
np.array([sidelobetime]),
f"{outputname}_autocorr_sidelobetime" + passsuffix + ".txt",
)
if optiondict["fix_autocorrelation"]:
LGR.info("Removing sidelobe")
if dolagmod:
LGR.info("subjecting lag times to modulus")
optiondict["lagmod"] = sidelobetime / 2.0
if doreferencenotch:
LGR.info("removing spectral component at sidelobe frequency")
acstopfreq = 1.0 / sidelobetime
acfixfilter = tide_filt.NoncausalFilter(
transferfunc=optiondict["transferfunc"],
debug=optiondict["debug"],
)
acfixfilter.settype("arb_stop")
acfixfilter.setfreqs(
acstopfreq * 0.9,
acstopfreq * 0.95,
acstopfreq * 1.05,
acstopfreq * 1.1,
)
cleaned_resampref_y = tide_math.corrnormalize(
acfixfilter.apply(1.0 / oversamptr, resampref_y),
windowfunc="None",
detrendorder=optiondict["detrendorder"],
)
cleaned_referencetc = tide_math.corrnormalize(
cleaned_resampref_y,
detrendorder=optiondict["detrendorder"],
windowfunc=optiondict["windowfunc"],
)
cleaned_nonosreferencetc = tide_math.stdnormalize(
acfixfilter.apply(fmrifreq, resampnonosref_y)
)
if optiondict["bidsoutput"]:
tide_io.writebidstsv(
f"{outputname}_desc-cleanedreferencefmrires_info",
cleaned_nonosreferencetc,
fmrifreq,
columns=[f"pass{thepass}"],
append=(thepass > 1),
)
tide_io.writebidstsv(
f"{outputname}_desc-cleanedreference_info",
cleaned_referencetc,
1.0 / oversamptr,
columns=[f"pass{thepass}"],
append=(thepass > 1),
)
tide_io.writebidstsv(
f"{outputname}_desc-cleanedresamprefy_info",
cleaned_resampref_y,
1.0 / oversamptr,
columns=[f"pass{thepass}"],
append=(thepass > 1),
)
else:
tide_io.writenpvecs(
cleaned_nonosreferencetc,
f"{outputname}_cleanedreference_fmrires_pass{thepass}.txt",
)
tide_io.writenpvecs(
cleaned_referencetc,
f"{outputname}_cleanedreference_pass{thepass}.txt",
)
tide_io.writenpvecs(
cleaned_resampref_y,
f"{outputname}_cleanedresampref_y_pass{thepass}.txt",
)
else:
cleaned_resampref_y = 1.0 * tide_math.corrnormalize(
resampref_y,
windowfunc="None",
detrendorder=optiondict["detrendorder"],
)
cleaned_referencetc = 1.0 * referencetc
cleaned_nonosreferencetc = 1.0 * resampnonosref_y
else:
LGR.info("no sidelobes found in range")
cleaned_resampref_y = 1.0 * tide_math.corrnormalize(
resampref_y,
windowfunc="None",
detrendorder=optiondict["detrendorder"],
)
cleaned_referencetc = 1.0 * referencetc
cleaned_nonosreferencetc = 1.0 * resampnonosref_y
else:
cleaned_resampref_y = 1.0 * tide_math.corrnormalize(
resampref_y, windowfunc="None", detrendorder=optiondict["detrendorder"]
)
cleaned_referencetc = 1.0 * referencetc
cleaned_nonosreferencetc = 1.0 * resampnonosref_y
# Step 0 - estimate significance
if optiondict["numestreps"] > 0:
TimingLGR.info(f"Significance estimation start, pass {thepass}")
LGR.info(f"\n\nSignificance estimation, pass {thepass}")
LGR.verbose(
"calling getNullDistributionData with args: "
f"{oversampfreq} {fmritr} {corrorigin} {lagmininpts} {lagmaxinpts}"
)
getNullDistributionData_func = addmemprofiling(
tide_nullsimfunc.getNullDistributionDatax,
optiondict["memprofile"],
"before getnulldistristributiondata",
)
if optiondict["checkpoint"]:
if optiondict["bidsoutput"]:
tide_io.writenpvecs(
cleaned_referencetc,
f"{outputname}_cleanedreference_pass" + str(thepass) + ".txt",
)
tide_io.writenpvecs(
cleaned_resampref_y,
f"{outputname}_cleanedresampref_y_pass" + str(thepass) + ".txt",
)
else:
tide_io.writenpvecs(
cleaned_referencetc,
f"{outputname}_cleanedreference_pass" + str(thepass) + ".txt",
)
tide_io.writenpvecs(
cleaned_resampref_y,
f"{outputname}_cleanedresampref_y_pass" + str(thepass) + ".txt",
)
tide_io.writedicttojson(
optiondict,
f"{outputname}_options_pregetnull_pass" + str(thepass) + ".json",
)
theCorrelator.setlimits(lagmininpts, lagmaxinpts)
theCorrelator.setreftc(cleaned_resampref_y)
theMutualInformationator.setlimits(lagmininpts, lagmaxinpts)
theMutualInformationator.setreftc(cleaned_resampref_y)
dummy, trimmedcorrscale, dummy = theCorrelator.getfunction()
thefitter.setcorrtimeaxis(trimmedcorrscale)
corrdistdata = getNullDistributionData_func(
cleaned_resampref_y,
oversampfreq,
theCorrelator,
thefitter,
numestreps=optiondict["numestreps"],
nprocs=optiondict["nprocs_getNullDist"],
alwaysmultiproc=optiondict["alwaysmultiproc"],
showprogressbar=optiondict["showprogressbar"],
chunksize=optiondict["mp_chunksize"],
permutationmethod=optiondict["permutationmethod"],
fixdelay=optiondict["fixdelay"],
fixeddelayvalue=optiondict["fixeddelayvalue"],
rt_floatset=np.float64,
rt_floattype="float64",
)
if optiondict["bidsoutput"]:
tide_io.writebidstsv(
f"{outputname}_desc-corrdistdata_info",
corrdistdata,
1.0,
columns=["pass" + str(thepass)],
append=(thepass > 1),
)
else:
tide_io.writenpvecs(
corrdistdata,
f"{outputname}_corrdistdata_pass" + str(thepass) + ".txt",
)
# calculate percentiles for the crosscorrelation from the distribution data
thepercentiles = np.array([0.95, 0.99, 0.995, 0.999])
thepvalnames = []
for thispercentile in thepercentiles:
thepvalnames.append("{:.3f}".format(1.0 - thispercentile).replace(".", "p"))
pcts, pcts_fit, sigfit = tide_stats.sigFromDistributionData(
corrdistdata,
optiondict["sighistlen"],
thepercentiles,
twotail=optiondict["bipolar"],
nozero=optiondict["nohistzero"],
dosighistfit=optiondict["dosighistfit"],
)
for i in range(len(thepvalnames)):
optiondict[
"p_lt_" + thepvalnames[i] + "_pass" + str(thepass) + "_thresh.txt"
] = pcts[i]
if optiondict["dosighistfit"]:
optiondict[
"p_lt_" + thepvalnames[i] + "_pass" + str(thepass) + "_fitthresh"
] = pcts_fit[i]
optiondict["sigfit"] = sigfit
if optiondict["ampthreshfromsig"]:
if pcts is not None:
LGR.info(
f"setting ampthresh to the p < {1.0 - thepercentiles[0]:.3f} threshhold"
)
optiondict["ampthresh"] = pcts[0]
tide_stats.printthresholds(
pcts,
thepercentiles,
"Crosscorrelation significance thresholds from data:",
)
if optiondict["dosighistfit"]:
tide_stats.printthresholds(
pcts_fit,
thepercentiles,
"Crosscorrelation significance thresholds from fit:",
)
if optiondict["bidsoutput"]:
namesuffix = "_desc-nullsimfunc_hist"
else:
namesuffix = "_nullsimfunchist_pass" + str(thepass)
tide_stats.makeandsavehistogram(
corrdistdata,
optiondict["sighistlen"],
0,
outputname + namesuffix,
displaytitle="Null correlation histogram, pass" + str(thepass),
refine=False,
dictvarname="nullsimfunchist_pass" + str(thepass),
saveasbids=optiondict["bidsoutput"],
therange=(0.0, 1.0),
append=(thepass > 1),
thedict=optiondict,
)
else:
LGR.info("leaving ampthresh unchanged")
del corrdistdata
TimingLGR.info(
f"Significance estimation end, pass {thepass}",
{
"message2": optiondict["numestreps"],
"message3": "repetitions",
},
)
# Step 1 - Correlation step
if optiondict["similaritymetric"] == "mutualinfo":
similaritytype = "Mutual information"
elif optiondict["similaritymetric"] == "correlation":
similaritytype = "Correlation"
else:
similaritytype = "MI enhanced correlation"
LGR.info(f"\n\n{similaritytype} calculation, pass {thepass}")
TimingLGR.info(f"{similaritytype} calculation start, pass {thepass}")
calcsimilaritypass_func = addmemprofiling(
tide_calcsimfunc.correlationpass,
optiondict["memprofile"],
"before correlationpass",
)
if optiondict["similaritymetric"] == "mutualinfo":
theMutualInformationator.setlimits(lagmininpts, lagmaxinpts)
(voxelsprocessed_cp, theglobalmaxlist, trimmedcorrscale,) = calcsimilaritypass_func(
fmri_data_valid[:, :],
cleaned_referencetc,
theMutualInformationator,
initial_fmri_x,
os_fmri_x,
lagmininpts,
lagmaxinpts,
corrout,
meanval,
nprocs=optiondict["nprocs_calcsimilarity"],
alwaysmultiproc=optiondict["alwaysmultiproc"],
oversampfactor=optiondict["oversampfactor"],
interptype=optiondict["interptype"],
showprogressbar=optiondict["showprogressbar"],
chunksize=optiondict["mp_chunksize"],
rt_floatset=rt_floatset,
rt_floattype=rt_floattype,
)
else:
(voxelsprocessed_cp, theglobalmaxlist, trimmedcorrscale,) = calcsimilaritypass_func(
fmri_data_valid[:, :],
cleaned_referencetc,
theCorrelator,
initial_fmri_x,
os_fmri_x,
lagmininpts,
lagmaxinpts,
corrout,
meanval,
nprocs=optiondict["nprocs_calcsimilarity"],
alwaysmultiproc=optiondict["alwaysmultiproc"],
oversampfactor=optiondict["oversampfactor"],
interptype=optiondict["interptype"],
showprogressbar=optiondict["showprogressbar"],
chunksize=optiondict["mp_chunksize"],
rt_floatset=rt_floatset,
rt_floattype=rt_floattype,
)
for i in range(len(theglobalmaxlist)):
theglobalmaxlist[i] = corrscale[theglobalmaxlist[i]]
if optiondict["bidsoutput"]:
namesuffix = "_desc-globallag_hist"
else:
namesuffix = "_globallaghist_pass" + str(thepass)
tide_stats.makeandsavehistogram(
np.asarray(theglobalmaxlist),
len(corrscale),
0,
outputname + namesuffix,
displaytitle="lagtime histogram",
therange=(corrscale[0], corrscale[-1]),
refine=False,
dictvarname="globallaghist_pass" + str(thepass),
saveasbids=optiondict["bidsoutput"],
append=(optiondict["echocancel"] or (thepass > 1)),
thedict=optiondict,
)
if optiondict["checkpoint"]:
outcorrarray[:, :] = 0.0
outcorrarray[validvoxels, :] = corrout[:, :]
if optiondict["textio"]:
tide_io.writenpvecs(
outcorrarray.reshape(nativecorrshape),
f"{outputname}_corrout_prefit_pass" + str(thepass) + ".txt",
)
else:
if optiondict["bidsoutput"]:
savename = f"{outputname}_desc-corroutprefit_pass-" + str(thepass)
else:
savename = f"{outputname}_corrout_prefit_pass" + str(thepass)
tide_io.savetonifti(outcorrarray.reshape(nativecorrshape), theheader, savename)
TimingLGR.info(
f"{similaritytype} calculation end, pass {thepass}",
{
"message2": voxelsprocessed_cp,
"message3": "voxels",
},
)
# Step 1b. Do a peak prefit
if optiondict["similaritymetric"] == "hybrid":
LGR.info(f"\n\nPeak prefit calculation, pass {thepass}")
TimingLGR.info(f"Peak prefit calculation start, pass {thepass}")
peakevalpass_func = addmemprofiling(
tide_peakeval.peakevalpass,
optiondict["memprofile"],
"before peakevalpass",
)
voxelsprocessed_pe, thepeakdict = peakevalpass_func(
fmri_data_valid[:, :],
cleaned_referencetc,
initial_fmri_x,
os_fmri_x,
theMutualInformationator,
trimmedcorrscale,
corrout,
nprocs=optiondict["nprocs_peakeval"],
alwaysmultiproc=optiondict["alwaysmultiproc"],
bipolar=optiondict["bipolar"],
oversampfactor=optiondict["oversampfactor"],
interptype=optiondict["interptype"],
showprogressbar=optiondict["showprogressbar"],
chunksize=optiondict["mp_chunksize"],
rt_floatset=rt_floatset,
rt_floattype=rt_floattype,
)
TimingLGR.info(
f"Peak prefit end, pass {thepass}",
{
"message2": voxelsprocessed_pe,
"message3": "voxels",
},
)
mipeaks = lagtimes * 0.0
for i in range(numvalidspatiallocs):
if len(thepeakdict[str(i)]) > 0:
mipeaks[i] = thepeakdict[str(i)][0][0]
else:
thepeakdict = None
# Step 2 - similarity function fitting and time lag estimation
LGR.info(f"\n\nTime lag estimation pass {thepass}")
TimingLGR.info(f"Time lag estimation start, pass {thepass}")
fitcorr_func = addmemprofiling(
tide_simfuncfit.fitcorr, optiondict["memprofile"], "before fitcorr"
)
thefitter.setfunctype(optiondict["similaritymetric"])
thefitter.setcorrtimeaxis(trimmedcorrscale)
# use initial lags if this is a hybrid fit
if optiondict["similaritymetric"] == "hybrid" and thepeakdict is not None:
initlags = mipeaks
else:
initlags = None
voxelsprocessed_fc = fitcorr_func(
genlagtc,
initial_fmri_x,
lagtc,
trimmedcorrscale,
thefitter,
corrout,
fitmask,
failreason,
lagtimes,
lagstrengths,
lagsigma,
gaussout,
windowout,
R2,
peakdict=thepeakdict,
nprocs=optiondict["nprocs_fitcorr"],
alwaysmultiproc=optiondict["alwaysmultiproc"],
fixdelay=optiondict["fixdelay"],
showprogressbar=optiondict["showprogressbar"],
chunksize=optiondict["mp_chunksize"],
despeckle_thresh=optiondict["despeckle_thresh"],
initiallags=initlags,
rt_floatset=rt_floatset,
rt_floattype=rt_floattype,
)
TimingLGR.info(
f"Time lag estimation end, pass {thepass}",
{
"message2": voxelsprocessed_fc,
"message3": "voxels",
},
)
# Step 2b - Correlation time despeckle
if optiondict["despeckle_passes"] > 0:
LGR.info(f"\n\nCorrelation despeckling pass {thepass}")
LGR.info(f"\tUsing despeckle_thresh = {optiondict['despeckle_thresh']:.3f}")
TimingLGR.info(f"Correlation despeckle start, pass {thepass}")
# find lags that are very different from their neighbors, and refit starting at the median lag for the point
voxelsprocessed_fc_ds = 0
despecklingdone = False
for despecklepass in range(optiondict["despeckle_passes"]):
LGR.info(f"\n\nCorrelation despeckling subpass {despecklepass + 1}")
outmaparray *= 0.0
outmaparray[validvoxels] = eval("lagtimes")[:]
medianlags = ndimage.median_filter(
outmaparray.reshape(nativespaceshape), 3
).reshape(numspatiallocs)
initlags = np.where(
np.abs(outmaparray - medianlags) > optiondict["despeckle_thresh"],
medianlags,
-1000000.0,
)[validvoxels]
if len(initlags) > 0:
if len(np.where(initlags != -1000000.0)[0]) > 0:
voxelsprocessed_thispass = fitcorr_func(
genlagtc,
initial_fmri_x,
lagtc,
trimmedcorrscale,
thefitter,
corrout,
fitmask,
failreason,
lagtimes,
lagstrengths,
lagsigma,
gaussout,
windowout,
R2,
peakdict=thepeakdict,
nprocs=optiondict["nprocs_fitcorr"],
alwaysmultiproc=optiondict["alwaysmultiproc"],
fixdelay=optiondict["fixdelay"],
showprogressbar=optiondict["showprogressbar"],
chunksize=optiondict["mp_chunksize"],
despeckle_thresh=optiondict["despeckle_thresh"],
initiallags=initlags,
rt_floatset=rt_floatset,
rt_floattype=rt_floattype,
)
voxelsprocessed_fc_ds += voxelsprocessed_thispass
optiondict[
"despecklemasksize_pass" + str(thepass) + "_d" + str(despecklepass + 1)
] = voxelsprocessed_thispass
optiondict[
"despecklemaskpct_pass" + str(thepass) + "_d" + str(despecklepass + 1)
] = (100.0 * voxelsprocessed_thispass / optiondict["corrmasksize"])
else:
despecklingdone = True
else:
despecklingdone = True
if despecklingdone:
LGR.info("Nothing left to do! Terminating despeckling")
break
if optiondict["savedespecklemasks"] and thepass == optiondict["passes"]:
theheader = copy.deepcopy(nim_hdr)
theheader["dim"][4] = 1
if optiondict["bidsoutput"]:
savename = f"{outputname}_desc-despeckle_mask"
else:
savename = f"{outputname}_despecklemask"
if not fileiscifti:
theheader["dim"][0] = 3
tide_io.savetonifti(
(
np.where(
np.abs(outmaparray - medianlags) > optiondict["despeckle_thresh"],
medianlags,
0.0,
)
).reshape(nativespaceshape),
theheader,
savename,
)
else:
timeindex = theheader["dim"][0] - 1
spaceindex = theheader["dim"][0]
theheader["dim"][timeindex] = 1
theheader["dim"][spaceindex] = numspatiallocs
tide_io.savetocifti(
(
np.where(
np.abs(outmaparray - medianlags) > optiondict["despeckle_thresh"],
medianlags,
0.0,
)
),
cifti_hdr,
theheader,
savename,
isseries=False,
names=["despecklemask"],
)
LGR.info(
f"\n\n{voxelsprocessed_fc_ds} voxels despeckled in "
f"{optiondict['despeckle_passes']} passes"
)
TimingLGR.info(
f"Correlation despeckle end, pass {thepass}",
{
"message2": voxelsprocessed_fc_ds,
"message3": "voxels",
},
)
# Step 3 - regressor refinement for next pass
if thepass < optiondict["passes"] or optiondict["convergencethresh"] is not None:
LGR.info(f"\n\nRegressor refinement, pass {thepass}")
TimingLGR.info(f"Regressor refinement start, pass {thepass}")
if optiondict["refineoffset"]:
peaklag, peakheight, peakwidth = tide_stats.gethistprops(
lagtimes[np.where(fitmask > 0)],
optiondict["histlen"],
pickleft=optiondict["pickleft"],
peakthresh=optiondict["pickleftthresh"],
)
optiondict["offsettime"] = peaklag
optiondict["offsettime_total"] += peaklag
LGR.info(
f"offset time set to {optiondict['offsettime']:.3f}, "
f"total is {optiondict['offsettime_total']:.3f}"
)
# regenerate regressor for next pass
refineregressor_func = addmemprofiling(
tide_refine.refineregressor,
optiondict["memprofile"],
"before refineregressor",
)
(
voxelsprocessed_rr,
outputdata,
refinemask,
locationfails,
ampfails,
lagfails,
sigmafails,
) = refineregressor_func(
fmri_data_valid,
fmritr,
shiftedtcs,
weights,
thepass,
lagstrengths,
lagtimes,
lagsigma,
fitmask,
R2,
theprefilter,
optiondict,
bipolar=optiondict["bipolar"],
padtrs=numpadtrs,
includemask=internalrefineincludemask_valid,
excludemask=internalrefineexcludemask_valid,
rt_floatset=rt_floatset,
rt_floattype=rt_floattype,
)
optiondict["refinemasksize_pass" + str(thepass)] = voxelsprocessed_rr
optiondict["refinemaskpct_pass" + str(thepass)] = (
100.0 * voxelsprocessed_rr / optiondict["corrmasksize"]
)
optiondict["refinelocationfails_pass" + str(thepass)] = locationfails
optiondict["refineampfails_pass" + str(thepass)] = ampfails
optiondict["refinelagfails_pass" + str(thepass)] = lagfails
optiondict["refinesigmafails_pass" + str(thepass)] = sigmafails
if voxelsprocessed_rr > 0:
normoutputdata = tide_math.stdnormalize(theprefilter.apply(fmrifreq, outputdata))
normunfilteredoutputdata = tide_math.stdnormalize(outputdata)
if optiondict["bidsoutput"]:
tide_io.writebidstsv(
f"{outputname}_desc-refinedmovingregressor_timeseries",
normunfilteredoutputdata,
1.0 / fmritr,
columns=["unfiltered_pass" + str(thepass)],
append=(thepass > 1),
)
tide_io.writebidstsv(
f"{outputname}_desc-refinedmovingregressor_timeseries",
normoutputdata,
1.0 / fmritr,
columns=["filtered_pass" + str(thepass)],
append=True,
)
else:
tide_io.writenpvecs(
normoutputdata,
f"{outputname}_refinedregressor_pass" + str(thepass) + ".txt",
)
tide_io.writenpvecs(
normunfilteredoutputdata,
f"{outputname}_unfilteredrefinedregressor_pass" + str(thepass) + ".txt",
)
# check for convergence
regressormse = mse(normoutputdata, previousnormoutputdata)
optiondict["regressormse_pass" + str(thepass).zfill(2)] = regressormse
LGR.info(f"regressor difference at end of pass {thepass:d} is {regressormse:.6f}")
if optiondict["convergencethresh"] is not None:
if thepass >= optiondict["maxpasses"]:
LGR.info("refinement ended (maxpasses reached)")
stoprefining = True
refinestopreason = "maxpassesreached"
elif regressormse < optiondict["convergencethresh"]:
LGR.info("refinement ended (refinement has converged")
stoprefining = True
refinestopreason = "convergence"
else:
stoprefining = False
elif thepass >= optiondict["passes"]:
stoprefining = True
refinestopreason = "passesreached"
else:
stoprefining = False
if optiondict["detrendorder"] > 0:
resampnonosref_y = tide_fit.detrend(
tide_resample.doresample(
initial_fmri_x,
normoutputdata,
initial_fmri_x,
method=optiondict["interptype"],
),
order=optiondict["detrendorder"],
demean=optiondict["dodemean"],
)
resampref_y = tide_fit.detrend(
tide_resample.doresample(
initial_fmri_x,
normoutputdata,
os_fmri_x,
method=optiondict["interptype"],
),
order=optiondict["detrendorder"],
demean=optiondict["dodemean"],
)
else:
resampnonosref_y = tide_resample.doresample(
initial_fmri_x,
normoutputdata,
initial_fmri_x,
method=optiondict["interptype"],
)
resampref_y = tide_resample.doresample(
initial_fmri_x,
normoutputdata,
os_fmri_x,
method=optiondict["interptype"],
)
if optiondict["tmaskname"] is not None:
resampnonosref_y *= tmask_y
thefit, R = tide_fit.mlregress(tmask_y, resampnonosref_y)
resampnonosref_y -= thefit[0, 1] * tmask_y
resampref_y *= tmaskos_y
thefit, R = tide_fit.mlregress(tmaskos_y, resampref_y)
resampref_y -= thefit[0, 1] * tmaskos_y
# reinitialize lagtc for resampling
previousnormoutputdata = normoutputdata + 0.0
genlagtc = tide_resample.FastResampler(
initial_fmri_x, normoutputdata, padtime=padtime
)
nonosrefname = "_reference_fmrires_pass" + str(thepass + 1) + ".txt"
osrefname = "_reference_resampres_pass" + str(thepass + 1) + ".txt"
(
optiondict["kurtosis_reference_pass" + str(thepass + 1)],
optiondict["kurtosisz_reference_pass" + str(thepass + 1)],
optiondict["kurtosisp_reference_pass" + str(thepass + 1)],
) = tide_stats.kurtosisstats(resampref_y)
if not stoprefining:
if optiondict["bidsoutput"]:
tide_io.writebidstsv(
f"{outputname}_desc-movingregressor_timeseries",
tide_math.stdnormalize(resampnonosref_y),
1.0 / fmritr,
columns=["pass" + str(thepass + 1)],
append=True,
)
tide_io.writebidstsv(
f"{outputname}_desc-oversampledmovingregressor_timeseries",
tide_math.stdnormalize(resampref_y),
oversampfreq,
columns=["pass" + str(thepass + 1)],
append=True,
)
else:
tide_io.writenpvecs(
tide_math.stdnormalize(resampnonosref_y),
outputname + nonosrefname,
)
tide_io.writenpvecs(
tide_math.stdnormalize(resampref_y), outputname + osrefname
)
else:
LGR.warning(f"refinement failed - terminating at end of pass {thepass}")
stoprefining = True
refinestopreason = "emptymask"
TimingLGR.info(
f"Regressor refinement end, pass {thepass}",
{
"message2": voxelsprocessed_rr,
"message3": "voxels",
},
)
if optiondict["saveintermediatemaps"]:
maplist = [
("lagtimes", "maxtime"),
("lagstrengths", "maxcorr"),
("lagsigma", "maxwidth"),
("fitmask", "fitmask"),
("failreason", "corrfitfailreason"),
]
if thepass < optiondict["passes"]:
maplist.append(("refinemask", "refinemask"))
for mapname, mapsuffix in maplist:
if optiondict["memprofile"]:
memcheckpoint(f"about to write {mapname} to {mapsuffix}")
else:
tide_util.logmem(f"about to write {mapname} to {mapsuffix}")
outmaparray[:] = 0.0
outmaparray[validvoxels] = eval(mapname)[:]
if optiondict["textio"]:
tide_io.writenpvecs(
outmaparray.reshape(nativespaceshape, 1),
f"{outputname}_{mapsuffix}{passsuffix}.txt",
)
else:
if optiondict["bidsoutput"]:
bidspasssuffix = f"_intermediatedata-pass{thepass}"
if mapname == "fitmask":
savename = f"{outputname}{bidspasssuffix}_desc-corrfit_mask"
elif mapname == "failreason":
savename = f"{outputname}{bidspasssuffix}_desc-corrfitfailreason_info"
else:
savename = f"{outputname}{bidspasssuffix}_desc-{mapsuffix}_map"
bidsdict = bidsbasedict.copy()
if mapname == "lagtimes" or mapname == "lagsigma":
bidsdict["Units"] = "second"
tide_io.writedicttojson(bidsdict, f"{savename}.json")
else:
savename = f"{outputname}_{mapname}" + passsuffix
tide_io.savetonifti(outmaparray.reshape(nativespaceshape), theheader, savename)
# We are done with refinement.
if optiondict["convergencethresh"] is None:
optiondict["actual_passes"] = optiondict["passes"]
else:
optiondict["actual_passes"] = thepass - 1
optiondict["refinestopreason"] = refinestopreason
# Post refinement step -1 - Coherence calculation
if optiondict["calccoherence"]:
TimingLGR.info("Coherence calculation start")
LGR.info("\n\nCoherence calculation")
reportstep = 1000
# make the Coherer
theCoherer = tide_classes.Coherer(
Fs=(1.0 / fmritr),
reftc=cleaned_nonosreferencetc,
freqmin=0.0,
freqmax=0.2,
ncprefilter=theprefilter,
windowfunc=optiondict["windowfunc"],
detrendorder=optiondict["detrendorder"],
debug=False,
)
theCoherer.setreftc(cleaned_nonosreferencetc)
(
coherencefreqstart,
dummy,
coherencefreqstep,
coherencefreqaxissize,
) = theCoherer.getaxisinfo()
if optiondict["textio"]:
nativecoherenceshape = (xsize, coherencefreqaxissize)
else:
if fileiscifti:
nativecoherenceshape = (1, 1, 1, coherencefreqaxissize, numspatiallocs)
else:
nativecoherenceshape = (xsize, ysize, numslices, coherencefreqaxissize)
internalvalidcoherenceshape = (numvalidspatiallocs, coherencefreqaxissize)
internalcoherenceshape = (numspatiallocs, coherencefreqaxissize)
# now allocate the arrays needed for the coherence calculation
if optiondict["sharedmem"]:
coherencefunc, dummy, dummy = allocshared(internalvalidcoherenceshape, rt_outfloatset)
coherencepeakval, dummy, dummy = allocshared(numvalidspatiallocs, rt_outfloatset)
coherencepeakfreq, dummy, dummy = allocshared(numvalidspatiallocs, rt_outfloatset)
else:
coherencefunc = np.zeros(internalvalidcoherenceshape, dtype=rt_outfloattype)
coherencepeakval, dummy, dummy = allocshared(numvalidspatiallocs, rt_outfloatset)
coherencepeakfreq = np.zeros(numvalidspatiallocs, dtype=rt_outfloattype)
coherencepass_func = addmemprofiling(
tide_calccoherence.coherencepass,
optiondict["memprofile"],
"before coherencepass",
)
voxelsprocessed_coherence = coherencepass_func(
fmri_data_valid,
theCoherer,
coherencefunc,
coherencepeakval,
coherencepeakfreq,
reportstep,
alt=True,
showprogressbar=optiondict["showprogressbar"],
chunksize=optiondict["mp_chunksize"],
nprocs=1,
alwaysmultiproc=False,
rt_floatset=rt_floatset,
rt_floattype=rt_floattype,
)
# save the results of the calculations
outcoherencearray = np.zeros(internalcoherenceshape, dtype=rt_floattype)
outcoherencearray[validvoxels, :] = coherencefunc[:, :]
theheader = copy.deepcopy(nim_hdr)
theheader["toffset"] = coherencefreqstart
theheader["pixdim"][4] = coherencefreqstep
if optiondict["textio"]:
tide_io.writenpvecs(
outcoherencearray.reshape(nativecoherenceshape),
f"{outputname}_coherence.txt",
)
else:
if optiondict["bidsoutput"]:
savename = f"{outputname}_desc-coherence_info"
else:
savename = f"{outputname}_coherence"
if fileiscifti:
timeindex = theheader["dim"][0] - 1
spaceindex = theheader["dim"][0]
theheader["dim"][timeindex] = coherencefreqaxissize
theheader["dim"][spaceindex] = numspatiallocs
tide_io.savetocifti(
outcoherencearray,
cifti_hdr,
theheader,
savename,
isseries=True,
names=["coherence"],
)
else:
theheader["dim"][0] = 3
theheader["dim"][4] = coherencefreqaxissize
tide_io.savetonifti(
outcoherencearray.reshape(nativecoherenceshape), theheader, savename
)
del coherencefunc
del outcoherencearray
TimingLGR.info(
"Coherence calculation end",
{
"message2": voxelsprocessed_coherence,
"message3": "voxels",
},
)
# Post refinement step 0 - Wiener deconvolution
if optiondict["dodeconv"]:
TimingLGR.info("Wiener deconvolution start")
LGR.info("\n\nWiener deconvolution")
reportstep = 1000
# now allocate the arrays needed for Wiener deconvolution
if optiondict["sharedmem"]:
wienerdeconv, dummy, dummy = allocshared(internalvalidspaceshape, rt_outfloatset)
wpeak, dummy, dummy = allocshared(internalvalidspaceshape, rt_outfloatset)
else:
wienerdeconv = np.zeros(internalvalidspaceshape, dtype=rt_outfloattype)
wpeak = np.zeros(internalvalidspaceshape, dtype=rt_outfloattype)
wienerpass_func = addmemprofiling(
tide_wiener.wienerpass,
optiondict["memprofile"],
"before wienerpass",
)
voxelsprocessed_wiener = wienerpass_func(
numspatiallocs,
reportstep,
fmri_data_valid,
threshval,
optiondict,
wienerdeconv,
wpeak,
resampref_y,
rt_floatset=rt_floatset,
rt_floattype=rt_floattype,
)
TimingLGR.info(
"Wiener deconvolution end",
{
"message2": voxelsprocessed_wiener,
"message3": "voxels",
},
)
# Post refinement step 1 - GLM fitting to remove moving signal
if optiondict["doglmfilt"]:
TimingLGR.info("GLM filtering start")
LGR.info("\n\nGLM filtering")
reportstep = 1000
if (optiondict["gausssigma"] > 0.0) or (optiondict["glmsourcefile"] is not None):
if optiondict["glmsourcefile"] is not None:
LGR.info(f"reading in {optiondict['glmsourcefile']} for GLM filter, please wait")
if optiondict["textio"]:
nim_data = tide_io.readvecs(optiondict["glmsourcefile"])
else:
nim, nim_data, nim_hdr, thedims, thesizes = tide_io.readfromnifti(
optiondict["glmsourcefile"]
)
else:
LGR.info(f"rereading {fmrifilename} for GLM filter, please wait")
if optiondict["textio"]:
nim_data = tide_io.readvecs(fmrifilename)
else:
nim, nim_data, nim_hdr, thedims, thesizes = tide_io.readfromnifti(fmrifilename)
"""meanvalue = np.mean(
nim_data.reshape((numspatiallocs, timepoints))[:, validstart : validend + 1],
axis=1,
)"""
fmri_data_valid = (
nim_data.reshape((numspatiallocs, timepoints))[:, validstart : validend + 1]
)[validvoxels, :] + 0.0
# move fmri_data_valid into shared memory
if optiondict["sharedmem"]:
LGR.info("moving fmri data to shared memory")
TimingLGR.info("Start moving fmri_data to shared memory")
numpy2shared_func = addmemprofiling(
numpy2shared,
optiondict["memprofile"],
"before movetoshared (glm)",
)
fmri_data_valid = numpy2shared_func(fmri_data_valid, rt_floatset)
TimingLGR.info("End moving fmri_data to shared memory")
del nim_data
# now allocate the arrays needed for GLM filtering
if optiondict["sharedmem"]:
glmmean, dummy, dummy = allocshared(internalvalidspaceshape, rt_outfloatset)
rvalue, dummy, dummy = allocshared(internalvalidspaceshape, rt_outfloatset)
r2value, dummy, dummy = allocshared(internalvalidspaceshape, rt_outfloatset)
fitNorm, dummy, dummy = allocshared(internalvalidspaceshape, rt_outfloatset)
fitcoeff, dummy, dummy = allocshared(internalvalidspaceshape, rt_outfloatset)
movingsignal, dummy, dummy = allocshared(internalvalidfmrishape, rt_outfloatset)
filtereddata, dummy, dummy = allocshared(internalvalidfmrishape, rt_outfloatset)
else:
glmmean = np.zeros(internalvalidspaceshape, dtype=rt_outfloattype)
rvalue = np.zeros(internalvalidspaceshape, dtype=rt_outfloattype)
r2value = np.zeros(internalvalidspaceshape, dtype=rt_outfloattype)
fitNorm = np.zeros(internalvalidspaceshape, dtype=rt_outfloattype)
fitcoeff = | np.zeros(internalvalidspaceshape, dtype=rt_outfloattype) | numpy.zeros |
import os
import scipy.io as io
from pyimzml.ImzMLParser import ImzMLParser
import numpy as np
import psutil
def convert_imaging_file_to_mat(imzml_filename, mat_filename, Z=0):
p = ImzMLParser(imzml_filename)
data={}
amount_of_points_in_image=0
zs=[]
RAM_available=psutil.virtual_memory().available
print("Set the only one Z-coordinate to be processed\nSkip (press Enter) to use the default value")
while amount_of_points_in_image==0:
try:
Z=int(input("Enter Z-coordinate: "))
except ValueError:
print('Default Z=0 will be used. Enter only digits.')
for i, (x,y,z) in enumerate(p.coordinates):
if z==Z:
amount_of_points_in_image+=1
if not (z in zs):
zs.append(z)
if amount_of_points_in_image==0:
print("There is no such Z-coordinate in your MS image.\nAvailable Z are:")
print(*zs, sep=' ')
print("Try again or use Ctrl+C to terminate the process")
#amount_of_points_in_image=len(p.intensityLengths)
data['peaks'] = np.empty((amount_of_points_in_image,), dtype=np.object)
data['R'] = np.ones(amount_of_points_in_image,dtype=np.int16)
data['X'] = | np.zeros(amount_of_points_in_image,dtype=np.int16) | numpy.zeros |
import networkx as nx
import numpy as np
import math
from tqdm import tqdm
import numba
from numba.experimental import jitclass
from numba import jit
steadyspec = [
('adj_matrix',numba.float64[:,:]),
('graph_size',numba.int32),
('background_field',numba.float64[:]),
('fixed_point_iter',numba.int32),
('fp_tol_fac',numba.float64),
]
@jitclass(steadyspec)
class steady_state(object):
"""
A class to calculate steady state of magnetisation.
...
Attributes
----------
adj_matrix : numpy.array
Adjacency matrix of the graph
fixed_point_iter : float, optional
Max number of iterations used in self-consistency equations (default 1e5)
fp_tol_fac : float, optional
Tolerance factor in stoppping condition for consistency equations (default 1e-6)
"""
def __init__(self,adj_matrix,fixed_point_iter=10000,fp_tol_fac=1e-6):
self.adj_matrix = adj_matrix
self.graph_size = self.adj_matrix.shape[0]
self.fixed_point_iter=fixed_point_iter
self.fp_tol_fac=fp_tol_fac
def single_mag(self,i,m,beta,field):
"""
Calculates magnetisation for a single node. Subfunction of magnetisation function.
Parameters
------------
i : int
Index of the node in question.
m : numpy.array
magnetisation array for all nodes.
beta: float
Interaction strength
field: numpy.array
Array of agent's control field for each node
"""
gamma=1.0
spin_field = self.adj_matrix[i].dot(m)
term = math.tanh(beta*(spin_field+field[i]))
return (1.0-gamma)*m[i] + gamma*term
def magnetisation(self,mag,beta,field):
"""
Calculates magnetisation for the whole system
Parameters
------------
m : numpy.array
magnetisation array for all nodes.
beta: float
Interaction strength
field: numpy.array
Array of agent's control field for each node
"""
m_old = mag
m_new = np.zeros(len(m_old))
for i in range(self.graph_size):
m_new[i]=self.single_mag(i,m_old,beta,field)
return m_new
def aitken_method(self,mag0,beta,field):
"""
Solves self-consistency equation by following Aitken method* for accelerating convergence.
* Numerical Analysis Richard L.Burden 9th Edition, p. 105
Parameters
------------
m0 : numpy.array
Initial guess of magnetisation for all nodes.
beta: float
Interaction strength
field: numpy.array
Array of agent's control field for each node
"""
mag1=self.magnetisation(mag0,beta,field)
for i in range(self.fixed_point_iter):
mag2=self.magnetisation(mag1,beta,field)
if ((mag0+mag2-2*mag1)!=0).all():
mag_d = mag0 - (mag1-mag0)**2/(mag0+mag2-2*mag1)
else:
mag_d = mag1
if abs(np.sum(mag0)-np.sum(mag_d))<self.fp_tol_fac:
break
mag0=mag1
mag1=mag2
if i+1==self.fixed_point_iter:
mag_d = mag1
return mag_d
@jit(nopython=True)
def isclose(a,b):
return abs(a-b) <= max(1e-9 * max(abs(a), abs(b)), 1e-5)
@jit(nopython=True)
def susc_grad(beta,mag,adj_matrix):
"""
Calculates mean field susceptibility.
Parameters
------------
beta: float
Interaction strength.
mag : numpy.array
Magnetisation array for all nodes.
adj_matrix : numpy.array
Adjacency matrix of the network.
"""
D=np.identity(mag.shape[0])*np.array([(1-i**2) for i in mag])
inv = np.linalg.inv(np.identity(mag.shape[0])-beta*D.dot(adj_matrix))
susc_matrix = beta*inv.dot(D)
gradient = np.sum(susc_matrix,axis=1).flatten()
return gradient
def mag_grad(beta,mag,adj_matrix):
"""
Calculates gradient of the magnetisation with respect to change in the external control field. Nominally mean field susceptibility.
Parameters
------------
beta : float
Interaction strength.
mag : numpy.array
Magnetisation array for all nodes.
adj_matrix : numpy.array
Adjacency matrix of the network.
"""
if np.all([isclose(i,j) for i,j in zip(mag,np.ones(mag.shape[0]))]):
return np.zeros(len(mag))
else:
return susc_grad(beta,mag,adj_matrix)
@jit(nopython=True)
def projection_simplex_sort(v, z):
"""
Bounds control field to agent's magnetic field budget.
...
Parameters
----------
v : numpy.array
Control field allocation of the agent.
z : float
Magnetic field budget.
"""
n_features = v.shape[0]
v = np.abs(v)
u = np.sort(v)[::-1]
cssv = np.cumsum(u) - z
ind = np.arange(n_features) + 1
cond = u - cssv / ind > 0
rho = ind[cond][-1]
theta = cssv[cond][-1] / float(rho)
w = np.maximum(v - theta, 0)
return w
@jit(nopython=True)
def lr_1(x,iim_iter=5000):
return np.exp(-x/(0.1*iim_iter))
@jit(nopython=True)
def lr_2(x,iim_iter=5000):
return np.exp(-x/(0.1*iim_iter))
@jit(nopython=True)
def adam(grad,it,typ,ms,vs,iim_iter,beta1=0.9,beta2=0.999,eps=0.1):
"""
Adam optimiser.
Parameters
------------
grad : numpy.array
Gradient array for all nodes.
it : int
Iteration index.
typ : string
'pos' if calculating for positive agent; 'neg' if calculating for negative agent.
ms : numpy.array
Momentum array with linear gradients
vs : numpy.array
Momentum array with squared gradients
iim_iter : int
Max number of iteration in optimisation algorithm.
beta1 : float
Default 0.9
beta2 : float
Default 0.999
eps : float
Default 0.1
"""
if typ=='pos':
lr=lr_1(it)
elif typ=='neg':
lr=lr_2(it)
ms_new = beta1 * ms + (1.0 - beta1) * grad
vs_new = beta2 * vs + (1.0 - beta2) * grad**2
mhat = ms_new / (1.0 - beta1**(it+1))
vhat = vs_new / (1.0 - beta2**(it+1))
ms = ms_new
vs = vs_new
change = lr* mhat/( | np.sqrt(vhat) | numpy.sqrt |
"""
@author: <NAME>
Animation for understanding rotating phasors, negative frequency in DSP concepts
Add, remove, or modify signals in rotating_phasors
Script will animate the individual phasors and the combined output in both rectangular and polar plots
Press any keyboard key to pause the animation
"""
# @todo
# reorganize the object oriented scheme
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
import cmath as cm
import matplotlib.patheffects as pe
from scipy.fftpack import fft, fftshift, fftfreq, ifft
import math
import custom_tools.fftplot as fftplot
import custom_tools.list_accessories as list_acs
import custom_tools.handyfuncs as hf
import custom_tools.dsp_accessories as dsp_acs
import custom_tools.fft_accessories as fft_acs
import helper_functions as hlpf
import scipy.signal as sig
import csv
import os
from datetime import datetime
pi = np.pi
def wrap_around(x, count):
return x % count
# datalog vars
curr_date = datetime.now().replace(microsecond=0)
curr_dir = os.path.abspath(os.getcwd())
csv_file_name = str(curr_date).replace(':', '') + '_debug_datalog.csv'
results_file_path = os.path.join(curr_dir, csv_file_name)
# ********************* choose operating mode here *********************
# direct_phasor: Enter time-domain signals (such as real cosine, complex cosine) in rotating_phasors.
# See predefined examples below.
# FT_mode: Enter time domain samples (real or complex) in input_vector and the polar plot will
# show reconstructed time domain samples
# FIR_mode: Enter FIR filter coefficients h[k] or bk in input vector. polar plot will show how frequency
# response of FIR filter is made
available_op_modes = ['direct_phasor', 'FT_mode', 'FIR_mode']
op_mode = 'direct_phasor'
Fs = 80e3 # 200kHz (Sample Rate)
Ts = 1 / Fs
Ts_sci, Ts_pow10 = hf.return_sci_notation(Ts)
# num_sampls = Fs # number of samples
num_sampls = 2 ** 12 # number of samples
# x_t = np.arange(0, num_sampls * Ts, Ts)
# x_t_1 = np.arange(0, num_sampls * Ts, Ts)
x_t = np.linspace(0, num_sampls * Ts, num_sampls, endpoint=False)
n = x_t
# list of phasor arrays that get passed into animation function
rotating_phasors = []
pause = False
# Select if you want to display the sine as a continuous wave
# True = continuous (not able to zoom in x-direction)
# False = Non-continuous (able to zoom)
continuous = False
# if set True, all phasors in rotating_phasors will spin with respect to center of polar plot
# if False, all phasors will spin with respect to the end of the previous phasor end point (true vector addition)
spin_orig_center = False
double_sided_FFT = True
fft_mag_in_log = False
# turning coherency on will drift the rect displays, but produces clean FFTs
# This happens when Fs/fund is not an integer since the coherency works only for whole window length (num_sampls),
# and rect plot shows only one cycle
coherency = True
debug = False
# this data is from noise cancellation filter
# input_vector = np.array([0.13083826, 0.12517881, 0.11899678, 0.11231907, 0.10508106,
# 0.09738001, 0.08925131, 0.08073239, 0.07186244, 0.06268219,
# 0.05323363, 0.04355975, 0.03370433, 0.02371163, 0.01362624,
# 0.00349278, -0.00664429, -0.01674086, -0.0267534, -0.03663912])
input_vector = np.array([1, -1])
N = len(input_vector)
max_mag = | np.absolute(input_vector) | numpy.absolute |
import warnings
from typing import Any, List, Set, Tuple, Union
import numpy as np
from xarray import Dataset
from .typing import ArrayLike, DType
def check_array_like(
a: Any,
dtype: Union[None, DType, Set[DType]] = None,
kind: Union[None, str, Set[str]] = None,
ndim: Union[None, int, Set[int]] = None,
) -> None:
"""Raise an error if an array does not match given attributes (dtype, kind, dimensions).
Parameters
----------
a : Any
Array of any type.
dtype : Union[None, DType, Set[DType]], optional
The dtype the array must have, by default None (don't check)
If a set, then the array must have one of the dtypes in the set.
kind : Union[None, str, Set[str]], optional
The dtype kind the array must be, by default None (don't check).
If a set, then the array must be one of the kinds in the set.
ndim : Union[None, int, Set[int]], optional
Number of dimensions the array must have, by default None (don't check)
If a set, then the array must have one of the number of dimensions in the set.
Raises
------
TypeError
* If `a` does not have the attibutes `dtype`, `shape`, and `ndim`.
* If `a` does not have a dtype that matches `dtype`.
* If `a` is not a dtype kind that matches `kind`.
ValueError
If the number of dimensions of `a` does not match `ndim`.
"""
array_attrs = "ndim", "dtype", "shape"
for k in array_attrs:
if not hasattr(a, k):
raise TypeError(f"Not an array. Missing attribute '{k}'")
if dtype is not None:
if isinstance(dtype, set):
dtype = {np.dtype(t) for t in dtype}
if a.dtype not in dtype:
raise TypeError(
f"Array dtype ({a.dtype}) does not match one of {dtype}"
)
elif a.dtype != np.dtype(dtype):
raise TypeError(f"Array dtype ({a.dtype}) does not match {np.dtype(dtype)}")
if kind is not None:
if isinstance(kind, set):
if a.dtype.kind not in kind:
raise TypeError(
f"Array dtype kind ({a.dtype.kind}) does not match one of {kind}"
)
elif a.dtype.kind != kind:
raise TypeError(f"Array dtype kind ({a.dtype.kind}) does not match {kind}")
if ndim is not None:
if isinstance(ndim, set):
if a.ndim not in ndim:
raise ValueError(
f"Number of dimensions ({a.ndim}) does not match one of {ndim}"
)
elif ndim != a.ndim:
raise ValueError(f"Number of dimensions ({a.ndim}) does not match {ndim}")
def encode_array(x: ArrayLike) -> Tuple[ArrayLike, List[Any]]:
"""Encode array values as integers indexing unique values.
The codes created for each unique element in the array correspond
to order of appearance, not the natural sort order for the array
dtype.
Examples
--------
>>> encode_array(['c', 'a', 'a', 'b'])
(array([0, 1, 1, 2]), array(['c', 'a', 'b'], dtype='<U1'))
Parameters
----------
x : (M,) array-like
Array of elements to encode of any type.
Returns
-------
indexes : (M,) ndarray
Encoded values as integer indices.
values : ndarray
Unique values in original array in order of appearance.
"""
# argsort not implemented in dask: https://github.com/dask/dask/issues/4368
names, index, inverse = np.unique(x, return_index=True, return_inverse=True)
index = np.argsort(index)
rank = | np.empty_like(index) | numpy.empty_like |
""" Functions for algebraic fitting """
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import numpy as np
MODE_DICT_ELLIPSE = {'circle': 'xy', 'ellipse_aligned': '0', 'ellipse': ''}
MODE_DICT_ELLIPSOID = {'sphere': 'xyz', 'prolate': 'xy', 'oblate': 'xy',
'ellipsoid': '', 'ellipsoid_aligned': '0',
'prolate_aligned': '0xy', 'oblate_aligned': '0xy'}
def fit_ellipse(coords, mode=''):
""" Fits an ellipse to datapoints using an algebraic method.
This method is different from least squares minimization of the distnace
between each datapoint and the fitted ellipse (so-called geometrical
approach). For circles, this makes no difference. The higher the aspect
ratio of the ellipse, the worse the approximation gets.
Parameters
----------
coords : numpy array of floats
array of shape (N, 2) containing datapoints
mode : {'circle', 'ellipse', 'ellipse_aligned'}
'ellipse' or None fits an arbitrary ellipse (default)
'circle' fits a circle
'ellipse_aligned' fits an ellipse with its axes aligned along [x y] axes
Returns
-------
center, radii, angle
References
----------
.. [1] <NAME> (2010) Multi-dimensional ellipsoidal fitting.
"""
if coords.shape[0] != 2:
raise ValueError('Input data must have two columns!')
if mode in MODE_DICT_ELLIPSE:
mode = MODE_DICT_ELLIPSE[mode]
x = coords[0, :, np.newaxis]
y = coords[1, :, np.newaxis]
if mode == '':
D = np.hstack((x**2 - y**2, 2*x*y, 2*x, 2*y, np.ones_like(x)))
elif mode == '0':
D = np.hstack((x**2 - y**2, 2*x, 2*y, np.ones_like(x)))
elif mode == 'xy':
D = np.hstack((2*x, 2*y, np.ones_like(x)))
d2 = x**2 + y**2 # the RHS of the llsq problem (y's)
u = np.linalg.solve(np.dot(D.T, D), (np.dot(D.T, d2)))[:, 0]
v = np.empty((6), dtype=u.dtype)
if mode == '':
v[0] = u[0] - 1
v[1] = -u[0] - 1
v[2:] = u[1:]
elif mode == '0':
v[0] = u[0] - 1
v[1] = -u[0] - 1
v[2] = 0
v[3:] = u[1:]
elif mode == 'xy':
v[:2] = -1
v[2] = 0
v[3:] = u
A = np.array([[v[0], v[2], v[3]],
[v[2], v[1], v[4]],
[v[3], v[4], v[5]]])
# find the center of the ellipse
center = -np.linalg.solve(A[:2, :2], v[3:5])
# translate to the center
T = np.identity(3, dtype=A.dtype)
T[2, :2] = center
R = np.dot(np.dot(T, A), T.T)
# solve the eigenproblem
evals, evecs = np.linalg.eig(R[:2, :2] / -R[2, 2])
radius = (np.sqrt(1 / np.abs(evals)) * np.sign(evals))
if mode == '':
new_order = np.argmax(np.abs(evecs), 1)
radius = radius[new_order]
evecs = evecs[:, new_order]
r11, r12, r21, r22 = evecs.T.flat
angle = np.arctan(-r12/r11)
else:
angle = 0
return radius, center, angle
def fit_ellipsoid(coords, mode='', return_mode=''):
"""
Fit an ellipsoid/sphere/paraboloid/hyperboloid to a set of xyz data points:
Parameters
----------
coords : ndarray
Cartesian coordinates, 3 x n array
mode : {'', 'xy', 'xz', 'xyz', '0', '0xy', '0xz'} t
'' or None fits an arbitrary ellipsoid (default)
'xy' fits a spheroid with x- and y- radii equal
'xz' fits a spheroid with x- and z- radii equal
'xyz' fits a sphere
'0' fits an ellipsoid with its axes aligned along [x y z] axes
'0xy' the same with x- and y- radii equal
'0xz' the same with x- and z- radii equal
return_mode : {'', 'euler', 'skew'}
'' returns the directions of the radii as 3x3 array
'euler' returns euler angles
'skew' returns skew in xy
Returns
-------
radius : ndarray
ellipsoid radii [zr, yr, xr]
center : ndarray
ellipsoid center coordinates [zc, yc, xc]
value :
return_mode == '': the radii directions as columns of the 3x3 matrix
return_mode == 'euler':
euler angles, applied in x, y, z order [z, y, x]
the y value is the angle with the z axis (tilt)
the z value is the angle around the z axis (rotation)
the x value is the 3rd rotation, should be around 0
return_mode == 'skew':
skew in y, x order
Notes
-----
Author: <NAME>, Oculus VR Date: September, 2015
ported to python by <NAME>, December 2015
added euler angles and skew by <NAME>
"""
if coords.shape[0] != 3:
raise ValueError('Input data must have three columns!')
if mode in MODE_DICT_ELLIPSOID:
mode = MODE_DICT_ELLIPSOID[mode]
if return_mode == 'skew' and 'xy' not in mode:
raise ValueError('Cannot return skew when x, y radii are not equal')
if return_mode == 'euler':
raise ValueError('Euler mode is not implemented fully')
z = coords[0, :, np.newaxis]
y = coords[1, :, np.newaxis]
x = coords[2, :, np.newaxis]
# fit ellipsoid in the form Ax^2 + By^2 + Cz^2 + 2Dxy + 2Exz + 2Fyz + 2Gx +
# 2Hy + 2Iz + J = 0 and A + B + C = 3 constraint removing one extra param
if mode == '':
D = np.hstack((x**2 + y**2 - 2 * z**2, x**2 + z**2 - 2 * y**2,
2 * x * y, 2 * x * z, 2 * y * z, 2 * x, 2 * y, 2 * z,
np.ones_like(x)))
elif mode == 'xy':
D = np.hstack((x**2 + y**2 - 2 * z**2, 2 * x * y, 2 * x * z, 2 * y * z,
2 * x, 2 * y, 2 * z, np.ones_like(x)))
elif mode == 'xz':
D = np.hstack((x**2 + z**2 - 2 * y**2, 2 * x * y, 2 * x * z, 2 * y * z,
2 * x, 2 * y, 2 * z, | np.ones_like(x) | numpy.ones_like |
# -*- coding: utf-8 -*-
'''
Copyright (c) 2021, MIT Interactive Robotics Group, PI <NAME>.
Authors: <NAME>, <NAME>, <NAME>, <NAME>
All rights reserved.
'''
import casadi as cas
import numpy as np
from casadi import MX, mtimes, vertcat, sum2, sqrt, jacobian
from casadi import reshape as cas_reshape
from scipy import interpolate
import matplotlib.pyplot as plt
import hr_planning
from hr_planning.visualization.utils_visualization import print_FAIL
from hr_planning.utils_interp import waypts_2_pwsplines
use_human_ui_bound = True
# use_human_ui_bound = False
class HumanRefTracker:
def __init__(self, pH_view_pH_pR_min_sep_dist,
pH_min, pH_max, vH_min, vH_max, uH_min, uH_max,
w_ref, w_u, w_move_to_pR, w_avoid_pR, dt, mass):
"""
Class for an MPC to compute human trajectory in continuous state space.
n_pH = dimensionality of human position.
n_vH = dimensionality of human velocity.
n_uH = dimensionality of human control.
Parameters
----------
pH_view_pH_pR_min_sep_dist: float, from the human's view,
the min separation distance that the human
wants to keep from the robot.
The boundary conditions:
pH_max: (n_pH,) np vector = max human position.
pH_min: (n_pH,) np vector = min human position.
vH_max: (n_pH,) np vector = max human velocity.
vH_min: (n_pH,) np vector = min human velocity.
uH_max: (n_pH,) np vector = max human control.
uH_min: (n_pH,) np vector = min human control.
"""
self.pH_view_pH_pR_min_sep_dist = pH_view_pH_pR_min_sep_dist
self.mass = mass
assert mass > 1e-5
self.feas_tol = 1e-6
self.pH_min = pH_min
self.pH_max = pH_max
self.vH_min = vH_min
self.vH_max = vH_max
self.uH_min = uH_min
self.uH_max = uH_max
self.w_ref = w_ref
self.w_move_to_pR = w_move_to_pR
self.w_avoid_pR = w_avoid_pR
self.w_u = w_u
# self.dt = dt of MPC != dt_ref = dt of ref traj.
# We will use piecewise cubics to interlate the ref traj.
self.dt = dt
self.n_pH = self.pH_min.shape[0]
self.n_vH = self.vH_min.shape[0]
self.n_uH = self.uH_min.shape[0]
# We want the nx0 array, so that tolist works well
assert self.n_pH == self.n_vH
assert self.pH_min.shape == (self.n_pH,)
assert self.pH_max.shape == (self.n_pH,)
assert self.vH_min.shape == (self.n_vH,)
assert self.vH_max.shape == (self.n_vH,)
assert self.uH_min.shape == (self.n_uH,)
assert self.uH_max.shape == (self.n_uH,)
assert self.w_ref.shape == (self.n_pH, self.n_pH)
assert self.w_move_to_pR.shape == (self.n_pH, self.n_pH)
assert self.w_avoid_pR.shape == (self.n_pH, self.n_pH)
assert self.w_u.shape == (self.n_uH, self.n_uH)
def check_shapes(self, pHs_1_T=None, vHs_1_T=None, uHs_1_T=None,
pH_0=None, vH_0=None, horizon=None):
"""Ensure all shapes are correct."""
if pHs_1_T is not None:
assert pHs_1_T.shape == (horizon, self.n_pH)
if vHs_1_T is not None:
assert vHs_1_T.shape == (horizon, self.n_vH)
if uHs_1_T is not None:
assert uHs_1_T.shape == (horizon, self.n_uH)
if pH_0 is not None:
assert pH_0.shape == (self.n_pH, 1)
if vH_0 is not None:
assert vH_0.shape == (self.n_vH, 1)
def solve_mpc(self, pH_mode, pHs_0_T_ref, dt_ref, vH_0,
pR_0=None, plot=False):
"""
Solve MPC to find a trajectory for the human.
Parameters
----------
pH_mode: str
pH_indep_pR: H-Indep-R condition in the paper.
pH_avoid_pR: H-Away-R condition in the paper.
pH_move_to_pR: H-To-R condition in the paper.
pHs_0_T_ref: n_time_stepsxn_pH np array, the reference trajectory.
In our work, this comes from a human MDP policy rollout.
dt_ref: the dt of pHs_0_T_ref.
vH_0: n_vHx1 np array = initial human velocity.
pR_0: n_pRx1 np array = initial robot position.
plot: bool, whether to plot or not (for debugging).
Returns
----------
pHs_1_T_opt: horizon x n_pH, human positions computed by the MPC.
vHs_1_T_opt: horizon x n_vH, human velocities computed by the MPC.
uHs_1_T_opt: horizon x n_uH, controls computed by the MPC.
"""
assert pH_mode in ["pH_indep_pR", "pH_avoid_pR", "pH_move_to_pR"]
if pH_mode in ["pH_avoid_pR", "pH_move_to_pR"]:
assert pR_0 is not None
# pR, pH have to be in the same space
pH_0 = pHs_0_T_ref[0, :]
pR_0_sqz = pR_0.squeeze()
assert pR_0_sqz.shape == pH_0.shape
pw_spliness, dts_pw = waypts_2_pwsplines(
wp_traj=pHs_0_T_ref, dt=dt_ref,
degree=3, plot=False)
pH_0 = np.reshape(pHs_0_T_ref[0, :], (self.n_pH, 1))
assert vH_0.shape == (self.n_vH, 1)
for i in range(self.n_pH):
tmp = interpolate.splev(x=[0], tck=pw_spliness[i], ext=2)
assert abs(tmp[0] - pH_0[i, 0]) < 1e-5
end_time_pwc = dts_pw[-1]
# Note: horizon + 1 = the length of traj including x0.
horizon = int(np.ceil(end_time_pwc / self.dt))
assert horizon * self.dt >= end_time_pwc
# Decision variables
pHs_1_T = MX.sym("pHs_1_T", (horizon, self.n_pH))
vHs_1_T = MX.sym("vHs_1_T", (horizon, self.n_vH))
uHs_1_T = MX.sym("uHs_1_T", (horizon, self.n_uH))
# Constraints
g = []
lbg = []
ubg = []
g_name = []
# We make terminal goal as in the objective, rather than a constraint.
terminal_goal_cst = False
g_bd, lbg_bd, ubg_bd, g_names_bd = self.generate_boundary_csts_bounds(
pHs_1_T, vHs_1_T, uHs_1_T, horizon, pw_spliness,
terminal_goal_cst=terminal_goal_cst)
g = vertcat(g, g_bd)
lbg += lbg_bd
ubg += ubg_bd
g_name += g_names_bd
# XXX: Collision avoidance with obstacles in the env
# is handled by the MDP policy.
g_dyn, lbg_dyn, ubg_dyn, g_names_dyn = self.generate_dyn_csts(
pHs_1_T, vHs_1_T, uHs_1_T, pH_0, vH_0, horizon)
g = vertcat(g, g_dyn)
lbg += lbg_dyn
ubg += ubg_dyn
g_name += g_names_dyn
assert g.shape[0] == len(lbg) == len(ubg) == len(g_name)
track_traj = True
pTarget = None
pAvoid = None
if pH_mode == "pH_indep_pR":
track_traj = True
pTarget = None
pAvoid = None
elif pH_mode == "pH_move_to_pR":
track_traj = True
pTarget = pR_0
pAvoid = None
elif pH_mode == "pH_avoid_pR":
track_traj = True
pTarget = None
pAvoid = pR_0
else:
raise ValueError()
cost = self.generate_cost_function(
pHs_1_T=pHs_1_T, uHs_1_T=uHs_1_T, horizon=horizon,
pw_spliness=pw_spliness,
track_traj=track_traj, pTarget=pTarget, pAvoid=pAvoid)
opt_vars = vertcat(
pHs_1_T.reshape((-1, 1)),
vHs_1_T.reshape((-1, 1)),
uHs_1_T.reshape((-1, 1)))
prob = {'f': cost, 'x': opt_vars, 'g': g}
if True:
opt = {'error_on_fail': False,
'ipopt': {
'print_level': 0,
# 'hessian_approximation': 'limited-memory',
"max_iter": 400,
"expect_infeasible_problem": "no",
"acceptable_tol": 1e-4,
"acceptable_constr_viol_tol": 1e-5,
"bound_frac": 0.5,
"start_with_resto": "no",
"required_infeasibility_reduction": 0.85,
"acceptable_iter": 8}} # ipopt
solver = cas.nlpsol('solver', 'ipopt', prob, opt)
else:
raise ValueError()
# --------------------
# Solve
end_time = dts_pw[-1]
dts = np.linspace(0, end_time, num=horizon+1, endpoint=True)
# (horizon + 1) x npH
pHs_0_T_init = np.zeros((dts.shape[0], self.n_pH))
for i in range(self.n_pH):
tmp = interpolate.splev(x=dts, tck=pw_spliness[i], ext=2)
assert pHs_0_T_init[:, i].shape == tmp.shape
pHs_0_T_init[:, i] = tmp
pHs_1_T_init = pHs_0_T_init[1:, :]
assert pHs_1_T_init.shape == pHs_1_T.shape
pHs_0_T_minus_1_init = pHs_0_T_init[:-1, :]
uHs_1_T_init = (pHs_1_T_init - pHs_0_T_minus_1_init) / self.dt
assert uHs_1_T_init.shape == uHs_1_T.shape
vHs_1_T_init = np.zeros((horizon, self.n_vH))
assert vHs_1_T_init.shape == vHs_1_T.shape
opt_vars_init = vertcat(
pHs_1_T_init.reshape((-1, 1)),
vHs_1_T_init.reshape((-1, 1)),
uHs_1_T_init.reshape((-1, 1)))
assert opt_vars.shape == opt_vars_init.shape
sol = solver(x0=opt_vars_init, lbg=lbg, ubg=ubg)
x_opt = sol['x']
f_opt = sol['f']
print('f_opt = ', f_opt)
g_res = np.array(sol["g"]).squeeze()
feasible = True
# This is not sufficient to determine feasibility,
# since casadi gives out wrong feasibility values.
if np.any(np.array(lbg) - self.feas_tol > g_res) or np.any(
np.array(ubg) + self.feas_tol < g_res):
feasible = False
if not feasible:
print_FAIL("Hmpc is not feasible")
# Manually checking feasibility:
# Get indices of the respective variables:
c = 0
n_pHs_1_T = horizon * self.n_pH
idx_pHs_1_T = np.arange(n_pHs_1_T)
c += n_pHs_1_T
n_vHs_1_T = horizon * self.n_vH
idx_vHs_1_T = np.arange(c, c + n_vHs_1_T)
c += n_vHs_1_T
nH_us_1_T = horizon * self.n_uH
idx_us_1_T = np.arange(c, c + nH_us_1_T)
c += nH_us_1_T
assert c == x_opt.shape[0]
pHs_1_T_opt = np.array(cas_reshape(x_opt[idx_pHs_1_T],
(horizon, self.n_pH)))
assert pHs_1_T.shape == pHs_1_T_opt.shape
vHs_1_T_opt = np.array(cas_reshape(x_opt[idx_vHs_1_T],
(horizon, self.n_vH)))
assert vHs_1_T.shape == vHs_1_T_opt.shape
uHs_1_T_opt = np.array(cas_reshape(x_opt[idx_us_1_T],
(horizon, self.n_uH)))
assert uHs_1_T.shape == uHs_1_T_opt.shape
# ui bound
if use_human_ui_bound:
for i in range(horizon - 1):
ui = uHs_1_T_opt[i, :].T
if (ui > self.uH_max).any() or (ui < self.uH_min).any():
print_FAIL("At i={}, ui={} is out of bound"
.format(i, ui))
uT = uHs_1_T_opt[horizon-1, :].T
# if (np.abs(uT) > 1e-5).any():
if (uT > self.uH_max).any() or (uT < self.uH_min).any():
print_FAIL("At i={}, ui={} is out of bound"
.format(horizon-1, uT))
# pH bound
for i in range(horizon):
pH = pHs_1_T_opt[i, :].T
if (pH > self.pH_max).any() or (pH < self.pH_min).any():
print_FAIL("At i={}, pH={} is out of bound"
.format(i, pH))
# vH bound
for i in range(horizon - 1):
vHi = vHs_1_T_opt[i, :].T
if (vHi > self.vH_max).any() or (vHi < self.vH_min).any():
print_FAIL("At i={}, vHi={} is out of bound"
.format(i, vHi))
vHT = vHs_1_T_opt[horizon-1, :].T
if (np.abs(vHT) > 1e-5).any():
print_FAIL("At i={}, vHi={} is out of bound"
.format(horizon-1, vHT))
# pH ~ vH
cur_pH = pH_0
next_pH = np.reshape(pHs_1_T_opt[0, :].T, (self.n_pH, 1))
next_vH = np.reshape(vHs_1_T_opt[0, :].T, (self.n_vH, 1))
assert next_pH.shape == cur_pH.shape == next_vH.shape
tmp = next_pH - cur_pH - self.dt * next_vH
if ((np.abs(tmp)) > 1e-5).any():
print_FAIL("At i={}, cur_pH={}, next_pH={}, next_vH={} out of bound"
.format(0, cur_pH, next_pH, next_vH))
for i in range(horizon - 1):
cur_pH = pHs_1_T_opt[i, :].T
next_pH = pHs_1_T_opt[i+1, :].T
next_vH = vHs_1_T_opt[i+1, :].T
assert next_pH.shape == cur_pH.shape == next_vH.shape
tmp = next_pH - cur_pH - self.dt * next_vH
assert ((np.abs(tmp)) < 1e-5).all()
# vH ~ uH
cur_vH = vH_0
next_vH = np.reshape(vHs_1_T_opt[0, :].T, (self.n_vH, 1))
next_uH = np.reshape(uHs_1_T_opt[0, :].T, (self.n_uH, 1))
assert next_vH.shape == cur_vH.shape == next_uH.shape
tmp = next_vH - cur_vH - self.dt * next_uH / self.mass
assert ((np.abs(tmp)) < 1e-5).all()
for i in range(horizon - 1):
cur_vH = vHs_1_T_opt[i, :].T
next_vH = vHs_1_T_opt[i+1, :].T
next_uH = uHs_1_T_opt[i+1, :].T
assert next_vH.shape == cur_vH.shape == next_uH.shape
tmp = next_vH - cur_vH - self.dt * next_uH / self.mass
assert ((np.abs(tmp)) < 1e-5).all()
# --------------------
if plot:
# (horizon + 1) x npH
pHs_0_T_int = np.zeros((dts.shape[0], self.n_pH))
for i in range(self.n_pH):
tmp = interpolate.splev(x=dts, tck=pw_spliness[i], ext=2)
assert pHs_0_T_int[:, i].shape == tmp.shape
pHs_0_T_int[:, i] = tmp
ref = pHs_0_T_ref
intp = pHs_0_T_int
opt = | np.vstack((pH_0.T, pHs_1_T_opt)) | numpy.vstack |
"""
Signals and Systems Function Module
Copyright (c) March 2017, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
Notes
-----
The primary purpose of this function library is to support the book Signals and Systems for Dummies. Beyond that it should be useful to anyone who wants to use Pylab for general signals and systems modeling and simulation. There is a good collection of digital communication simulation primitives included in the library. More enhancements are planned over time.
The formatted docstrings for the library follow. Click index in the upper right to get an
alphabetical listing of the library functions. In all of the example code given it is assumed that ssd has been imported into your workspace. See the examples below for import options.
Examples
--------
>>> import sk_dsp_comm.sigsys as ssd
>>> # Commands then need to be prefixed with ssd., i.e.,
>>> ssd.tri(t,tau)
>>> # A full import of the module, to avoid the the need to prefix with ssd, is:
>>> from sk_dsp_comm.sigsys import *
Function Catalog
----------------
"""
from matplotlib import pylab
import numpy as np
from numpy import fft
import matplotlib.pyplot as plt
from scipy import signal
from scipy.io import wavfile
from logging import getLogger
log = getLogger(__name__)
import warnings
def cic(m, k):
"""
A functional form implementation of a cascade of integrator comb (CIC) filters.
Parameters
----------
m : Effective number of taps per section (typically the decimation factor).
k : The number of CIC sections cascaded (larger K gives the filter a wider image rejection bandwidth).
Returns
-------
b : FIR filter coefficients for a simple direct form implementation using the filter() function.
Notes
-----
Commonly used in multirate signal processing digital down-converters and digital up-converters. A true CIC filter
requires no multiplies, only add and subtract operations. The functional form created here is a simple FIR requiring
real coefficient multiplies via filter().
<NAME> July 2013
"""
if k == 1:
b = np.ones(m)
else:
h = np.ones(m)
b = h
for i in range(1, k):
b = signal.convolve(b, h) # cascade by convolving impulse responses
# Make filter have unity gain at DC
return b / np.sum(b)
def ten_band_eq_filt(x,GdB,Q=3.5):
"""
Filter the input signal x with a ten-band equalizer having octave gain values in ndarray GdB.
The signal x is filtered using octave-spaced peaking filters starting at 31.25 Hz and
stopping at 16 kHz. The Q of each filter is 3.5, but can be changed. The sampling rate
is assumed to be 44.1 kHz.
Parameters
----------
x : ndarray of the input signal samples
GdB : ndarray containing ten octave band gain values [G0dB,...,G9dB]
Q : Quality factor vector for each of the NB peaking filters
Returns
-------
y : ndarray of output signal samples
Examples
--------
>>> # Test with white noise
>>> w = randn(100000)
>>> y = ten_band_eq_filt(x,GdB)
>>> psd(y,2**10,44.1)
"""
fs = 44100.0 # Hz
NB = len(GdB)
if not NB == 10:
raise ValueError("GdB length not equal to ten")
Fc = 31.25*2**np.arange(NB)
B = np.zeros((NB,3))
A = np.zeros((NB,3))
# Create matrix of cascade coefficients
for k in range(NB):
[b,a] = peaking(GdB[k],Fc[k],Q)
B[k,:] = b
A[k,:] = a
# Pass signal x through the cascade of ten filters
y = np.zeros(len(x))
for k in range(NB):
if k == 0:
y = signal.lfilter(B[k,:],A[k,:],x)
else:
y = signal.lfilter(B[k,:],A[k,:],y)
return y
def ten_band_eq_resp(GdB,Q=3.5):
"""
Create a frequency response magnitude plot in dB of a ten band equalizer
using a semilogplot (semilogx()) type plot
Parameters
----------
GdB : Gain vector for 10 peaking filters [G0,...,G9]
Q : Quality factor for each peaking filter (default 3.5)
Returns
-------
Nothing : two plots are created
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from sk_dsp_comm import sigsys as ss
>>> ss.ten_band_eq_resp([0,10.0,0,0,-1,0,5,0,-4,0])
>>> plt.show()
"""
fs = 44100.0 # Hz
NB = len(GdB)
if not NB == 10:
raise ValueError("GdB length not equal to ten")
Fc = 31.25*2**np.arange(NB)
B = np.zeros((NB,3));
A = np.zeros((NB,3));
# Create matrix of cascade coefficients
for k in range(NB):
b,a = peaking(GdB[k],Fc[k],Q,fs)
B[k,:] = b
A[k,:] = a
# Create the cascade frequency response
F = np.logspace(1,np.log10(20e3),1000)
H = np.ones(len(F))*np.complex(1.0,0.0)
for k in range(NB):
w,Htemp = signal.freqz(B[k,:],A[k,:],2*np.pi*F/fs)
H *= Htemp
plt.figure(figsize=(6,4))
plt.subplot(211)
plt.semilogx(F,20*np.log10(abs(H)))
plt.axis([10, fs/2, -12, 12])
plt.grid()
plt.title('Ten-Band Equalizer Frequency Response')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Gain (dB)')
plt.subplot(212)
plt.stem(np.arange(NB),GdB,'b','bs')
#plt.bar(np.arange(NB)-.1,GdB,0.2)
plt.axis([0, NB-1, -12, 12])
plt.xlabel('Equalizer Band Number')
plt.ylabel('Gain Set (dB)')
plt.grid()
def peaking(GdB, fc, Q=3.5, fs=44100.):
"""
A second-order peaking filter having GdB gain at fc and approximately
and 0 dB otherwise.
The filter coefficients returns correspond to a biquadratic system function
containing five parameters.
Parameters
----------
GdB : Lowpass gain in dB
fc : Center frequency in Hz
Q : Filter Q which is inversely proportional to bandwidth
fs : Sampling frquency in Hz
Returns
-------
b : ndarray containing the numerator filter coefficients
a : ndarray containing the denominator filter coefficients
Examples
--------
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from sk_dsp_comm.sigsys import peaking
>>> from scipy import signal
>>> b,a = peaking(2.0,500)
>>> f = np.logspace(1,5,400)
>>> w,H = signal.freqz(b,a,2*np.pi*f/44100)
>>> plt.semilogx(f,20*np.log10(abs(H)))
>>> plt.ylabel("Power Spectral Density (dB)")
>>> plt.xlabel("Frequency (Hz)")
>>> plt.show()
>>> b,a = peaking(-5.0,500,4)
>>> w,H = signal.freqz(b,a,2*np.pi*f/44100)
>>> plt.semilogx(f,20*np.log10(abs(H)))
>>> plt.ylabel("Power Spectral Density (dB)")
>>> plt.xlabel("Frequency (Hz)")
"""
mu = 10**(GdB/20.)
kq = 4/(1 + mu)*np.tan(2*np.pi*fc/fs/(2*Q))
Cpk = (1 + kq *mu)/(1 + kq)
b1 = -2*np.cos(2*np.pi*fc/fs)/(1 + kq*mu)
b2 = (1 - kq*mu)/(1 + kq*mu)
a1 = -2*np.cos(2*np.pi*fc/fs)/(1 + kq)
a2 = (1 - kq)/(1 + kq)
b = Cpk*np.array([1, b1, b2])
a = np.array([1, a1, a2])
return b,a
def ex6_2(n):
"""
Generate a triangle pulse as described in Example 6-2
of Chapter 6.
You need to supply an index array n that covers at least [-2, 5].
The function returns the hard-coded signal of the example.
Parameters
----------
n : time index ndarray covering at least -2 to +5.
Returns
-------
x : ndarray of signal samples in x
Examples
--------
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from sk_dsp_comm import sigsys as ss
>>> n = np.arange(-5,8)
>>> x = ss.ex6_2(n)
>>> plt.stem(n,x) # creates a stem plot of x vs n
"""
x = np.zeros(len(n))
for k, nn in enumerate(n):
if nn >= -2 and nn <= 5:
x[k] = 8 - nn
return x
def position_cd(Ka, out_type ='fb_exact'):
"""
CD sled position control case study of Chapter 18.
The function returns the closed-loop and open-loop
system function for a CD/DVD sled position control
system. The loop amplifier gain is the only variable
that may be changed. The returned system function can
however be changed.
Parameters
----------
Ka : loop amplifier gain, start with 50.
out_type : 'open_loop' for open loop system function
out_type : 'fb_approx' for closed-loop approximation
out_type : 'fb_exact' for closed-loop exact
Returns
-------
b : numerator coefficient ndarray
a : denominator coefficient ndarray
Notes
-----
With the exception of the loop amplifier gain, all
other parameters are hard-coded from Case Study example.
Examples
--------
>>> b,a = position_cd(Ka,'fb_approx')
>>> b,a = position_cd(Ka,'fb_exact')
"""
rs = 10/(2*np.pi)
# Load b and a ndarrays with the coefficients
if out_type.lower() == 'open_loop':
b = np.array([Ka*4000*rs])
a = np.array([1,1275,31250,0])
elif out_type.lower() == 'fb_approx':
b = np.array([3.2*Ka*rs])
a = np.array([1, 25, 3.2*Ka*rs])
elif out_type.lower() == 'fb_exact':
b = np.array([4000*Ka*rs])
a = np.array([1, 1250+25, 25*1250, 4000*Ka*rs])
else:
raise ValueError('out_type must be: open_loop, fb_approx, or fc_exact')
return b, a
def cruise_control(wn,zeta,T,vcruise,vmax,tf_mode='H'):
"""
Cruise control with PI controller and hill disturbance.
This function returns various system function configurations
for a the cruise control Case Study example found in
the supplementary article. The plant model is obtained by the
linearizing the equations of motion and the controller contains a
proportional and integral gain term set via the closed-loop parameters
natural frequency wn (rad/s) and damping zeta.
Parameters
----------
wn : closed-loop natural frequency in rad/s, nominally 0.1
zeta : closed-loop damping factor, nominally 1.0
T : vehicle time constant, nominally 10 s
vcruise : cruise velocity set point, nominally 75 mph
vmax : maximum vehicle velocity, nominally 120 mph
tf_mode : 'H', 'HE', 'HVW', or 'HED' controls the system function returned by the function
'H' : closed-loop system function V(s)/R(s)
'HE' : closed-loop system function E(s)/R(s)
'HVW' : closed-loop system function V(s)/W(s)
'HED' : closed-loop system function E(s)/D(s), where D is the hill disturbance input
Returns
-------
b : numerator coefficient ndarray
a : denominator coefficient ndarray
Examples
--------
>>> # return the closed-loop system function output/input velocity
>>> b,a = cruise_control(wn,zeta,T,vcruise,vmax,tf_mode='H')
>>> # return the closed-loop system function loop error/hill disturbance
>>> b,a = cruise_control(wn,zeta,T,vcruise,vmax,tf_mode='HED')
"""
tau = T/2.*vmax/vcruise
g = 9.8
g *= 3*60**2/5280. # m/s to mph conversion
Kp = T*(2*zeta*wn-1/tau)/vmax
Ki = T*wn**2./vmax
K = Kp*vmax/T
wn = np.sqrt(K/(Kp/Ki))
zeta = (K + 1/tau)/(2*wn)
log.info('wn = %s' % (wn))
log.info('zeta = %s' % (zeta))
a = np.array([1, 2*zeta*wn, wn**2])
if tf_mode == 'H':
b = np.array([K, wn**2])
elif tf_mode == 'HE':
b = np.array([1, 2*zeta*wn-K, 0.])
elif tf_mode == 'HVW':
b = np.array([ 1, wn**2/K+1/tau, wn**2/(K*tau)])
b *= Kp
elif tf_mode == 'HED':
b = np.array([g, 0])
else:
raise ValueError('tf_mode must be: H, HE, HVU, or HED')
return b, a
def splane(b,a,auto_scale=True,size=[-1,1,-1,1]):
"""
Create an s-plane pole-zero plot.
As input the function uses the numerator and denominator
s-domain system function coefficient ndarrays b and a respectively.
Assumed to be stored in descending powers of s.
Parameters
----------
b : numerator coefficient ndarray.
a : denominator coefficient ndarray.
auto_scale : True
size : [xmin,xmax,ymin,ymax] plot scaling when scale = False
Returns
-------
(M,N) : tuple of zero and pole counts + plot window
Notes
-----
This function tries to identify repeated poles and zeros and will
place the multiplicity number above and to the right of the pole or zero.
The difficulty is setting the tolerance for this detection. Currently it
is set at 1e-3 via the function signal.unique_roots.
Examples
--------
>>> # Here the plot is generated using auto_scale
>>> splane(b,a)
>>> # Here the plot is generated using manual scaling
>>> splane(b,a,False,[-10,1,-10,10])
"""
if (isinstance(a,int) or isinstance(a,float)):
a = [a]
if (isinstance(b,int) or isinstance(b,float)):
b = [b]
M = len(b) - 1
N = len(a) - 1
plt.figure(figsize=(5,5))
#plt.axis('equal')
N_roots = np.array([0.0])
if M > 0:
N_roots = np.roots(b)
D_roots = np.array([0.0])
if N > 0:
D_roots = np.roots(a)
if auto_scale:
size[0] = min(np.min(np.real(N_roots)),np.min(np.real(D_roots)))-0.5
size[1] = max(np.max(np.real(N_roots)),np.max(np.real(D_roots)))+0.5
size[1] = max(size[1],0.5)
size[2] = min(np.min(np.imag(N_roots)),np.min(np.imag(D_roots)))-0.5
size[3] = max(np.max(np.imag(N_roots)),np.max(np.imag(D_roots)))+0.5
plt.plot([size[0],size[1]],[0,0],'k--')
plt.plot([0,0],[size[2],size[3]],'r--')
# Plot labels if multiplicity greater than 1
x_scale = size[1]-size[0]
y_scale = size[3]-size[2]
x_off = 0.03
y_off = 0.01
if M > 0:
#N_roots = np.roots(b)
N_uniq, N_mult=signal.unique_roots(N_roots,tol=1e-3, rtype='avg')
plt.plot(np.real(N_uniq),np.imag(N_uniq),'ko',mfc='None',ms=8)
idx_N_mult = np.nonzero(np.ravel(N_mult>1))[0]
for k in range(len(idx_N_mult)):
x_loc = np.real(N_uniq[idx_N_mult[k]]) + x_off*x_scale
y_loc =np.imag(N_uniq[idx_N_mult[k]]) + y_off*y_scale
plt.text(x_loc,y_loc,str(N_mult[idx_N_mult[k]]),ha='center',va='bottom',fontsize=10)
if N > 0:
#D_roots = np.roots(a)
D_uniq, D_mult=signal.unique_roots(D_roots,tol=1e-3, rtype='avg')
plt.plot(np.real(D_uniq),np.imag(D_uniq),'kx',ms=8)
idx_D_mult = np.nonzero(np.ravel(D_mult>1))[0]
for k in range(len(idx_D_mult)):
x_loc = np.real(D_uniq[idx_D_mult[k]]) + x_off*x_scale
y_loc =np.imag(D_uniq[idx_D_mult[k]]) + y_off*y_scale
plt.text(x_loc,y_loc,str(D_mult[idx_D_mult[k]]),ha='center',va='bottom',fontsize=10)
plt.xlabel('Real Part')
plt.ylabel('Imaginary Part')
plt.title('Pole-Zero Plot')
#plt.grid()
plt.axis(np.array(size))
return M,N
def os_filter(x, h, N, mode=0):
"""
Overlap and save transform domain FIR filtering.
This function implements the classical overlap and save method of
transform domain filtering using a length P FIR filter.
Parameters
----------
x : input signal to be filtered as an ndarray
h : FIR filter coefficients as an ndarray of length P
N : FFT size > P, typically a power of two
mode : 0 or 1, when 1 returns a diagnostic matrix
Returns
-------
y : the filtered output as an ndarray
y_mat : an ndarray whose rows are the individual overlap outputs.
Notes
-----
y_mat is used for diagnostics and to gain understanding of the algorithm.
Examples
--------
>>> from numpy import arange, cos, pi, ones
>>> n = arange(0,100)
>>> x = cos(2*pi*0.05*n)
>>> b = ones(10)
>>> y = os_filter(x,h,N)
>>> # set mode = 1
>>> y, y_mat = os_filter(x,h,N,1)
"""
P = len(h)
# zero pad start of x so first frame can recover first true samples of x
x = np.hstack((np.zeros(P-1),x))
L = N - P + 1
Nx = len(x)
Nframe = int(np.ceil(Nx/float(L)))
# zero pad end of x to full number of frames needed
x = np.hstack((x,np.zeros(Nframe*L-Nx)))
y = np.zeros(int(Nframe*N))
# create an instrumentation matrix to observe the overlap and save behavior
y_mat = np.zeros((Nframe,int(Nframe*N)))
H = fft.fft(h,N)
# begin the filtering operation
for k in range(Nframe):
xk = x[k*L:k*L+N]
Xk = fft.fft(xk,N)
Yk = H*Xk
yk = np.real(fft.ifft(Yk)) # imag part should be zero
y[k*L+P-1:k*L+N] = yk[P-1:]
y_mat[k,k*L:k*L+N] = yk
if mode == 1:
return y[P-1:Nx], y_mat[:,P-1:Nx]
else:
return y[P-1:Nx]
def oa_filter(x, h, N, mode=0):
"""
Overlap and add transform domain FIR filtering.
This function implements the classical overlap and add method of
transform domain filtering using a length P FIR filter.
Parameters
----------
x : input signal to be filtered as an ndarray
h : FIR filter coefficients as an ndarray of length P
N : FFT size > P, typically a power of two
mode : 0 or 1, when 1 returns a diagnostic matrix
Returns
-------
y : the filtered output as an ndarray
y_mat : an ndarray whose rows are the individual overlap outputs.
Notes
-----
y_mat is used for diagnostics and to gain understanding of the algorithm.
Examples
--------
>>> import numpy as np
>>> from sk_dsp_comm.sigsys import oa_filter
>>> n = np.arange(0,100)
>>> x = np.cos(2*np.pi*0.05*n)
>>> b = np.ones(10)
>>> y = oa_filter(x,h,N)
>>> # set mode = 1
>>> y, y_mat = oa_filter(x,h,N,1)
"""
P = len(h)
L = int(N) - P + 1 # need N >= L + P -1
Nx = len(x)
Nframe = int(np.ceil(Nx/float(L)))
# zero pad to full number of frames needed
x = np.hstack((x,np.zeros(Nframe*L-Nx)))
y = np.zeros(Nframe*N)
# create an instrumentation matrix to observe the overlap and add behavior
y_mat = np.zeros((Nframe,Nframe*N))
H = fft.fft(h,N)
# begin the filtering operation
for k in range(Nframe):
xk = x[k*L:(k+1)*L]
Xk = fft.fft(xk,N)
Yk = H*Xk
yk = np.real(fft.ifft(Yk))
y[k*L:k*L+N] += yk
y_mat[k,k*L:k*L+N] = yk
if mode == 1:
return y[0:Nx], y_mat[:,0:Nx]
else:
return y[0:Nx]
def lp_samp(fb,fs,fmax,N,shape='tri',fsize=(6,4)):
"""
Lowpass sampling theorem plotting function.
Display the spectrum of a sampled signal after setting the bandwidth,
sampling frequency, maximum display frequency, and spectral shape.
Parameters
----------
fb : spectrum lowpass bandwidth in Hz
fs : sampling frequency in Hz
fmax : plot over [-fmax,fmax]
shape : 'tri' or 'line'
N : number of translates, N positive and N negative
fsize : the size of the figure window, default (6,4)
Returns
-------
Nothing : A plot window opens containing the spectrum plot
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from sk_dsp_comm.sigsys import lp_samp
No aliasing as bandwidth 10 Hz < 25/2; fs > fb.
>>> lp_samp(10,25,50,10)
>>> plt.show()
Now aliasing as bandwidth 15 Hz > 25/2; fs < fb.
>>> lp_samp(15,25,50,10)
"""
plt.figure(figsize=fsize)
# define the plot interval
f = np.arange(-fmax,fmax+fmax/200.,fmax/200.)
A = 1.0
line_ampl = A/2.*np.array([0, 1])
# plot the lowpass spectrum in black
shapes = ['tri', 'line']
if shape.lower() not in shapes:
raise ValueError('shape must be tri or line')
if shape.lower() == 'tri':
plt.plot(f,lp_tri(f,fb))
# overlay positive and negative frequency translates
for n in range(N):
plt.plot(f, lp_tri(f - (n + 1) * fs, fb), '--r')
plt.plot(f, lp_tri(f + (n + 1) * fs, fb), '--g')
elif shape.lower() == 'line':
plt.plot([fb, fb],line_ampl,'b', linewidth=2)
plt.plot([-fb, -fb],line_ampl,'b', linewidth=2)
# overlay positive and negative frequency translates
for n in range(N):
plt.plot([fb+(n+1)*fs, fb+(n+1)*fs],line_ampl,'--r', linewidth=2)
plt.plot([-fb+(n+1)*fs, -fb+(n+1)*fs],line_ampl,'--r', linewidth=2)
plt.plot([fb-(n+1)*fs, fb-(n+1)*fs],line_ampl,'--g', linewidth=2)
plt.plot([-fb-(n+1)*fs, -fb-(n+1)*fs],line_ampl,'--g', linewidth=2)
plt.ylabel('Spectrum Magnitude')
plt.xlabel('Frequency in Hz')
plt.axis([-fmax,fmax,0,1])
plt.grid()
def lp_tri(f, fb):
"""
Triangle spectral shape function used by :func:`lp_samp`.
Parameters
----------
f : ndarray containing frequency samples
fb : the bandwidth as a float constant
Returns
-------
x : ndarray of spectrum samples for a single triangle shape
Notes
-----
This is a support function for the lowpass spectrum plotting function
:func:`lp_samp`.
Examples
--------
>>> x = lp_tri(f, fb)
"""
x = np.zeros(len(f))
for k in range(len(f)):
if abs(f[k]) <= fb:
x[k] = 1 - abs(f[k])/float(fb)
return x
def sinusoid_awgn(x, SNRdB):
"""
Add white Gaussian noise to a single real sinusoid.
Input a single sinusoid to this function and it returns a noisy
sinusoid at a specific SNR value in dB. Sinusoid power is calculated
using np.var.
Parameters
----------
x : Input signal as ndarray consisting of a single sinusoid
SNRdB : SNR in dB for output sinusoid
Returns
-------
y : Noisy sinusoid return vector
Examples
--------
>>> # set the SNR to 10 dB
>>> n = arange(0,10000)
>>> x = cos(2*pi*0.04*n)
>>> y = sinusoid_awgn(x,10.0)
"""
# Estimate signal power
x_pwr = np.var(x)
# Create noise vector
noise = np.sqrt(x_pwr/10**(SNRdB/10.))*np.random.randn(len(x));
return x + noise
def simple_quant(x, b_tot, x_max, limit):
"""
A simple rounding quantizer for bipolar signals having Btot = B + 1 bits.
This function models a quantizer that employs Btot bits that has one of
three selectable limiting types: saturation, overflow, and none.
The quantizer is bipolar and implements rounding.
Parameters
----------
x : input signal ndarray to be quantized
b_tot : total number of bits in the quantizer, e.g. 16
x_max : quantizer full-scale dynamic range is [-Xmax, Xmax]
Limit = Limiting of the form 'sat', 'over', 'none'
Returns
-------
xq : quantized output ndarray
Notes
-----
The quantization can be formed as e = xq - x
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from matplotlib.mlab import psd
>>> import numpy as np
>>> from sk_dsp_comm import sigsys as ss
>>> n = np.arange(0,10000)
>>> x = np.cos(2*np.pi*0.211*n)
>>> y = ss.sinusoid_awgn(x,90)
>>> Px, f = psd(y,2**10,Fs=1)
>>> plt.plot(f, 10*np.log10(Px))
>>> plt.ylim([-80, 25])
>>> plt.ylabel("Power Spectral Density (dB)")
>>> plt.xlabel(r'Normalized Frequency $\omega/2\pi$')
>>> plt.show()
>>> yq = ss.simple_quant(y,12,1,'sat')
>>> Px, f = psd(yq,2**10,Fs=1)
>>> plt.plot(f, 10*np.log10(Px))
>>> plt.ylim([-80, 25])
>>> plt.ylabel("Power Spectral Density (dB)")
>>> plt.xlabel(r'Normalized Frequency $\omega/2\pi$')
>>> plt.show()
"""
B = b_tot - 1
x = x / x_max
if limit.lower() == 'over':
xq = (np.mod(np.round(x*2**B) + 2 ** B, 2 ** b_tot) - 2 ** B) / 2 ** B
elif limit.lower() == 'sat':
xq = np.round(x*2**B)+2**B
s1 = np.nonzero(np.ravel(xq >= 2 ** b_tot - 1))[0]
s2 = np.nonzero(np.ravel(xq < 0))[0]
xq[s1] = (2 ** b_tot - 1) * np.ones(len(s1))
xq[s2] = np.zeros(len(s2))
xq = (xq - 2**B)/2**B
elif limit.lower() == 'none':
xq = np.round(x*2**B)/2**B
else:
raise ValueError('limit must be the string over, sat, or none')
return xq * x_max
def prin_alias(f_in,fs):
"""
Calculate the principle alias frequencies.
Given an array of input frequencies the function returns an
array of principle alias frequencies.
Parameters
----------
f_in : ndarray of input frequencies
fs : sampling frequency
Returns
-------
f_out : ndarray of principle alias frequencies
Examples
--------
>>> # Linear frequency sweep from 0 to 50 Hz
>>> f_in = arange(0,50,0.1)
>>> # Calculate principle alias with fs = 10 Hz
>>> f_out = prin_alias(f_in,10)
"""
return abs(np.rint(f_in/fs)*fs - f_in)
"""
Principle alias via recursion
f_out = np.copy(f_in)
for k in range(len(f_out)):
while f_out[k] > fs/2.:
f_out[k] = abs(f_out[k] - fs)
return f_out
"""
def cascade_filters(b1,a1,b2,a2):
"""
Cascade two IIR digital filters into a single (b,a) coefficient set.
To cascade two digital filters (system functions) given their numerator
and denominator coefficients you simply convolve the coefficient arrays.
Parameters
----------
b1 : ndarray of numerator coefficients for filter 1
a1 : ndarray of denominator coefficients for filter 1
b2 : ndarray of numerator coefficients for filter 2
a2 : ndarray of denominator coefficients for filter 2
Returns
-------
b : ndarray of numerator coefficients for the cascade
a : ndarray of denominator coefficients for the cascade
Examples
--------
>>> from scipy import signal
>>> b1,a1 = signal.butter(3, 0.1)
>>> b2,a2 = signal.butter(3, 0.15)
>>> b,a = cascade_filters(b1,a1,b2,a2)
"""
return signal.convolve(b1,b2), signal.convolve(a1,a2)
def soi_snoi_gen(s,SIR_dB,N,fi,fs = 8000):
"""
Add an interfering sinusoidal tone to the input signal at a given SIR_dB.
The input is the signal of interest (SOI) and number of sinsuoid signals
not of interest (SNOI) are addedto the SOI at a prescribed signal-to-
intereference SIR level in dB.
Parameters
----------
s : ndarray of signal of SOI
SIR_dB : interference level in dB
N : Trim input signal s to length N + 1 samples
fi : ndarray of intereference frequencies in Hz
fs : sampling rate in Hz, default is 8000 Hz
Returns
-------
r : ndarray of combined signal plus intereference of length N+1 samples
Examples
--------
>>> # load a speech ndarray and trim to 5*8000 + 1 samples
>>> fs,s = from_wav('OSR_us_000_0030_8k.wav')
>>> r = soi_snoi_gen(s,10,5*8000,[1000, 1500])
"""
n = np.arange(0,N+1)
K = len(fi)
si = np.zeros(N+1)
for k in range(K):
si += np.cos(2*np.pi*fi[k]/fs*n);
s = s[:N+1]
Ps = np.var(s)
Psi = np.var(si)
r = s + np.sqrt(Ps/Psi*10**(-SIR_dB/10))*si
return r
def lms_ic(r,M,mu,delta=1):
"""
Least mean square (LMS) interference canceller adaptive filter.
A complete LMS adaptive filter simulation function for the case of
interference cancellation. Used in the digital filtering case study.
Parameters
----------
M : FIR Filter length (order M-1)
delta : Delay used to generate the reference signal
mu : LMS step-size
delta : decorrelation delay between input and FIR filter input
Returns
-------
n : ndarray Index vector
r : ndarray noisy (with interference) input signal
r_hat : ndarray filtered output (NB_hat[n])
e : ndarray error sequence (WB_hat[n])
ao : ndarray final value of weight vector
F : ndarray frequency response axis vector
Ao : ndarray frequency response of filter
Examples
----------
>>> # import a speech signal
>>> fs,s = from_wav('OSR_us_000_0030_8k.wav')
>>> # add interference at 1kHz and 1.5 kHz and
>>> # truncate to 5 seconds
>>> r = soi_snoi_gen(s,10,5*8000,[1000, 1500])
>>> # simulate with a 64 tap FIR and mu = 0.005
>>> n,r,r_hat,e,ao,F,Ao = lms_ic(r,64,0.005)
"""
N = len(r)-1;
# Form the reference signal y via delay delta
y = signal.lfilter(np.hstack((np.zeros(delta), np.array([1]))),1,r)
# Initialize output vector x_hat to zero
r_hat = np.zeros(N+1)
# Initialize error vector e to zero
e = np.zeros(N+1)
# Initialize weight vector to zero
ao = np.zeros(M+1)
# Initialize filter memory to zero
z = np.zeros(M)
# Initialize a vector for holding ym of length M+1
ym = np.zeros(M+1)
for k in range(N+1):
# Filter one sample at a time
r_hat[k],z = signal.lfilter(ao,np.array([1]),np.array([y[k]]),zi=z)
# Form the error sequence
e[k] = r[k] - r_hat[k]
# Update the weight vector
ao = ao + 2*mu*e[k]*ym
# Update vector used for correlation with e(k)
ym = np.hstack((np.array([y[k]]), ym[:-1]))
# Create filter frequency response
F, Ao = signal.freqz(ao,1,1024)
F/= (2*np.pi)
Ao = 20*np.log10(abs(Ao))
return np.arange(0,N+1), r, r_hat, e, ao, F, Ao
def fir_iir_notch(fi,fs,r=0.95):
"""
Design a second-order FIR or IIR notch filter.
A second-order FIR notch filter is created by placing conjugate
zeros on the unit circle at angle corresponidng to the notch center
frequency. The IIR notch variation places a pair of conjugate poles
at the same angle, but with radius r < 1 (typically 0.9 to 0.95).
Parameters
----------
fi : notch frequency is Hz relative to fs
fs : the sampling frequency in Hz, e.g. 8000
r : pole radius for IIR version, default = 0.95
Returns
-------
b : numerator coefficient ndarray
a : denominator coefficient ndarray
Notes
-----
If the pole radius is 0 then an FIR version is created, that is
there are no poles except at z = 0.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from sk_dsp_comm import sigsys as ss
>>> b_FIR, a_FIR = ss.fir_iir_notch(1000,8000,0)
>>> ss.zplane(b_FIR, a_FIR)
>>> plt.show()
>>> b_IIR, a_IIR = ss.fir_iir_notch(1000,8000)
>>> ss.zplane(b_IIR, a_IIR)
"""
w0 = 2*np.pi*fi/float(fs)
if r >= 1:
raise ValueError('Poles on or outside unit circle.')
elif r == 0:
a = np.array([1.0])
else:
a = np.array([1, -2*r*np.cos(w0), r**2])
b = np.array([1, -2*np.cos(w0), 1])
return b, a
def simple_sa(x, NS, NFFT, fs, NAVG=1, window='boxcar'):
"""
Spectral estimation using windowing and averaging.
This function implements averaged periodogram spectral estimation
estimation similar to the NumPy's psd() function, but more
specialized for the windowing case study of Chapter 16.
Parameters
----------
x : ndarray containing the input signal
NS : The subrecord length less zero padding, e.g. NS < NFFT
NFFT : FFT length, e.g., 1024 = 2**10
fs : sampling rate in Hz
NAVG : the number of averages, e.g., 1 for deterministic signals
window : hardcoded window 'boxcar' (default) or 'hanning'
Returns
-------
f : ndarray frequency axis in Hz on [0, fs/2]
Sx : ndarray the power spectrum estimate
Notes
-----
The function also prints the maximum number of averages K possible
for the input data record.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from sk_dsp_comm import sigsys as ss
>>> n = np.arange(0,2048)
>>> x = np.cos(2*np.pi*1000/10000*n) + 0.01*np.cos(2*np.pi*3000/10000*n)
>>> f, Sx = ss.simple_sa(x,128,512,10000)
>>> plt.plot(f, 10*np.log10(Sx))
>>> plt.ylim([-80, 0])
>>> plt.xlabel("Frequency (Hz)")
>>> plt.ylabel("Power Spectral Density (dB)")
>>> plt.show()
With a hanning window.
>>> f, Sx = ss.simple_sa(x,256,1024,10000,window='hanning')
>>> plt.plot(f, 10*np.log10(Sx))
>>> plt.xlabel("Frequency (Hz)")
>>> plt.ylabel("Power Spectral Density (dB)")
>>> plt.ylim([-80, 0])
"""
Nx = len(x)
K = int(Nx/NS)
log.info('K = ', K)
if NAVG > K:
warnings.warn('NAVG exceeds number of available subrecords')
return 0,0
if window.lower() == 'boxcar' or window.lower() == 'rectangle':
w = signal.boxcar(NS)
elif window.lower() == 'hanning':
w = signal.hanning(NS)
xsw = np.zeros((K,NS)) + 1j*np.zeros((K,NS))
for k in range(NAVG):
xsw[k,] = w*x[k*NS:(k+1)*NS]
Sx = np.zeros(NFFT)
for k in range(NAVG):
X = fft.fft(xsw[k,],NFFT)
Sx += abs(X)**2
Sx /= float(NAVG)
Sx /= float(NFFT**2)
NFFTby2 = int(NFFT/2)
if x.dtype != 'complex128':
n = np.arange(NFFTby2)
f = fs*n/float(NFFT)
Sx = Sx[0:NFFTby2]
else:
n = np.arange(NFFTby2)
f = fs*np.hstack((np.arange(-NFFTby2,0),np.arange(NFFTby2)))/float(NFFT)
Sx = np.hstack((Sx[NFFTby2:],Sx[0:NFFTby2]))
return f, Sx
def line_spectra(fk,Xk,mode,sides=2,linetype='b',lwidth=2,floor_dB=-100,fsize=(6,4)):
"""
Plot the Fourier series line spectral given the coefficients.
This function plots two-sided and one-sided line spectra of a periodic
signal given the complex exponential Fourier series coefficients and
the corresponding harmonic frequencies.
Parameters
----------
fk : vector of real sinusoid frequencies
Xk : magnitude and phase at each positive frequency in fk
mode : 'mag' => magnitude plot, 'magdB' => magnitude in dB plot,
mode cont : 'magdBn' => magnitude in dB normalized, 'phase' => a phase plot in radians
sides : 2; 2-sided or 1-sided
linetype : line type per Matplotlib definitions, e.g., 'b';
lwidth : 2; linewidth in points
fsize : optional figure size in inches, default = (6,4) inches
Returns
-------
Nothing : A plot window opens containing the line spectrum plot
Notes
-----
Since real signals are assumed the frequencies of fk are 0 and/or positive
numbers. The supplied Fourier coefficients correspond.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from sk_dsp_comm.sigsys import line_spectra
>>> n = np.arange(0,25)
>>> # a pulse train with 10 Hz fundamental and 20% duty cycle
>>> fk = n*10
>>> Xk = np.sinc(n*10*.02)*np.exp(-1j*2*np.pi*n*10*.01) # 1j = sqrt(-1)
>>> line_spectra(fk,Xk,'mag')
>>> plt.show()
>>> line_spectra(fk,Xk,'phase')
"""
plt.figure(figsize=fsize)
# Eliminate zero valued coefficients
idx = np.nonzero(Xk)[0]
Xk = Xk[idx]
fk = fk[idx]
if mode == 'mag':
for k in range(len(fk)):
if fk[k] == 0 and sides == 2:
plt.plot([fk[k], fk[k]],[0, np.abs(Xk[k])],linetype, linewidth=lwidth)
elif fk[k] == 0 and sides == 1:
plt.plot([fk[k], fk[k]],[0, np.abs(Xk[k])],linetype, linewidth=2*lwidth)
elif fk[k] > 0 and sides == 2:
plt.plot([fk[k], fk[k]],[0, np.abs(Xk[k])],linetype, linewidth=lwidth)
plt.plot([-fk[k], -fk[k]],[0, np.abs(Xk[k])],linetype, linewidth=lwidth)
elif fk[k] > 0 and sides == 1:
plt.plot([fk[k], fk[k]],[0, 2.*np.abs(Xk[k])],linetype, linewidth=lwidth)
else:
warnings.warn('Invalid sides type')
plt.grid()
if sides == 2:
plt.axis([-1.2*max(fk), 1.2*max(fk), 0, 1.05*max(abs(Xk))])
elif sides == 1:
plt.axis([0, 1.2*max(fk), 0, 1.05*2*max(abs(Xk))])
else:
warnings.warn('Invalid sides type')
plt.ylabel('Magnitude')
plt.xlabel('Frequency (Hz)')
elif mode == 'magdB':
Xk_dB = 20*np.log10(np.abs(Xk))
for k in range(len(fk)):
if fk[k] == 0 and sides == 2:
plt.plot([fk[k], fk[k]],[floor_dB, Xk_dB[k]],linetype, linewidth=lwidth)
elif fk[k] == 0 and sides == 1:
plt.plot([fk[k], fk[k]],[floor_dB, Xk_dB[k]],linetype, linewidth=2*lwidth)
elif fk[k] > 0 and sides == 2:
plt.plot([fk[k], fk[k]],[floor_dB, Xk_dB[k]],linetype, linewidth=lwidth)
plt.plot([-fk[k], -fk[k]],[floor_dB, Xk_dB[k]],linetype, linewidth=lwidth)
elif fk[k] > 0 and sides == 1:
plt.plot([fk[k], fk[k]],[floor_dB, Xk_dB[k]+6.02],linetype, linewidth=lwidth)
else:
warnings.warn('Invalid sides type')
plt.grid()
max_dB = np.ceil(max(Xk_dB/10.))*10
min_dB = max(floor_dB,np.floor(min(Xk_dB/10.))*10)
if sides == 2:
plt.axis([-1.2*max(fk), 1.2*max(fk), min_dB, max_dB])
elif sides == 1:
plt.axis([0, 1.2*max(fk), min_dB, max_dB])
else:
warnings.warn('Invalid sides type')
plt.ylabel('Magnitude (dB)')
plt.xlabel('Frequency (Hz)')
elif mode == 'magdBn':
Xk_dB = 20*np.log10(np.abs(Xk)/max(np.abs(Xk)))
for k in range(len(fk)):
if fk[k] == 0 and sides == 2:
plt.plot([fk[k], fk[k]],[floor_dB, Xk_dB[k]],linetype, linewidth=lwidth)
elif fk[k] == 0 and sides == 1:
plt.plot([fk[k], fk[k]],[floor_dB, Xk_dB[k]],linetype, linewidth=2*lwidth)
elif fk[k] > 0 and sides == 2:
plt.plot([fk[k], fk[k]],[floor_dB, Xk_dB[k]],linetype, linewidth=lwidth)
plt.plot([-fk[k], -fk[k]],[floor_dB, Xk_dB[k]],linetype, linewidth=lwidth)
elif fk[k] > 0 and sides == 1:
plt.plot([fk[k], fk[k]],[floor_dB, Xk_dB[k]+6.02],linetype, linewidth=lwidth)
else:
warnings.warn('Invalid sides type')
plt.grid()
max_dB = np.ceil(max(Xk_dB/10.))*10
min_dB = max(floor_dB,np.floor(min(Xk_dB/10.))*10)
if sides == 2:
plt.axis([-1.2*max(fk), 1.2*max(fk), min_dB, max_dB])
elif sides == 1:
plt.axis([0, 1.2*max(fk), min_dB, max_dB])
else:
warnings.warn('Invalid sides type')
plt.ylabel('Normalized Magnitude (dB)')
plt.xlabel('Frequency (Hz)')
elif mode == 'phase':
for k in range(len(fk)):
if fk[k] == 0 and sides == 2:
plt.plot([fk[k], fk[k]],[0, np.angle(Xk[k])],linetype, linewidth=lwidth)
elif fk[k] == 0 and sides == 1:
plt.plot([fk[k], fk[k]],[0, np.angle(Xk[k])],linetype, linewidth=2*lwidth)
elif fk[k] > 0 and sides == 2:
plt.plot([fk[k], fk[k]],[0, np.angle(Xk[k])],linetype, linewidth=lwidth)
plt.plot([-fk[k], -fk[k]],[0, -np.angle(Xk[k])],linetype, linewidth=lwidth)
elif fk[k] > 0 and sides == 1:
plt.plot([fk[k], fk[k]],[0, np.angle(Xk[k])],linetype, linewidth=lwidth)
else:
warnings.warn('Invalid sides type')
plt.grid()
if sides == 2:
plt.plot([-1.2*max(fk), 1.2*max(fk)], [0, 0],'k')
plt.axis([-1.2*max(fk), 1.2*max(fk), -1.1*max(np.abs(np.angle(Xk))), 1.1*max(np.abs(np.angle(Xk)))])
elif sides == 1:
plt.plot([0, 1.2*max(fk)], [0, 0],'k')
plt.axis([0, 1.2*max(fk), -1.1*max(np.abs(np.angle(Xk))), 1.1*max(np.abs(np.angle(Xk)))])
else:
warnings.warn('Invalid sides type')
plt.ylabel('Phase (rad)')
plt.xlabel('Frequency (Hz)')
else:
warnings.warn('Invalid mode type')
def fs_coeff(xp,N,f0,one_side=True):
"""
Numerically approximate the Fourier series coefficients given periodic x(t).
The input is assummed to represent one period of the waveform
x(t) that has been uniformly sampled. The number of samples supplied
to represent one period of the waveform sets the sampling rate.
Parameters
----------
xp : ndarray of one period of the waveform x(t)
N : maximum Fourier series coefficient, [0,...,N]
f0 : fundamental frequency used to form fk.
Returns
-------
Xk : ndarray of the coefficients over indices [0,1,...,N]
fk : ndarray of the harmonic frequencies [0, f0,2f0,...,Nf0]
Notes
-----
len(xp) >= 2*N+1 as len(xp) is the fft length.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from numpy import arange
>>> import sk_dsp_comm.sigsys as ss
>>> t = arange(0,1,1/1024.)
>>> # a 20% duty cycle pulse starting at t = 0
>>> x_rect = ss.rect(t-.1,0.2)
>>> Xk, fk = ss.fs_coeff(x_rect,25,10)
>>> # plot the spectral lines
>>> ss.line_spectra(fk,Xk,'mag')
>>> plt.show()
"""
Nint = len(xp)
if Nint < 2*N+1:
raise ValueError('Number of samples in xp insufficient for requested N.')
Xp = fft.fft(xp,Nint)/float(Nint)
# To interface with the line_spectra function use one_side mode
if one_side:
Xk = Xp[0:N+1]
fk = f0*np.arange(0,N+1)
else:
Xk = np.hstack((Xp[-N:],Xp[0:N+1]))
fk = f0*np.arange(-N,N+1)
return Xk, fk
def fs_approx(Xk,fk,t):
"""
Synthesize periodic signal x(t) using Fourier series coefficients at harmonic frequencies
Assume the signal is real so coefficients Xk are supplied for nonnegative
indicies. The negative index coefficients are assumed to be complex
conjugates.
Parameters
----------
Xk : ndarray of complex Fourier series coefficients
fk : ndarray of harmonic frequencies in Hz
t : ndarray time axis corresponding to output signal array x_approx
Returns
-------
x_approx : ndarray of periodic waveform approximation over time span t
Examples
--------
>>> t = arange(0,2,.002)
>>> # a 20% duty cycle pulse train
>>> n = arange(0,20,1) # 0 to 19th harmonic
>>> fk = 1*n % period = 1s
>>> t, x_approx = fs_approx(Xk,fk,t)
>>> plot(t,x_approx)
"""
x_approx = np.zeros(len(t))
for k,Xkk in enumerate(Xk):
if fk[k] == 0:
x_approx += Xkk.real*np.ones(len(t))
else:
x_approx += 2*np.abs(Xkk)*np.cos(2*np.pi*fk[k]*t+np.angle(Xkk))
return x_approx
def ft_approx(x,t,Nfft):
'''
Approximate the Fourier transform of a finite duration signal using scipy.signal.freqz()
Parameters
----------
x : input signal array
t : time array used to create x(t)
Nfft : the number of frdquency domain points used to
approximate X(f) on the interval [fs/2,fs/2], where
fs = 1/Dt. Dt being the time spacing in array t
Returns
-------
f : frequency axis array in Hz
X : the Fourier transform approximation (complex)
Notes
-----
The output time axis starts at the sum of the starting values in x1 and x2
and ends at the sum of the two ending values in x1 and x2. The default
extents of ('f','f') are used for signals that are active (have support)
on or within n1 and n2 respectively. A right-sided signal such as
:math:`a^n*u[n]` is semi-infinite, so it has extent 'r' and the
convolution output will be truncated to display only the valid results.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> import sk_dsp_comm.sigsys as ss
>>> fs = 100 # sampling rate in Hz
>>> tau = 1
>>> t = np.arange(-5,5,1/fs)
>>> x0 = ss.rect(t-.5,tau)
>>> plt.figure(figsize=(6,5))
>>> plt.plot(t,x0)
>>> plt.grid()
>>> plt.ylim([-0.1,1.1])
>>> plt.xlim([-2,2])
>>> plt.title(r'Exact Waveform')
>>> plt.xlabel(r'Time (s)')
>>> plt.ylabel(r'$x_0(t)$')
>>> plt.show()
>>> # FT Exact Plot
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> import sk_dsp_comm.sigsys as ss
>>> fs = 100 # sampling rate in Hz
>>> tau = 1
>>> t = np.arange(-5,5,1/fs)
>>> x0 = ss.rect(t-.5,tau)
>>> fe = np.arange(-10,10,.01)
>>> X0e = tau*np.sinc(fe*tau)
>>> plt.plot(fe,abs(X0e))
>>> #plot(f,angle(X0))
>>> plt.grid()
>>> plt.xlim([-10,10])
>>> plt.title(r'Exact (Theory) Spectrum Magnitude')
>>> plt.xlabel(r'Frequency (Hz)')
>>> plt.ylabel(r'$|X_0e(f)|$')
>>> plt.show()
>>> # FT Approximation Plot
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> import sk_dsp_comm.sigsys as ss
>>> fs = 100 # sampling rate in Hz
>>> tau = 1
>>> t = np.arange(-5,5,1/fs)
>>> x0 = ss.rect(t-.5,tau)
>>> f,X0 = ss.ft_approx(x0,t,4096)
>>> plt.plot(f,abs(X0))
>>> #plt.plot(f,angle(X0))
>>> plt.grid()
>>> plt.xlim([-10,10])
>>> plt.title(r'Approximation Spectrum Magnitude')
>>> plt.xlabel(r'Frequency (Hz)')
>>> plt.ylabel(r'$|X_0(f)|$');
>>> plt.tight_layout()
>>> plt.show()
'''
fs = 1/(t[1] - t[0])
t0 = (t[-1]+t[0])/2 # time delay at center
N0 = len(t)/2 # FFT center in samples
f = np.arange(-1./2,1./2,1./Nfft)
w, X = signal.freqz(x,1,2*np.pi*f)
X /= fs # account for dt = 1/fs in integral
X *= np.exp(-1j*2*np.pi*f*fs*t0)# time interval correction
X *= np.exp(1j*2*np.pi*f*N0)# FFT time interval is [0,Nfft-1]
F = f*fs
return F, X
def conv_sum(x1,nx1,x2,nx2,extent=('f','f')):
"""
Discrete convolution of x1 and x2 with proper tracking of the output time axis.
Convolve two discrete-time signals using the SciPy function :func:`scipy.signal.convolution`.
The time (sequence axis) are managed from input to output. y[n] = x1[n]*x2[n].
Parameters
----------
x1 : ndarray of signal x1 corresponding to nx1
nx1 : ndarray time axis for x1
x2 : ndarray of signal x2 corresponding to nx2
nx2 : ndarray time axis for x2
extent : ('e1','e2') where 'e1', 'e2' may be 'f' finite, 'r' right-sided, or 'l' left-sided
Returns
-------
y : ndarray of output values y
ny : ndarray of the corresponding sequence index n
Notes
-----
The output time axis starts at the sum of the starting values in x1 and x2
and ends at the sum of the two ending values in x1 and x2. The default
extents of ('f','f') are used for signals that are active (have support)
on or within n1 and n2 respectively. A right-sided signal such as
a^n*u[n] is semi-infinite, so it has extent 'r' and the
convolution output will be truncated to display only the valid results.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> import sk_dsp_comm.sigsys as ss
>>> nx = np.arange(-5,10)
>>> x = ss.drect(nx,4)
>>> y,ny = ss.conv_sum(x,nx,x,nx)
>>> plt.stem(ny,y)
>>> plt.show()
Consider a pulse convolved with an exponential. ('r' type extent)
>>> h = 0.5**nx*ss.dstep(nx)
>>> y,ny = ss.conv_sum(x,nx,h,nx,('f','r')) # note extents set
>>> plt.stem(ny,y) # expect a pulse charge and discharge sequence
"""
nnx1 = np.arange(0,len(nx1))
nnx2 = np.arange(0,len(nx2))
n1 = nnx1[0]
n2 = nnx1[-1]
n3 = nnx2[0]
n4 = nnx2[-1]
# Start by finding the valid output support or extent interval to insure that
# for no finite extent signals ambiquous results are not returned.
# Valid extents are f (finite), r (right-sided), and l (left-sided)
if extent[0] == 'f' and extent[1] == 'f':
nny = np.arange(n1+n3,n2+1+n4+1-1)
ny = np.arange(0,len(x1)+len(x2)-1) + nx1[0]+nx2[0]
elif extent[0] == 'f' and extent[1] == 'r':
nny = np.arange(n1+n3,n1+1+n4+1-1)
ny = nny + nx1[0]+nx2[0]
elif extent[0] == 'r' and extent[1] == 'f':
nny = np.arange(n1+n3,n2+1+n3+1-1)
ny = nny + nx1[0]+nx2[0]
elif extent[0] == 'f' and extent[1] == 'l':
nny = np.arange(n2+n3,n2+1+n4+1-1)
ny = nny + nx1[-1]+nx2[0]
elif extent[0] == 'l' and extent[1] == 'f':
nny = np.arange(n1+n4,n2+1+n4+1-1)
ny = nny + nx1[0]+nx2[-1]
elif extent[0] == 'r' and extent[1] == 'r':
nny = np.arange(n1+n3,min(n1+1+n4+1,n2+1+n3+1)-1)
ny = nny + nx1[0]+nx2[0]
elif extent[0] == 'l' and extent[1] == 'l':
nny = np.arange(max(n1+n4,n2+n3),n2+1+n4+1-1)
ny = nny + max(nx1[0]+nx2[-1],nx1[-1]+nx2[0])
else:
raise ValueError('Invalid x1 x2 extents specified or valid extent not found!')
# Finally convolve the sequences
y = signal.convolve(x1, x2)
log.info('Output support: (%+d, %+d)' % (ny[0],ny[-1]))
return y[nny], ny
def conv_integral(x1,tx1,x2,tx2,extent=('f','f')):
"""
Continuous-time convolution of x1 and x2 with proper tracking of the output time axis.
Appromimate the convolution integral for the convolution of two continuous-time signals using the SciPy function signal. The time (sequence axis) are managed from input to output. y(t) = x1(t)*x2(t).
Parameters
----------
x1 : ndarray of signal x1 corresponding to tx1
tx1 : ndarray time axis for x1
x2 : ndarray of signal x2 corresponding to tx2
tx2 : ndarray time axis for x2
extent : ('e1','e2') where 'e1', 'e2' may be 'f' finite, 'r' right-sided, or 'l' left-sided
Returns
-------
y : ndarray of output values y
ty : ndarray of the corresponding time axis for y
Notes
-----
The output time axis starts at the sum of the starting values in x1 and x2
and ends at the sum of the two ending values in x1 and x2. The time steps used in
x1(t) and x2(t) must match. The default extents of ('f','f') are used for signals
that are active (have support) on or within t1 and t2 respectively. A right-sided
signal such as exp(-a*t)*u(t) is semi-infinite, so it has extent 'r' and the
convolution output will be truncated to display only the valid results.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> import sk_dsp_comm.sigsys as ss
>>> tx = np.arange(-5,10,.01)
>>> x = ss.rect(tx-2,4) # pulse starts at t = 0
>>> y,ty = ss.conv_integral(x,tx,x,tx)
>>> plt.plot(ty,y) # expect a triangle on [0,8]
>>> plt.show()
Now, consider a pulse convolved with an exponential.
>>> h = 4*np.exp(-4*tx)*ss.step(tx)
>>> y,ty = ss.conv_integral(x,tx,h,tx,extent=('f','r')) # note extents set
>>> plt.plot(ty,y) # expect a pulse charge and discharge waveform
"""
dt = tx1[1] - tx1[0]
nx1 = np.arange(0,len(tx1))
nx2 = np.arange(0,len(tx2))
n1 = nx1[0]
n2 = nx1[-1]
n3 = nx2[0]
n4 = nx2[-1]
# Start by finding the valid output support or extent interval to insure that
# for no finite extent signals ambiquous results are not returned.
# Valid extents are f (finite), r (right-sided), and l (left-sided)
if extent[0] == 'f' and extent[1] == 'f':
ny = np.arange(n1+n3,n2+1+n4+1-1)
ty = np.arange(0,len(x1)+len(x2)-1)*dt + tx1[0]+tx2[0]
elif extent[0] == 'f' and extent[1] == 'r':
ny = np.arange(n1+n3,n1+1+n4+1-1)
ty = ny*dt + tx1[0]+tx2[0]
elif extent[0] == 'r' and extent[1] == 'f':
ny = np.arange(n1+n3,n2+1+n3+1-1)
ty = ny*dt + tx1[0]+tx2[0]
elif extent[0] == 'f' and extent[1] == 'l':
ny = np.arange(n2+n3,n2+1+n4+1-1)
ty = ny*dt + tx1[-1]+tx2[0]
elif extent[0] == 'l' and extent[1] == 'f':
ny = np.arange(n1+n4,n2+1+n4+1-1)
ty = ny*dt + tx1[0]+tx2[-1]
elif extent[0] == 'r' and extent[1] == 'r':
ny = np.arange(n1+n3,min(n1+1+n4+1,n2+1+n3+1)-1)
ty = ny*dt + tx1[0]+tx2[0]
elif extent[0] == 'l' and extent[1] == 'l':
ny = np.arange(max(n1+n4,n2+n3),n2+1+n4+1-1)
ty = ny*dt + max(tx1[0]+tx2[-1],tx1[-1]+tx2[0])
else:
raise ValueError('Invalid x1 x2 extents specified or valid extent not found!')
# Finally convolve the sampled sequences and scale by dt
y = signal.convolve(x1, x2)*dt
log.info('Output support: (%+2.2f, %+2.2f)' % (ty[0],ty[-1]))
return y[ny], ty
def delta_eps(t,eps):
"""
Rectangular pulse approximation to impulse function.
Parameters
----------
t : ndarray of time axis
eps : pulse width
Returns
-------
d : ndarray containing the impulse approximation
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from numpy import arange
>>> from sk_dsp_comm.sigsys import delta_eps
>>> t = np.arange(-2,2,.001)
>>> d = delta_eps(t,.1)
>>> plt.plot(t,d)
>>> plt.show()
"""
d = np.zeros(len(t))
for k,tt in enumerate(t):
if abs(tt) <= eps/2.:
d[k] = 1/float(eps)
return d
def step(t):
"""
Approximation to step function signal u(t).
In this numerical version of u(t) the step turns on at t = 0.
Parameters
----------
t : ndarray of the time axis
Returns
-------
x : ndarray of the step function signal u(t)
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from numpy import arange
>>> from sk_dsp_comm.sigsys import step
>>> t = arange(-1,5,.01)
>>> x = step(t)
>>> plt.plot(t,x)
>>> plt.ylim([-0.01, 1.01])
>>> plt.show()
To turn on at t = 1, shift t.
>>> x = step(t - 1.0)
>>> plt.ylim([-0.01, 1.01])
>>> plt.plot(t,x)
"""
x = np.zeros(len(t))
for k,tt in enumerate(t):
if tt >= 0:
x[k] = 1.0
return x
def rect(t,tau):
"""
Approximation to the rectangle pulse Pi(t/tau).
In this numerical version of Pi(t/tau) the pulse is active
over -tau/2 <= t <= tau/2.
Parameters
----------
t : ndarray of the time axis
tau : the pulse width
Returns
-------
x : ndarray of the signal Pi(t/tau)
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from numpy import arange
>>> from sk_dsp_comm.sigsys import rect
>>> t = arange(-1,5,.01)
>>> x = rect(t,1.0)
>>> plt.plot(t,x)
>>> plt.ylim([0, 1.01])
>>> plt.show()
To turn on the pulse at t = 1 shift t.
>>> x = rect(t - 1.0,1.0)
>>> plt.plot(t,x)
>>> plt.ylim([0, 1.01])
"""
x = np.zeros(len(t))
for k,tk in enumerate(t):
if np.abs(tk) > tau/2.:
x[k] = 0
else:
x[k] = 1
return x
def tri(t,tau):
"""
Approximation to the triangle pulse Lambda(t/tau).
In this numerical version of Lambda(t/tau) the pulse is active
over -tau <= t <= tau.
Parameters
----------
t : ndarray of the time axis
tau : one half the triangle base width
Returns
-------
x : ndarray of the signal Lambda(t/tau)
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from numpy import arange
>>> from sk_dsp_comm.sigsys import tri
>>> t = arange(-1,5,.01)
>>> x = tri(t,1.0)
>>> plt.plot(t,x)
>>> plt.show()
To turn on at t = 1, shift t.
>>> x = tri(t - 1.0,1.0)
>>> plt.plot(t,x)
"""
x = np.zeros(len(t))
for k,tk in enumerate(t):
if np.abs(tk) > tau/1.:
x[k] = 0
else:
x[k] = 1 - np.abs(tk)/tau
return x
def dimpulse(n):
"""
Discrete impulse function delta[n].
Parameters
----------
n : ndarray of the time axis
Returns
-------
x : ndarray of the signal delta[n]
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from numpy import arange
>>> from sk_dsp_comm.sigsys import dimpulse
>>> n = arange(-5,5)
>>> x = dimpulse(n)
>>> plt.stem(n,x)
>>> plt.show()
Shift the delta left by 2.
>>> x = dimpulse(n+2)
>>> plt.stem(n,x)
"""
x = np.zeros(len(n))
for k,nn in enumerate(n):
if nn == 0:
x[k] = 1.0
return x
def dstep(n):
"""
Discrete step function u[n].
Parameters
----------
n : ndarray of the time axis
Returns
-------
x : ndarray of the signal u[n]
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from numpy import arange
>>> from sk_dsp_comm.sigsys import dstep
>>> n = arange(-5,5)
>>> x = dstep(n)
>>> plt.stem(n,x)
>>> plt.show()
Shift the delta left by 2.
>>> x = dstep(n+2)
>>> plt.stem(n,x)
"""
x = np.zeros(len(n))
for k,nn in enumerate(n):
if nn >= 0:
x[k] = 1.0
return x
def drect(n,N):
"""
Discrete rectangle function of duration N samples.
The signal is active on the interval 0 <= n <= N-1. Also known
as the rectangular window function, which is available in
scipy.signal.
Parameters
----------
n : ndarray of the time axis
N : the pulse duration
Returns
-------
x : ndarray of the signal
Notes
-----
The discrete rectangle turns on at n = 0, off at n = N-1 and
has duration of exactly N samples.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from numpy import arange
>>> from sk_dsp_comm.sigsys import drect
>>> n = arange(-5,5)
>>> x = drect(n, N=3)
>>> plt.stem(n,x)
>>> plt.show()
Shift the delta left by 2.
>>> x = drect(n+2, N=3)
>>> plt.stem(n,x)
"""
x = np.zeros(len(n))
for k,nn in enumerate(n):
if nn >= 0 and nn < N:
x[k] = 1.0
return x
def rc_imp(Ns,alpha,M=6):
"""
A truncated raised cosine pulse used in digital communications.
The pulse shaping factor :math:`0< \\alpha < 1` is required as well as the
truncation factor M which sets the pulse duration to be 2*M*Tsymbol.
Parameters
----------
Ns : number of samples per symbol
alpha : excess bandwidth factor on (0, 1), e.g., 0.35
M : equals RC one-sided symbol truncation factor
Returns
-------
b : ndarray containing the pulse shape
Notes
-----
The pulse shape b is typically used as the FIR filter coefficients
when forming a pulse shaped digital communications waveform.
Examples
--------
Ten samples per symbol and alpha = 0.35.
>>> import matplotlib.pyplot as plt
>>> from numpy import arange
>>> from sk_dsp_comm.sigsys import rc_imp
>>> b = rc_imp(10,0.35)
>>> n = arange(-10*6,10*6+1)
>>> plt.stem(n,b)
>>> plt.show()
"""
# Design the filter
n = np.arange(-M*Ns,M*Ns+1)
b = np.zeros(len(n));
a = alpha;
Ns *= 1.0
for i in range(len(n)):
if (1 - 4*(a*n[i]/Ns)**2) == 0:
b[i] = np.pi/4*np.sinc(1/(2.*a))
else:
b[i] = np.sinc(n[i]/Ns)*np.cos(np.pi*a*n[i]/Ns)/(1 - 4*(a*n[i]/Ns)**2)
return b
def sqrt_rc_imp(Ns,alpha,M=6):
"""
A truncated square root raised cosine pulse used in digital communications.
The pulse shaping factor 0< alpha < 1 is required as well as the
truncation factor M which sets the pulse duration to be 2*M*Tsymbol.
Parameters
----------
Ns : number of samples per symbol
alpha : excess bandwidth factor on (0, 1), e.g., 0.35
M : equals RC one-sided symbol truncation factor
Returns
-------
b : ndarray containing the pulse shape
Notes
-----
The pulse shape b is typically used as the FIR filter coefficients
when forming a pulse shaped digital communications waveform. When
square root raised cosine (SRC) pulse is used generate Tx signals and
at the receiver used as a matched filter (receiver FIR filter), the
received signal is now raised cosine shaped, this having zero
intersymbol interference and the optimum removal of additive white
noise if present at the receiver input.
Examples
--------
>>> # ten samples per symbol and alpha = 0.35
>>> import matplotlib.pyplot as plt
>>> from numpy import arange
>>> from sk_dsp_comm.sigsys import sqrt_rc_imp
>>> b = sqrt_rc_imp(10,0.35)
>>> n = arange(-10*6,10*6+1)
>>> plt.stem(n,b)
>>> plt.show()
"""
# Design the filter
n = np.arange(-M*Ns,M*Ns+1)
b = np.zeros(len(n))
Ns *= 1.0
a = alpha
for i in range(len(n)):
if abs(1 - 16*a**2*(n[i]/Ns)**2) <= np.finfo(np.float).eps/2:
b[i] = 1/2.*((1+a)*np.sin((1+a)*np.pi/(4.*a))-(1-a)*np.cos((1-a)*np.pi/(4.*a))+(4*a)/np.pi*np.sin((1-a)*np.pi/(4.*a)))
else:
b[i] = 4*a/(np.pi*(1 - 16*a**2*(n[i]/Ns)**2))
b[i] = b[i]*(np.cos((1+a)*np.pi*n[i]/Ns) + np.sinc((1-a)*n[i]/Ns)*(1-a)*np.pi/(4.*a))
return b
def pn_gen(n_bits, m=5):
"""
Maximal length sequence signal generator.
Generates a sequence 0/1 bits of N_bit duration. The bits themselves
are obtained from an m-sequence of length m. Available m-sequence
(PN generators) include m = 2,3,...,12, & 16.
Parameters
----------
n_bits : the number of bits to generate
m : the number of shift registers. 2,3, .., 12, & 16
Returns
-------
PN : ndarray of the generator output over N_bits
Notes
-----
The sequence is periodic having period 2**m - 1 (2^m - 1).
Examples
--------
>>> # A 15 bit period signal nover 50 bits
>>> PN = pn_gen(50,4)
"""
c = m_seq(m)
Q = len(c)
max_periods = int(np.ceil(n_bits / float(Q)))
PN = np.zeros(max_periods*Q)
for k in range(max_periods):
PN[k*Q:(k+1)*Q] = c
PN = np.resize(PN, (1, n_bits))
return PN.flatten()
def m_seq(m):
"""
Generate an m-sequence ndarray using an all-ones initialization.
Available m-sequence (PN generators) include m = 2,3,...,12, & 16.
Parameters
----------
m : the number of shift registers. 2,3, .., 12, & 16
Returns
-------
c : ndarray of one period of the m-sequence
Notes
-----
The sequence period is 2**m - 1 (2^m - 1).
Examples
--------
>>> c = m_seq(5)
"""
if m == 2:
taps = np.array([1, 1, 1])
elif m == 3:
taps = np.array([1, 0, 1, 1])
elif m == 4:
taps = np.array([1, 0, 0, 1, 1])
elif m == 5:
taps = np.array([1, 0, 0, 1, 0, 1])
elif m == 6:
taps = np.array([1, 0, 0, 0, 0, 1, 1])
elif m == 7:
taps = np.array([1, 0, 0, 0, 1, 0, 0, 1])
elif m == 8:
taps = np.array([1, 0, 0, 0, 1, 1, 1, 0, 1])
elif m == 9:
taps = np.array([1, 0, 0, 0, 0, 1, 0, 0, 0, 1])
elif m == 10:
taps = np.array([1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1])
elif m == 11:
taps = np.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1])
elif m == 12:
taps = np.array([1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1])
elif m == 16:
taps = np.array([1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1])
else:
raise ValueError('Invalid length specified')
# Load shift register with all ones to start
sr = np.ones(m)
# M-squence length is:
Q = 2**m - 1
c = np.zeros(Q)
for n in range(Q):
tap_xor = 0
c[n] = sr[-1]
for k in range(1,m):
if taps[k] == 1:
tap_xor = np.bitwise_xor(tap_xor,np.bitwise_xor(int(sr[-1]),int(sr[m-1-k])))
sr[1:] = sr[:-1]
sr[0] = tap_xor
return c
def bpsk_tx(N_bits, Ns, ach_fc=2.0, ach_lvl_dB=-100, pulse='rect', alpha = 0.25, M=6):
"""
Generates biphase shift keyed (BPSK) transmitter with adjacent channel interference.
Generates three BPSK signals with rectangular or square root raised cosine (SRC)
pulse shaping of duration N_bits and Ns samples per bit. The desired signal is
centered on f = 0, which the adjacent channel signals to the left and right
are also generated at dB level relative to the desired signal. Used in the
digital communications Case Study supplement.
Parameters
----------
N_bits : the number of bits to simulate
Ns : the number of samples per bit
ach_fc : the frequency offset of the adjacent channel signals (default 2.0)
ach_lvl_dB : the level of the adjacent channel signals in dB (default -100)
pulse :the pulse shape 'rect' or 'src'
alpha : square root raised cosine pulse shape factor (default = 0.25)
M : square root raised cosine pulse truncation factor (default = 6)
Returns
-------
x : ndarray of the composite signal x0 + ach_lvl*(x1p + x1m)
b : the transmit pulse shape
data0 : the data bits used to form the desired signal; used for error checking
Notes
-----
Examples
--------
>>> x,b,data0 = bpsk_tx(1000,10,pulse='src')
"""
pulse_types = ['rect', 'src']
if pulse not in pulse_types:
raise ValueError('Pulse shape must be \'rect\' or \'src\'''')
x0,b,data0 = nrz_bits(N_bits, Ns, pulse, alpha, M)
x1p,b,data1p = nrz_bits(N_bits, Ns, pulse, alpha, M)
x1m,b,data1m = nrz_bits(N_bits, Ns, pulse, alpha, M)
n = np.arange(len(x0))
x1p = x1p*np.exp(1j*2*np.pi*ach_fc/float(Ns)*n)
x1m = x1m*np.exp(-1j*2*np.pi*ach_fc/float(Ns)*n)
ach_lvl = 10**(ach_lvl_dB/20.)
return x0 + ach_lvl*(x1p + x1m), b, data0
def nrz_bits(n_bits, ns, pulse='rect', alpha=0.25, m=6):
"""
Generate non-return-to-zero (NRZ) data bits with pulse shaping.
A baseband digital data signal using +/-1 amplitude signal values
and including pulse shaping.
Parameters
----------
n_bits : number of NRZ +/-1 data bits to produce
ns : the number of samples per bit,
pulse_type : 'rect' , 'rc', 'src' (default 'rect')
alpha : excess bandwidth factor(default 0.25)
m : single sided pulse duration (default = 6)
Returns
-------
x : ndarray of the NRZ signal values
b : ndarray of the pulse shape
data : ndarray of the underlying data bits
Notes
-----
Pulse shapes include 'rect' (rectangular), 'rc' (raised cosine),
'src' (root raised cosine). The actual pulse length is 2*M+1 samples.
This function is used by BPSK_tx in the Case Study article.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from sk_dsp_comm.sigsys import nrz_bits
>>> from numpy import arange
>>> x,b,data = nrz_bits(100, 10)
>>> t = arange(len(x))
>>> plt.plot(t, x)
>>> plt.ylim([-1.01, 1.01])
>>> plt.show()
"""
data = np.random.randint(0, 2, n_bits)
n_zeros = np.zeros((n_bits, int(ns) - 1))
x = np.hstack((2 * data.reshape(n_bits, 1) - 1, n_zeros))
x =x.flatten()
if pulse.lower() == 'rect':
b = np.ones(int(ns))
elif pulse.lower() == 'rc':
b = rc_imp(ns, alpha, m)
elif pulse.lower() == 'src':
b = sqrt_rc_imp(ns, alpha, m)
else:
raise ValueError('pulse type must be rec, rc, or src')
x = signal.lfilter(b,1,x)
return x, b / float(ns), data
def nrz_bits2(data, Ns, pulse='rect', alpha = 0.25, M=6):
"""
Generate non-return-to-zero (NRZ) data bits with pulse shaping with user data
A baseband digital data signal using +/-1 amplitude signal values
and including pulse shaping. The data sequence is user supplied.
Parameters
----------
data : ndarray of the data bits as 0/1 values
Ns : the number of samples per bit,
pulse_type : 'rect' , 'rc', 'src' (default 'rect')
alpha : excess bandwidth factor(default 0.25)
M : single sided pulse duration (default = 6)
Returns
-------
x : ndarray of the NRZ signal values
b : ndarray of the pulse shape
Notes
-----
Pulse shapes include 'rect' (rectangular), 'rc' (raised cosine),
'src' (root raised cosine). The actual pulse length is 2*M+1 samples.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from sk_dsp_comm.sigsys import nrz_bits2
>>> from sk_dsp_comm.sigsys import m_seq
>>> from numpy import arange
>>> x,b = nrz_bits2(m_seq(5),10)
>>> t = arange(len(x))
>>> plt.ylim([-1.01, 1.01])
>>> plt.plot(t,x)
"""
N_bits = len(data)
n_zeros = np.zeros((N_bits,int(Ns)-1))
x = np.hstack((2*data.reshape(N_bits,1)-1,n_zeros))
x = x.flatten()
if pulse.lower() == 'rect':
b = np.ones(int(Ns))
elif pulse.lower() == 'rc':
b = rc_imp(Ns,alpha,M)
elif pulse.lower() == 'src':
b = sqrt_rc_imp(Ns,alpha,M)
else:
raise ValueError('pulse type must be rec, rc, or src')
x = signal.lfilter(b,1,x)
return x,b/float(Ns)
def eye_plot(x, l, s=0):
"""
Eye pattern plot of a baseband digital communications waveform.
The signal must be real, but can be multivalued in terms of the underlying
modulation scheme. Used for BPSK eye plots in the Case Study article.
Parameters
----------
x : ndarray of the real input data vector/array
l : display length in samples (usually two symbols)
s : start index
Returns
-------
Nothing : A plot window opens containing the eye plot
Notes
-----
Increase S to eliminate filter transients.
Examples
--------
1000 bits at 10 samples per bit with 'rc' shaping.
>>> import matplotlib.pyplot as plt
>>> from sk_dsp_comm import sigsys as ss
>>> x,b, data = ss.nrz_bits(1000,10,'rc')
>>> ss.eye_plot(x,20,60)
"""
plt.figure(figsize=(6,4))
idx = np.arange(0, l + 1)
plt.plot(idx, x[s:s + l + 1], 'b')
k_max = int((len(x) - s) / l) - 1
for k in range(1,k_max):
plt.plot(idx, x[s + k * l:s + l + 1 + k * l], 'b')
plt.grid()
plt.xlabel('Time Index - n')
plt.ylabel('Amplitude')
plt.title('Eye Plot')
return 0
def scatter(x, ns, start):
"""
Sample a baseband digital communications waveform at the symbol spacing.
Parameters
----------
x : ndarray of the input digital comm signal
ns : number of samples per symbol (bit)
start : the array index to start the sampling
Returns
-------
xI : ndarray of the real part of x following sampling
xQ : ndarray of the imaginary part of x following sampling
Notes
-----
Normally the signal is complex, so the scatter plot contains
clusters at points in the complex plane. For a binary signal
such as BPSK, the point centers are nominally +/-1 on the real
axis. Start is used to eliminate transients from the FIR
pulse shaping filters from appearing in the scatter plot.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from sk_dsp_comm import sigsys as ss
>>> x,b, data = ss.nrz_bits(1000,10,'rc')
>>> # Add some noise so points are now scattered about +/-1
>>> y = ss.cpx_awgn(x,20,10)
>>> yI,yQ = ss.scatter(y,10,60)
>>> plt.plot(yI,yQ,'.')
>>> plt.axis('equal')
>>> plt.ylabel("Quadrature")
>>> plt.xlabel("In-Phase")
>>> plt.grid()
>>> plt.show()
"""
xI = np.real(x[start::ns])
xQ = np.imag(x[start::ns])
return xI, xQ
def bit_errors(z, data, start, ns):
"""
A simple bit error counting function.
In its present form this function counts bit errors between
hard decision BPSK bits in +/-1 form and compares them with
0/1 binary data that was transmitted. Timing between the Tx
and Rx data is the responsibility of the user. An enhanced
version of this function, which features automatic synching
will be created in the future.
Parameters
----------
z : ndarray of hard decision BPSK data prior to symbol spaced sampling
data : ndarray of reference bits in 1/0 format
start : timing reference for the received
ns : the number of samples per symbol
Returns
-------
Pe_hat : the estimated probability of a bit error
Notes
-----
The Tx and Rx data streams are exclusive-or'd and the then the bit errors
are summed, and finally divided by the number of bits observed to form an
estimate of the bit error probability. This function needs to be
enhanced to be more useful.
Examples
--------
>>> from scipy import signal
>>> x,b, data = nrz_bits(1000,10)
>>> # set Eb/N0 to 8 dB
>>> y = cpx_awgn(x,8,10)
>>> # matched filter the signal
>>> z = signal.lfilter(b,1,y)
>>> # make bit decisions at 10 and Ns multiples thereafter
>>> Pe_hat = bit_errors(z,data,10,10)
"""
Pe_hat = np.sum(data[0:len(z[start::ns])] ^ np.int64((np.sign(np.real(z[start::ns])) + 1) / 2)) / float(len(z[start::ns]))
return Pe_hat
def cpx_awgn(x, es_n0, ns):
"""
Apply white Gaussian noise to a digital communications signal.
This function represents a complex baseband white Gaussian noise
digital communications channel. The input signal array may be real
or complex.
Parameters
----------
x : ndarray noise free complex baseband input signal.
EsNO : set the channel Es/N0 (Eb/N0 for binary) level in dB
ns : number of samples per symbol (bit)
Returns
-------
y : ndarray x with additive noise added.
Notes
-----
Set the channel energy per symbol-to-noise power spectral
density ratio (Es/N0) in dB.
Examples
--------
>>> x,b, data = nrz_bits(1000,10)
>>> # set Eb/N0 = 10 dB
>>> y = cpx_awgn(x,10,10)
"""
w = np.sqrt(ns * np.var(x) * 10 ** (-es_n0 / 10.) / 2.) * (np.random.randn(len(x)) + 1j * np.random.randn(len(x)))
return x+w
def my_psd(x,NFFT=2**10,Fs=1):
"""
A local version of NumPy's PSD function that returns the plot arrays.
A mlab.psd wrapper function that returns two ndarrays;
makes no attempt to auto plot anything.
Parameters
----------
x : ndarray input signal
NFFT : a power of two, e.g., 2**10 = 1024
Fs : the sampling rate in Hz
Returns
-------
Px : ndarray of the power spectrum estimate
f : ndarray of frequency values
Notes
-----
This function makes it easier to overlay spectrum plots because
you have better control over the axis scaling than when using psd()
in the autoscale mode.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from numpy import log10
>>> from sk_dsp_comm import sigsys as ss
>>> x,b, data = ss.nrz_bits(10000,10)
>>> Px,f = ss.my_psd(x,2**10,10)
>>> plt.plot(f, 10*log10(Px))
>>> plt.ylabel("Power Spectral Density (dB)")
>>> plt.xlabel("Frequency (Hz)")
>>> plt.show()
"""
Px,f = pylab.mlab.psd(x,NFFT,Fs)
return Px.flatten(), f
def am_tx(m,a_mod,fc=75e3):
"""
AM transmitter for Case Study of Chapter 17.
Assume input is sampled at 8 Ksps and upsampling
by 24 is performed to arrive at fs_out = 192 Ksps.
Parameters
----------
m : ndarray of the input message signal
a_mod : AM modulation index, between 0 and 1
fc : the carrier frequency in Hz
Returns
-------
x192 : ndarray of the upsampled by 24 and modulated carrier
t192 : ndarray of the upsampled by 24 time axis
m24 : ndarray of the upsampled by 24 message signal
Notes
-----
The sampling rate of the input signal is assumed to be 8 kHz.
Examples
--------
>>> n = arange(0,1000)
>>> # 1 kHz message signal
>>> m = cos(2*pi*1000/8000.*n)
>>> x192, t192 = am_tx(m,0.8,fc=75e3)
"""
m24 = interp24(m)
t192 = np.arange(len(m24))/192.0e3
#m24 = np.cos(2*np.pi*2.0e3*t192)
m_max = np.max(np.abs(m24))
x192 = (1 + a_mod*m24/m_max)*np.cos(2*np.pi*fc*t192)
return x192, t192, m24
def am_rx(x192):
"""
AM envelope detector receiver for the Chapter 17 Case Study
The receiver bandpass filter is not included in this function.
Parameters
----------
x192 : ndarray of the AM signal at sampling rate 192 ksps
Returns
-------
m_rx8 : ndarray of the demodulated message at 8 ksps
t8 : ndarray of the time axis at 8 ksps
m_rx192 : ndarray of the demodulated output at 192 ksps
x_edet192 : ndarray of the envelope detector output at 192 ksps
Notes
-----
The bandpass filter needed at the receiver front-end can be designed
using b_bpf,a_bpf = :func:`am_rx_BPF`.
Examples
--------
>>> import numpy as np
>>> n = np.arange(0,1000)
>>> # 1 kHz message signal
>>> m = np.cos(2*np.pi*1000/8000.*n)
>>> m_rx8,t8,m_rx192,x_edet192 = am_rx(x192)
"""
x_edet192 = env_det(x192)
m_rx8 = deci24(x_edet192)
# remove DC offset from the env_det + LPF output
m_rx8 -= np.mean(m_rx8)
t8 = np.arange(len(m_rx8))/8.0e3
"""
For performance testing also filter x_env_det
192e3 using a Butterworth cascade.
The filter cutoff is 5kHz, the message BW.
"""
b192,a192 = signal.butter(5,2*5.0e3/192.0e3)
m_rx192 = signal.lfilter(b192,a192,x_edet192)
m_rx192 = signal.lfilter(b192,a192,m_rx192)
m_rx192 -= np.mean(m_rx192)
return m_rx8,t8,m_rx192,x_edet192
def am_rx_bpf(n_order=7, ripple_dB=1, b=10e3, fs=192e3):
"""
Bandpass filter design for the AM receiver Case Study of Chapter 17.
Design a 7th-order Chebyshev type 1 bandpass filter to remove/reduce
adjacent channel intereference at the envelope detector input.
Parameters
----------
n_order : the filter order (default = 7)
ripple_dB : the passband ripple in dB (default = 1)
b : the RF bandwidth (default = 10e3)
fs : the sampling frequency
Returns
-------
b_bpf : ndarray of the numerator filter coefficients
a_bpf : ndarray of the denominator filter coefficients
Examples
--------
>>> from scipy import signal
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> import sk_dsp_comm.sigsys as ss
>>> # Use the default values
>>> b_bpf,a_bpf = ss.am_rx_bpf()
Pole-zero plot of the filter.
>>> ss.zplane(b_bpf,a_bpf)
>>> plt.show()
Plot of the frequency response.
>>> f = np.arange(0,192/2.,.1)
>>> w, Hbpf = signal.freqz(b_bpf,a_bpf,2*np.pi*f/192)
>>> plt.plot(f*10,20*np.log10(abs(Hbpf)))
>>> plt.axis([0,1920/2.,-80,10])
>>> plt.ylabel("Power Spectral Density (dB)")
>>> plt.xlabel("Frequency (kHz)")
>>> plt.show()
"""
b_bpf,a_bpf = signal.cheby1(n_order, ripple_dB, 2 * np.array([75e3 - b / 2., 75e3 + b / 2.]) / fs, 'bandpass')
return b_bpf,a_bpf
def env_det(x):
"""
Ideal envelope detector.
This function retains the positive half cycles of the input signal.
Parameters
----------
x : ndarray of the input sugnal
Returns
-------
y : ndarray of the output signal
Examples
--------
>>> n = arange(0,100)
>>> # 1 kHz message signal
>>> m = cos(2*pi*1000/8000.*n)
>>> x192, t192, m24 = am_tx(m,0.8,fc=75e3)
>>> y = env_det(x192)
"""
y = np.zeros(len(x))
for k,xx in enumerate(x):
if xx >= 0:
y[k] = xx
return y
def interp24(x):
"""
Interpolate by L = 24 using Butterworth filters.
The interpolation is done using three stages. Upsample by
L = 2 and lowpass filter, upsample by 3 and lowpass filter, then
upsample by L = 4 and lowpass filter. In all cases the lowpass
filter is a 10th-order Butterworth lowpass.
Parameters
----------
x : ndarray of the input signal
Returns
-------
y : ndarray of the output signal
Notes
-----
The cutoff frequency of the lowpass filters is 1/2, 1/3, and 1/4 to
track the upsampling by 2, 3, and 4 respectively.
Examples
--------
>>> y = interp24(x)
"""
# Stage 1: L = 2
b2,a2 = signal.butter(10,1/2.)
y1 = upsample(x,2)
y1 = signal.lfilter(b2,a2,2*y1)
# Stage 2: L = 3
b3,a3 = signal.butter(10,1/3.)
y2 = upsample(y1,3)
y2 = signal.lfilter(b3,a3,3*y2)
# Stage 3: L = 4
b4,a4 = signal.butter(10,1/4.)
y3 = upsample(y2,4)
y3 = signal.lfilter(b4,a4,4*y3)
return y3
def deci24(x):
"""
Decimate by L = 24 using Butterworth filters.
The decimation is done using two three stages. Downsample sample by
L = 2 and lowpass filter, downsample by 3 and lowpass filter, then
downsample by L = 4 and lowpass filter. In all cases the lowpass
filter is a 10th-order Butterworth lowpass.
Parameters
----------
x : ndarray of the input signal
Returns
-------
y : ndarray of the output signal
Notes
-----
The cutoff frequency of the lowpass filters is 1/2, 1/3, and 1/4 to
track the upsampling by 2, 3, and 4 respectively.
Examples
--------
>>> y = deci24(x)
"""
# Stage 1: M = 2
b2,a2 = signal.butter(10,1/2.)
y1 = signal.lfilter(b2,a2,x)
y1 = downsample(y1,2)
# Stage 2: M = 3
b3,a3 = signal.butter(10,1/3.)
y2 = signal.lfilter(b3,a3,y1)
y2 = downsample(y2,3)
# Stage 3: L = 4
b4,a4 = signal.butter(10,1/4.)
y3 = signal.lfilter(b4,a4,y2)
y3 = downsample(y3,4)
return y3
def upsample(x,L):
"""
Upsample by factor L
Insert L - 1 zero samples in between each input sample.
Parameters
----------
x : ndarray of input signal values
L : upsample factor
Returns
-------
y : ndarray of the output signal values
Examples
--------
>>> y = upsample(x,3)
"""
N_input = len(x)
y = np.hstack((x.reshape(N_input,1),np.zeros((N_input, int(L-1)))))
y = y.flatten()
return y
def downsample(x,M,p=0):
"""
Downsample by factor M
Keep every Mth sample of the input. The phase of the input samples
kept can be selected.
Parameters
----------
x : ndarray of input signal values
M : downsample factor
p : phase of decimated value, 0 (default), 1, ..., M-1
Returns
-------
y : ndarray of the output signal values
Examples
--------
>>> y = downsample(x,3)
>>> y = downsample(x,3,1)
"""
if not isinstance(M, int):
raise TypeError("M must be an int")
x = x[0:int(np.floor(len(x)/M))*M]
x = x.reshape((int(np.floor(len(x)/M)),M))
y = x[:,p]
return y
def unique_cpx_roots(rlist,tol = 0.001):
"""
The average of the root values is used when multiplicity
is greater than one.
<NAME> October 2016
"""
uniq = [rlist[0]]
mult = [1]
for k in range(1,len(rlist)):
N_uniq = len(uniq)
for m in range(N_uniq):
if abs(rlist[k]-uniq[m]) <= tol:
mult[m] += 1
uniq[m] = (uniq[m]*(mult[m]-1) + rlist[k])/float(mult[m])
break
uniq = np.hstack((uniq,rlist[k]))
mult = np.hstack((mult,[1]))
return np.array(uniq), np.array(mult)
def zplane(b,a,auto_scale=True,size=2,detect_mult=True,tol=0.001):
"""
Create an z-plane pole-zero plot.
Create an z-plane pole-zero plot using the numerator
and denominator z-domain system function coefficient
ndarrays b and a respectively. Assume descending powers of z.
Parameters
----------
b : ndarray of the numerator coefficients
a : ndarray of the denominator coefficients
auto_scale : bool (default True)
size : plot radius maximum when scale = False
Returns
-------
(M,N) : tuple of zero and pole counts + plot window
Notes
-----
This function tries to identify repeated poles and zeros and will
place the multiplicity number above and to the right of the pole or zero.
The difficulty is setting the tolerance for this detection. Currently it
is set at 1e-3 via the function signal.unique_roots.
Examples
--------
>>> # Here the plot is generated using auto_scale
>>> zplane(b,a)
>>> # Here the plot is generated using manual scaling
>>> zplane(b,a,False,1.5)
"""
if (isinstance(a,int) or isinstance(a,float)):
a = [a]
if (isinstance(b,int) or isinstance(b,float)):
b = [b]
M = len(b) - 1
N = len(a) - 1
# Plot labels if multiplicity greater than 1
x_scale = 1.5*size
y_scale = 1.5*size
x_off = 0.02
y_off = 0.01
#N_roots = np.array([1.0])
if M > 0:
N_roots = np.roots(b)
#D_roots = np.array([1.0])
if N > 0:
D_roots = np.roots(a)
if auto_scale:
if M > 0 and N > 0:
size = max(np.max(np.abs(N_roots)),np.max(np.abs(D_roots)))+.1
elif M > 0:
size = max(np.max( | np.abs(N_roots) | numpy.abs |
import operator
from enum import Enum
from typing import Union, Any, Optional, Hashable
import numpy as np
import pandas as pd
import pandas_flavor as pf
from pandas.core.construction import extract_array
from pandas.core.dtypes.common import (
is_categorical_dtype,
is_datetime64_dtype,
is_dtype_equal,
is_extension_array_dtype,
is_numeric_dtype,
is_string_dtype,
)
from pandas.core.reshape.merge import _MergeOperation
from janitor.utils import check, check_column
@pf.register_dataframe_method
def conditional_join(
df: pd.DataFrame,
right: Union[pd.DataFrame, pd.Series],
*conditions,
how: str = "inner",
sort_by_appearance: bool = False,
df_columns: Optional[Any] = None,
right_columns: Optional[Any] = None,
) -> pd.DataFrame:
"""
This is a convenience function that operates similarly to `pd.merge`,
but allows joins on inequality operators,
or a combination of equi and non-equi joins.
Join solely on equality are not supported.
If the join is solely on equality, `pd.merge` function
covers that; if you are interested in nearest joins, or rolling joins,
or the first match (lowest or highest) - `pd.merge_asof` covers that.
There is also the IntervalIndex, which is usually more efficient
for range joins, especially if the intervals do not overlap.
Column selection in `df_columns` and `right_columns` is possible using the
[`select_columns`][janitor.functions.select_columns.select_columns] syntax.
This function returns rows, if any, where values from `df` meet the
condition(s) for values from `right`. The conditions are passed in
as a variable argument of tuples, where the tuple is of
the form `(left_on, right_on, op)`; `left_on` is the column
label from `df`, `right_on` is the column label from `right`,
while `op` is the operator. For multiple conditions, the and(`&`)
operator is used to combine the results of the individual conditions.
The operator can be any of `==`, `!=`, `<=`, `<`, `>=`, `>`.
A binary search is used to get the relevant rows for non-equi joins;
this avoids a cartesian join, and makes the process less memory intensive.
For equi-joins, Pandas internal merge function is used.
The join is done only on the columns.
MultiIndex columns are not supported.
For non-equi joins, only numeric and date columns are supported.
Only `inner`, `left`, and `right` joins are supported.
If the columns from `df` and `right` have nothing in common,
a single index column is returned; else, a MultiIndex column
is returned.
Example:
>>> import pandas as pd
>>> import janitor
>>> df1 = pd.DataFrame({"value_1": [2, 5, 7, 1, 3, 4]})
>>> df2 = pd.DataFrame({"value_2A": [0, 3, 7, 12, 0, 2, 3, 1],
... "value_2B": [1, 5, 9, 15, 1, 4, 6, 3],
... })
>>> df1
value_1
0 2
1 5
2 7
3 1
4 3
5 4
>>> df2
value_2A value_2B
0 0 1
1 3 5
2 7 9
3 12 15
4 0 1
5 2 4
6 3 6
7 1 3
>>> df1.conditional_join(
... df2,
... ("value_1", "value_2A", ">="),
... ("value_1", "value_2B", "<=")
... )
value_1 value_2A value_2B
0 2 1 3
1 2 2 4
2 5 3 5
3 5 3 6
4 7 7 9
5 1 0 1
6 1 0 1
7 1 1 3
8 3 1 3
9 3 2 4
10 3 3 5
11 3 3 6
12 4 2 4
13 4 3 5
14 4 3 6
:param df: A pandas DataFrame.
:param right: Named Series or DataFrame to join to.
:param conditions: Variable argument of tuple(s) of the form
`(left_on, right_on, op)`, where `left_on` is the column
label from `df`, `right_on` is the column label from `right`,
while `op` is the operator. The operator can be any of
`==`, `!=`, `<=`, `<`, `>=`, `>`. For multiple conditions,
the and(`&`) operator is used to combine the results
of the individual conditions.
:param how: Indicates the type of join to be performed.
It can be one of `inner`, `left`, `right`.
Full join is not supported. Defaults to `inner`.
:param sort_by_appearance: Default is `False`.
This is useful for strictly non-equi joins,
where the user wants the original order maintained.
If True, values from `df` and `right`
that meet the join condition will be returned
in the final dataframe in the same order
that they were before the join.
:param df_columns: Columns to select from `df`.
It can be a single column or a list of columns.
It is also possible to rename the output columns via a dictionary.
:param right_columns: Columns to select from `right`.
It can be a single column or a list of columns.
It is also possible to rename the output columns via a dictionary.
:returns: A pandas DataFrame of the two merged Pandas objects.
"""
return _conditional_join_compute(
df,
right,
conditions,
how,
sort_by_appearance,
df_columns,
right_columns,
)
class _JoinOperator(Enum):
"""
List of operators used in conditional_join.
"""
GREATER_THAN = ">"
LESS_THAN = "<"
GREATER_THAN_OR_EQUAL = ">="
LESS_THAN_OR_EQUAL = "<="
STRICTLY_EQUAL = "=="
NOT_EQUAL = "!="
class _JoinTypes(Enum):
"""
List of join types for conditional_join.
"""
INNER = "inner"
LEFT = "left"
RIGHT = "right"
operator_map = {
_JoinOperator.STRICTLY_EQUAL.value: operator.eq,
_JoinOperator.LESS_THAN.value: operator.lt,
_JoinOperator.LESS_THAN_OR_EQUAL.value: operator.le,
_JoinOperator.GREATER_THAN.value: operator.gt,
_JoinOperator.GREATER_THAN_OR_EQUAL.value: operator.ge,
_JoinOperator.NOT_EQUAL.value: operator.ne,
}
less_than_join_types = {
_JoinOperator.LESS_THAN.value,
_JoinOperator.LESS_THAN_OR_EQUAL.value,
}
greater_than_join_types = {
_JoinOperator.GREATER_THAN.value,
_JoinOperator.GREATER_THAN_OR_EQUAL.value,
}
def _check_operator(op: str):
"""
Check that operator is one of
`>`, `>=`, `==`, `!=`, `<`, `<=`.
Used in `conditional_join`.
"""
sequence_of_operators = {op.value for op in _JoinOperator}
if op not in sequence_of_operators:
raise ValueError(
"The conditional join operator "
f"should be one of {sequence_of_operators}"
)
def _conditional_join_preliminary_checks(
df: pd.DataFrame,
right: Union[pd.DataFrame, pd.Series],
conditions: tuple,
how: str,
sort_by_appearance: bool,
df_columns: Any,
right_columns: Any,
) -> tuple:
"""
Preliminary checks for conditional_join are conducted here.
Checks include differences in number of column levels,
length of conditions, existence of columns in dataframe, etc.
"""
check("right", right, [pd.DataFrame, pd.Series])
df = df.copy()
right = right.copy()
if isinstance(right, pd.Series):
if not right.name:
raise ValueError(
"Unnamed Series are not supported for conditional_join."
)
right = right.to_frame()
if df.columns.nlevels != right.columns.nlevels:
raise ValueError(
"The number of column levels "
"from the left and right frames must match. "
"The number of column levels from the left dataframe "
f"is {df.columns.nlevels}, while the number of column levels "
f"from the right dataframe is {right.columns.nlevels}."
)
if not conditions:
raise ValueError("Kindly provide at least one join condition.")
for condition in conditions:
check("condition", condition, [tuple])
len_condition = len(condition)
if len_condition != 3:
raise ValueError(
"condition should have only three elements; "
f"{condition} however is of length {len_condition}."
)
for left_on, right_on, op in conditions:
check("left_on", left_on, [Hashable])
check("right_on", right_on, [Hashable])
check("operator", op, [str])
check_column(df, [left_on])
check_column(right, [right_on])
_check_operator(op)
if all(
(op == _JoinOperator.STRICTLY_EQUAL.value for *_, op in conditions)
):
raise ValueError("Equality only joins are not supported.")
check("how", how, [str])
checker = {jointype.value for jointype in _JoinTypes}
if how not in checker:
raise ValueError(f"'how' should be one of {checker}.")
check("sort_by_appearance", sort_by_appearance, [bool])
if (df.columns.nlevels > 1) and (
isinstance(df_columns, dict) or isinstance(right_columns, dict)
):
raise ValueError(
"Column renaming with a dictionary is not supported "
"for MultiIndex columns."
)
return (
df,
right,
conditions,
how,
sort_by_appearance,
df_columns,
right_columns,
)
def _conditional_join_type_check(
left_column: pd.Series, right_column: pd.Series, op: str
) -> None:
"""
Raise error if column type is not any of numeric or datetime or string.
"""
permitted_types = {
is_datetime64_dtype,
is_numeric_dtype,
is_string_dtype,
is_categorical_dtype,
}
for func in permitted_types:
if func(left_column):
break
else:
raise ValueError(
"conditional_join only supports "
"string, category, numeric, or date dtypes (without timezone) - "
f"'{left_column.name} is of type {left_column.dtype}."
)
lk_is_cat = is_categorical_dtype(left_column)
rk_is_cat = is_categorical_dtype(right_column)
if lk_is_cat & rk_is_cat:
if not left_column.array._categories_match_up_to_permutation(
right_column.array
):
raise ValueError(
f"'{left_column.name}' and '{right_column.name}' "
"should have the same categories, and the same order."
)
elif not is_dtype_equal(left_column, right_column):
raise ValueError(
f"Both columns should have the same type - "
f"'{left_column.name}' has {left_column.dtype} type;"
f"'{right_column.name}' has {right_column.dtype} type."
)
if (op in less_than_join_types.union(greater_than_join_types)) & (
(is_string_dtype(left_column) | is_categorical_dtype(left_column))
):
raise ValueError(
"non-equi joins are supported "
"only for datetime and numeric dtypes. "
f"{left_column.name} in condition "
f"({left_column.name}, {right_column.name}, {op}) "
f"has a dtype {left_column.dtype}."
)
return None
def _conditional_join_compute(
df: pd.DataFrame,
right: pd.DataFrame,
conditions: list,
how: str,
sort_by_appearance: bool,
df_columns: Any,
right_columns: Any,
) -> pd.DataFrame:
"""
This is where the actual computation
for the conditional join takes place.
A pandas DataFrame is returned.
"""
(
df,
right,
conditions,
how,
sort_by_appearance,
df_columns,
right_columns,
) = _conditional_join_preliminary_checks(
df,
right,
conditions,
how,
sort_by_appearance,
df_columns,
right_columns,
)
eq_check = False
le_lt_check = False
for condition in conditions:
left_on, right_on, op = condition
_conditional_join_type_check(df[left_on], right[right_on], op)
if op == _JoinOperator.STRICTLY_EQUAL.value:
eq_check = True
elif op in less_than_join_types.union(greater_than_join_types):
le_lt_check = True
df.index = range(len(df))
right.index = range(len(right))
multiple_conditions = len(conditions) > 1
if not multiple_conditions:
left_on, right_on, op = conditions[0]
result = _generic_func_cond_join(
df[left_on], right[right_on], op, multiple_conditions
)
if result is None:
return _create_conditional_join_empty_frame(
df, right, how, df_columns, right_columns
)
return _create_conditional_join_frame(
df,
right,
*result,
how,
sort_by_appearance,
df_columns,
right_columns,
)
if eq_check:
result = _multiple_conditional_join_eq(df, right, conditions)
elif le_lt_check:
result = _multiple_conditional_join_le_lt(df, right, conditions)
else:
result = _multiple_conditional_join_ne(df, right, conditions)
if result is None:
return _create_conditional_join_empty_frame(
df, right, how, df_columns, right_columns
)
return _create_conditional_join_frame(
df, right, *result, how, sort_by_appearance, df_columns, right_columns
)
def _less_than_indices(
left_c: pd.Series,
right_c: pd.Series,
strict: bool,
) -> tuple:
"""
Use binary search to get indices where left_c
is less than or equal to right_c.
If strict is True, then only indices
where `left_c` is less than
(but not equal to) `right_c` are returned.
A tuple of integer indexes
for left_c and right_c is returned.
"""
# no point going through all the hassle
if left_c.min() > right_c.max():
return None
any_nulls = pd.isna(right_c)
if any_nulls.any():
right_c = right_c[~any_nulls]
if right_c.empty:
return None
any_nulls = pd.isna(left_c)
if any_nulls.any():
left_c = left_c[~any_nulls]
if left_c.empty:
return None
any_nulls = None
if not right_c.is_monotonic_increasing:
right_c = right_c.sort_values(kind="stable")
left_index = left_c.index.to_numpy(dtype=int, copy=False)
left_c = extract_array(left_c, extract_numpy=True)
right_index = right_c.index.to_numpy(dtype=int, copy=False)
right_c = extract_array(right_c, extract_numpy=True)
search_indices = right_c.searchsorted(left_c, side="left")
# if any of the positions in `search_indices`
# is equal to the length of `right_keys`
# that means the respective position in `left_c`
# has no values from `right_c` that are less than
# or equal, and should therefore be discarded
len_right = right_c.size
rows_equal = search_indices == len_right
if rows_equal.any():
left_c = left_c[~rows_equal]
left_index = left_index[~rows_equal]
search_indices = search_indices[~rows_equal]
# the idea here is that if there are any equal values
# shift to the right to the immediate next position
# that is not equal
if strict:
rows_equal = right_c[search_indices]
rows_equal = left_c == rows_equal
# replace positions where rows are equal
# with positions from searchsorted('right')
# positions from searchsorted('right') will never
# be equal and will be the furthermost in terms of position
# example : right_c -> [2, 2, 2, 3], and we need
# positions where values are not equal for 2;
# the furthermost will be 3, and searchsorted('right')
# will return position 3.
if rows_equal.any():
replacements = right_c.searchsorted(left_c, side="right")
# now we can safely replace values
# with strictly less than positions
search_indices = np.where(rows_equal, replacements, search_indices)
# check again if any of the values
# have become equal to length of right_c
# and get rid of them
rows_equal = search_indices == len_right
if rows_equal.any():
left_c = left_c[~rows_equal]
left_index = left_index[~rows_equal]
search_indices = search_indices[~rows_equal]
if not search_indices.size:
return None
right_c = [right_index[ind:len_right] for ind in search_indices]
right_c = np.concatenate(right_c)
left_c = np.repeat(left_index, len_right - search_indices)
return left_c, right_c
def _greater_than_indices(
left_c: pd.Series,
right_c: pd.Series,
strict: bool,
multiple_conditions: bool,
) -> tuple:
"""
Use binary search to get indices where left_c
is greater than or equal to right_c.
If strict is True, then only indices
where `left_c` is greater than
(but not equal to) `right_c` are returned.
if multiple_conditions is False, a tuple of integer indexes
for left_c and right_c is returned;
else a tuple of the index for left_c, right_c, as well
as the positions of left_c in right_c is returned.
"""
# quick break, avoiding the hassle
if left_c.max() < right_c.min():
return None
any_nulls = pd.isna(right_c)
if any_nulls.any():
right_c = right_c[~any_nulls]
if right_c.empty:
return None
any_nulls = pd.isna(left_c)
if any_nulls.any():
left_c = left_c[~any_nulls]
if left_c.empty:
return None
any_nulls = None
if not right_c.is_monotonic_increasing:
right_c = right_c.sort_values(kind="stable")
left_index = left_c.index.to_numpy(dtype=int, copy=False)
left_c = extract_array(left_c, extract_numpy=True)
right_index = right_c.index.to_numpy(dtype=int, copy=False)
right_c = extract_array(right_c, extract_numpy=True)
search_indices = right_c.searchsorted(left_c, side="right")
# if any of the positions in `search_indices`
# is equal to 0 (less than 1), it implies that
# left_c[position] is not greater than any value
# in right_c
rows_equal = search_indices < 1
if rows_equal.any():
left_c = left_c[~rows_equal]
left_index = left_index[~rows_equal]
search_indices = search_indices[~rows_equal]
# the idea here is that if there are any equal values
# shift downwards to the immediate next position
# that is not equal
if strict:
rows_equal = right_c[search_indices - 1]
rows_equal = left_c == rows_equal
# replace positions where rows are equal with
# searchsorted('left');
# however there can be scenarios where positions
# from searchsorted('left') would still be equal;
# in that case, we shift down by 1
if rows_equal.any():
replacements = right_c.searchsorted(left_c, side="left")
# return replacements
# `left` might result in values equal to len right_c
replacements = np.where(
replacements == right_c.size, replacements - 1, replacements
)
# now we can safely replace values
# with strictly greater than positions
search_indices = np.where(rows_equal, replacements, search_indices)
# any value less than 1 should be discarded
# since the lowest value for binary search
# with side='right' should be 1
rows_equal = search_indices < 1
if rows_equal.any():
left_c = left_c[~rows_equal]
left_index = left_index[~rows_equal]
search_indices = search_indices[~rows_equal]
if not search_indices.size:
return None
if multiple_conditions:
return left_index, right_index, search_indices
right_c = [right_index[:ind] for ind in search_indices]
right_c = np.concatenate(right_c)
left_c = np.repeat(left_index, search_indices)
return left_c, right_c
def _not_equal_indices(left_c: pd.Series, right_c: pd.Series) -> tuple:
"""
Use binary search to get indices where
`left_c` is exactly not equal to `right_c`.
It is a combination of strictly less than
and strictly greater than indices.
A tuple of integer indexes for left_c and right_c
is returned.
"""
dummy = np.array([], dtype=int)
# deal with nulls
l1_nulls = dummy
r1_nulls = dummy
l2_nulls = dummy
r2_nulls = dummy
any_left_nulls = left_c.isna()
any_right_nulls = right_c.isna()
if any_left_nulls.any():
l1_nulls = left_c.index[any_left_nulls.array]
l1_nulls = l1_nulls.to_numpy(copy=False)
r1_nulls = right_c.index
# avoid NAN duplicates
if any_right_nulls.any():
r1_nulls = r1_nulls[~any_right_nulls.array]
r1_nulls = r1_nulls.to_numpy(copy=False)
nulls_count = l1_nulls.size
# blow up nulls to match length of right
l1_nulls = np.tile(l1_nulls, r1_nulls.size)
# ensure length of right matches left
if nulls_count > 1:
r1_nulls = np.repeat(r1_nulls, nulls_count)
if any_right_nulls.any():
r2_nulls = right_c.index[any_right_nulls.array]
r2_nulls = r2_nulls.to_numpy(copy=False)
l2_nulls = left_c.index
nulls_count = r2_nulls.size
# blow up nulls to match length of left
r2_nulls = np.tile(r2_nulls, l2_nulls.size)
# ensure length of left matches right
if nulls_count > 1:
l2_nulls = np.repeat(l2_nulls, nulls_count)
l1_nulls = np.concatenate([l1_nulls, l2_nulls])
r1_nulls = np.concatenate([r1_nulls, r2_nulls])
outcome = _less_than_indices(left_c, right_c, strict=True)
if outcome is None:
lt_left = dummy
lt_right = dummy
else:
lt_left, lt_right = outcome
outcome = _greater_than_indices(
left_c, right_c, strict=True, multiple_conditions=False
)
if outcome is None:
gt_left = dummy
gt_right = dummy
else:
gt_left, gt_right = outcome
left_c = np.concatenate([lt_left, gt_left, l1_nulls])
right_c = np.concatenate([lt_right, gt_right, r1_nulls])
if (not left_c.size) & (not right_c.size):
return None
return left_c, right_c
def _eq_indices(
left_c: pd.Series,
right_c: pd.Series,
) -> tuple:
"""
Use binary search to get indices where left_c
is equal to right_c.
Returns a tuple of the left_index, right_index,
lower_boundary and upper_boundary.
"""
# no point going through all the hassle
if left_c.min() > right_c.max():
return None
if left_c.max() < right_c.min():
return None
any_nulls = pd.isna(right_c)
if any_nulls.any():
right_c = right_c[~any_nulls]
if right_c.empty:
return None
any_nulls = pd.isna(left_c)
if any_nulls.any():
left_c = left_c[~any_nulls]
if left_c.empty:
return None
any_nulls = None
if not right_c.is_monotonic_increasing:
right_c = right_c.sort_values(kind="stable")
left_index = left_c.index.to_numpy(dtype=int, copy=False)
left_c = extract_array(left_c, extract_numpy=True)
right_index = right_c.index.to_numpy(dtype=int, copy=False)
right_c = extract_array(right_c, extract_numpy=True)
lower_boundary = right_c.searchsorted(left_c, side="left")
upper_boundary = right_c.searchsorted(left_c, side="right")
keep_rows = lower_boundary < upper_boundary
if not keep_rows.any():
return None
if not keep_rows.all():
left_index = left_index[keep_rows]
lower_boundary = lower_boundary[keep_rows]
upper_boundary = upper_boundary[keep_rows]
return left_index, right_index, lower_boundary, upper_boundary
def _generic_func_cond_join(
left_c: pd.Series,
right_c: pd.Series,
op: str,
multiple_conditions: bool,
) -> tuple:
"""
Generic function to call any of the individual functions
(_less_than_indices, _greater_than_indices,
or _not_equal_indices).
"""
strict = False
if op in {
_JoinOperator.GREATER_THAN.value,
_JoinOperator.LESS_THAN.value,
_JoinOperator.NOT_EQUAL.value,
}:
strict = True
if op in less_than_join_types:
return _less_than_indices(left_c, right_c, strict)
elif op in greater_than_join_types:
return _greater_than_indices(
left_c, right_c, strict, multiple_conditions
)
elif op == _JoinOperator.NOT_EQUAL.value:
return _not_equal_indices(left_c, right_c)
def _generate_indices(
left_index: np.ndarray, right_index: np.ndarray, conditions: list
) -> tuple:
"""
Run a for loop to get the final indices.
This iteratively goes through each condition,
builds a boolean array,
and gets indices for rows that meet the condition requirements.
`conditions` is a list of tuples, where a tuple is of the form:
`(Series from df, Series from right, operator)`.
"""
for condition in conditions:
left_c, right_c, op = condition
left_c = extract_array(left_c, extract_numpy=True)[left_index]
right_c = extract_array(right_c, extract_numpy=True)[right_index]
op = operator_map[op]
mask = op(left_c, right_c)
if not mask.any():
return None
if is_extension_array_dtype(mask):
mask = mask.to_numpy(dtype=bool, na_value=False)
if not mask.all():
left_index = left_index[mask]
right_index = right_index[mask]
return left_index, right_index
def _multiple_conditional_join_ne(
df: pd.DataFrame, right: pd.DataFrame, conditions: list
) -> tuple:
"""
Get indices for multiple conditions,
where all the operators are `!=`.
Returns a tuple of (left_index, right_index)
"""
# currently, there is no optimization option here
# not equal typically combines less than
# and greater than, so a lot more rows are returned
# than just less than or greater than
# here we get indices for the first condition in conditions
# then use those indices to get the final indices,
# using _generate_indices
first, *rest = conditions
left_on, right_on, op = first
# get indices from the first condition
result = _generic_func_cond_join(
df[left_on], right[right_on], op, multiple_conditions=False
)
if result is None:
return None
rest = (
(df[left_on], right[right_on], op) for left_on, right_on, op in rest
)
return _generate_indices(*result, rest)
def _multiple_conditional_join_eq(
df: pd.DataFrame, right: pd.DataFrame, conditions: list
) -> tuple:
"""
Get indices for multiple conditions,
if any of the conditions has an `==` operator.
Returns a tuple of (df_index, right_index)
"""
# TODO
# this uses the idea in the `_range_indices` function
# for less than and greater than;
# I'd like to believe there is a smarter/more efficient way of doing this
# where the filter occurs within the join, and avoids a blow-up
# the current implementation uses
# a list comprehension to find first matches
# in a bid to reduce the blow up size ...
# this applies only to integers/dates
# and only offers advantages in scenarios
# where the right is duplicated
# for one to many joins,
# or one to one or strings/category, use merge
# as it is significantly faster than a binary search
eqs = [
(left_on, right_on)
for left_on, right_on, op in conditions
if op == _JoinOperator.STRICTLY_EQUAL.value
]
left_on, right_on = zip(*eqs)
left_on = [*left_on]
right_on = [*right_on]
strings_or_category = any(
col
for col in left_on
if (is_string_dtype(df[col]) | is_categorical_dtype(df[col]))
)
if (
strings_or_category
| (not right.duplicated(subset=right_on).any(axis=None))
| (not df.duplicated(subset=left_on).any(axis=None))
):
rest = (
(df[left_on], right[right_on], op)
for left_on, right_on, op in conditions
if op != _JoinOperator.STRICTLY_EQUAL.value
)
left_index, right_index = _MergeOperation(
df,
right,
left_on=left_on,
right_on=right_on,
sort=False,
copy=False,
)._get_join_indexers()
if not left_index.size:
return None
return _generate_indices(left_index, right_index, rest)
left_on, right_on = eqs[0]
outcome = _eq_indices(df[left_on], right[right_on])
if not outcome:
return None
left_index, right_index, lower_boundary, upper_boundary = outcome
eq_check = [condition for condition in conditions if condition != eqs[0]]
rest = [
(df.loc[left_index, left_on], right.loc[right_index, right_on], op)
for left_on, right_on, op in eq_check
]
rest = [
(
extract_array(left_c, extract_numpy=True),
extract_array(right_c, extract_numpy=True),
operator_map[op],
)
for left_c, right_c, op in rest
]
def _extension_array_check(arr):
"""
Convert boolean array to numpy array
if it is an extension array.
"""
if is_extension_array_dtype(arr):
return arr.to_numpy(dtype=bool, na_value=False, copy=False)
return arr
pos = np.copy(upper_boundary)
upper = | np.copy(upper_boundary) | numpy.copy |
"""
see: get_sorted_connected_regions
input a 3D mask numpy array, output a dict, with key 1, 2, 3, ... (int), which conforms to the ranking of the volume of
the connected component. The value of the dict is lists of locations like {1: [(x1, y1, z1), (x2, y2, z2), ...], ...}
"""
import numpy as np
import Tool_Functions.Functions as Functions
import Analysis.connected_region2d_and_scale_free_stat as rim_detect
np.set_printoptions(precision=10, suppress=True)
epsilon = 0.001
class DimensionError(Exception):
def __init__(self, array):
self.shape = np.shape(array)
self.dimension = len(self.shape)
def __str__(self):
print("invalid dimension of", self.dimension, ", array has shape", self.shape)
def get_connected_regions(input_array, threshold=None, strict=False, start_id=None):
"""
:param input_array: the mask array, with shape [x, y, z]
:param threshold: the threshold of cast the mask array to binary
:param strict: whether diagonal pixel is considered as adjacent.
:param start_id: the connect region id
:return: a dict, with key 1, 2, 3, ... (int), value is list of location: {1: [(x1, y1, z1), (x2, y2, z2), ...], ...}
a dict, with key 1, 2, 3, ... (int), value is length(list of location)
helper_array has shape [a, b, c, 2], first channel is the merge count, second for region id
optional: start_id for next stage
"""
if threshold is not None:
input_array = np.array(input_array > threshold, 'float32')
shape = np.shape(input_array)
helper_array = np.zeros([shape[0], shape[1], shape[2], 2])
# the last dim has two channels, the first is the key, the second is the volume
helper_array[:, :, :, 0] = -input_array
tracheae_points = np.where(helper_array[:, :, :, 0] < -epsilon)
num_checking_points = len(tracheae_points[0])
# print("we will check:", num_checking_points)
id_volume_dict = {}
id_loc_dict = {}
if start_id is None:
connected_id = 1
else:
connected_id = start_id
for index in range(num_checking_points):
pixel_location = (tracheae_points[0][index], tracheae_points[1][index], tracheae_points[2][index])
if helper_array[pixel_location[0], pixel_location[1], pixel_location[2], 0] > epsilon:
# this means this point has been allocated id and volume
continue
else:
# this means this point has been allocated id and volume
if strict:
volume, locations = broadcast_connected_component(helper_array, pixel_location, connected_id)
else:
volume, locations = broadcast_connected_component_2(helper_array, pixel_location, connected_id)
# now, the volume and id has been broadcast to this connected component.
id_volume_dict[connected_id] = volume
id_loc_dict[connected_id] = locations
connected_id += 1 # the id is 1, 2, 3, ...
if start_id is None:
return id_volume_dict, id_loc_dict, helper_array
else:
return id_volume_dict, id_loc_dict, helper_array, connected_id
def get_connected_regions_light(input_flow, strict=False):
"""
:param input_flow: the binary mask array, with shape [x, y, z], pid_id
:param strict: whether diagonal pixel is considered as adjacent.
:return: a dict, with key 1, 2, 3, ... (int), value is list of location: {1: [(x1, y1, z1), (x2, y2, z2), ...], ...}
"""
input_array = input_flow[0]
print("processing interval", input_flow[1])
shape = | np.shape(input_array) | numpy.shape |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 26 12:27:48 2021
@author: bjorn
Traininer and Evaluation loops functioning with WandB
"""
import torch
import time
from tqdm import tqdm
import wandb
import numpy as np
from sklearn.metrics import confusion_matrix
from model_utils import get_rri, plot_grad_flow
def train(args, model, optimizer, criterion):
model.train() # Turn on the train mode
total_loss = 0.
batch_nr = 0
start_time = time.time()
# src_mask = model.generate_square_subsequent_mask(bptt).to(device)
# for batch, i in enumerate(range(0, train_data.size(0) - 1, bptt)):
# data, targets = get_batch(train_data, i)
for batch in tqdm(train_loader):
batch_nr += 1
data, targets = batch
data = data[:,:,0]
# plt.plot(data[0,:])
# plt.show()
rri = get_rri(data)
data, rri, targets = torch.tensor(data, dtype=torch.float, device=device), torch.tensor(rri, dtype=torch.float, device=device), torch.tensor(targets, dtype=torch.float, device=device)
optimizer.zero_grad()
# if data.size(0) != bptt:
# src_mask = model.generate_square_subsequent_mask(data.size(0)).to(device)
# print(data.shape)
# print(src_mask.shape)
# output = model(data) # if n_class>2, and use cross entropy loss
output = model(data, rri)[:,0] # if n_class==2
# output = torch.argmax(output, dim=1)
# output = torch.tensor(output, dtype=torch.float, device=device, requires_grad=True)
# print('output:', output)
# print('targets:', targets)
loss = criterion(output, targets)
loss.backward()
# plot_grad_flow(model.named_parameters())
# torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=2.0 , norm_type=2)
optimizer.step()
total_loss += loss.item()
log_interval = 50
if batch_nr % log_interval == 0 and batch_nr > 0:
cur_loss = total_loss / log_interval
elapsed = time.time() - start_time
# print('| epoch', epoch,
# '| train loss', np.round(cur_loss, 4),
# '| ms/batch', np.round(elapsed*1000/log_interval, 3),
# '| lr', np.round(scheduler.get_last_lr()[0], 4)
# )
total_loss = 0.
start_time = time.time()
# scheduler.step()
wandb.log({
"Train Loss": cur_loss})
return model, cur_loss
def evaluate(args, eval_model, data_source, criterion):
true_label = np.array([])
predictions = np.array([])
loss_list = []
eval_model.eval() # Turn on the evaluation mode
tot_val_loss = 0.
val_batch_nr = 0
# src_mask = model.generate_square_subsequent_mask(bptt).to(device)
with torch.no_grad():
# for i in range(0, data_source.size(0) - 1, bptt):
# data, targets = get_batch(data_source, i)
for batch in data_source:
data, targets = batch
data = data[:,:,0]
rri = get_rri(data)
data, rri, targets = torch.tensor(data, dtype=torch.float, device=device), torch.tensor(rri, dtype=torch.float, device=device), torch.tensor(targets, dtype=torch.float, device=device)
# if data.size(0) != bptt:
# src_mask = model.generate_square_subsequent_mask(data.size(0)).to(device)
output = eval_model(data, rri)[:,0]
# output = torch.argmax(output, dim=1)
# output = torch.tensor(output, dtype=torch.float, device=device, requires_grad=True)
loss = criterion(output, targets)
tot_val_loss += loss.item()
val_batch_nr+=1
preds = np.round(torch.sigmoid(output).cpu().detach())
# print('val preds:', preds)
# print('val targets:', targets.cpu().detach())
predictions = np.append(predictions, preds)
true_label = np.append(true_label, targets.cpu().detach())
# Get losses and accuracy
cm = confusion_matrix(true_label, predictions, labels=[0,1])
acc = np.sum( | np.diag(cm) | numpy.diag |
import numpy as np
import scipy as sp
from scipy.stats import multivariate_normal
import unittest
from gp_project import *
class TestKronecker(unittest.TestCase):
"""Test the functions defined in gp_project.kronecker.
"""
def test_kronecker(self):
np.random.seed(1)
# Create random matrices
[a, b, c] = [np.random.rand(3, 3+i) for i in range(3)]
np.testing.assert_array_almost_equal(
kronecker([a, b, c]), # Custom version
np.kron(a, np.kron(b, c)) # Standard nested version
)
def test_cartesian(self):
np.random.seed(1)
a = [1, 2, 3]
b = [0, 2]
c = [5, 6]
manual_cartesian = np.array(
[[1, 0, 5],
[1, 0, 6],
[1, 2, 5],
[1, 2, 6],
[2, 0, 5],
[2, 0, 6],
[2, 2, 5],
[2, 2, 6],
[3, 0, 5],
[3, 0, 6],
[3, 2, 5],
[3, 2, 6],
]
)
auto_cart = cartesian(a, b, c)
print(auto_cart)
np.testing.assert_array_almost_equal(manual_cartesian, auto_cart)
def test_kron_mvprod(self):
np.random.seed(1)
# Create random matrices
Ks = [np.random.rand(3, 3+i) for i in range(3)]
# Create random vector with correct shape
tot_size = np.prod([k.shape[1] for k in Ks])
x = np.random.rand(tot_size).reshape((tot_size, 1))
# Construct entire kronecker product then multiply
big = kronecker(Ks)
slow_ans = np.matmul(big, x)
# Use tricks to avoid construction of entire kronecker product
fast_ans = kron_mvprod(Ks, x)
np.testing.assert_array_almost_equal(slow_ans, fast_ans)
def test_kron_mmprod(self):
np.random.seed(1)
# Create random matrices
Ks = [np.random.rand(3, 3+i) for i in range(3)]
# Create random matrix with correct shape
tot_size = np.prod([k.shape[1] for k in Ks])
m = np.random.rand(tot_size, 4) # column size could be anything
# Construct entire kronecker product then multiply
big = kronecker(Ks)
slow_ans = np.matmul(big, m)
# Use tricks to avoid construction of entire kronecker product
fast_ans = kron_mmprod(Ks, m)
np.testing.assert_array_almost_equal(slow_ans, fast_ans)
def test_kron_diag(self):
np.random.seed(1)
# Create random matrices
Ks = [np.random.rand(5, 5) for i in range(4)]
slow_ans = np.diag(kronecker(Ks))
Kdiags = map(np.diag, Ks)
fast_ans = kron_diag(Kdiags)
np.testing.assert_array_almost_equal(slow_ans, fast_ans)
def test_kron_chol_vsolve(self):
np.random.seed(1)
# Make mean, covariance, and noise
nvars = 3
lenvars = 5
xs = np.random.rand(nvars, lenvars)
xs = np.sort(xs)
Ks = [gaussian_kernel(x, x, .1) for x in xs]
chols = list(map(np.linalg.cholesky, Ks))
tot_size = np.prod([k.shape[1] for k in Ks])
b = np.random.rand(tot_size, 1)
fast_ans = kron_chol_vsolve(chols, b)
big = kronecker(Ks)
big_chol = np.linalg.cholesky(big)
slow_ans = sp.linalg.cho_solve((big_chol, True), b)
np.testing.assert_array_almost_equal(slow_ans, fast_ans)
def test_kron_chol_msolve(self):
np.random.seed(1)
# Make mean, covariance, and noise
nvars = 3
lenvars = 5
xs = np.random.rand(nvars, lenvars)
xs = np.sort(xs)
Ks = [gaussian_kernel(x, x, .1) for x in xs]
chols = list(map(np.linalg.cholesky, Ks))
tot_size = np.prod([k.shape[1] for k in Ks])
b = np.random.rand(tot_size, 4)
fast_ans = kron_chol_msolve(chols, b)
big = kronecker(Ks)
big_chol = np.linalg.cholesky(big)
slow_ans = sp.linalg.cho_solve((big_chol, True), b)
np.testing.assert_array_almost_equal(slow_ans, fast_ans)
def test_KroneckerNormal_EVDs_logp(self):
np.random.seed(1)
# Make mean, covariance, and noise
nvars = 3
lenvars = 5
xs = np.random.rand(nvars, lenvars)
xs = np.sort(xs)
Ks = [gaussian_kernel(x, x, .1) for x in xs]
tot_size = | np.prod([k.shape[1] for k in Ks]) | numpy.prod |
import numpy as np
import main.utils as utils
import matplotlib.pyplot as plt
from scipy.io import loadmat
import cv2
import os
from random import sample
import pickle
# ---------------------------- 说明 ----------------------------------
# 可视化图像检索效果图
# 需要 1. database和query数据集路径 2. xxx.npz文件(其中保存了相似度矩阵)
# 3. SMCNTF生成的最优路径文件 pathid.pkl
# 4. SeqSLAM生成的相似度矩阵 xxx.mat
# 每行打(*)号的需要根据实际情况配置
# 在论文中,对比了pairwise、MCN、SeqSLAM、SMCN和SMCNTF一共5种方法
# ---------------------------- 说明 ----------------------------------
# dataset root dir
root = 'E:/project/scut/graduation/datasets/gardens_point/' #(*)
# load xxx.npz
S_file = './vis3/gp_dlnr.npz' #(*)
S = np.load(S_file)
S_pw = S['S_pw']
S_mcn = S['S_mcn']
# use SeqSLAM2.0 toolbox from matlab, the similarity matrix has much nan value
S_seq = loadmat('../cp3_4/seqslam/gp_dlnr.mat')['S'] #(*)
tmp = np.isnan(S_seq)
S_seq[tmp] = np.max(S_seq[~tmp])
S_smcn = S['S_smcn']
S_smcntf = S['S_smcntf']
with open('../cp3_4/s_dd.pkl', 'rb') as f:
S_dd = pickle.load(f)
dbfile = 'day_left/' #(*) database file
qfile = 'night_right/' #(*) query file
dbn = len(os.listdir(root + dbfile))
qn = len(os.listdir(root + qfile))
qn = min(dbn, qn)
numPicToShow = 10 #(*)
if root.endswith('scut/'):
qn = qn // 4
picid = sample(range(0, qn), numPicToShow)
numpic = len(picid)
img_format = 'Image%03d.jpg' #(*)
err = 3 #(*)
saveName = './vis2/gp.png' #(*)
if root.endswith('robotcar/'):
db_gps = np.load(root + 'gps_snow.npy')
q_gps = np.load(root + 'gps_night.npy')
_, gt = utils.getGpsGT(db_gps, q_gps, err)
else:
gt = utils.getGroundTruthMatrix(qn, err)
gtl = []
for each in picid:
gtl.append(list(np.where(gt[:, each])[0]))
id_pw = np.argmax(S_pw[:, picid], axis=0)
id_dd = | np.argmax(S_dd[:, picid], axis=0) | numpy.argmax |
"""
The guts are in:
run_transit_inference
run_onetransit_inference
run_alltransit_inference
run_allindivtransit_inference
"""
import numpy as np, matplotlib.pyplot as plt, pandas as pd, pymc3 as pm
import pickle, os
from astropy import units as units, constants as const
from numpy import array as nparr
from functools import partial
from collections import OrderedDict
import exoplanet as xo
from exoplanet.gp import terms, GP
import theano.tensor as tt
from timmy.plotting import plot_MAP_data as plot_MAP_phot
from timmy.plotting import plot_MAP_rv
from timmy.paths import RESULTSDIR
from timmy.priors import RSTAR, RSTAR_STDEV, LOGG, LOGG_STDEV
# factor * 10**logg / r_star = rho
factor = 5.141596357654149e-05
class ModelParser:
def __init__(self, modelid):
self.initialize_model(modelid)
def initialize_model(self, modelid):
self.modelid = modelid
self.modelcomponents = modelid.split('_')
self.verify_modelcomponents()
def verify_modelcomponents(self):
validcomponents = ['transit', 'gprot', 'rv', 'alltransit', 'quad',
'quaddepthvar', 'onetransit', 'allindivtransit',
'tessindivtransit', 'oddindivtransit',
'evenindivtransit']
for i in range(5):
validcomponents.append('{}sincosPorb'.format(i))
validcomponents.append('{}sincosProt'.format(i))
assert len(self.modelcomponents) >= 1
for modelcomponent in self.modelcomponents:
if modelcomponent not in validcomponents:
errmsg = (
'Got modelcomponent {}. validcomponents include {}.'
.format(modelcomponent, validcomponents)
)
raise ValueError(errmsg)
class ModelFitter(ModelParser):
"""
Given a modelid of the form "transit", or "rv" and a dataframe containing
(time and flux), or (time and rv), run the inference.
"""
def __init__(self, modelid, data_df, prior_d, N_samples=2000, N_cores=16,
target_accept=0.8, N_chains=4, plotdir=None, pklpath=None,
overwrite=1, rvdf=None):
self.N_samples = N_samples
self.N_cores = N_cores
self.N_chains = N_chains
self.PLOTDIR = plotdir
self.OVERWRITE = overwrite
if 'transit' == modelid:
self.data = data_df
self.x_obs = nparr(data_df['x_obs'])
self.y_obs = nparr(data_df['y_obs'])
self.y_err = nparr(data_df['y_err'])
self.t_exp = np.nanmedian(np.diff(self.x_obs))
if modelid in ['alltransit', 'alltransit_quad',
'alltransit_quaddepthvar', 'onetransit',
'allindivtransit', 'tessindivtransit',
'oddindivtransit', 'evenindivtransit']:
assert isinstance(data_df, OrderedDict)
self.data = data_df
if 'rv' in modelid:
raise NotImplementedError
self.initialize_model(modelid)
if modelid not in ['alltransit', 'alltransit_quad',
'alltransit_quaddepthvar', 'onetransit',
'allindivtransit', 'tessindivtransit',
'oddindivtransit', 'evenindivtransit']:
self.verify_inputdata()
#NOTE threadsafety needn't be hardcoded
make_threadsafe = False
if modelid == 'transit':
self.run_transit_inference(
prior_d, pklpath, make_threadsafe=make_threadsafe
)
elif modelid == 'onetransit':
self.run_onetransit_inference(
prior_d, pklpath, make_threadsafe=make_threadsafe
)
elif modelid == 'rv':
self.run_rv_inference(
prior_d, pklpath, make_threadsafe=make_threadsafe
)
elif modelid in ['alltransit', 'alltransit_quad',
'alltransit_quaddepthvar']:
self.run_alltransit_inference(
prior_d, pklpath, make_threadsafe=make_threadsafe
)
elif modelid in ['allindivtransit', 'tessindivtransit',
'oddindivtransit', 'evenindivtransit']:
self.run_allindivtransit_inference(
prior_d, pklpath, make_threadsafe=make_threadsafe,
target_accept=target_accept
)
def verify_inputdata(self):
np.testing.assert_array_equal(
self.x_obs,
self.x_obs[np.argsort(self.x_obs)]
)
assert len(self.x_obs) == len(self.y_obs)
assert isinstance(self.x_obs, np.ndarray)
assert isinstance(self.y_obs, np.ndarray)
def run_transit_inference(self, prior_d, pklpath, make_threadsafe=True):
# if the model has already been run, pull the result from the
# pickle. otherwise, run it.
if os.path.exists(pklpath):
d = pickle.load(open(pklpath, 'rb'))
self.model = d['model']
self.trace = d['trace']
self.map_estimate = d['map_estimate']
return 1
with pm.Model() as model:
# Fixed data errors.
sigma = self.y_err
# Define priors and PyMC3 random variables to sample over.
# Stellar parameters. (Following tess.world notebooks).
logg_star = pm.Normal("logg_star", mu=LOGG, sd=LOGG_STDEV)
r_star = pm.Bound(pm.Normal, lower=0.0)(
"r_star", mu=RSTAR, sd=RSTAR_STDEV
)
rho_star = pm.Deterministic(
"rho_star", factor*10**logg_star / r_star
)
# Transit parameters.
mean = pm.Normal(
"mean", mu=prior_d['mean'], sd=1e-2, testval=prior_d['mean']
)
t0 = pm.Normal(
"t0", mu=prior_d['t0'], sd=2e-3, testval=prior_d['t0']
)
period = pm.Normal(
'period', mu=prior_d['period'], sd=5e-4,
testval=prior_d['period']
)
# NOTE: might want to implement kwarg for flexibility
# u = xo.distributions.QuadLimbDark(
# "u", testval=prior_d['u']
# )
u0 = pm.Uniform(
'u[0]', lower=prior_d['u[0]']-0.15,
upper=prior_d['u[0]']+0.15,
testval=prior_d['u[0]']
)
u1 = pm.Uniform(
'u[1]', lower=prior_d['u[1]']-0.15,
upper=prior_d['u[1]']+0.15,
testval=prior_d['u[1]']
)
u = [u0, u1]
# # The Espinoza (2018) parameterization for the joint radius ratio and
# # impact parameter distribution
# r, b = xo.distributions.get_joint_radius_impact(
# min_radius=0.001, max_radius=1.0,
# testval_r=prior_d['r'],
# testval_b=prior_d['b']
# )
# # NOTE: apparently, it's been deprecated. DFM's manuscript notes
# that it leads to Rp/Rs values biased high
log_r = pm.Uniform('log_r', lower=np.log(1e-2), upper=np.log(1),
testval=prior_d['log_r'])
r = pm.Deterministic('r', tt.exp(log_r))
b = xo.distributions.ImpactParameter(
"b", ror=r, testval=prior_d['b']
)
orbit = xo.orbits.KeplerianOrbit(
period=period, t0=t0, b=b, rho_star=rho_star, r_star=r_star
)
mu_transit = pm.Deterministic(
'mu_transit',
xo.LimbDarkLightCurve(u).get_light_curve(
orbit=orbit, r=r, t=self.x_obs, texp=self.t_exp
).T.flatten()
)
#
# Derived parameters
#
# planet radius in jupiter radii
r_planet = pm.Deterministic(
"r_planet", (r*r_star)*( 1*units.Rsun/(1*units.Rjup) ).cgs.value
)
#
# eq 30 of winn+2010, ignoring planet density.
#
a_Rs = pm.Deterministic(
"a_Rs",
(rho_star * period**2)**(1/3)
*
(( (1*units.gram/(1*units.cm)**3) * (1*units.day**2)
* const.G / (3*np.pi)
)**(1/3)).cgs.value
)
#
# cosi. assumes e=0 (e.g., Winn+2010 eq 7)
#
cosi = pm.Deterministic("cosi", b / a_Rs)
# probably safer than tt.arccos(cosi)
sini = pm.Deterministic("sini", pm.math.sqrt( 1 - cosi**2 ))
#
# transit durations (T_14, T_13) for circular orbits. Winn+2010 Eq 14, 15.
# units: hours.
#
T_14 = pm.Deterministic(
'T_14',
(period/np.pi)*
tt.arcsin(
(1/a_Rs) * pm.math.sqrt( (1+r)**2 - b**2 )
* (1/sini)
)*24
)
T_13 = pm.Deterministic(
'T_13',
(period/np.pi)*
tt.arcsin(
(1/a_Rs) * pm.math.sqrt( (1-r)**2 - b**2 )
* (1/sini)
)*24
)
#
# mean model and likelihood
#
mean_model = mu_transit + mean
mu_model = pm.Deterministic('mu_model', mean_model)
likelihood = pm.Normal('obs', mu=mean_model, sigma=sigma,
observed=self.y_obs)
# Optimizing
map_estimate = pm.find_MAP(model=model)
# start = model.test_point
# if 'transit' in self.modelcomponents:
# map_estimate = xo.optimize(start=start,
# vars=[r, b, period, t0])
# map_estimate = xo.optimize(start=map_estimate)
# Plot the simulated data and the maximum a posteriori model to
# make sure that our initialization looks ok.
self.y_MAP = (
map_estimate['mean'] + map_estimate['mu_transit']
)
if make_threadsafe:
pass
else:
# as described in
# https://github.com/matplotlib/matplotlib/issues/15410
# matplotlib is not threadsafe. so do not make plots before
# sampling, because some child processes tries to close a
# cached file, and crashes the sampler.
print(map_estimate)
if self.PLOTDIR is None:
raise NotImplementedError
outpath = os.path.join(self.PLOTDIR,
'test_{}_MAP.png'.format(self.modelid))
plot_MAP_phot(self.x_obs, self.y_obs, self.y_MAP, outpath)
# sample from the posterior defined by this model.
trace = pm.sample(
tune=self.N_samples, draws=self.N_samples,
start=map_estimate, cores=self.N_cores,
chains=self.N_chains,
step=xo.get_dense_nuts_step(target_accept=0.8),
)
with open(pklpath, 'wb') as buff:
pickle.dump({'model': model, 'trace': trace,
'map_estimate': map_estimate}, buff)
self.model = model
self.trace = trace
self.map_estimate = map_estimate
def run_rv_inference(self, prior_d, pklpath, make_threadsafe=True):
# if the model has already been run, pull the result from the
# pickle. otherwise, run it.
if os.path.exists(pklpath):
d = pickle.load(open(pklpath, 'rb'))
self.model = d['model']
self.trace = d['trace']
self.map_estimate = d['map_estimate']
return 1
with pm.Model() as model:
# Fixed data errors.
sigma = self.y_err
# Define priors and PyMC3 random variables to sample over.
# Stellar parameters. (Following tess.world notebooks).
logg_star = pm.Normal("logg_star", mu=prior_d['logg_star'][0],
sd=prior_d['logg_star'][1])
r_star = pm.Bound(pm.Normal, lower=0.0)(
"r_star", mu=prior_d['r_star'][0], sd=prior_d['r_star'][1]
)
rho_star = pm.Deterministic(
"rho_star", factor*10**logg_star / r_star
)
# RV parameters.
# Chen & Kipping predicted M: 49.631 Mearth, based on Rp of 8Re. It
# could be bigger, e.g., 94m/s if 1 Mjup.
# Predicted K: 14.26 m/s
#K = pm.Lognormal("K", mu=np.log(prior_d['K'][0]),
# sigma=prior_d['K'][1])
log_K = pm.Uniform('log_K', lower=prior_d['log_K'][0],
upper=prior_d['log_K'][1])
K = pm.Deterministic('K', tt.exp(log_K))
period = pm.Normal("period", mu=prior_d['period'][0],
sigma=prior_d['period'][1])
ecs = xo.UnitDisk("ecs", testval=np.array([0.7, -0.3]))
ecc = pm.Deterministic("ecc", tt.sum(ecs ** 2))
omega = pm.Deterministic("omega", tt.arctan2(ecs[1], ecs[0]))
phase = xo.UnitUniform("phase")
# use time of transit, rather than time of periastron. we do, after
# all, know it.
t0 = pm.Normal(
"t0", mu=prior_d['t0'][0], sd=prior_d['t0'][1],
testval=prior_d['t0'][0]
)
orbit = xo.orbits.KeplerianOrbit(
period=period, t0=t0, rho_star=rho_star, ecc=ecc, omega=omega,
r_star=r_star
)
#FIXME edit these
# noise model parameters: FIXME what are these?
S_tot = pm.Lognormal("S_tot", mu=np.log(prior_d['S_tot'][0]),
sigma=prior_d['S_tot'][1])
ell = pm.Lognormal("ell", mu=np.log(prior_d['ell'][0]),
sigma=prior_d['ell'][1])
# per instrument parameters
means = pm.Normal(
"means",
mu=np.array([np.median(self.y_obs[self.telvec == u]) for u in
self.uniqueinstrs]),
sigma=500,
shape=self.num_inst,
)
# different instruments have different intrinsic jitters. assign
# those based on the reported error bars. (NOTE: might inflate or
# overwrite these, for say, CHIRON)
sigmas = pm.HalfNormal(
"sigmas",
sigma=np.array([np.median(self.y_err[self.telvec == u]) for u
in self.uniqueinstrs]),
shape=self.num_inst
)
# Compute the RV offset and jitter for each data point depending on
# its instrument
mean = tt.zeros(len(self.x_obs))
diag = tt.zeros(len(self.x_obs))
for i, u in enumerate(self.uniqueinstrs):
mean += means[i] * (self.telvec == u)
diag += (self.y_err ** 2 + sigmas[i] ** 2) * (self.telvec == u)
pm.Deterministic("mean", mean)
pm.Deterministic("diag", diag)
# NOTE: local function definition is jank
def rv_model(x):
return orbit.get_radial_velocity(x, K=K)
kernel = xo.gp.terms.SHOTerm(S_tot=S_tot, w0=2*np.pi/ell, Q=1.0/3)
# NOTE temp
gp = xo.gp.GP(kernel, self.x_obs, diag, mean=rv_model)
# gp = xo.gp.GP(kernel, self.x_obs, diag,
# mean=orbit.get_radial_velocity(self.x_obs, K=K))
# the actual "conditioning" step, i.e. the likelihood definition
gp.marginal("obs", observed=self.y_obs-mean)
pm.Deterministic("gp_pred", gp.predict())
map_estimate = model.test_point
map_estimate = xo.optimize(map_estimate, [means])
map_estimate = xo.optimize(map_estimate, [means, phase])
map_estimate = xo.optimize(map_estimate, [means, phase, log_K])
map_estimate = xo.optimize(map_estimate, [means, t0, log_K, period, ecs])
map_estimate = xo.optimize(map_estimate, [sigmas, S_tot, ell])
map_estimate = xo.optimize(map_estimate)
#
# Derived parameters
#
#TODO
# # planet radius in jupiter radii
# r_planet = pm.Deterministic(
# "r_planet", (r*r_star)*( 1*units.Rsun/(1*units.Rjup) ).cgs.value
# )
# Plot the simulated data and the maximum a posteriori model to
# make sure that our initialization looks ok.
# i.e., "detrended". the "rv data" are y_obs - mean. The "trend" model
# is a GP. FIXME: AFAIK, it doesn't do much as-implemented.
self.y_MAP = (
self.y_obs - map_estimate["mean"] - map_estimate["gp_pred"]
)
t_pred = np.linspace(
self.x_obs.min() - 10, self.x_obs.max() + 10, 10000
)
with model:
# NOTE temp
y_pred_MAP = xo.eval_in_model(rv_model(t_pred), map_estimate)
# # NOTE temp
# y_pred_MAP = xo.eval_in_model(
# orbit.get_radial_velocity(t_pred, K=K), map_estimate
# )
self.x_pred = t_pred
self.y_pred_MAP = y_pred_MAP
if make_threadsafe:
pass
else:
# as described in
# https://github.com/matplotlib/matplotlib/issues/15410
# matplotlib is not threadsafe. so do not make plots before
# sampling, because some child processes tries to close a
# cached file, and crashes the sampler.
print(map_estimate)
if self.PLOTDIR is None:
raise NotImplementedError
outpath = os.path.join(self.PLOTDIR,
'test_{}_MAP.png'.format(self.modelid))
plot_MAP_rv(self.x_obs, self.y_obs, self.y_MAP, self.y_err,
self.telcolors, self.x_pred, self.y_pred_MAP,
map_estimate, outpath)
with model:
# sample from the posterior defined by this model.
trace = pm.sample(
tune=self.N_samples, draws=self.N_samples,
start=map_estimate, cores=self.N_cores,
chains=self.N_chains,
step=xo.get_dense_nuts_step(target_accept=0.8),
)
# with open(pklpath, 'wb') as buff:
# pickle.dump({'model': model, 'trace': trace,
# 'map_estimate': map_estimate}, buff)
self.model = model
self.trace = trace
self.map_estimate = map_estimate
def run_alltransit_inference(self, prior_d, pklpath, make_threadsafe=True):
# if the model has already been run, pull the result from the
# pickle. otherwise, run it.
if os.path.exists(pklpath):
d = pickle.load(open(pklpath, 'rb'))
self.model = d['model']
self.trace = d['trace']
self.map_estimate = d['map_estimate']
return 1
with pm.Model() as model:
# Shared parameters
# Stellar parameters. (Following tess.world notebooks).
logg_star = pm.Normal("logg_star", mu=LOGG, sd=LOGG_STDEV)
r_star = pm.Bound(pm.Normal, lower=0.0)(
"r_star", mu=RSTAR, sd=RSTAR_STDEV
)
rho_star = pm.Deterministic(
"rho_star", factor*10**logg_star / r_star
)
# fix Rp/Rs across bandpasses, b/c you're assuming it's a planet
if 'quaddepthvar' not in self.modelid:
log_r = pm.Uniform('log_r', lower=np.log(1e-2),
upper=np.log(1), testval=prior_d['log_r'])
r = pm.Deterministic('r', tt.exp(log_r))
else:
log_r_Tband = pm.Uniform('log_r_Tband', lower=np.log(1e-2),
upper=np.log(1),
testval=prior_d['log_r_Tband'])
r_Tband = pm.Deterministic('r_Tband', tt.exp(log_r_Tband))
log_r_Rband = pm.Uniform('log_r_Rband', lower=np.log(1e-2),
upper=np.log(1),
testval=prior_d['log_r_Rband'])
r_Rband = pm.Deterministic('r_Rband', tt.exp(log_r_Rband))
log_r_Bband = pm.Uniform('log_r_Bband', lower=np.log(1e-2),
upper=np.log(1),
testval=prior_d['log_r_Bband'])
r_Bband = pm.Deterministic('r_Bband', tt.exp(log_r_Bband))
r = r_Tband
# Some orbital parameters
t0 = pm.Normal(
"t0", mu=prior_d['t0'], sd=5e-3, testval=prior_d['t0']
)
period = pm.Normal(
'period', mu=prior_d['period'], sd=5e-3,
testval=prior_d['period']
)
b = xo.distributions.ImpactParameter(
"b", ror=r, testval=prior_d['b']
)
orbit = xo.orbits.KeplerianOrbit(
period=period, t0=t0, b=b, rho_star=rho_star, r_star=r_star
)
# NOTE: limb-darkening should be bandpass specific, but we don't
# have the SNR to justify that, so go with TESS-dominated
u0 = pm.Uniform(
'u[0]', lower=prior_d['u[0]']-0.15,
upper=prior_d['u[0]']+0.15,
testval=prior_d['u[0]']
)
u1 = pm.Uniform(
'u[1]', lower=prior_d['u[1]']-0.15,
upper=prior_d['u[1]']+0.15,
testval=prior_d['u[1]']
)
u = [u0, u1]
star = xo.LimbDarkLightCurve(u)
# Loop over "instruments" (TESS, then each ground-based lightcurve)
parameters = dict()
lc_models = dict()
roughdepths = dict()
for n, (name, (x, y, yerr, texp)) in enumerate(self.data.items()):
# Define per-instrument parameters in a submodel, to not need
# to prefix the names. Yields e.g., "TESS_mean",
# "elsauce_0_mean", "elsauce_2_a2"
with pm.Model(name=name, model=model):
# Transit parameters.
mean = pm.Normal(
"mean", mu=prior_d[f'{name}_mean'], sd=1e-2,
testval=prior_d[f'{name}_mean']
)
if 'quad' in self.modelid:
if name != 'tess':
# units: rel flux per day.
a1 = pm.Normal(
"a1", mu=prior_d[f'{name}_a1'], sd=1,
testval=prior_d[f'{name}_a1']
)
# units: rel flux per day^2.
a2 = pm.Normal(
"a2", mu=prior_d[f'{name}_a2'], sd=1,
testval=prior_d[f'{name}_a2']
)
if self.modelid == 'alltransit':
lc_models[name] = pm.Deterministic(
f'{name}_mu_transit',
mean +
star.get_light_curve(
orbit=orbit, r=r, t=x, texp=texp
).T.flatten()
)
elif self.modelid == 'alltransit_quad':
if name != 'tess':
# midpoint for this definition of the quadratic trend
_tmid = np.nanmedian(x)
lc_models[name] = pm.Deterministic(
f'{name}_mu_transit',
mean +
a1*(x-_tmid) +
a2*(x-_tmid)**2 +
star.get_light_curve(
orbit=orbit, r=r, t=x, texp=texp
).T.flatten()
)
elif name == 'tess':
lc_models[name] = pm.Deterministic(
f'{name}_mu_transit',
mean +
star.get_light_curve(
orbit=orbit, r=r, t=x, texp=texp
).T.flatten()
)
elif self.modelid == 'alltransit_quaddepthvar':
if name != 'tess':
# midpoint for this definition of the quadratic trend
_tmid = np.nanmedian(x)
# do custom depth-to-
if (name == 'elsauce_20200401' or
name == 'elsauce_20200426'
):
r = r_Rband
elif name == 'elsauce_20200521':
r = r_Tband
elif name == 'elsauce_20200614':
r = r_Bband
transit_lc = star.get_light_curve(
orbit=orbit, r=r, t=x, texp=texp
).T.flatten()
lc_models[name] = pm.Deterministic(
f'{name}_mu_transit',
mean +
a1*(x-_tmid) +
a2*(x-_tmid)**2 +
transit_lc
)
roughdepths[name] = pm.Deterministic(
f'{name}_roughdepth',
pm.math.abs_(transit_lc).max()
)
elif name == 'tess':
r = r_Tband
transit_lc = star.get_light_curve(
orbit=orbit, r=r, t=x, texp=texp
).T.flatten()
lc_models[name] = pm.Deterministic(
f'{name}_mu_transit',
mean +
transit_lc
)
roughdepths[name] = pm.Deterministic(
f'{name}_roughdepth',
pm.math.abs_(transit_lc).max()
)
# TODO: add error bar fudge
likelihood = pm.Normal(
f'{name}_obs', mu=lc_models[name], sigma=yerr, observed=y
)
#
# Derived parameters
#
if self.modelid == 'alltransit_quaddepthvar':
r = r_Tband
# planet radius in jupiter radii
r_planet = pm.Deterministic(
"r_planet", (r*r_star)*( 1*units.Rsun/(1*units.Rjup) ).cgs.value
)
#
# eq 30 of winn+2010, ignoring planet density.
#
a_Rs = pm.Deterministic(
"a_Rs",
(rho_star * period**2)**(1/3)
*
(( (1*units.gram/(1*units.cm)**3) * (1*units.day**2)
* const.G / (3*np.pi)
)**(1/3)).cgs.value
)
#
# cosi. assumes e=0 (e.g., Winn+2010 eq 7)
#
cosi = pm.Deterministic("cosi", b / a_Rs)
# probably safer than tt.arccos(cosi)
sini = pm.Deterministic("sini", pm.math.sqrt( 1 - cosi**2 ))
#
# transit durations (T_14, T_13) for circular orbits. Winn+2010 Eq 14, 15.
# units: hours.
#
T_14 = pm.Deterministic(
'T_14',
(period/np.pi)*
tt.arcsin(
(1/a_Rs) * pm.math.sqrt( (1+r)**2 - b**2 )
* (1/sini)
)*24
)
T_13 = pm.Deterministic(
'T_13',
(period/np.pi)*
tt.arcsin(
(1/a_Rs) * pm.math.sqrt( (1-r)**2 - b**2 )
* (1/sini)
)*24
)
# Optimizing
map_estimate = pm.find_MAP(model=model)
# start = model.test_point
# if 'transit' in self.modelcomponents:
# map_estimate = xo.optimize(start=start,
# vars=[r, b, period, t0])
# map_estimate = xo.optimize(start=map_estimate)
if make_threadsafe:
pass
else:
# NOTE: would usually plot MAP estimate here, but really
# there's not a huge need.
print(map_estimate)
pass
# sample from the posterior defined by this model.
trace = pm.sample(
tune=self.N_samples, draws=self.N_samples,
start=map_estimate, cores=self.N_cores,
chains=self.N_chains,
step=xo.get_dense_nuts_step(target_accept=0.8),
)
with open(pklpath, 'wb') as buff:
pickle.dump({'model': model, 'trace': trace,
'map_estimate': map_estimate}, buff)
self.model = model
self.trace = trace
self.map_estimate = map_estimate
def run_onetransit_inference(self, prior_d, pklpath, make_threadsafe=True):
"""
Similar to "run_transit_inference", but with more restrictive priors on
ephemeris. Also, it simultaneously fits for quadratic trend.
"""
# if the model has already been run, pull the result from the
# pickle. otherwise, run it.
if os.path.exists(pklpath):
d = pickle.load(open(pklpath, 'rb'))
self.model = d['model']
self.trace = d['trace']
self.map_estimate = d['map_estimate']
return 1
with pm.Model() as model:
assert len(self.data.keys()) == 1
name = list(self.data.keys())[0]
x_obs = list(self.data.values())[0][0]
y_obs = list(self.data.values())[0][1]
y_err = list(self.data.values())[0][2]
t_exp = list(self.data.values())[0][3]
# Fixed data errors.
sigma = y_err
# Define priors and PyMC3 random variables to sample over.
# Stellar parameters. (Following tess.world notebooks).
logg_star = pm.Normal("logg_star", mu=LOGG, sd=LOGG_STDEV)
r_star = pm.Bound(pm.Normal, lower=0.0)(
"r_star", mu=RSTAR, sd=RSTAR_STDEV
)
rho_star = pm.Deterministic(
"rho_star", factor*10**logg_star / r_star
)
# Transit parameters.
t0 = pm.Normal(
"t0", mu=prior_d['t0'], sd=1e-3, testval=prior_d['t0']
)
period = pm.Normal(
'period', mu=prior_d['period'], sd=3e-4,
testval=prior_d['period']
)
# NOTE: might want to implement kwarg for flexibility
# u = xo.distributions.QuadLimbDark(
# "u", testval=prior_d['u']
# )
u0 = pm.Uniform(
'u[0]', lower=prior_d['u[0]']-0.15,
upper=prior_d['u[0]']+0.15,
testval=prior_d['u[0]']
)
u1 = pm.Uniform(
'u[1]', lower=prior_d['u[1]']-0.15,
upper=prior_d['u[1]']+0.15,
testval=prior_d['u[1]']
)
u = [u0, u1]
# # The Espinoza (2018) parameterization for the joint radius ratio and
# # impact parameter distribution
# r, b = xo.distributions.get_joint_radius_impact(
# min_radius=0.001, max_radius=1.0,
# testval_r=prior_d['r'],
# testval_b=prior_d['b']
# )
# # NOTE: apparently, it's been deprecated. DFM's manuscript notes
# that it leads to Rp/Rs values biased high
log_r = pm.Uniform('log_r', lower=np.log(1e-2), upper=np.log(1),
testval=prior_d['log_r'])
r = pm.Deterministic('r', tt.exp(log_r))
b = xo.distributions.ImpactParameter(
"b", ror=r, testval=prior_d['b']
)
# the transit
orbit = xo.orbits.KeplerianOrbit(
period=period, t0=t0, b=b, rho_star=rho_star, r_star=r_star
)
transit_lc = pm.Deterministic(
'transit_lc',
xo.LimbDarkLightCurve(u).get_light_curve(
orbit=orbit, r=r, t=x_obs, texp=t_exp
).T.flatten()
)
# quadratic trend parameters
mean = pm.Normal(
f"{name}_mean", mu=prior_d[f'{name}_mean'], sd=1e-2,
testval=prior_d[f'{name}_mean']
)
a1 = pm.Normal(
f"{name}_a1", mu=prior_d[f'{name}_a1'], sd=1,
testval=prior_d[f'{name}_a1']
)
a2 = pm.Normal(
f"{name}_a2", mu=prior_d[f'{name}_a2'], sd=1,
testval=prior_d[f'{name}_a2']
)
_tmid = np.nanmedian(x_obs)
lc_model = pm.Deterministic(
'mu_transit',
mean +
a1*(x_obs-_tmid) +
a2*(x_obs-_tmid)**2 +
transit_lc
)
roughdepth = pm.Deterministic(
f'roughdepth',
pm.math.abs_(transit_lc).max()
)
#
# Derived parameters
#
# planet radius in jupiter radii
r_planet = pm.Deterministic(
"r_planet", (r*r_star)*( 1*units.Rsun/(1*units.Rjup) ).cgs.value
)
#
# eq 30 of winn+2010, ignoring planet density.
#
a_Rs = pm.Deterministic(
"a_Rs",
(rho_star * period**2)**(1/3)
*
(( (1*units.gram/(1*units.cm)**3) * (1*units.day**2)
* const.G / (3*np.pi)
)**(1/3)).cgs.value
)
#
# cosi. assumes e=0 (e.g., Winn+2010 eq 7)
#
cosi = pm.Deterministic("cosi", b / a_Rs)
# safer than tt.arccos(cosi)
sini = pm.Deterministic("sini", pm.math.sqrt( 1 - cosi**2 ))
#
# transit durations (T_14, T_13) for circular orbits. Winn+2010 Eq 14, 15.
# units: hours.
#
T_14 = pm.Deterministic(
'T_14',
(period/np.pi)*
tt.arcsin(
(1/a_Rs) * pm.math.sqrt( (1+r)**2 - b**2 )
* (1/sini)
)*24
)
T_13 = pm.Deterministic(
'T_13',
(period/np.pi)*
tt.arcsin(
(1/a_Rs) * pm.math.sqrt( (1-r)**2 - b**2 )
* (1/sini)
)*24
)
#
# mean model and likelihood
#
# mean_model = mu_transit + mean
# mu_model = pm.Deterministic('mu_model', lc_model)
likelihood = pm.Normal('obs', mu=lc_model, sigma=sigma,
observed=y_obs)
# Optimizing
map_estimate = pm.find_MAP(model=model)
# start = model.test_point
# if 'transit' in self.modelcomponents:
# map_estimate = xo.optimize(start=start,
# vars=[r, b, period, t0])
# map_estimate = xo.optimize(start=map_estimate)
if make_threadsafe:
pass
else:
# as described in
# https://github.com/matplotlib/matplotlib/issues/15410
# matplotlib is not threadsafe. so do not make plots before
# sampling, because some child processes tries to close a
# cached file, and crashes the sampler.
print(map_estimate)
# sample from the posterior defined by this model.
trace = pm.sample(
tune=self.N_samples, draws=self.N_samples,
start=map_estimate, cores=self.N_cores,
chains=self.N_chains,
step=xo.get_dense_nuts_step(target_accept=0.8),
)
with open(pklpath, 'wb') as buff:
pickle.dump({'model': model, 'trace': trace,
'map_estimate': map_estimate}, buff)
self.model = model
self.trace = trace
self.map_estimate = map_estimate
def run_allindivtransit_inference(self, prior_d, pklpath,
make_threadsafe=True, target_accept=0.8):
# if the model has already been run, pull the result from the
# pickle. otherwise, run it.
if os.path.exists(pklpath):
d = pickle.load(open(pklpath, 'rb'))
self.model = d['model']
self.trace = d['trace']
self.map_estimate = d['map_estimate']
return 1
with pm.Model() as model:
# Shared parameters
# Stellar parameters. (Following tess.world notebooks).
logg_star = pm.Normal("logg_star", mu=LOGG, sd=LOGG_STDEV)
r_star = pm.Bound(pm.Normal, lower=0.0)(
"r_star", mu=RSTAR, sd=RSTAR_STDEV
)
rho_star = pm.Deterministic(
"rho_star", factor*10**logg_star / r_star
)
# fix Rp/Rs across bandpasses, b/c you're assuming it's a planet
# #NOTE: to impose max Rp = 3 Rjup, would uncomment this!
# #(20200831 tessindivtransit fit did this)
# upper_rprs = pm.Deterministic("upper_rprs",
# ( 1*units.Rjup/(1*units.Rsun) ).cgs.value * (3) / r_star
# )
upper_rprs = 1
log_r = pm.Uniform('log_r', lower=np.log(1e-2),
upper= | np.log(upper_rprs) | numpy.log |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Tests models.parameters
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import itertools
import pytest
import numpy as np
from . import irafutil
from .. import models, fitting
from ..core import Model, FittableModel
from ..parameters import Parameter, InputParameterError
from ...utils.data import get_pkg_data_filename
def setter1(val):
return val
def setter2(val, model):
model.do_something(val)
return val * model.p
class SetterModel(FittableModel):
inputs = ('x', 'y')
outputs = ('z',)
xc = Parameter(default=1, setter=setter1)
yc = Parameter(default=1, setter=setter2)
def __init__(self, xc, yc, p):
self.p = p # p is a value intended to be used by the setter
super(SetterModel, self).__init__()
self.xc = xc
self.yc = yc
def evaluate(self, x, y, xc, yc):
return ((x - xc)**2 + (y - yc)**2)
def do_something(self, v):
pass
class TParModel(Model):
"""
A toy model to test parameters machinery
"""
coeff = Parameter()
e = Parameter()
def __init__(self, coeff, e, **kwargs):
super(TParModel, self).__init__(coeff=coeff, e=e, **kwargs)
@staticmethod
def evaluate(coeff, e):
pass
class MockModel(FittableModel):
alpha = Parameter(name='alpha', default=42)
@staticmethod
def evaluate(*args):
pass
def test_parameter_properties():
"""Test if getting / setting of Parameter properties works."""
m = MockModel()
p = m.alpha
assert p.name == 'alpha'
# Parameter names are immutable
with pytest.raises(AttributeError):
p.name = 'beta'
assert p.fixed is False
p.fixed = True
assert p.fixed is True
assert p.tied is False
p.tied = lambda _: 0
p.tied = False
assert p.tied is False
assert p.min is None
p.min = 42
assert p.min == 42
p.min = None
assert p.min is None
assert p.max is None
# TODO: shouldn't setting a max < min give an error?
p.max = 41
assert p.max == 41
def test_parameter_operators():
"""Test if the parameter arithmetic operators work."""
m = MockModel()
par = m.alpha
num = 42.
val = 3
assert par - val == num - val
assert val - par == val - num
assert par / val == num / val
assert val / par == val / num
assert par ** val == num ** val
assert val ** par == val ** num
assert par < 45
assert par > 41
assert par <= par
assert par >= par
assert par == par
assert -par == -num
assert abs(par) == abs(num)
class TestParameters(object):
def setup_class(self):
"""
Unit tests for parameters
Read an iraf database file created by onedspec.identify. Use the
information to create a 1D Chebyshev model and perform the same fit.
Create also a gausian model.
"""
test_file = get_pkg_data_filename('data/idcompspec.fits')
f = open(test_file)
lines = f.read()
reclist = lines.split("begin")
f.close()
record = irafutil.IdentifyRecord(reclist[1])
self.icoeff = record.coeff
order = int(record.fields['order'])
self.model = models.Chebyshev1D(order - 1)
self.gmodel = models.Gaussian1D(2, mean=3, stddev=4)
self.linear_fitter = fitting.LinearLSQFitter()
self.x = record.x
self.y = record.z
self.yy = np.array([record.z, record.z])
def test_set_slice(self):
"""
Tests updating the parameters attribute with a slice.
This is what fitters internally do.
"""
self.model.parameters[:] = np.array([3, 4, 5, 6, 7])
assert (self.model.parameters == [3., 4., 5., 6., 7.]).all()
def test_set_parameters_as_list(self):
"""Tests updating parameters using a list."""
self.model.parameters = [30, 40, 50, 60, 70]
assert (self.model.parameters == [30., 40., 50., 60, 70]).all()
def test_set_parameters_as_array(self):
"""Tests updating parameters using an array."""
self.model.parameters = np.array([3, 4, 5, 6, 7])
assert (self.model.parameters == [3., 4., 5., 6., 7.]).all()
def test_set_as_tuple(self):
"""Tests updating parameters using a tuple."""
self.model.parameters = (1, 2, 3, 4, 5)
assert (self.model.parameters == [1, 2, 3, 4, 5]).all()
def test_set_model_attr_seq(self):
"""
Tests updating the parameters attribute when a model's
parameter (in this case coeff) is updated.
"""
self.model.parameters = [0, 0., 0., 0, 0]
self.model.c0 = 7
assert (self.model.parameters == [7, 0., 0., 0, 0]).all()
def test_set_model_attr_num(self):
"""Update the parameter list when a model's parameter is updated."""
self.gmodel.amplitude = 7
assert (self.gmodel.parameters == [7, 3, 4]).all()
def test_set_item(self):
"""Update the parameters using indexing."""
self.model.parameters = [1, 2, 3, 4, 5]
self.model.parameters[0] = 10.
assert (self.model.parameters == [10, 2, 3, 4, 5]).all()
assert self.model.c0 == 10
def test_wrong_size1(self):
"""
Tests raising an error when attempting to reset the parameters
using a list of a different size.
"""
with pytest.raises(InputParameterError):
self.model.parameters = [1, 2, 3]
def test_wrong_size2(self):
"""
Tests raising an exception when attempting to update a model's
parameter (in this case coeff) with a sequence of the wrong size.
"""
with pytest.raises(InputParameterError):
self.model.c0 = [1, 2, 3]
def test_wrong_shape(self):
"""
Tests raising an exception when attempting to update a model's
parameter and the new value has the wrong shape.
"""
with pytest.raises(InputParameterError):
self.gmodel.amplitude = [1, 2]
def test_par_against_iraf(self):
"""
Test the fitter modifies model.parameters.
Uses an iraf example.
"""
new_model = self.linear_fitter(self.model, self.x, self.y)
np.testing.assert_allclose(
new_model.parameters,
np.array([4826.1066602783685, 952.8943813407858, 12.641236013982386,
-1.7910672553339604, 0.90252884366711317]),
rtol=10 ** (-2))
def testPolynomial1D(self):
d = {'c0': 11, 'c1': 12, 'c2': 13, 'c3': 14}
p1 = models.Polynomial1D(3, **d)
np.testing.assert_equal(p1.parameters, [11, 12, 13, 14])
def test_poly1d_multiple_sets(self):
p1 = models.Polynomial1D(3, n_models=3)
np.testing.assert_equal(p1.parameters, [0.0, 0.0, 0.0, 0, 0, 0,
0, 0, 0, 0, 0, 0])
np.testing.assert_array_equal(p1.c0, [0, 0, 0])
p1.c0 = [10, 10, 10]
np.testing.assert_equal(p1.parameters, [10.0, 10.0, 10.0, 0, 0,
0, 0, 0, 0, 0, 0, 0])
def test_par_slicing(self):
"""
Test assigning to a parameter slice
"""
p1 = models.Polynomial1D(3, n_models=3)
p1.c0[:2] = [10, 10]
np.testing.assert_equal(p1.parameters, [10.0, 10.0, 0.0, 0, 0,
0, 0, 0, 0, 0, 0, 0])
def test_poly2d(self):
p2 = models.Polynomial2D(degree=3)
p2.c0_0 = 5
np.testing.assert_equal(p2.parameters, [5, 0, 0, 0, 0, 0, 0, 0, 0, 0])
def test_poly2d_multiple_sets(self):
kw = {'c0_0': [2, 3], 'c1_0': [1, 2], 'c2_0': [4, 5],
'c0_1': [1, 1], 'c0_2': [2, 2], 'c1_1': [5, 5]}
p2 = models.Polynomial2D(2, **kw)
np.testing.assert_equal(p2.parameters, [2, 3, 1, 2, 4, 5,
1, 1, 2, 2, 5, 5])
def test_shift_model_parameters1d(self):
sh1 = models.Shift(2)
sh1.offset = 3
assert sh1.offset == 3
assert sh1.offset.value == 3
def test_scale_model_parametersnd(self):
sc1 = models.Scale([2, 2])
sc1.factor = [3, 3]
assert np.all(sc1.factor == [3, 3])
np.testing.assert_array_equal(sc1.factor.value, [3, 3])
def test_parameters_wrong_shape(self):
sh1 = models.Shift(2)
with pytest.raises(InputParameterError):
sh1.offset = [3, 3]
class TestMultipleParameterSets(object):
def setup_class(self):
self.x1 = np.arange(1, 10, .1)
self.y, self.x = np.mgrid[:10, :7]
self.x11 = np.array([self.x1, self.x1]).T
self.gmodel = models.Gaussian1D([12, 10], [3.5, 5.2], stddev=[.4, .7],
n_models=2)
def test_change_par(self):
"""
Test that a change to one parameter as a set propagates to param_sets.
"""
self.gmodel.amplitude = [1, 10]
np.testing.assert_almost_equal(
self.gmodel.param_sets,
np.array([[1.,
10],
[3.5,
5.2],
[0.4,
0.7]]))
np.all(self.gmodel.parameters == [1.0, 10.0, 3.5, 5.2, 0.4, 0.7])
def test_change_par2(self):
"""
Test that a change to one single parameter in a set propagates to
param_sets.
"""
self.gmodel.amplitude[0] = 11
np.testing.assert_almost_equal(
self.gmodel.param_sets,
np.array([[11.,
10],
[3.5,
5.2],
[0.4,
0.7]]))
np.all(self.gmodel.parameters == [11.0, 10.0, 3.5, 5.2, 0.4, 0.7])
def test_change_parameters(self):
self.gmodel.parameters = [13, 10, 9, 5.2, 0.4, 0.7]
np.testing.assert_almost_equal(self.gmodel.amplitude.value, [13., 10.])
np.testing.assert_almost_equal(self.gmodel.mean.value, [9., 5.2])
class TestParameterInitialization(object):
"""
This suite of tests checks most if not all cases if instantiating a model
with parameters of different shapes/sizes and with different numbers of
parameter sets.
"""
def test_single_model_scalar_parameters(self):
t = TParModel(10, 1)
assert len(t) == 1
assert t.model_set_axis is False
assert np.all(t.param_sets == [[10], [1]])
assert np.all(t.parameters == [10, 1])
assert t.coeff.shape == ()
assert t.e.shape == ()
def test_single_model_scalar_and_array_parameters(self):
t = TParModel(10, [1, 2])
assert len(t) == 1
assert t.model_set_axis is False
assert np.issubdtype(t.param_sets.dtype, np.object_)
assert len(t.param_sets) == 2
assert np.all(t.param_sets[0] == [10])
assert np.all(t.param_sets[1] == [[1, 2]])
assert np.all(t.parameters == [10, 1, 2])
assert t.coeff.shape == ()
assert t.e.shape == (2,)
def test_single_model_1d_array_parameters(self):
t = TParModel([10, 20], [1, 2])
assert len(t) == 1
assert t.model_set_axis is False
assert np.all(t.param_sets == [[[10, 20]], [[1, 2]]])
assert np.all(t.parameters == [10, 20, 1, 2])
assert t.coeff.shape == (2,)
assert t.e.shape == (2,)
def test_single_model_1d_array_different_length_parameters(self):
with pytest.raises(InputParameterError):
# Not broadcastable
t = TParModel([1, 2], [3, 4, 5])
def test_single_model_2d_array_parameters(self):
t = TParModel([[10, 20], [30, 40]], [[1, 2], [3, 4]])
assert len(t) == 1
assert t.model_set_axis is False
assert np.all(t.param_sets == [[[[10, 20], [30, 40]]],
[[[1, 2], [3, 4]]]])
assert np.all(t.parameters == [10, 20, 30, 40, 1, 2, 3, 4])
assert t.coeff.shape == (2, 2)
assert t.e.shape == (2, 2)
def test_single_model_2d_non_square_parameters(self):
coeff = np.array([[10, 20], [30, 40], [50, 60]])
e = np.array([[1, 2], [3, 4], [5, 6]])
t = TParModel(coeff, e)
assert len(t) == 1
assert t.model_set_axis is False
assert np.all(t.param_sets == [[[[10, 20], [30, 40], [50, 60]]],
[[[1, 2], [3, 4], [5, 6]]]])
assert np.all(t.parameters == [10, 20, 30, 40, 50, 60,
1, 2, 3, 4, 5, 6])
assert t.coeff.shape == (3, 2)
assert t.e.shape == (3, 2)
t2 = TParModel(coeff.T, e.T)
assert len(t2) == 1
assert t2.model_set_axis is False
assert np.all(t2.param_sets == [[[[10, 30, 50], [20, 40, 60]]],
[[[1, 3, 5], [2, 4, 6]]]])
assert np.all(t2.parameters == [10, 30, 50, 20, 40, 60,
1, 3, 5, 2, 4, 6])
assert t2.coeff.shape == (2, 3)
assert t2.e.shape == (2, 3)
# Not broadcastable
with pytest.raises(InputParameterError):
TParModel(coeff, e.T)
with pytest.raises(InputParameterError):
TParModel(coeff.T, e)
def test_single_model_2d_broadcastable_parameters(self):
t = TParModel([[10, 20, 30], [40, 50, 60]], [1, 2, 3])
assert len(t) == 1
assert t.model_set_axis is False
assert len(t.param_sets) == 2
assert np.issubdtype(t.param_sets.dtype, np.object_)
assert np.all(t.param_sets[0] == [[[10, 20, 30], [40, 50, 60]]])
assert np.all(t.param_sets[1] == [[1, 2, 3]])
assert np.all(t.parameters == [10, 20, 30, 40, 50, 60, 1, 2, 3])
@pytest.mark.parametrize(('p1', 'p2'), [
(1, 2), (1, [2, 3]), ([1, 2], 3), ([1, 2, 3], [4, 5]),
([1, 2], [3, 4, 5])])
def test_two_model_incorrect_scalar_parameters(self, p1, p2):
with pytest.raises(InputParameterError):
TParModel(p1, p2, n_models=2)
@pytest.mark.parametrize('kwargs', [
{'n_models': 2}, {'model_set_axis': 0},
{'n_models': 2, 'model_set_axis': 0}])
def test_two_model_scalar_parameters(self, kwargs):
t = TParModel([10, 20], [1, 2], **kwargs)
assert len(t) == 2
assert t.model_set_axis == 0
assert np.all(t.param_sets == [[10, 20], [1, 2]])
assert np.all(t.parameters == [10, 20, 1, 2])
assert t.coeff.shape == ()
assert t.e.shape == ()
@pytest.mark.parametrize('kwargs', [
{'n_models': 2}, {'model_set_axis': 0},
{'n_models': 2, 'model_set_axis': 0}])
def test_two_model_scalar_and_array_parameters(self, kwargs):
t = TParModel([10, 20], [[1, 2], [3, 4]], **kwargs)
assert len(t) == 2
assert t.model_set_axis == 0
assert len(t.param_sets) == 2
assert np.issubdtype(t.param_sets.dtype, np.object_)
assert np.all(t.param_sets[0] == [[10], [20]])
assert np.all(t.param_sets[1] == [[1, 2], [3, 4]])
assert np.all(t.parameters == [10, 20, 1, 2, 3, 4])
assert t.coeff.shape == ()
assert t.e.shape == (2,)
def test_two_model_1d_array_parameters(self):
t = TParModel([[10, 20], [30, 40]], [[1, 2], [3, 4]], n_models=2)
assert len(t) == 2
assert t.model_set_axis == 0
assert np.all(t.param_sets == [[[10, 20], [30, 40]],
[[1, 2], [3, 4]]])
assert | np.all(t.parameters == [10, 20, 30, 40, 1, 2, 3, 4]) | numpy.all |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Module containing useful metric functions for ROI detection.
Created on Mon Nov 12 09:37:00 2018
@author: nicolas
"""
import numpy as np
from skimage import measure
def loss_mae(predictions, targets, masks=None, reduction='mean'):
"""Compute the (Mean) Average Error between predictions and targets."""
if masks is None:
masks = np.ones(targets.shape)
masks = masks.astype(np.bool)
if reduction in ["elementwise_mean", "mean", "ave", "average"]:
return np.abs(targets[masks] - predictions[masks]).mean()
elif reduction in ["sum"]:
return np.abs(targets[masks] - predictions[masks]).sum()
elif reduction in ["array", "no_reduction", "full"]:
return np.abs(targets[masks] - predictions[masks])
else:
raise ValueError("""Unknown reduction method "%s".""" % reduction)
def loss_l2(predictions, targets, masks=None, reduction='mean'):
"""Compute the L2-norm loss between predictions and targets."""
if masks is None:
masks = np.ones(targets.shape)
masks = masks.astype(np.bool)
loss = []
for i in range(len(targets)):
loss.append(np.linalg.norm(targets[i][masks[i]] - predictions[i][masks[i]]))
if reduction in ["elementwise_mean", "mean", "ave", "average"]:
return np.mean(loss)
elif reduction in ["sum"]:
return np.sum(loss)
elif reduction in ["array", "no_reduction", "full"]:
return np.array(loss)
else:
raise ValueError("""Unknown reduction method "%s".""" % reduction)
def dice_coef(predictions, targets, masks=None, reduction='mean'):
"""Compute the Dice coefficient between predictions and targets."""
if masks is None:
masks = np.ones(targets.shape)
masks = masks.astype(np.bool)
dice = []
for i in range(len(targets)):
total_pos = targets[i][masks[i]].sum() + predictions[i][masks[i]].sum()
if total_pos == 0: # No true positive, and no false positive --> correct
dice.append(1.0)
else:
dice.append(2.0 * np.logical_and(targets[i][masks[i]], predictions[i][masks[i]]).sum() / total_pos)
if reduction in ["elementwise_mean", "mean", "ave", "average"]:
return np.mean(dice)
elif reduction in ["sum"]:
return np.sum(dice)
elif reduction in ["array", "no_reduction", "full"]:
return np.array(dice)
else:
raise ValueError("""Unknown reduction method "%s".""" % reduction)
def crop_metric(metric_fn, predictions, targets, masks=None, scale=4.0, reduction='mean'):
"""
Compute the metric around the cropped targets' connected regions.
Size of the cropped region will be bounding_box * scale.
"""
metric = []
n_no_positive = 0 # number of target with no positive pixels (fully background)
for i in range(len(targets)):
labels = measure.label(targets[i])
# If no true positive region, does not consider the image
if labels.max() == 0:
n_no_positive += 1.0
continue
regionprops = measure.regionprops(labels)
local_metric = 0.0
# Loop over targets' connected regions
for region in regionprops:
min_row, min_col, max_row, max_col = region.bbox
height = max_row - min_row
width = max_col - min_col
max_row = int(min(targets[i].shape[0], max_row + height * (scale-1) / 2))
min_row = int(max(0, min_row - height * (scale-1) / 2))
max_col = int(min(targets[i].shape[1], max_col + width * (scale-1) / 2))
min_col = int(max(0, min_col - width * (scale-1) / 2))
if masks is None:
local_mask = None
else:
local_mask = | np.array([masks[i][min_row:max_row, min_col:max_col]], dtype=np.bool) | numpy.array |
import numpy as np
import cv2 , os
import torch
from torch.autograd import Variable
def preprocess_image(cv2im, resize_im=True):
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
if resize_im:
cv2im = cv2.resize(cv2im, (224, 224))
im_as_arr = | np.float32(cv2im) | numpy.float32 |
# Copyright 2018 Waseda University (<NAME>)
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pyimagesource.abscoeff import ISM_RIRpow_approx
import logging # NOQA
import numpy as np
RIRvec = None
TimePoints = None
def ISM_RIR_DecayTime(delta_dB_vec, rt_type, rt_val, aa, room, X_src, X_rcv, Fs, cc=343.0):
"""ISM_RIR_DecayTime RIR decay time using Lehmann & Johansson's EDC approximation method
DT = ISM_RIR_DecayTime(DELTA_dB,RT_TYPE,RT_VAL,ALPHA,ROOM,SOURCE,SENSOR,Fs)
DT = ISM_RIR_DecayTime(DELTA_dB,RT_TYPE,RT_VAL,ALPHA,ROOM,SOURCE,SENSOR,Fs,C)
This function determines the time DT taken by the energy in a RIR to
decay by DELTA_dB when using Lehmann & Johansson's image-source method
implementation (see: "Prediction of energy decay in room impulse
responses simulated with an image-source model", J. Acoust. Soc. Am.,
vol. 124(1), pp. 269-277, July 2008). The parameter DELTA_dB can be
defined as a vector of dB values, in which case this function returns DT
as a vector containing the corresponding decay times. Note that DT does
not necessarily correspond to the usual definition of quantities such as
T20, T30, or T60. The resulting DT values are computed according to
Lehmann and Johannson's EDC (energy decay curve) approximation method
(see above reference) used in conjunction with a RIR reconstruction
method based on diffuse reverberation modeling (see "Diffuse
reverberation model for efficient image-source simulation of room
impulse responses", IEEE Trans. Audio, Speech, Lang. Process., 2010).
The environmental room setting is given via the following parameters:
Fs: scalar, sampling frequency (in Hz). Eg: 8000.
ALPHA: 1-by-6 vector, corresponding to each wall's absorption
coefficient: [x1 x2 y1 y2 z1 z2]. Index 1 indicates wall
closest to the origin. E.g.: [0.5 0.5 0.45 0.87 0.84 0.32].
RT_TYPE: character string, measure of reverberation time used for the
definition of the coefficients in ALPHA. Set to either 'T60' or
'T20'.
RT_VAL: scalar, value of the reverberation time (in seconds) defined by
RT_TYPE. E.g.: 0.25.
SOURCE: 1-by-3 vector, indicating the location of the source in space
(in m): [x y z]. E.g.: [1 1 1.5].
SENSOR: 1-by-3 vector, indicating the location of the microphone in
space (in m): [x y z]. E.g.: [2 2 1.5].
ROOM: 1-by-3 vector, indicating the rectangular room dimensions
(in m): [x_length y_length z_length]. E.g.: [4 4 3].
C: (optional) scalar (in m/s), propagation speed of sound waves.
If omitted, C will default to 343m/s.
"""
if isinstance(delta_dB_vec, float):
delta_dB_vec = np.asarray([delta_dB_vec])
delta_dB_vec = np.abs(delta_dB_vec)
# -=:=- Check user input:
if np.any(aa > 1) or np.any(aa < 0):
raise ValueError('Parameter ''ALPHA'' must be in range (0...1].')
elif np.any(delta_dB_vec == 0):
raise ValueError('Parameter ''DELTA_dB'' must contain non-zero scalar values.')
elif len(delta_dB_vec.shape) > 1:
raise ValueError('Parameter ''DELTA_dB'' must be a 1-D vector (float).')
if np.all(aa == 1) or rt_val == 0:
raise ValueError('ISM_RIR_DecayTime cannot be used for anechoic environments.')
if rt_type == 60:
t60_appval = rt_val
elif rt_type == 20:
t60_appval = rt_val * 3 # coarse t60 estimate to determnine end time in EDCapprox computations
else:
raise ValueError('Unknown ''RT_TYPE'' argument.')
# -=:=- Pre-processing -=:=-
dp_del = np.linalg.norm(X_src - X_rcv) / cc # direct path
delta_dB_max = np.max(delta_dB_vec)
n_ddbv = 1 if len(delta_dB_vec.shape) < 1 else len(delta_dB_vec.shape)
starttime = np.amax([1.4 * np.mean(room) / cc, dp_del]) # start time t0, ensure >= dp_delay
starttime_sind = np.floor(starttime * Fs) # sample index
RIR_start_DTime = 2 * starttime
# -=:=- select window size -=:=-
n_win_meas = 6 # approximate nr of (useful) measurements
TT = (RIR_start_DTime - starttime) / n_win_meas
w_len = np.floor(TT * Fs) # current window length (samples)
w_len = w_len + (w_len % 2) - 1 # make w_len odd
w_len_half = int(np.floor(w_len / 2))
# -=:=- pre-compute start of RIR for lambda correction -=:=-
RIR = ISM_RoomResp(Fs, np.sqrt(1 - aa), rt_type, rt_val, X_src, X_rcv, room, MaxDelay=RIR_start_DTime, c=cc)
RIRlen = len(RIR)
# -=:=- Measure average energy -=:=-
fit_time_perc = 0.35
we_sind_vec = np.arange(starttime_sind + w_len_half, RIRlen, w_len).astype(np.int) # window end indices
wc_sind_vec = we_sind_vec - w_len_half # window centre indices
wb_sind_vec = wc_sind_vec - w_len_half - 1 # window beginning indices
if wb_sind_vec[0] <= 0:
wb_sind_vec[0] = 1 # case where t0 is less than a half window
n_win_meas = len(wc_sind_vec)
en_vec_meas = np.zeros((n_win_meas,))
for ww in range(n_win_meas):
en_vec_meas[ww] = np.mean(RIR[wb_sind_vec[ww]:we_sind_vec[ww]] ** 2)
t_vec_meas = wc_sind_vec / Fs
fit_starttime = RIRlen * fit_time_perc / Fs
fit_start_wind = np.where(t_vec_meas >= fit_starttime)[0][0] # window index of start of fit
# -=:=- Decay time estimate -=:=-
DTime_vec = np.nan * np.ones(delta_dB_vec.shape)
stind = 3
while stind > 0:
# compute + lambda-adjust EDC approximation
# IMapprox computed up to several times what linear decay predicts
stoptime = stind * delta_dB_max / 60 * t60_appval
timepts = np.arange(starttime_sind, stoptime * Fs, w_len) / Fs
stoptime = timepts[-1]
# compute EDC approximation
amppts1, timepts, okflag = ISM_RIRpow_approx(aa, room, cc, timepts, rt_type, rt_val)
foo = en_vec_meas[fit_start_wind:] / amppts1[fit_start_wind:n_win_meas] # offset compensation (lambda)
amppts1 = amppts1 * np.mean(foo)
# reconstruct approx. full RIR for proper EDC estimation (logistic noise approx.)
amppts1_rec = np.interp(np.arange(RIRlen + 1, stoptime * Fs) / Fs, timepts, amppts1)
RIR_rec = np.concatenate([RIR.T, np.sqrt(amppts1_rec)])
RIR_rec_len = len(RIR_rec)
# approx. full RIR EDC
edc_rec = np.zeros((RIR_rec_len,))
for nn in range(RIR_rec_len):
edc_rec[nn] = np.sum(RIR_rec[nn:] ** 2) # Energy decay using Schroeder's integration method
edc_rec = 10 * np.log10(edc_rec / edc_rec[0]) # Decay curve in dB.
tvec_rec = np.arange(RIR_rec_len) / Fs
# Determine time of EDC reaching delta_dB decay:
if edc_rec[-1] > -delta_dB_max:
stind += 1
if okflag == 0:
raise ValueError('Problem computing decay time (parameter ''DELTA_dB'' may be too large)')
if stind >= 25:
raise ValueError('Problem computing decay time (parameter ''DELTA_dB'' may be too large)')
continue
for nn in range(n_ddbv):
foo = np.where(edc_rec <= -delta_dB_vec[nn])[0][0]
DTime_vec[nn] = 1.15 * tvec_rec[foo] # statistical offset correction...
# make sure IM approx was computed for more than 3/2 the resulting decay time
if np.max(DTime_vec) > stoptime * 2 / 3:
stind += 1 # increase time if necessary
if okflag == 0:
raise ValueError('Problem computing decay time (parameter ''DELTA_dB'' may be too large)')
if stind >= 25:
raise ValueError('Problem computing decay time (parameter ''DELTA_dB'' may be too large)')
continue
else:
stind = 0 # stop the computations
return DTime_vec
def Check_nDim(a, b, d, l, m, X_rcv, X_src, Rr, c, MaxDelay, beta, Fs):
global RIRvec
global TimePoints
FoundNValBelowLim = 0
n = 1 # Check delay values for n=1 and above
dist = np.linalg.norm([2 * a - 1, 2 * b - 1, 2 * d - 1] * X_src + X_rcv - Rr * [n, l, m])
foo_time = dist / c
while foo_time <= MaxDelay: # if delay is below TF length limit for n=1, check n=2,3,4...
foo_amplitude = np.prod(beta ** np.abs([n - a, n, l - b, l, m - d, m])) / (4 * np.pi * dist)
RIRvec = RIRvec + foo_amplitude * | np.sinc((TimePoints - foo_time) * Fs) | numpy.sinc |
"""
Bayesian Degree Corrected Stochastic Block Model
roughly based on Infinite-degree-corrected stochastic block model by Herlau et. al.,
but with a fixed number of cluster sizes and a different update equation for the collapsed Gibbs sampler;
see accompanying documentation
"""
import numpy as np
import sys
sys.path.append("/home/victor/Documents/community_detection/MCMC")
from cgs_llhds import diri_multi_llhd
from multi_sbm_helpers import comp_edge_cts, softmax
from dcsbm_helpers import GD, BD, samp_shape_post_step, samp_rate_post_step, samp_gam_post_step
class gen_data:
def __init__(self, n, phis, eta):
"""
:param n: number of vertices in each community
:param phis: list of probability distributions, phis[l] should be length n[l] and sum to 1
:param eta: symmetric matrix, eta[k,l] is expected number of edges between vertex in k and vertex in l
"""
self.n = n
self.n_vert = sum(n)
self.n_comm = len(n)
self.phis = phis
self.eta = eta
z = np.repeat(0, self.n_vert)
acc = 0
for l in range(self.n_comm - 1):
acc += self.n[l]
z[acc: acc + self.n[l + 1]] = l + 1
self.z = z
phi = np.repeat(0., self.n_vert)
phi[0:self.n[0]] = phis[0]
acc = 0
for l in range(self.n_comm - 1):
acc += self.n[l]
phi[acc: acc + self.n[l + 1]] = phis[l + 1]
self.phi = phi
self.A = self.sampleA()
def sampleA(self):
"""
Sample an adjacency matrix conditional on all other parameters
:return ndarray, float. Sampled adjacency matrix
"""
A = np.zeros([self.n_vert, self.n_vert])
for i in range(self.n_vert):
for j in range(i + 1, self.n_vert):
thetai = self.n[self.z[i]] * self.phi[i]
thetaj = self.n[self.z[j]] * self.phi[j]
A[i, j] = np.random.poisson(thetai * thetaj * self.eta[self.z[i], self.z[j]])
A[j, i] = A[i, j]
return A
class gen_data_hypers(gen_data):
"Sample a graph from the Bayesian DCSBM"
def __init__(self, n_vert, n_comm, alpha, kap, lam, gam):
"""
:param n_vert: number of vertices in the graph
:param n_comm: number of communities
:param alpha: dirichlet prior parameter for community memberships
:param kap: scalar, gamma dist param
:param lam: scalar, gamma dist param
:param gam: scalar, param for deg correction dirichlet dist. Basic block model recovered in gamma->inf limit
"""
self.n_vert = n_vert
self.n_comm = n_comm
self.alpha = alpha
self.kap = kap
self.lam = lam
self.gam = gam
self.n = np.random.multinomial(n_vert, np.random.dirichlet(np.repeat(alpha, n_comm)))
z = np.repeat(0,n_vert)
acc = 0
for l in range(n_comm-1):
acc += self.n[l]
z[acc : acc + self.n[l + 1]] = l+1
self.z=z
phi_ls = [np.random.dirichlet(np.repeat(gam, nl)) for nl in self.n]
phi = np.repeat(0.,self.n_vert)
phi[0:self.n[0]] = phi_ls[0]
acc = 0
for l in range(n_comm-1):
acc += self.n[l]
phi[acc : acc + self.n[l + 1]] = phi_ls[l+1]
self.phis = phi_ls
self.phi = phi
eta = | np.random.gamma(kap,1./lam,[n_comm,n_comm]) | numpy.random.gamma |
import numpy as np
import pytest
from scipy.stats import (bootstrap, BootstrapDegenerateDistributionWarning,
monte_carlo_test, permutation_test)
from numpy.testing import assert_allclose, assert_equal, suppress_warnings
from scipy import stats
from scipy import special
from .. import _resampling as _resampling
from scipy._lib._util import rng_integers
from scipy.optimize import root
def test_bootstrap_iv():
message = "`data` must be a sequence of samples."
with pytest.raises(ValueError, match=message):
bootstrap(1, np.mean)
message = "`data` must contain at least one sample."
with pytest.raises(ValueError, match=message):
bootstrap(tuple(), np.mean)
message = "each sample in `data` must contain two or more observations..."
with pytest.raises(ValueError, match=message):
bootstrap(([1, 2, 3], [1]), np.mean)
message = ("When `paired is True`, all samples must have the same length ")
with pytest.raises(ValueError, match=message):
bootstrap(([1, 2, 3], [1, 2, 3, 4]), np.mean, paired=True)
message = "`vectorized` must be `True` or `False`."
with pytest.raises(ValueError, match=message):
bootstrap(1, np.mean, vectorized='ekki')
message = "`axis` must be an integer."
with pytest.raises(ValueError, match=message):
bootstrap(([1, 2, 3],), np.mean, axis=1.5)
message = "could not convert string to float"
with pytest.raises(ValueError, match=message):
bootstrap(([1, 2, 3],), np.mean, confidence_level='ni')
message = "`n_resamples` must be a positive integer."
with pytest.raises(ValueError, match=message):
bootstrap(([1, 2, 3],), np.mean, n_resamples=-1000)
message = "`n_resamples` must be a positive integer."
with pytest.raises(ValueError, match=message):
bootstrap(([1, 2, 3],), np.mean, n_resamples=1000.5)
message = "`batch` must be a positive integer or None."
with pytest.raises(ValueError, match=message):
bootstrap(([1, 2, 3],), np.mean, batch=-1000)
message = "`batch` must be a positive integer or None."
with pytest.raises(ValueError, match=message):
bootstrap(([1, 2, 3],), np.mean, batch=1000.5)
message = "`method` must be in"
with pytest.raises(ValueError, match=message):
bootstrap(([1, 2, 3],), np.mean, method='ekki')
message = "`method = 'BCa' is only available for one-sample statistics"
def statistic(x, y, axis):
mean1 = np.mean(x, axis)
mean2 = np.mean(y, axis)
return mean1 - mean2
with pytest.raises(ValueError, match=message):
bootstrap(([.1, .2, .3], [.1, .2, .3]), statistic, method='BCa')
message = "'herring' cannot be used to seed a"
with pytest.raises(ValueError, match=message):
bootstrap(([1, 2, 3],), np.mean, random_state='herring')
@pytest.mark.parametrize("method", ['basic', 'percentile', 'BCa'])
@pytest.mark.parametrize("axis", [0, 1, 2])
def test_bootstrap_batch(method, axis):
# for one-sample statistics, batch size shouldn't affect the result
np.random.seed(0)
x = np.random.rand(10, 11, 12)
res1 = bootstrap((x,), np.mean, batch=None, method=method,
random_state=0, axis=axis, n_resamples=100)
res2 = bootstrap((x,), np.mean, batch=10, method=method,
random_state=0, axis=axis, n_resamples=100)
assert_equal(res2.confidence_interval.low, res1.confidence_interval.low)
assert_equal(res2.confidence_interval.high, res1.confidence_interval.high)
assert_equal(res2.standard_error, res1.standard_error)
@pytest.mark.parametrize("method", ['basic', 'percentile', 'BCa'])
def test_bootstrap_paired(method):
# test that `paired` works as expected
np.random.seed(0)
n = 100
x = np.random.rand(n)
y = np.random.rand(n)
def my_statistic(x, y, axis=-1):
return ((x-y)**2).mean(axis=axis)
def my_paired_statistic(i, axis=-1):
a = x[i]
b = y[i]
res = my_statistic(a, b)
return res
i = np.arange(len(x))
res1 = bootstrap((i,), my_paired_statistic, random_state=0)
res2 = bootstrap((x, y), my_statistic, paired=True, random_state=0)
assert_allclose(res1.confidence_interval, res2.confidence_interval)
assert_allclose(res1.standard_error, res2.standard_error)
@pytest.mark.parametrize("method", ['basic', 'percentile', 'BCa'])
@pytest.mark.parametrize("axis", [0, 1, 2])
@pytest.mark.parametrize("paired", [True, False])
def test_bootstrap_vectorized(method, axis, paired):
# test that paired is vectorized as expected: when samples are tiled,
# CI and standard_error of each axis-slice is the same as those of the
# original 1d sample
if not paired and method == 'BCa':
# should re-assess when BCa is extended
pytest.xfail(reason="BCa currently for 1-sample statistics only")
np.random.seed(0)
def my_statistic(x, y, z, axis=-1):
return x.mean(axis=axis) + y.mean(axis=axis) + z.mean(axis=axis)
shape = 10, 11, 12
n_samples = shape[axis]
x = np.random.rand(n_samples)
y = np.random.rand(n_samples)
z = np.random.rand(n_samples)
res1 = bootstrap((x, y, z), my_statistic, paired=paired, method=method,
random_state=0, axis=0, n_resamples=100)
reshape = [1, 1, 1]
reshape[axis] = n_samples
x = np.broadcast_to(x.reshape(reshape), shape)
y = np.broadcast_to(y.reshape(reshape), shape)
z = np.broadcast_to(z.reshape(reshape), shape)
res2 = bootstrap((x, y, z), my_statistic, paired=paired, method=method,
random_state=0, axis=axis, n_resamples=100)
assert_allclose(res2.confidence_interval.low,
res1.confidence_interval.low)
assert_allclose(res2.confidence_interval.high,
res1.confidence_interval.high)
assert_allclose(res2.standard_error, res1.standard_error)
result_shape = list(shape)
result_shape.pop(axis)
assert_equal(res2.confidence_interval.low.shape, result_shape)
assert_equal(res2.confidence_interval.high.shape, result_shape)
assert_equal(res2.standard_error.shape, result_shape)
@pytest.mark.parametrize("method", ['basic', 'percentile', 'BCa'])
def test_bootstrap_against_theory(method):
# based on https://www.statology.org/confidence-intervals-python/
data = stats.norm.rvs(loc=5, scale=2, size=5000, random_state=0)
alpha = 0.95
dist = stats.t(df=len(data)-1, loc=np.mean(data), scale=stats.sem(data))
expected_interval = dist.interval(confidence=alpha)
expected_se = dist.std()
res = bootstrap((data,), np.mean, n_resamples=5000,
confidence_level=alpha, method=method,
random_state=0)
assert_allclose(res.confidence_interval, expected_interval, rtol=5e-4)
assert_allclose(res.standard_error, expected_se, atol=3e-4)
tests_R = {"basic": (23.77, 79.12),
"percentile": (28.86, 84.21),
"BCa": (32.31, 91.43)}
@pytest.mark.parametrize("method, expected", tests_R.items())
def test_bootstrap_against_R(method, expected):
# Compare against R's "boot" library
# library(boot)
# stat <- function (x, a) {
# mean(x[a])
# }
# x <- c(10, 12, 12.5, 12.5, 13.9, 15, 21, 22,
# 23, 34, 50, 81, 89, 121, 134, 213)
# # Use a large value so we get a few significant digits for the CI.
# n = 1000000
# bootresult = boot(x, stat, n)
# result <- boot.ci(bootresult)
# print(result)
x = np.array([10, 12, 12.5, 12.5, 13.9, 15, 21, 22,
23, 34, 50, 81, 89, 121, 134, 213])
res = bootstrap((x,), np.mean, n_resamples=1000000, method=method,
random_state=0)
assert_allclose(res.confidence_interval, expected, rtol=0.005)
tests_against_itself_1samp = {"basic": 1780,
"percentile": 1784,
"BCa": 1784}
@pytest.mark.parametrize("method, expected",
tests_against_itself_1samp.items())
def test_bootstrap_against_itself_1samp(method, expected):
# The expected values in this test were generated using bootstrap
# to check for unintended changes in behavior. The test also makes sure
# that bootstrap works with multi-sample statistics and that the
# `axis` argument works as expected / function is vectorized.
np.random.seed(0)
n = 100 # size of sample
n_resamples = 999 # number of bootstrap resamples used to form each CI
confidence_level = 0.9
# The true mean is 5
dist = stats.norm(loc=5, scale=1)
stat_true = dist.mean()
# Do the same thing 2000 times. (The code is fully vectorized.)
n_replications = 2000
data = dist.rvs(size=(n_replications, n))
res = bootstrap((data,),
statistic=np.mean,
confidence_level=confidence_level,
n_resamples=n_resamples,
batch=50,
method=method,
axis=-1)
ci = res.confidence_interval
# ci contains vectors of lower and upper confidence interval bounds
ci_contains_true = np.sum((ci[0] < stat_true) & (stat_true < ci[1]))
assert ci_contains_true == expected
# ci_contains_true is not inconsistent with confidence_level
pvalue = stats.binomtest(ci_contains_true, n_replications,
confidence_level).pvalue
assert pvalue > 0.1
tests_against_itself_2samp = {"basic": 892,
"percentile": 890}
@pytest.mark.parametrize("method, expected",
tests_against_itself_2samp.items())
def test_bootstrap_against_itself_2samp(method, expected):
# The expected values in this test were generated using bootstrap
# to check for unintended changes in behavior. The test also makes sure
# that bootstrap works with multi-sample statistics and that the
# `axis` argument works as expected / function is vectorized.
np.random.seed(0)
n1 = 100 # size of sample 1
n2 = 120 # size of sample 2
n_resamples = 999 # number of bootstrap resamples used to form each CI
confidence_level = 0.9
# The statistic we're interested in is the difference in means
def my_stat(data1, data2, axis=-1):
mean1 = np.mean(data1, axis=axis)
mean2 = np.mean(data2, axis=axis)
return mean1 - mean2
# The true difference in the means is -0.1
dist1 = stats.norm(loc=0, scale=1)
dist2 = stats.norm(loc=0.1, scale=1)
stat_true = dist1.mean() - dist2.mean()
# Do the same thing 1000 times. (The code is fully vectorized.)
n_replications = 1000
data1 = dist1.rvs(size=(n_replications, n1))
data2 = dist2.rvs(size=(n_replications, n2))
res = bootstrap((data1, data2),
statistic=my_stat,
confidence_level=confidence_level,
n_resamples=n_resamples,
batch=50,
method=method,
axis=-1)
ci = res.confidence_interval
# ci contains vectors of lower and upper confidence interval bounds
ci_contains_true = np.sum((ci[0] < stat_true) & (stat_true < ci[1]))
assert ci_contains_true == expected
# ci_contains_true is not inconsistent with confidence_level
pvalue = stats.binomtest(ci_contains_true, n_replications,
confidence_level).pvalue
assert pvalue > 0.1
@pytest.mark.parametrize("method", ["basic", "percentile"])
@pytest.mark.parametrize("axis", [0, 1])
def test_bootstrap_vectorized_3samp(method, axis):
def statistic(*data, axis=0):
# an arbitrary, vectorized statistic
return sum((sample.mean(axis) for sample in data))
def statistic_1d(*data):
# the same statistic, not vectorized
for sample in data:
assert sample.ndim == 1
return statistic(*data, axis=0)
np.random.seed(0)
x = np.random.rand(4, 5)
y = np.random.rand(4, 5)
z = np.random.rand(4, 5)
res1 = bootstrap((x, y, z), statistic, vectorized=True,
axis=axis, n_resamples=100, method=method, random_state=0)
res2 = bootstrap((x, y, z), statistic_1d, vectorized=False,
axis=axis, n_resamples=100, method=method, random_state=0)
assert_allclose(res1.confidence_interval, res2.confidence_interval)
assert_allclose(res1.standard_error, res2.standard_error)
@pytest.mark.xfail_on_32bit("Failure is not concerning; see gh-14107")
@pytest.mark.parametrize("method", ["basic", "percentile", "BCa"])
@pytest.mark.parametrize("axis", [0, 1])
def test_bootstrap_vectorized_1samp(method, axis):
def statistic(x, axis=0):
# an arbitrary, vectorized statistic
return x.mean(axis=axis)
def statistic_1d(x):
# the same statistic, not vectorized
assert x.ndim == 1
return statistic(x, axis=0)
np.random.seed(0)
x = np.random.rand(4, 5)
res1 = bootstrap((x,), statistic, vectorized=True, axis=axis,
n_resamples=100, batch=None, method=method,
random_state=0)
res2 = bootstrap((x,), statistic_1d, vectorized=False, axis=axis,
n_resamples=100, batch=10, method=method,
random_state=0)
assert_allclose(res1.confidence_interval, res2.confidence_interval)
assert_allclose(res1.standard_error, res2.standard_error)
@pytest.mark.parametrize("method", ["basic", "percentile", "BCa"])
def test_bootstrap_degenerate(method):
data = 35 * [10000.]
if method == "BCa":
with np.errstate(invalid='ignore'):
with pytest.warns(BootstrapDegenerateDistributionWarning):
res = bootstrap([data, ], np.mean, method=method)
assert_equal(res.confidence_interval, (np.nan, np.nan))
else:
res = bootstrap([data, ], np.mean, method=method)
assert_equal(res.confidence_interval, (10000., 10000.))
assert_equal(res.standard_error, 0)
@pytest.mark.parametrize("method", ["basic", "percentile", "BCa"])
def test_bootstrap_gh15678(method):
# Check that gh-15678 is fixed: when statistic function returned a Python
# float, method="BCa" failed when trying to add a dimension to the float
rng = np.random.default_rng(354645618886684)
dist = stats.norm(loc=2, scale=4)
data = dist.rvs(size=100, random_state=rng)
data = (data,)
res = bootstrap(data, stats.skew, method=method, n_resamples=100,
random_state=np.random.default_rng(9563))
# this always worked because np.apply_along_axis returns NumPy data type
ref = bootstrap(data, stats.skew, method=method, n_resamples=100,
random_state=np.random.default_rng(9563), vectorized=False)
assert_allclose(res.confidence_interval, ref.confidence_interval)
assert_allclose(res.standard_error, ref.standard_error)
assert isinstance(res.standard_error, np.float64)
def test_jackknife_resample():
shape = 3, 4, 5, 6
np.random.seed(0)
x = np.random.rand(*shape)
y = next(_resampling._jackknife_resample(x))
for i in range(shape[-1]):
# each resample is indexed along second to last axis
# (last axis is the one the statistic will be taken over / consumed)
slc = y[..., i, :]
expected = np.delete(x, i, axis=-1)
assert np.array_equal(slc, expected)
y2 = np.concatenate(list(_resampling._jackknife_resample(x, batch=2)),
axis=-2)
assert np.array_equal(y2, y)
@pytest.mark.parametrize("rng_name", ["RandomState", "default_rng"])
def test_bootstrap_resample(rng_name):
rng = getattr(np.random, rng_name, None)
if rng is None:
pytest.skip(f"{rng_name} not available.")
rng1 = rng(0)
rng2 = rng(0)
n_resamples = 10
shape = 3, 4, 5, 6
np.random.seed(0)
x = np.random.rand(*shape)
y = _resampling._bootstrap_resample(x, n_resamples, random_state=rng1)
for i in range(n_resamples):
# each resample is indexed along second to last axis
# (last axis is the one the statistic will be taken over / consumed)
slc = y[..., i, :]
js = rng_integers(rng2, 0, shape[-1], shape[-1])
expected = x[..., js]
assert np.array_equal(slc, expected)
@pytest.mark.parametrize("score", [0, 0.5, 1])
@pytest.mark.parametrize("axis", [0, 1, 2])
def test_percentile_of_score(score, axis):
shape = 10, 20, 30
np.random.seed(0)
x = np.random.rand(*shape)
p = _resampling._percentile_of_score(x, score, axis=-1)
def vectorized_pos(a, score, axis):
return np.apply_along_axis(stats.percentileofscore, axis, a, score)
p2 = vectorized_pos(x, score, axis=-1)/100
assert_allclose(p, p2, 1e-15)
def test_percentile_along_axis():
# the difference between _percentile_along_axis and np.percentile is that
# np.percentile gets _all_ the qs for each axis slice, whereas
# _percentile_along_axis gets the q corresponding with each axis slice
shape = 10, 20
np.random.seed(0)
x = np.random.rand(*shape)
q = np.random.rand(*shape[:-1]) * 100
y = _resampling._percentile_along_axis(x, q)
for i in range(shape[0]):
res = y[i]
expected = np.percentile(x[i], q[i], axis=-1)
assert_allclose(res, expected, 1e-15)
@pytest.mark.parametrize("axis", [0, 1, 2])
def test_vectorize_statistic(axis):
# test that _vectorize_statistic vectorizes a statistic along `axis`
def statistic(*data, axis):
# an arbitrary, vectorized statistic
return sum((sample.mean(axis) for sample in data))
def statistic_1d(*data):
# the same statistic, not vectorized
for sample in data:
assert sample.ndim == 1
return statistic(*data, axis=0)
# vectorize the non-vectorized statistic
statistic2 = _resampling._vectorize_statistic(statistic_1d)
np.random.seed(0)
x = np.random.rand(4, 5, 6)
y = np.random.rand(4, 1, 6)
z = np.random.rand(1, 5, 6)
res1 = statistic(x, y, z, axis=axis)
res2 = statistic2(x, y, z, axis=axis)
assert_allclose(res1, res2)
@pytest.mark.xslow()
@pytest.mark.parametrize("method", ["basic", "percentile", "BCa"])
def test_vector_valued_statistic(method):
# Generate 95% confidence interval around MLE of normal distribution
# parameters. Repeat 100 times, each time on sample of size 100.
# Check that confidence interval contains true parameters ~95 times.
# Confidence intervals are estimated and stochastic; a test failure
# does not necessarily indicate that something is wrong. More important
# than values of `counts` below is that the shapes of the outputs are
# correct.
rng = np.random.default_rng(2196847219)
params = 1, 0.5
sample = stats.norm.rvs(*params, size=(100, 100), random_state=rng)
def statistic(data):
return stats.norm.fit(data)
res = bootstrap((sample,), statistic, method=method, axis=-1,
vectorized=False)
counts = np.sum((res.confidence_interval.low.T < params)
& (res.confidence_interval.high.T > params),
axis=0)
assert np.all(counts >= 90)
assert np.all(counts <= 100)
assert res.confidence_interval.low.shape == (2, 100)
assert res.confidence_interval.high.shape == (2, 100)
assert res.standard_error.shape == (2, 100)
# --- Test Monte Carlo Hypothesis Test --- #
class TestMonteCarloHypothesisTest:
atol = 2.5e-2 # for comparing p-value
def rvs(self, rvs_in, rs):
return lambda *args, **kwds: rvs_in(*args, random_state=rs, **kwds)
def test_input_validation(self):
# test that the appropriate error messages are raised for invalid input
def stat(x):
return stats.skewnorm(x).statistic
message = "`axis` must be an integer."
with pytest.raises(ValueError, match=message):
monte_carlo_test([1, 2, 3], stats.norm.rvs, stat, axis=1.5)
message = "`vectorized` must be `True` or `False`."
with pytest.raises(ValueError, match=message):
monte_carlo_test([1, 2, 3], stats.norm.rvs, stat, vectorized=1.5)
message = "`rvs` must be callable."
with pytest.raises(TypeError, match=message):
monte_carlo_test([1, 2, 3], None, stat)
message = "`statistic` must be callable."
with pytest.raises(TypeError, match=message):
monte_carlo_test([1, 2, 3], stats.norm.rvs, None)
message = "`n_resamples` must be a positive integer."
with pytest.raises(ValueError, match=message):
monte_carlo_test([1, 2, 3], stats.norm.rvs, stat,
n_resamples=-1000)
message = "`n_resamples` must be a positive integer."
with pytest.raises(ValueError, match=message):
monte_carlo_test([1, 2, 3], stats.norm.rvs, stat,
n_resamples=1000.5)
message = "`batch` must be a positive integer or None."
with pytest.raises(ValueError, match=message):
monte_carlo_test([1, 2, 3], stats.norm.rvs, stat, batch=-1000)
message = "`batch` must be a positive integer or None."
with pytest.raises(ValueError, match=message):
monte_carlo_test([1, 2, 3], stats.norm.rvs, stat, batch=1000.5)
message = "`alternative` must be in..."
with pytest.raises(ValueError, match=message):
monte_carlo_test([1, 2, 3], stats.norm.rvs, stat,
alternative='ekki')
def test_batch(self):
# make sure that the `batch` parameter is respected by checking the
# maximum batch size provided in calls to `statistic`
rng = np.random.default_rng(23492340193)
x = rng.random(10)
def statistic(x, axis):
batch_size = 1 if x.ndim == 1 else len(x)
statistic.batch_size = max(batch_size, statistic.batch_size)
statistic.counter += 1
return stats.skewtest(x, axis=axis).statistic
statistic.counter = 0
statistic.batch_size = 0
kwds = {'sample': x, 'statistic': statistic,
'n_resamples': 1000, 'vectorized': True}
kwds['rvs'] = self.rvs(stats.norm.rvs, np.random.default_rng(32842398))
res1 = monte_carlo_test(batch=1, **kwds)
assert_equal(statistic.counter, 1001)
assert_equal(statistic.batch_size, 1)
kwds['rvs'] = self.rvs(stats.norm.rvs, np.random.default_rng(32842398))
statistic.counter = 0
res2 = monte_carlo_test(batch=50, **kwds)
assert_equal(statistic.counter, 21)
assert_equal(statistic.batch_size, 50)
kwds['rvs'] = self.rvs(stats.norm.rvs, np.random.default_rng(32842398))
statistic.counter = 0
res3 = monte_carlo_test(**kwds)
assert_equal(statistic.counter, 2)
assert_equal(statistic.batch_size, 1000)
assert_equal(res1.pvalue, res3.pvalue)
assert_equal(res2.pvalue, res3.pvalue)
@pytest.mark.parametrize('axis', range(-3, 3))
def test_axis(self, axis):
# test that Nd-array samples are handled correctly for valid values
# of the `axis` parameter
rng = np.random.default_rng(2389234)
norm_rvs = self.rvs(stats.norm.rvs, rng)
size = [2, 3, 4]
size[axis] = 100
x = norm_rvs(size=size)
expected = stats.skewtest(x, axis=axis)
def statistic(x, axis):
return stats.skewtest(x, axis=axis).statistic
res = monte_carlo_test(x, norm_rvs, statistic, vectorized=True,
n_resamples=20000, axis=axis)
assert_allclose(res.statistic, expected.statistic)
assert_allclose(res.pvalue, expected.pvalue, atol=self.atol)
@pytest.mark.parametrize('alternative', ("less", "greater"))
@pytest.mark.parametrize('a', np.linspace(-0.5, 0.5, 5)) # skewness
def test_against_ks_1samp(self, alternative, a):
# test that monte_carlo_test can reproduce pvalue of ks_1samp
rng = np.random.default_rng(65723433)
x = stats.skewnorm.rvs(a=a, size=30, random_state=rng)
expected = stats.ks_1samp(x, stats.norm.cdf, alternative=alternative)
def statistic1d(x):
return stats.ks_1samp(x, stats.norm.cdf, mode='asymp',
alternative=alternative).statistic
norm_rvs = self.rvs(stats.norm.rvs, rng)
res = monte_carlo_test(x, norm_rvs, statistic1d,
n_resamples=1000, vectorized=False,
alternative=alternative)
assert_allclose(res.statistic, expected.statistic)
if alternative == 'greater':
assert_allclose(res.pvalue, expected.pvalue, atol=self.atol)
elif alternative == 'less':
assert_allclose(1-res.pvalue, expected.pvalue, atol=self.atol)
@pytest.mark.parametrize('hypotest', (stats.skewtest, stats.kurtosistest))
@pytest.mark.parametrize('alternative', ("less", "greater", "two-sided"))
@pytest.mark.parametrize('a', np.linspace(-2, 2, 5)) # skewness
def test_against_normality_tests(self, hypotest, alternative, a):
# test that monte_carlo_test can reproduce pvalue of normality tests
rng = np.random.default_rng(85723405)
x = stats.skewnorm.rvs(a=a, size=150, random_state=rng)
expected = hypotest(x, alternative=alternative)
def statistic(x, axis):
return hypotest(x, axis=axis).statistic
norm_rvs = self.rvs(stats.norm.rvs, rng)
res = monte_carlo_test(x, norm_rvs, statistic, vectorized=True,
alternative=alternative)
assert_allclose(res.statistic, expected.statistic)
assert_allclose(res.pvalue, expected.pvalue, atol=self.atol)
@pytest.mark.parametrize('a', np.arange(-2, 3)) # skewness parameter
def test_against_normaltest(self, a):
# test that monte_carlo_test can reproduce pvalue of normaltest
rng = np.random.default_rng(12340513)
x = stats.skewnorm.rvs(a=a, size=150, random_state=rng)
expected = stats.normaltest(x)
def statistic(x, axis):
return stats.normaltest(x, axis=axis).statistic
norm_rvs = self.rvs(stats.norm.rvs, rng)
res = monte_carlo_test(x, norm_rvs, statistic, vectorized=True,
alternative='greater')
assert_allclose(res.statistic, expected.statistic)
assert_allclose(res.pvalue, expected.pvalue, atol=self.atol)
@pytest.mark.parametrize('a', np.linspace(-0.5, 0.5, 5)) # skewness
def test_against_cramervonmises(self, a):
# test that monte_carlo_test can reproduce pvalue of cramervonmises
rng = np.random.default_rng(234874135)
x = stats.skewnorm.rvs(a=a, size=30, random_state=rng)
expected = stats.cramervonmises(x, stats.norm.cdf)
def statistic1d(x):
return stats.cramervonmises(x, stats.norm.cdf).statistic
norm_rvs = self.rvs(stats.norm.rvs, rng)
res = monte_carlo_test(x, norm_rvs, statistic1d,
n_resamples=1000, vectorized=False,
alternative='greater')
assert_allclose(res.statistic, expected.statistic)
assert_allclose(res.pvalue, expected.pvalue, atol=self.atol)
@pytest.mark.parametrize('dist_name', ('norm', 'logistic'))
@pytest.mark.parametrize('i', range(5))
def test_against_anderson(self, dist_name, i):
# test that monte_carlo_test can reproduce results of `anderson`. Note:
# `anderson` does not provide a p-value; it provides a list of
# significance levels and the associated critical value of the test
# statistic. `i` used to index this list.
# find the skewness for which the sample statistic matches one of the
# critical values provided by `stats.anderson`
def fun(a):
rng = np.random.default_rng(394295467)
x = stats.tukeylambda.rvs(a, size=100, random_state=rng)
expected = stats.anderson(x, dist_name)
return expected.statistic - expected.critical_values[i]
with suppress_warnings() as sup:
sup.filter(RuntimeWarning)
sol = root(fun, x0=0)
assert(sol.success)
# get the significance level (p-value) associated with that critical
# value
a = sol.x[0]
rng = np.random.default_rng(394295467)
x = stats.tukeylambda.rvs(a, size=100, random_state=rng)
expected = stats.anderson(x, dist_name)
expected_stat = expected.statistic
expected_p = expected.significance_level[i]/100
# perform equivalent Monte Carlo test and compare results
def statistic1d(x):
return stats.anderson(x, dist_name).statistic
dist_rvs = self.rvs(getattr(stats, dist_name).rvs, rng)
with suppress_warnings() as sup:
sup.filter(RuntimeWarning)
res = monte_carlo_test(x, dist_rvs,
statistic1d, n_resamples=1000,
vectorized=False, alternative='greater')
assert_allclose(res.statistic, expected_stat)
assert_allclose(res.pvalue, expected_p, atol=2*self.atol)
class TestPermutationTest:
rtol = 1e-14
# -- Input validation -- #
def test_permutation_test_iv(self):
def stat(x, y, axis):
return stats.ttest_ind((x, y), axis).statistic
message = "each sample in `data` must contain two or more ..."
with pytest.raises(ValueError, match=message):
permutation_test(([1, 2, 3], [1]), stat)
message = "`data` must be a tuple containing at least two samples"
with pytest.raises(ValueError, match=message):
permutation_test((1,), stat)
with pytest.raises(TypeError, match=message):
permutation_test(1, stat)
message = "`axis` must be an integer."
with pytest.raises(ValueError, match=message):
permutation_test(([1, 2, 3], [1, 2, 3]), stat, axis=1.5)
message = "`permutation_type` must be in..."
with pytest.raises(ValueError, match=message):
permutation_test(([1, 2, 3], [1, 2, 3]), stat,
permutation_type="ekki")
message = "`vectorized` must be `True` or `False`."
with pytest.raises(ValueError, match=message):
permutation_test(([1, 2, 3], [1, 2, 3]), stat, vectorized=1.5)
message = "`n_resamples` must be a positive integer."
with pytest.raises(ValueError, match=message):
permutation_test(([1, 2, 3], [1, 2, 3]), stat, n_resamples=-1000)
message = "`n_resamples` must be a positive integer."
with pytest.raises(ValueError, match=message):
permutation_test(([1, 2, 3], [1, 2, 3]), stat, n_resamples=1000.5)
message = "`batch` must be a positive integer or None."
with pytest.raises(ValueError, match=message):
permutation_test(([1, 2, 3], [1, 2, 3]), stat, batch=-1000)
message = "`batch` must be a positive integer or None."
with pytest.raises(ValueError, match=message):
permutation_test(([1, 2, 3], [1, 2, 3]), stat, batch=1000.5)
message = "`alternative` must be in..."
with pytest.raises(ValueError, match=message):
permutation_test(([1, 2, 3], [1, 2, 3]), stat, alternative='ekki')
message = "'herring' cannot be used to seed a"
with pytest.raises(ValueError, match=message):
permutation_test(([1, 2, 3], [1, 2, 3]), stat,
random_state='herring')
# -- Test Parameters -- #
@pytest.mark.parametrize('permutation_type',
['pairings', 'samples', 'independent'])
def test_batch(self, permutation_type):
# make sure that the `batch` parameter is respected by checking the
# maximum batch size provided in calls to `statistic`
np.random.seed(0)
x = np.random.rand(10)
y = np.random.rand(10)
def statistic(x, y, axis):
batch_size = 1 if x.ndim == 1 else len(x)
statistic.batch_size = max(batch_size, statistic.batch_size)
statistic.counter += 1
return np.mean(x, axis=axis) - np.mean(y, axis=axis)
statistic.counter = 0
statistic.batch_size = 0
kwds = {'n_resamples': 1000, 'permutation_type': permutation_type,
'vectorized': True, 'random_state': 0}
res1 = stats.permutation_test((x, y), statistic, batch=1, **kwds)
assert_equal(statistic.counter, 1001)
| assert_equal(statistic.batch_size, 1) | numpy.testing.assert_equal |
import pandas as pd
import datetime as datetime
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.nonparametric.smoothers_lowess import lowess
"""
cgmquantify package
Description:
The cgmquantify package is a comprehensive library for computing metrics from continuous glucose monitors.
Requirements:
pandas, datetime, numpy, matplotlib, statsmodels
Functions:
importdexcom(): Imports data from Dexcom continuous glucose monitor devices
interdaycv(): Computes and returns the interday coefficient of variation of glucose
interdaysd(): Computes and returns the interday standard deviation of glucose
intradaycv(): Computes and returns the intraday coefficient of variation of glucose
intradaysd(): Computes and returns the intraday standard deviation of glucose
TIR(): Computes and returns the time in range
TOR(): Computes and returns the time outside range
PIR(): Computes and returns the percent time in range
POR(): Computes and returns the percent time outside range
MGE(): Computes and returns the mean of glucose outside specified range
MGN(): Computes and returns the mean of glucose inside specified range
MAGE(): Computes and returns the mean amplitude of glucose excursions
J_index(): Computes and returns the J-index
LBGI(): Computes and returns the low blood glucose index
HBGI(): Computes and returns the high blood glucose index
ADRR(): Computes and returns the average daily risk range, an assessment of total daily glucose variations within risk space
MODD(): Computes and returns the mean of daily differences. Examines mean of value + value 24 hours before
CONGA24(): Computes and returns the continuous overall net glycemic action over 24 hours
GMI(): Computes and returns the glucose management index
eA1c(): Computes and returns the American Diabetes Association estimated HbA1c
summary(): Computes and returns glucose summary metrics, including interday mean glucose, interday median glucose, interday minimum glucose, interday maximum glucose, interday first quartile glucose, and interday third quartile glucose
plotglucosesd(): Plots glucose with specified standard deviation lines
plotglucosebounds(): Plots glucose with user-defined boundaries
plotglucosesmooth(): Plots smoothed glucose plot (with LOWESS smoothing)
"""
def importdexcom(filename):
"""
Imports data from Dexcom continuous glucose monitor devices
Args:
filename (String): path to file
Returns:
(pd.DataFrame): dataframe of data with Time, Glucose, and Day columns
"""
data = pd.read_csv(filename)
df = pd.DataFrame()
df['Time'] = data['Timestamp (YYYY-MM-DDThh:mm:ss)']
df['Glucose'] = pd.to_numeric(data['Glucose Value (mg/dL)'])
df.drop(df.index[:12], inplace=True)
df['Time'] = pd.to_datetime(df['Time'], format='%Y-%m-%dT%H:%M:%S')
df['Day'] = df['Time'].dt.date
df = df.reset_index()
return df
def importfreestylelibre(filename):
"""
Imports data from Abbott FreeStyle Libre continuous glucose monitor devices
Args:
filename (String): path to file
Returns:
(pd.DataFrame): dataframe of data with Time, Glucose, and Day columns
"""
data = pd.read_csv(filename, header=1, parse_dates=['Device Timestamp'])
df = pd.DataFrame()
historic_id = 0
df['Time'] = data.loc[data['Record Type'] == historic_id, 'Device Timestamp']
df['Glucose'] = pd.to_numeric(data.loc[data['Record Type'] == historic_id, 'Historic Glucose mg/dL'])
df['Day'] = df['Time'].dt.date
return df
def interdaycv(df):
"""
Computes and returns the interday coefficient of variation of glucose
Args:
(pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns
Returns:
cvx (float): interday coefficient of variation averaged over all days
"""
cvx = (np.std(df['Glucose']) / (np.mean(df['Glucose'])))*100
return cvx
def interdaysd(df):
"""
Computes and returns the interday standard deviation of glucose
Args:
(pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns
Returns:
interdaysd (float): interday standard deviation averaged over all days
"""
interdaysd = np.std(df['Glucose'])
return interdaysd
def intradaycv(df):
"""
Computes and returns the intraday coefficient of variation of glucose
Args:
(pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns
Returns:
intradaycv_mean (float): intraday coefficient of variation averaged over all days
intradaycv_medan (float): intraday coefficient of variation median over all days
intradaycv_sd (float): intraday coefficient of variation standard deviation over all days
"""
intradaycv = []
for i in pd.unique(df['Day']):
intradaycv.append(interdaycv(df[df['Day']==i]))
intradaycv_mean = np.mean(intradaycv)
intradaycv_median = np.median(intradaycv)
intradaycv_sd = np.std(intradaycv)
return intradaycv_mean, intradaycv_median, intradaycv_sd
def intradaysd(df):
"""
Computes and returns the intraday standard deviation of glucose
Args:
(pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns
Returns:
intradaysd_mean (float): intraday standard deviation averaged over all days
intradaysd_medan (float): intraday standard deviation median over all days
intradaysd_sd (float): intraday standard deviation standard deviation over all days
"""
intradaysd =[]
for i in pd.unique(df['Day']):
intradaysd.append(np.std(df[df['Day']==i]))
intradaysd_mean = np.mean(intradaysd)
intradaysd_median = np.median(intradaysd)
intradaysd_sd = | np.std(intradaysd) | numpy.std |
# This code aims to draw 3 activation function
# Engineer: <NAME>
# Last Update: 8/3/2021
import matplotlib.pyplot as plt
import numpy as np
def sigmoid(x):
s = 1 / (1 + np.exp(-x))
return s
def tanh(x):
s1 = np.exp(x) - np.exp(-x)
s2 = | np.exp(x) | numpy.exp |
#+
#
# This file is part of h5py, a low-level Python interface to the HDF5 library.
#
# Copyright (C) 2008 <NAME>
# http://h5py.alfven.org
# License: BSD (See LICENSE.txt for full license)
#
# $Date$
#
#-
"""
Contains code to "bootstrap" HDF5 files for the test suite. Since it
uses the same code that will eventually be tested, the files it produces
are manually inspected using HDFView, and distributed with the package.
"""
import numpy as np
import h5py
class Group(dict):
def __init__(self, *args, **kwds):
dict.__init__(self, *args, **kwds)
self.attrs = {}
class File(Group):
def __init__(self, name, *args, **kwds):
Group.__init__(self, *args, **kwds)
self.name = name
class Dataset(object):
argnames = ('shape', 'dtype', 'data','chunks', 'compression', 'shuffle',
'fletcher32', 'maxshape')
def __init__(self, *args, **kwds):
kwds.update(zip(self.argnames, args))
self.kwds = kwds
self.attrs = {}
class Datatype(object):
def __init__(self, dtype):
self.dtype = dtype
self.attrs = {}
def compile_hdf5(fileobj):
""" Take a "model" HDF5 tree and write it to an actual file. """
def update_attrs(hdf_obj, attrs_dict):
for name in sorted(attrs_dict):
val = attrs_dict[name]
hdf_obj.attrs[name] = val
def store_dataset(group, name, obj):
""" Create and store a dataset in the given group """
dset = group.create_dataset(name, **obj.kwds)
update_attrs(dset, obj.attrs)
def store_type(group, name, obj):
""" Commit the given datatype to the group """
group[name] = obj.dtype
htype = group[name]
update_attrs(htype, obj.attrs)
def store_group(group, name, obj):
""" Create a new group inside this existing group. """
# First create the new group (if it's not the root group)
if name is not None:
hgroup = group.create_group(name)
else:
hgroup = group
# Now populate it
for new_name in sorted(obj):
new_obj = obj[new_name]
if isinstance(new_obj, Dataset):
store_dataset(hgroup, new_name, new_obj)
elif isinstance(new_obj, Datatype):
store_type(hgroup, new_name, new_obj)
elif isinstance(new_obj, Group):
store_group(hgroup, new_name, new_obj)
update_attrs(hgroup, obj.attrs)
f = h5py.File(fileobj.name, 'w')
store_group(f['/'], None, fileobj)
f.close()
def file_attrs():
""" "Attributes" test file (also used by group tests) """
sg1 = Group()
sg2 = Group()
sg3 = Group()
grp = Group({'Subgroup1': sg1, 'Subgroup2': sg2, 'Subgroup3': sg3})
grp.attrs = {'String Attribute': np.asarray("This is a string.", '|S18'),
'Integer': np.asarray(42, '<i4'),
'Integer Array': np.asarray([0,1,2,3], '<i4'),
'Byte': | np.asarray(-34, '|i1') | numpy.asarray |
from src.vehicle import Vehicle
from src.visualiser import Vis
from src.track import TrackHandler
from src.nn import NeuralNetwork
from sandbox.game_pad_inputs import GamePad
from src.lidar import Lidar
import numpy as np
from time import sleep
import time
# ####################
# NN OUTPUT HANDLING #
# ####################
def update_nn_outputs( outputs, nn):
"""
Assumes outputs are [Thr/Brake, Steering]
"""
thr_brake = max(0.0, min(1.0, nn.outputs[0])) * 2 - 1
if thr_brake >= 0:
outputs[0] = thr_brake
outputs[1] = 0.0
else:
outputs[0] = 0.0
outputs[1] = thr_brake
outputs[2] = (max(0.0, min(1.0, nn.outputs[1])) * 2 - 1) * 360.0
# ###################
# NN INPUT HANDLING #
# ###################
def update_nn_inputs(inputs, veh):
"""
Fixes the order of the inputs
Lidar is scaled 0-1 - out of range lidar is set to max distance.
"""
collArr = | np.hstack((veh.lidar_front.collision_array, veh.lidar_left.collision_array, veh.lidar_right.collision_array)) | numpy.hstack |
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
def plot_gam(a, b):
'''
:param a: gamma shape parameter n
:param b: gamma scale parameter ℷ
'''
x = | np.linspace(0, 15, 10000) | numpy.linspace |
__author__ = '<NAME>'
import numpy as np
import lasagne
def batch_generator(data, target, BATCH_SIZE, shuffle=False):
if shuffle:
while True:
ids = np.random.choice(len(data), BATCH_SIZE)
yield data[ids], target[ids]
else:
for idx in range(0, len(data), BATCH_SIZE):
ids = slice(idx, idx + BATCH_SIZE)
yield data[ids], target[ids]
def batch_generator_old(data, target, BATCH_SIZE, shuffle=False):
'''
just a simple batch iterator, no cropping, no rotation, no anything
'''
np.random.seed()
idx = np.arange(data.shape[0])
if shuffle:
np.random.shuffle(idx)
idx_2 = np.array(idx)
# if BATCH_SIZE is larger than len(data) we need to artificially enlarge the idx array (loop around)
while BATCH_SIZE > len(idx):
idx_2 = np.concatenate((idx_2, idx))
del(idx)
while True:
ctr = 0
yield np.array(data[idx_2[ctr:ctr+BATCH_SIZE]]), np.array(target[idx_2[ctr:ctr+BATCH_SIZE]])
ctr += BATCH_SIZE
if ctr >= data.shape[0]:
ctr -= data.shape[0]
def center_crop_generator(generator, output_size):
'''
yields center crop of size output_size (may be 1d or 2d) from data and seg
'''
'''if type(output_size) not in (tuple, list):
center_crop = [output_size, output_size]
elif len(output_size) == 2:
center_crop = list(output_size)
else:
raise ValueError("invalid output_size")'''
center_crop = lasagne.utils.as_tuple(output_size, 2, int)
for data, seg in generator:
center = np.array(data.shape[2:])/2
yield data[:, :, int(center[0]-center_crop[0]/2.):int(center[0]+center_crop[0]/2.), int(center[1]-center_crop[1]/2.):int(center[1]+center_crop[1]/2.)], seg[:, :, int(center[0]-center_crop[0]/2.):int(center[0]+center_crop[0]/2.), int(center[1]-center_crop[1]/2.):int(center[1]+center_crop[1]/2.)]
def random_crop_generator(generator, crop_size=(128, 128)):
'''
yields a random crop of size crop_size
'''
if type(crop_size) not in (tuple, list):
crop_size = [crop_size, crop_size]
elif len(crop_size) == 2:
crop_size = list(crop_size)
else:
raise ValueError("invalid crop_size")
for data, seg in generator:
lb_x = np.random.randint(0, data.shape[2]-crop_size[0])
lb_y = | np.random.randint(0, data.shape[3]-crop_size[1]) | numpy.random.randint |
"""
Implementation of DOGRE / WOGRE approach.
Notice projection==embedding.
"""
import numpy as np
from sklearn.linear_model import Ridge
import time
from state_of_the_art.state_of_the_art_embedding import final
from math import pow
from utils import get_initial_proj_nodes_by_k_core, get_initial_proj_nodes_by_degrees
import heapq
import networkx as nx
def user_print(item, user_wish):
"""
A function to show the user the state of the our_embeddings_methods. If you want a live update of the current state
of code and some details: set user wish to True else False
"""
if user_wish is True:
print(item, sep=' ', end='', flush=True)
time.sleep(3)
print(" ", end='\r')
def create_sub_G(proj_nodes, G):
"""
Creating a new graph from the nodes in the initial embedding so we can do the initial embedding on it
:param proj_nodes: The nodes in the initial embedding
:param G: Our graph
:return: A sub graph of G that its nodes are the nodes in the initial embedding.
"""
sub_G = G.subgraph(list(proj_nodes))
return sub_G
def create_dict_neighbors(G):
"""
Create a dictionary of neighbors.
:param G: Our graph
:return: neighbors_dict where key==node and value==set_of_neighbors (both incoming and outgoing)
"""
G_nodes = list(G.nodes())
neighbors_dict = {}
for i in range(len(G_nodes)):
node = G_nodes[i]
neighbors_dict.update({node: set(G[node])})
return neighbors_dict
def create_dicts_same_nodes(my_set, neighbors_dict, node, dict_out, dict_in):
"""
A function to create useful dictionaries to represent connections between nodes that have the same type, i.e between
nodes that are in the embedding and between nodes that aren't in the embedding. It depends on the input.
:param my_set: Set of the nodes that aren't currently in the embedding OR Set of the nodes that are currently in
the embedding
:param neighbors_dict: Dictionary of all nodes and neighbors (both incoming and outgoing)
:param node: Current node
:param dict_out: explained below
:param dict_in: explained below
:return: There are 4 possibilities (2 versions, 2 to every version):
A) 1. dict_node_node_out: key == nodes not in embedding, value == set of outgoing nodes not in embedding
(i.e there is a directed edge (i,j) when i is the key node and j isn't in the embedding)
2. dict_node_node_in: key == nodes not in embedding , value == set of incoming nodes not in embedding
(i.e there is a directed edge (j,i) when i is the key node and j isn't in the embedding)
B) 1. dict_enode_enode_out: key == nodes in embedding , value == set of outgoing nodes in embedding
(i.e there is a directed edge (i,j) when i is the key node and j is in the embedding)
2. dict_enode_enode_in: key == nodes in embedding , value == set of incoming nodes in embedding
(i.e there is a directed edge (j,i) when i is the key node and j is in the embedding)
"""
set1 = neighbors_dict[node].intersection(my_set)
count_1 = 0
count_2 = 0
if (len(set1)) > 0:
count_1 += 1
dict_out.update({node: set1})
neigh = list(set1)
for j in range(len(neigh)):
if dict_in.get(neigh[j]) is None:
dict_in.update({neigh[j]: set([node])})
else:
dict_in[neigh[j]].update(set([node]))
else:
count_2 += 1
return dict_out, dict_in
def create_dict_node_enode(set_proj_nodes, neighbors_dict, H, node, dict_node_enode, dict_enode_node):
"""
A function to create useful dictionaries to represent connections between nodes that are in the embedding and
nodes that are not in the embedding.
:param set_proj_nodes: Set of the nodes that are in the embedding
:param neighbors_dict: Dictionary of all nodes and neighbors (both incoming and outgoing)
:param H: H is the undirected version of our graph
:param node: Current node
:param dict_node_enode: explained below
:param dict_enode_node: explained below
:return: 1. dict_node_enode: key == nodes not in embedding, value == set of outdoing nodes in embedding (i.e
there is a directed edge (i,j) when i is the key node and j is in the embedding)
2. dict_enode_node: key == nodes not in embedding, value == set of incoming nodes in embedding (i.e
there is a directed edge (j,i) when i is the key node and j is in the embedding)
"""
set2 = neighbors_dict[node].intersection(set_proj_nodes)
set_all = set(H[node]).intersection(set_proj_nodes)
set_in = set_all - set2
if len(set2) > 0:
dict_node_enode.update({node: set2})
if len(set_in) > 0:
dict_enode_node.update({node: set_in})
return dict_node_enode, dict_enode_node
def create_dicts_of_connections(set_proj_nodes, set_no_proj_nodes, neighbors_dict, G):
"""
A function that creates 6 dictionaries of connections between different types of nodes.
:param set_proj_nodes: Set of the nodes that are in the projection
:param set_no_proj_nodes: Set of the nodes that aren't in the projection
:param neighbors_dict: Dictionary of neighbours
:return: 6 dictionaries, explained above (in the two former functions)
"""
dict_node_node_out = {}
dict_node_node_in = {}
dict_node_enode = {}
dict_enode_node = {}
dict_enode_enode_out = {}
dict_enode_enode_in = {}
list_no_proj = list(set_no_proj_nodes)
list_proj = list(set_proj_nodes)
H = G.to_undirected()
for i in range(len(list_no_proj)):
node = list_no_proj[i]
dict_node_node_out, dict_node_node_in = create_dicts_same_nodes(set_no_proj_nodes, neighbors_dict, node,
dict_node_node_out, dict_node_node_in)
dict_node_enode, dict_enode_node = create_dict_node_enode(set_proj_nodes, neighbors_dict, H, node,
dict_node_enode, dict_enode_node)
for i in range(len(list_proj)):
node = list_proj[i]
dict_enode_enode_out, dict_enode_enode_in = create_dicts_same_nodes(set_proj_nodes, neighbors_dict, node,
dict_enode_enode_out, dict_enode_enode_in)
return dict_node_node_out, dict_node_node_in, dict_node_enode, dict_enode_node, dict_enode_enode_out, dict_enode_enode_in
def calculate_average_projection_second_order(dict_proj, node, dict_enode_enode, average_two_order_proj, dim, G):
"""
A function to calculate the average embeddings of the second order neighbors, both outgoing and incoming,
depends on the input.
:param dict_proj: Dict of embeddings (key==node, value==its embedding)
:param node: Current node we're dealing with
:param dict_enode_enode: key==node in embedding , value==set of neighbors that are in the embedding. Direction
(i.e outgoing or incoming depends on the input)
:param average_two_order_proj: explained below
:return: Average embedding of second order neighbours, outgoing or incoming.
"""
two_order_neighs = dict_enode_enode.get(node)
k2 = 0
# if the neighbors in the projection also have neighbors in the projection calculate the average projection
if two_order_neighs is not None:
two_order_neighs_in = list(two_order_neighs)
k2 += len(two_order_neighs_in)
two_order_projs = []
for i in range(len(two_order_neighs_in)):
if G[node].get(two_order_neighs_in[i]) is not None:
two_order_proj = G[node][two_order_neighs_in[i]]["weight"]*dict_proj[two_order_neighs_in[i]]
else:
two_order_proj = G[two_order_neighs_in[i]][node]["weight"]*dict_proj[two_order_neighs_in[i]]
two_order_projs.append(two_order_proj)
two_order_projs = np.array(two_order_projs)
two_order_projs = np.mean(two_order_projs, axis=0)
# else, the average projection is 0
else:
two_order_projs = np.zeros(dim)
average_two_order_proj.append(two_order_projs)
return average_two_order_proj, k2
def calculate_projection_of_neighbors(current_node, proj_nodes, dict_proj, dict_enode_enode_in, dict_enode_enode_out, dim, G):
"""
A function to calculate average degree of first order neighbors and second order neighbors, direction
(outgoing or incoming) depends on the input.
:param proj_nodes: Neighbors that are in the embedding, direction depends on the input.
:param dict_proj: Dict of embeddings (key==node, value==embedding)
:return: Average degree of first order neighbors and second order neighbors
"""
proj = []
# average projections of the two order neighbors, both incoming and outgoing
average_two_order_proj_in = []
average_two_order_proj_out = []
list_proj_nodes = list(proj_nodes)
# the number of first order neighbors
k1 = len(proj_nodes)
# to calculate the number of the second order neighbors
k2_in = 0
k2_out = 0
# to calculate the average projection of the second order neighbors
for k in range(len(list_proj_nodes)):
node = list_proj_nodes[k]
average_two_order_proj_in, a = calculate_average_projection_second_order(dict_proj, node, dict_enode_enode_in,
average_two_order_proj_in, dim, G)
k2_in += a
average_two_order_proj_out, b = calculate_average_projection_second_order(dict_proj, node, dict_enode_enode_out,
average_two_order_proj_out, dim, G)
k2_out += b
proj.append(dict_proj[node])
if G[current_node].get(node) is not None:
proj.append(G[current_node][node]["weight"] * dict_proj[node])
else:
proj.append(G[node][current_node]["weight"] * dict_proj[node])
# for every neighbor we have the average projection of its neighbors, so now do average on all of them
average_two_order_proj_in = np.array(average_two_order_proj_in)
average_two_order_proj_in = np.mean(average_two_order_proj_in, axis=0)
average_two_order_proj_out = np.array(average_two_order_proj_out)
average_two_order_proj_out = np.mean(average_two_order_proj_out, axis=0)
proj = np.array(proj)
# find the average proj
proj = np.mean(proj, axis=0)
return proj, average_two_order_proj_in, average_two_order_proj_out, k1, k2_in, k2_out
def calculate_projection(current_node, G, proj_nodes_in, proj_nodes_out, dict_proj, dict_enode_enode_in, dict_enode_enode_out, dim,
alpha1, alpha2, beta_11, beta_12, beta_21, beta_22):
"""
A function to calculate the final embedding of the node by D-VERSE method as explained in the pdf file in github.
:param proj_nodes_in: embeddings of first order incoming neighbors.
:param proj_nodes_out: embeddings of first order outgoing neighbors.
:param dict_proj: Dict of embeddings (key==node, value==projection)
:param dim: Dimension of the embedding
:param alpha1, alpha2, beta_11, beta_12, beta_21, beta_22: Parameters to calculate the final projection.
:return: The final projection of our node.
"""
if len(proj_nodes_in) > 0:
x_1, z_11, z_12, k1, k2_in_in, k2_in_out = calculate_projection_of_neighbors(current_node,
proj_nodes_in, dict_proj, dict_enode_enode_in, dict_enode_enode_out, dim, G)
else:
x_1, z_11, z_12 = np.zeros(dim), np.zeros(dim), | np.zeros(dim) | numpy.zeros |
# -*- coding: utf-8 -*-
import numpy as np
import seawater as sw
# ===========================================================
# DYNAMICAL MODES AMPLITUDE
# ===========================================================
def vmode_amp(A,vi):
'''
This function makes the projection of every vertical mode to
timeseries or section matrix to obtain its amplitude.
It will be used to data reconstruction.
Operation: ((A'*A)^-1)*(A'*vi)
=============================================================
INPUT:
A =
vi =
OUTPUT:
AMP =
==============================================================
'''
return np.dot(np.linalg.inv(np.dot(A.T,A)),np.dot(A.T,vi))
# ===========================================================
# RELATIVE VORTICITY
# ===========================================================
def zeta(x,y,U,V):
'''
ZETA k-component of rotational by velocity field
Returns the scalar field of vorticity from U and V
velocity components. X and Y are longitude and latitude
matrices, respectively, as U and V. All matrices have
same dimension. Grid could be curvilinear, but the error
will increase.
--> !!! IMPORTANT !!! <-----------------------------------------
The grid indexes IM and JM must have origin on the left-inferior
corner, increasing to right and to up, respectively.
GRID
: : : :
| | | |
(JM = 2) o ---------- o ---------- o ---------- o --- ...
| | | |
| | | |
(JM = 1) o ---------- o ---------- o ---------- o --- ...
| | | |
| | | |
(JM = 0) o ---------- o ---------- o ---------- o --- ...
(IM = 0) (IM = 1) (IM = 2) (IM = 3)
================================================================
USAGE: ZETA = zeta(x,y,u,v)
INPUT:
x = decimal degrees (+ve E, -ve W) [-180..+180]
y = decimal degrees (+ve N, -ve S) [- 90.. +90]
u = velocity zonal component [m s^-1]
v = velocity meridional component [m s^-1]
OUTPUT:
ZETA = Relative vorticity field [s^-1]
================================================================
'''
#função para cálculo de ângulos
angcalc = lambda dy,dx: np.math.atan2(dy,dx)
#funções para os diferenciais com borda
dX = lambda d: np.hstack([(d[:,1]-d[:,0])[:,None],
d[:,2:]-d[:,:-2],(d[:,-1]-d[:,-2])[:,None]])
dY = lambda d: np.vstack([(d[1,:]-d[0,:])[None,:],
d[2:,:]-d[:-2,:],(d[-1,:]-d[-2,:])[None,:]])
# x = coordenada natural i
# y = coordenada natural j
# X = coordenada zonal cartesiana
# Y = coordenada meridional cartesiana
dyX = dX(y)*60*1852*np.cos(y*np.pi/180)
dyY = dY(y)*60*1852
dxX = dX(x)*60*1852*np.cos(y*np.pi/180)
dxY = dY(x)*60*1852
dsx = np.sqrt(dxX**2 + dyX**2)
dsy = np.sqrt(dxY**2 + dyY**2)
#Derivadas naturais de U
dUy = dY(U)
dUx = dX(U)
#Derivadas naturais de V
dVy = dY(V)
dVx = dX(V)
#a função map aplicará a função lambda angcalc em todos os elementos
#indicados depois da virgula e armazenará em uma lista
angX = list(map(angcalc,dyX.ravel(),dxX.ravel()))
angY = list(map(angcalc,dyY.ravel(),dxY.ravel()))
#fazendo rechape dos ângulos para o formato das matrizes de distâncias
angX = np.reshape(angX,dsx.shape)
angY = np.reshape(angY,dsy.shape)
#calculando as componentes X e Y das derivadas
dv1,dv2 = (dVy/dsy)*np.cos(angY), (dVx/dsx)*np.cos(angX)
du1,du2 = -(dUy/dsy)*np.sin(angY), -(dUx/dsx)*np.sin(angX)
# zerando valores aos quais a derivada tendeu ao infinito:
# isto só acontece se uma das dimensões da grade for paralalela a um
# eixo cartesiano
dv1[np.isinf(dv1)] = 0
dv2[np.isinf(dv2)] = 0
du1[np.isinf(du1)] = 0
du2[np.isinf(du2)] = 0
#somando as componentes
ZETA = dv1+dv2+du1+du2
return ZETA
# ===========================================================
# U AND V FROM STREAMFUNCTION
# ===========================================================
def psi2uv(x,y,psi):
'''
PSI2UV Velocity components from streamfunction
Returns the velocity components U and V
from streamfunction PSI. X and Y are longitude and latitude
matrices, respectively, as PSI.
All matrices have same dimension.
--> !!! IMPORTANT !!! <-----------------------------------
The grid indexes IM and JM must have origin on the
lower-left corner, increasing to right and to up.
GRID
: : : :
| | | |
(JM = 2) o ---------- o ---------- o ---------- o --- ...
| | | |
| | | |
(JM = 1) o ---------- o ---------- o ---------- o --- ...
| | | |
| | | |
(JM = 0) o ---------- o ---------- o ---------- o --- ...
(IM = 0) (IM = 1) (IM = 2) (IM = 3)
==============================================================
USAGE: u,v = psi2uv(x,y,psi)
INPUT:
x = decimal degrees (+ve E, -ve W) [-180..+180]
y = decimal degrees (+ve N, -ve S) [- 90.. +90]
psi = streamfunction [m^2 s^-1]
OUTPUT:
u = velocity zonal component [m s^-1]
v = velocity meridional component [m s^-1]
==========================================================
'''
#função para cálculo de ângulos
angcalc = lambda dy,dx: np.math.atan2(dy,dx)
#funções para os diferenciais com borda
dX = lambda d: np.hstack([(d[:,1]-d[:,0])[:,None],
d[:,2:]-d[:,:-2],(d[:,-1]-d[:,-2])[:,None]])
dY = lambda d: np.vstack([(d[1,:]-d[0,:])[None,:],
d[2:,:]-d[:-2,:],(d[-1,:]-d[-2,:])[None,:]])
# x = coordenada natural i
# y = coordenada natural j
# X = coordenada zonal cartesiana
# Y = coordenada meridional cartesiana
dyX = dX(y)*60*1852*np.cos(y*np.pi/180)
dyY = dY(y)*60*1852
dxX = dX(x)*60*1852*np.cos(y*np.pi/180)
dxY = dY(x)*60*1852
dsX = np.sqrt(dxX**2 + dyX**2)
dsY = np.sqrt(dxY**2 + dyY**2)
dpx = dX(psi)
dpy = dY(psi)
#a função map aplicará a função lambda angcalc em todos os elementos
#indicados depois da virgula e armazenará em uma lista
angX = list(map(angcalc,dyX.ravel(),dxX.ravel()))
angY = list(map(angcalc,dyY.ravel(),dxY.ravel()))
#fazendo rechape dos ângulos para o formato das matrizes de distâncias
angX = np.reshape(angX,dsX.shape)
angY = np.reshape(angY,dsY.shape)
#calculando as componentes u e v das velocidades calculadas em JM e IM
v1,u1 = (dpy/dsY)*np.cos(angY), -(dpy/dsY)*np.sin(angY)
u2,v2 = -(dpx/dsX)*np.sin(angX), (dpx/dsX)*np.cos(angX)
# zerando valores aos quais a derivada tendeu ao infinito:
# isto só acontece se uma das dimensões da grade for paralalela a um
# eixo cartesiano
v1[np.isinf(v1)] = 0
v2[np.isinf(v2)] = 0
u1[np.isinf(u1)] = 0
u2[np.isinf(u2)] = 0
#somando as componentes
U = u1+u2
V = v1+v2
return U,V
# ===========================================================
# EQUATORIAL MODES
# ===========================================================
def eqmodes(N2,z,nm,lat,pmodes=False):
'''
This function computes the equatorial velocity modes
============================================================
INPUT:
N2 = Brunt-Vaisala frequency data array
z = Depth data array (equaly spaced)
lat = Latitude scalar
nm = Number of modes to be computed
pmodes = If the return of pressure modes is required.
(Default is False)
OUTPUT:
Si = Equatorial modes matrix with MxN dimension being:
M = z array size
N = nm
Rdi = Deformation Radii array
Fi = Pressure modes matrix with MxN dimension being:
M = z array size
N = nm
(Returned only if input pmodes=True)
============================================================
'''
#nm will be the number of baroclinic modes
nm -= 1 #Barotropic mode will be added
#defines the orthonormalization function
onorm = lambda f: f/np.sqrt(dz*((np.array(f[1:])**2+\
np.array(f[:-1])**2)/(2*H)).sum())
# defines function to keep consistency multiply by plus/minus
# to make the leading term positive
plus_minus = lambda f: -f if (np.sign(f[1]) < 0) else f
dz = np.abs(z[1] - z[0])
# assembling matrices
# N2 matrix
N2 = np.diag(N2[1:-1],0)
# 2nd order difference matrix
A = np.diag(np.ones(z.size-2)*-2.,0)+\
np.diag(np.ones(z.size-3)*1.,-1)+\
np.diag(np.ones(z.size-3)*1.,1)
A = A/(dz**2)
A = np.matrix(A)
N2 = | np.matrix(N2) | numpy.matrix |
import numpy as np
x = np.load('../data/processed/one_hot_seqs.npy')
y = np.load('../data/processed/cell_type_array.npy')
peak_names = | np.load('../data/processed/peak_names.npy') | numpy.load |
import cv2 as cv
import numpy as np
import numpy as np
import math
import imutils
import os
beta = 0.75
class BodyPart():
def __init__(self, name='part'):
self.name = name
self.x = 0
self.y = 0
self.theta = 0
self.l = 0
self.w = 0
self.children = []
self.parent = None
self.left_upper_corner = None
self.right_upper_corner = None
self.left_lower_corner = None
self.right_lower_corner = None
self.priority = 0
self.area = 0
self.Si = 0 # intersection of synthesized body part with foreground
self.visited = 0 # number of time this body part was updated
def setData(self, x, y, theta, l, w):
self.x = x
self.y = y
self.theta = theta
self.l = l
self.w = w
self.area = l * w
self.setCorners()
def updateValue(self, indx, lamda):
if indx == 0:
self.x += int(lamda)
elif indx == 1:
self.y += int(lamda)
elif indx == 2:
self.theta += lamda
elif indx == 3:
self.l += int(lamda)
self.area = self.l * self.w
else:
self.w += int(lamda)
self.area = self.l * self.w
self.setCorners()
def addChildren(self, children):
for child in children:
self.children.append(child)
def setParent(self, parent):
self.parent = parent
def getData(self):
return (self.x, self.y, self.theta, self.l, self.w)
def setCorners(self):
if self.name == 'Torso':
center = True
else:
center = False
self.left_upper_corner = get_left_upper_corner(self.x, self.y, self.theta, self.l, self.w, center)
self.right_upper_corner = get_right_upper_corner(self.x, self.y, self.theta, self.l, self.w, center)
self.left_lower_corner = get_left_lower_corner(self.x, self.y, self.theta, self.l, self.w, center)
self.right_lower_corner = get_right_lower_corner(self.x, self.y, self.theta, self.l, self.w, center)
# input : frame , initial background with no human in it
# output: binary image
def segmentation (frame, background):
if len(frame.shape) > 2:
frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
if len(background.shape) > 2:
background = cv.cvtColor(background, cv.COLOR_BGR2GRAY)
diff = cv.absdiff(frame, background)
diff[diff > 35] = 255
diff[diff <= 35] = 0
return diff
def get_body_height(fore):
miniy = 0
maxiy = 0
for i in range(fore.shape[0]):
r= fore[i]
x = np.argmax(r)
if r[x] == 255:
miniy = i
break
for i in reversed(range(fore.shape[0])):
r = fore[i]
x = np.argmax(r)
if r[x] == 255:
maxiy = i
break
height = abs(maxiy - miniy)
return height
def get_torso_center(foreImage):
distMap= cv.distanceTransform(foreImage, cv.DIST_L2, 5)
(yTorso, xTorso) = np.where(distMap == np.amax(distMap))
return (xTorso[0], yTorso[0])
####################length of torso#############################
def get_torso_length(foreImage, lBody):
meanLTorso = .33
varLTorso = .001
mu = meanLTorso * lBody
sigma = np.sqrt(varLTorso * (lBody**2))
lTorso = np.random.normal(mu, sigma)
return lTorso
##################################################################
####################width of torso#############################
def get_torso_width(foreImage, wBody):
meanWTorso = 1
varWTorso = .001
mu = meanWTorso * wBody
sigma = np.sqrt(varWTorso * (wBody**2))
wTorso = np.random.normal(mu, sigma)
return wTorso
##################################################################
def get_torso_angle(foreImage):
fore = foreImage.copy()
# get horizontal histogram
num_rows = foreImage.shape[0]
distMap= cv.distanceTransform(foreImage, cv.DIST_L2, 5)
(yFirst, xFirst) = np.where(distMap == np.amax(distMap))
xFirst = int(xFirst[0])
yFirst = int(yFirst[0])
cropped_image = fore[min(yFirst + 5, num_rows - 1):, ]
distMap= cv.distanceTransform(cropped_image, cv.DIST_L2, 5)
(ySecond, xSecond) = np.where(distMap == np.amax(distMap))
xSecond = int(xSecond[0])
ySecond = int(ySecond[0]) + min(yFirst + 5, num_rows - 1)
if abs(ySecond - yFirst) < 30:
cropped_image = fore[0:max(yFirst - 5, 0), ]
distMap = cv.distanceTransform(cropped_image, cv.DIST_L2, 5)
if not distMap is None:
(ySecond, xSecond) = np.where(distMap == np.amax(distMap))
xSecond = int(xSecond[0])
ySecond = int(ySecond[0])
deltaY = ySecond - yFirst
deltaX = xSecond - xFirst
if deltaX != 0:
theta = np.arctan(deltaY/deltaX) * 180.0 / np.pi
else:
theta = 90.0
return 360
#return abs(90 - theta)
def get_torso_model(image_R,face,img):
lBody = get_body_height(img)
wBody = 0.17 * lBody
l = get_torso_length(img, lBody)
w = get_torso_width(img, wBody)
x,y= get_TFH(image_R,face,l)
theta = get_torso_angle(img)
torso_data = (x, y, theta, l, w)
return torso_data
def get_right_upper_arm_model(torso_center_x, torso_center_y, torso_theta,torso_height, torso_w):
meanHeight = .55 * torso_height
varHeight = .02
height = np.random.normal(meanHeight, varHeight)
meanW = .2 * torso_w
varW = .1
width = np.random.normal(meanW, varW)
(top_right_x,top_right_y) = get_right_upper_corner(torso_center_x, torso_center_y, torso_theta, torso_height, torso_w,True)
top_right_y = top_right_y + (.5 * width)
sigma_x = 1
right_x = top_right_x
right_y = top_right_y
theta = np.random.normal(45,10)
return right_x, right_y, theta, height, width
def get_left_upper_arm_model(torso_center_x, torso_center_y,torso_theta, torso_height, torso_w):
meanHeight = .55 * torso_height
varHeight = .02
height = np.random.normal(meanHeight, varHeight)
meanW = .2 * torso_w
varW = .1
width = np.random.normal(meanW, varW)
(top_left_x,top_left_y) = get_left_upper_corner(torso_center_x, torso_center_y, torso_theta, torso_height, torso_w,True)
top_left_y = top_left_y+(.5 * width)
sigma_x = 3
left_x = top_left_x
left_y = top_left_y
theta = np.random.normal(125, 10)
return left_x, left_y, theta, height, width
def get_right_lower_arm_model(end_x, end_y, torso_height, torso_w):
meanHeight = .55 * torso_height
varHeight = .02
height = np.random.normal(meanHeight, varHeight)
meanW = .2 * torso_w
varW = .1
width = np.random.normal(meanW, varW)
top_right_x = end_x
top_right_y = end_y
sigma_x = 1
right_x = np.random.normal(top_right_x, sigma_x)
right_y = np.random.normal(top_right_y, sigma_x)
theta = np.random.normal(45, 10)
return right_x, right_y, theta, height, width
def get_left_lower_arm_model(end_x, end_y, torso_height, torso_w):
meanHeight = .55 * torso_height
varHeight = .02
height = np.random.normal(meanHeight, varHeight)
meanW = .2 * torso_w
varW = .1
width = np.random.normal(meanW, varW)
top_left_x = end_x
top_left_y = end_y
sigma_x = 3
left_x = np.random.normal(top_left_x, sigma_x)
left_y = np.random.normal(top_left_y, sigma_x)
theta = np.random.normal(125, 10)
return left_x, left_y, theta, height, width
def get_left_upper_leg_model(torso_center_x,torso_center_y,torso_theta,torso_height,torso_w):
meanHeight = .7* torso_height
varHeight = .01
height = np.random.normal(meanHeight, varHeight)
meanW = .35 * torso_w
varW = .1
width = np.random.normal(meanW, varW)
(bottom_left_x,bottom_left_y) = get_left_lower_corner(torso_center_x, torso_center_y, torso_theta, torso_height, torso_w,True)
bottom_left_x = bottom_left_x+(.5 * width)
sigma_x = 0
left_x = np.random.normal(bottom_left_x, sigma_x)
left_y = np.random.normal(bottom_left_y, sigma_x)
theta = np.random.normal(100, 10)
return left_x, left_y, theta, height, width
def get_right_upper_leg_model(torso_center_x, torso_center_y,torso_theta, torso_height, torso_w):
meanHeight = .7 * torso_height
varHeight = .01
height = np.random.normal(meanHeight, varHeight)
meanW = .34 * torso_w
varW = .1
width= np.random.normal(meanW, varW)
(top_right_x,top_right_y) = get_right_lower_corner(torso_center_x, torso_center_y, torso_theta, torso_height, torso_w,True)
top_right_x = top_right_x - (.5 * width)
sigma_x = 0
right_x = np.random.normal(top_right_x, sigma_x)
right_y = np.random.normal(top_right_y, sigma_x)
theta = np.random.normal(80, 10)
return right_x, right_y, theta, height, width
def get_left_lower_leg_model(end_x, end_y, torso_height, torso_w):
meanHeight = .7 * torso_height
varHeight = .01
height = np.random.normal(meanHeight, varHeight)
meanW = .35* torso_w
varW = .1
width= np.random.normal(meanW, varW)
bottom_left_x = end_x
bottom_left_y = end_y
sigma_x = 0
left_x = np.random.normal(bottom_left_x, sigma_x)
left_y = np.random.normal(bottom_left_y, sigma_x)
theta = np.random.normal(110, 10)
return left_x, left_y, theta, height, width
def get_right_lower_leg_model(end_x, end_y, torso_height, torso_w):
meanHeight = .7 * torso_height
varHeight = .01
height = np.random.normal(meanHeight, varHeight)
meanW = .34 * torso_w
varW = .1
width= np.random.normal(meanW, varW)
top_right_x = end_x
top_right_y = end_y
sigma_x = 0
right_x = | np.random.normal(top_right_x, sigma_x) | numpy.random.normal |
import matplotlib.pyplot as plt
import numpy as np
from itertools import cycle, islice
from sklearn import cluster
figsize = (10,10)
point_size=150
point_border=0.8
from scipy.spatial.distance import euclidean, cdist
from scipy.sparse.csgraph import minimum_spanning_tree
from scipy.sparse import csgraph
def DBCV(X, labels, dist_function=euclidean):
"""
Density Based clustering validation
Args:
X (np.ndarray): ndarray with dimensions [n_samples, n_features]
data to check validity of clustering
labels (np.array): clustering assignments for data X
dist_dunction (func): function to determine distance between objects
func args must be [np.array, np.array] where each array is a point
Returns: cluster_validity (float)
score in range[-1, 1] indicating validity of clustering assignments
"""
graph = _mutual_reach_dist_graph(X, labels, dist_function)
mst = _mutual_reach_dist_MST(graph)
cluster_validity = _clustering_validity_index(mst, labels)
return cluster_validity
def _core_dist(point, neighbors, dist_function):
"""
Computes the core distance of a point.
Core distance is the inverse density of an object.
Args:
point (np.array): array of dimensions (n_features,)
point to compute core distance of
neighbors (np.ndarray): array of dimensions (n_neighbors, n_features):
array of all other points in object class
dist_dunction (func): function to determine distance between objects
func args must be [np.array, np.array] where each array is a point
Returns: core_dist (float)
inverse density of point
"""
n_features = np.shape(point)[0]
n_neighbors = np.shape(neighbors)[1]
distance_vector = cdist(point.reshape(1, -1), neighbors)
distance_vector = distance_vector[distance_vector != 0]
numerator = ((1/distance_vector)**n_features).sum()
core_dist = (numerator / (n_neighbors)) ** (-1/n_features)
return core_dist
def _mutual_reachability_dist(point_i, point_j, neighbors_i,
neighbors_j, dist_function):
""".
Computes the mutual reachability distance between points
Args:
point_i (np.array): array of dimensions (n_features,)
point i to compare to point j
point_j (np.array): array of dimensions (n_features,)
point i to compare to point i
neighbors_i (np.ndarray): array of dims (n_neighbors, n_features):
array of all other points in object class of point i
neighbors_j (np.ndarray): array of dims (n_neighbors, n_features):
array of all other points in object class of point j
dist_dunction (func): function to determine distance between objects
func args must be [np.array, np.array] where each array is a point
Returns: mutual_reachability (float)
mutual reachability between points i and j
"""
core_dist_i = _core_dist(point_i, neighbors_i, dist_function)
core_dist_j = _core_dist(point_j, neighbors_j, dist_function)
dist = dist_function(point_i, point_j)
mutual_reachability = np.max([core_dist_i, core_dist_j, dist])
return mutual_reachability
def _mutual_reach_dist_graph(X, labels, dist_function):
"""
Computes the mutual reach distance complete graph.
Graph of all pair-wise mutual reachability distances between points
Args:
X (np.ndarray): ndarray with dimensions [n_samples, n_features]
data to check validity of clustering
labels (np.array): clustering assignments for data X
dist_dunction (func): function to determine distance between objects
func args must be [np.array, np.array] where each array is a point
Returns: graph (np.ndarray)
array of dimensions (n_samples, n_samples)
Graph of all pair-wise mutual reachability distances between points.
"""
n_samples = np.shape(X)[0]
graph = []
counter = 0
for row in range(n_samples):
graph_row = []
for col in range(n_samples):
point_i = X[row]
point_j = X[col]
class_i = labels[row]
class_j = labels[col]
members_i = _get_label_members(X, labels, class_i)
members_j = _get_label_members(X, labels, class_j)
dist = _mutual_reachability_dist(point_i, point_j,
members_i, members_j,
dist_function)
graph_row.append(dist)
counter += 1
graph.append(graph_row)
graph = np.array(graph)
return graph
def _mutual_reach_dist_MST(dist_tree):
"""
Computes minimum spanning tree of the mutual reach distance complete graph
Args:
dist_tree (np.ndarray): array of dimensions (n_samples, n_samples)
Graph of all pair-wise mutual reachability distances
between points.
Returns: minimum_spanning_tree (np.ndarray)
array of dimensions (n_samples, n_samples)
minimum spanning tree of all pair-wise mutual reachability
distances between points.
"""
mst = minimum_spanning_tree(dist_tree).toarray()
return mst + np.transpose(mst)
def _cluster_density_sparseness(MST, labels, cluster):
"""
Computes the cluster density sparseness, the minimum density
within a cluster
Args:
MST (np.ndarray): minimum spanning tree of all pair-wise
mutual reachability distances between points.
labels (np.array): clustering assignments for data X
cluster (int): cluster of interest
Returns: cluster_density_sparseness (float)
value corresponding to the minimum density within a cluster
"""
indices = np.where(labels == cluster)[0]
cluster_MST = MST[indices][:, indices]
cluster_density_sparseness = np.max(cluster_MST)
return cluster_density_sparseness
def _cluster_density_separation(MST, labels, cluster_i, cluster_j):
"""
Computes the density separation between two clusters, the maximum
density between clusters.
Args:
MST (np.ndarray): minimum spanning tree of all pair-wise
mutual reachability distances between points.
labels (np.array): clustering assignments for data X
cluster_i (int): cluster i of interest
cluster_j (int): cluster j of interest
Returns: density_separation (float):
value corresponding to the maximum density between clusters
"""
indices_i = np.where(labels == cluster_i)[0]
indices_j = | np.where(labels == cluster_j) | numpy.where |
import random
import numpy as np
class OrnsteinUhlenbeckAndEpsilonGreedy:
"""
See https://github.com/keras-rl/keras-rl/blob/master/rl/random.py
"""
def __init__(self, theta, mu: float = 0, sigma: float = 1, dt=1e-2, size: int = 1, epsilon_actions: int = 0):
self.mu = mu
self.sigma = sigma
self.size = size
self.theta = theta
self.dt = dt
self.previous_noise = None
self.epsilon_actions = epsilon_actions
self.reset_states()
def get_action(self, action: np.ndarray):
action = action + self.sample()
for i in range(self.epsilon_actions):
if random.random() < 0.1:
action[-i - 1] = random.getrandbits(1) - 0.5
return action
def sample(self):
noise = self.previous_noise + \
self.theta * (self.mu - self.previous_noise) * self.dt + \
self.sigma * np.sqrt(self.dt) * np.random.normal(size=self.size)
self.previous_noise = noise
return noise
def reset_states(self):
self.previous_noise = np.random.normal(self.mu, self.sigma, size=self.size)
if __name__ == '__main__':
size = 5
ou = OrnsteinUhlenbeckAndEpsilonGreedy(theta=0.15, sigma=0.05, size=size)
for i in range(100):
action = ou.get_action( | np.zeros(size) | numpy.zeros |
# general imports
import numpy as np
from abc import ABC, abstractmethod
# local module imports
from . import interpolation as ip, global_functions as g_func, \
channel as chl, output_object as oo
class ParallelFlowCircuit(ABC, oo.OutputObject):
def __new__(cls, dict_flow_circuit, manifolds, channels,
n_subchannels=1.0, **kwargs):
circuit_type = dict_flow_circuit.get('type', 'Koh')
if circuit_type == 'Koh':
return super(ParallelFlowCircuit, cls).\
__new__(KohFlowCircuit)
elif circuit_type == 'ModifiedKoh':
return super(ParallelFlowCircuit, cls).\
__new__(ModifiedKohFlowCircuit)
elif circuit_type == 'UpdatedKoh':
return super(ParallelFlowCircuit, cls).\
__new__(UpdatedKohFlowCircuit)
elif circuit_type == 'Wang':
return super(ParallelFlowCircuit, cls).\
__new__(WangFlowCircuit)
else:
raise NotImplementedError
def __init__(self, dict_flow_circuit, manifolds, channels,
n_subchannels=1.0, **kwargs):
name = dict_flow_circuit['name']
super().__init__(name)
assert isinstance(dict_flow_circuit, dict)
assert isinstance(manifolds, (list, tuple))
assert isinstance(channels, (list, tuple))
err_message = 'manifolds must be tuple or list with two objects of ' \
'class Channel'
if len(manifolds) != 2:
raise ValueError(err_message)
elif not isinstance(manifolds[0], chl.Channel):
raise TypeError(err_message)
if not isinstance(channels[0], chl.Channel):
raise TypeError(err_message)
self.print_variables = \
{
'names': ['normalized_flow_distribution'],
'units': ['-'],
'sub_names': ['None']
}
self.combine_print_variables(self.print_variables,
kwargs.get('print_variables', None))
self.manifolds = manifolds
self.manifolds[0].name = self.name + ': Inlet Manifold'
self.manifolds[0].fluid.name = self.manifolds[0].name + ': ' \
+ self.manifolds[0].fluid.TYPE_NAME
self.manifolds[1].name = self.name + ': Outlet Manifold'
self.manifolds[1].fluid.name = self.manifolds[1].name + ': ' \
+ self.manifolds[1].fluid.TYPE_NAME
self.channels = channels
self.manifolds[0].flow_direction = 1
self.shape = dict_flow_circuit.get('shape', 'U')
if self.shape not in ('U', 'Z'):
raise ValueError('shape of flow circuit must be either U or Z')
if self.shape == 'U':
self.manifolds[1].flow_direction = -1
else:
self.manifolds[1].flow_direction = 1
if hasattr(self.manifolds[0].fluid, 'mass_fraction'):
self.multi_component = True
else:
self.multi_component = False
self.n_channels = len(self.channels)
self.n_subchannels = n_subchannels
self.tolerance = dict_flow_circuit.get('tolerance', 1e-6)
self.max_iter = dict_flow_circuit.get('max_iter', 20)
self.min_iter = dict_flow_circuit.get('min_iter', 3)
self.calc_distribution = \
dict_flow_circuit.get('calc_distribution', True)
self.mass_flow_in = \
self.manifolds[0].mass_flow_total[self.manifolds[0].id_in]
self.vol_flow_in = 0.0
self.channel_mass_flow = \
np.ones(self.n_channels) * self.mass_flow_in / self.n_channels
self.channel_vol_flow = np.zeros(self.channel_mass_flow.shape)
self.channel_vol_flow_old = np.zeros(self.channel_vol_flow.shape)
self.channel_length = \
np.asarray([channel.length for channel in channels])
self.channel_cross_area = \
np.asarray([channel.cross_area for channel in channels])
self.initialize = True
self.update_channels(update_fluid=True)
self.normalized_flow_distribution = \
np.zeros(self.channel_vol_flow.shape)
self.iteration = 0
self.add_print_variables(self.print_variables)
def update(self, inlet_mass_flow=None, calc_distribution=None,
update_fluid=False, **kwargs):
"""
Update the flow circuit
"""
if inlet_mass_flow is not None:
id_in = self.manifolds[0].id_in
self.vol_flow_in = \
inlet_mass_flow / self.manifolds[0].fluid.density[id_in]
if self.initialize:
# homogeneous distribution
self.channel_mass_flow[:] = inlet_mass_flow / self.n_channels
self.channel_vol_flow[:] = self.vol_flow_in / self.n_channels
else:
# use previous distribution scaled to new mass flow
self.channel_mass_flow[:] *= inlet_mass_flow / self.mass_flow_in
self.channel_vol_flow[:] *= inlet_mass_flow / self.mass_flow_in
# set new mass and volume flows
self.mass_flow_in = inlet_mass_flow
if self.initialize:
self.update_channels(update_fluid=True)
self.channel_vol_flow_old[:] = 1e8
# channel_vol_flow_old = np.zeros(self.channel_vol_flow.shape)
if calc_distribution is None:
calc_distribution = self.calc_distribution
if calc_distribution and self.n_channels > 1:
for i in range(self.max_iter):
# print(self.name + ' Iteration # ', str(i+1))
self.iteration = i
self.single_loop()
if i == 0:
self.initialize = False
error = \
np.sum(
np.divide(self.channel_vol_flow -
self.channel_vol_flow_old[:],
self.channel_vol_flow,
where=self.channel_vol_flow != 0.0) ** 2.0)
# print(channel_vol_flow_old)
# print(self.channel_vol_flow)
self.channel_vol_flow_old[:] = self.channel_vol_flow
# print(error)
if error < self.tolerance and i >= self.min_iter:
break
if i == (self.max_iter - 1):
print('maximum number of iterations n = {} '
'with error = {} in update() of {} '
'reached'.format(self.max_iter, error, self))
else:
self.initialize = False
# final channel updates within flow circuit iteration
self.update_channels(update_fluid=True)
try:
self.normalized_flow_distribution[:] = \
self.channel_mass_flow / np.average(self.channel_mass_flow)
except FloatingPointError:
self.normalized_flow_distribution[:] = 0.0
@abstractmethod
def single_loop(self, inlet_mass_flow=None, update_channels=True):
pass
def update_channels(self, update_fluid=True):
if self.initialize:
channel_mass_flow_in = np.ones(self.n_channels) \
* self.mass_flow_in / self.n_channels
channel_mass_flow_out = channel_mass_flow_in
else:
channel_mass_flow_in = self.channel_mass_flow
# channel_mass_flow_out = \
# np.array([channel.mass_flow_total[channel.id_out]
# for channel in self.channels])
# channel_mass_flow_out *= self.n_subchannels
channel_mass_flow_out = self.channel_mass_flow
if self.multi_component:
mass_fraction = \
np.array([channel.fluid.mass_fraction[:, channel.id_out]
for channel in self.channels]).transpose()
else:
mass_fraction = 1.0
mass_source = channel_mass_flow_out * mass_fraction
# mass_source = self.channel_mass_flow * mass_fraction
channel_enthalpy_out = \
np.asarray([ch.g_fluid[ch.id_out] * ch.temperature[ch.id_out]
for ch in self.channels]) * self.n_subchannels
self.manifolds[1].update(mass_flow_in=0.0, mass_source=mass_source,
update_mass=True, update_flow=True,
update_heat=False, update_fluid=update_fluid,
enthalpy_source=channel_enthalpy_out)
# Channel update
for i, channel in enumerate(self.channels):
channel.p_out = ip.interpolate_1d(self.manifolds[1].pressure)[i]
channel.temperature[channel.id_in] = self.manifolds[0].temp_ele[i]
channel.update(mass_flow_in=
channel_mass_flow_in[i] / self.n_subchannels,
update_mass=True, update_flow=True,
update_heat=False, update_fluid=update_fluid)
# Inlet header update
id_in = self.channels[-1].id_in
self.manifolds[0].p_out = self.channels[-1].pressure[id_in]
if self.multi_component:
mass_fraction = self.manifolds[0].fluid.mass_fraction[:, :-1]
else:
mass_fraction = 1.0
mass_source = -self.channel_mass_flow * mass_fraction
self.manifolds[0].update(mass_flow_in=self.mass_flow_in, # * 1.00000,
mass_source=mass_source,
update_mass=True, update_flow=True,
update_heat=False, update_fluid=update_fluid)
id_in = self.manifolds[0].id_in
self.vol_flow_in = \
self.mass_flow_in / self.manifolds[0].fluid.density[id_in]
class KohFlowCircuit(ParallelFlowCircuit):
def __init__(self, dict_flow_circuit, manifolds, channels,
n_subchannels=1.0):
super().__init__(dict_flow_circuit, manifolds, channels,
n_subchannels)
# Distribution factor
self.alpha = np.ones(self.n_channels)
id_in = self.channels[-1].id_in
id_out = self.channels[-1].id_out
self.dp_ref = \
self.channels[-1].pressure[id_in] \
- self.channels[-1].pressure[id_out]
self.k_perm = np.zeros(self.n_channels)
self.l_by_a = np.array([channel.length / channel.cross_area
for channel in self.channels])
self.visc_channel = np.zeros(self.n_channels)
self.dp_channel = | np.zeros(self.n_channels) | numpy.zeros |
import numpy as np
from numpy.linalg import norm
__all__ = [
'FLOAT_EPSILON',
'constants',
'geom_units',
'Ray',
'NullRay',
'Plane',
'Sphere',
'plane_intersect',
'sphere_intersect',
'rotate3D',
'wrap',
'unwrap',
'sph2pix',
'pix2sph',
]
# This error tolerance will maintain accuracy up to 10 meters in units of c
# or about 5 kilometers in astronomical units
FLOAT_EPSILON = 3.3356409519815204e-08
constants = {
'c': 299792458.0,
'G': 6.67408e-11,
'gravitational constant': 6.67408e-11,
'solar_mass': 1.98847e+30,
'au': 149597870691.0,
'astronomical unit': 149597870691.0,
'parsec': 3.0856775813057292e+16,
'ly': 9460730472580800.0,
'light year': 9460730472580800.0,
}
# geometrized units
geom_units = {
'm': 1.0,
'length': 1.0,
's': 299792458.0,
'time': 299792458.0,
'kg': 7.425915486106335e-28, # G/c**2
'mass': 7.425915486106335e-28,
'velocity': 3.3356409519815204e-09, # 1/c
'acceleration': 1.1126500560536185e-17, # 1/c**2
'energy': 8.262445281865645e-45, # G/c**4
}
class Ray (object):
"""
Basic Ray object containing both an origin and a direction.
Does not contain information on length, however, allows parameterization.
When called, returns the location of the ray's endpoint if it had the
magnitude specified by the input parameter.
Parameters
==========
origin: iterable
3D coordinate specified by either a list, tuple, or ndarray.
direction: iterable
Either described by a pair of angles or a 3D coordinate.
In either case, it must be a list, tuple, or ndarray.
"""
def __init__(self, origin, direction):
# type check origin; direction will be checked in the _build method
if (not isinstance(origin, (list, tuple, np.ndarray))
or len(origin) is not 3):
raise TypeError('origin must be a 3D cartesian coordinate')
self.origin = np.array(origin, dtype=np.float)
self._angles = None
self._dir = None
if len(direction) is 2:
self.angles = direction
elif len(direction) is 3:
self.dir = direction
else:
raise TypeError('direction must be given as either a pair of '\
'angles or a 3D vector')
@property
def angles(self):
return self._angles
@property
def dir(self):
return self._dir
@angles.setter
def angles(self, direction):
if len(direction) is 2:
mod_theta = np.clip(direction[0],0,np.pi)
mod_phi = unwrap(direction[1])
self._angles = np.array([mod_theta, mod_phi])
self._dir = np.array([
np.sin(self._angles[0])*np.cos(self._angles[1]),
np.sin(self._angles[0])*np.sin(self._angles[1]),
np.cos(self._angles[0])])
self._dir = self._dir/np.linalg.norm(self._dir)
# np.isclose helps remedy floating point precision errors.
for idx, elem in enumerate(self._dir):
if np.isclose(elem, 0, atol=FLOAT_EPSILON): self._dir[idx] = 0.
else:
raise TypeError('direction must be given as a pair of angles')
@dir.setter
def dir(self, direction):
if len(direction) is 3:
self._dir = np.array(direction)/np.linalg.norm(direction)
self._angles = np.array([np.arccos(self._dir[2]),
np.arctan2(self._dir[1], self._dir[0])])
# np.isclose helps remedy floating point precision errors.
for idx, elem in enumerate(self._angles):
if np.isclose(elem, 0, atol=FLOAT_EPSILON):
self._angles[idx] = 0.
else:
raise TypeError('direction must be given as a 3D vector')
def rotate(self, angle, axis=[0,0,1]):
self.dir = rotate3D(angle, axis) @ self.dir
def __call__(self, param):
return self.dir*param + self.origin
def __str__(self):
return '{}(O:{}, D:{})'.format(
self.__class__.__name__, self.origin, self.angles)
def __repr__(self):
return str(self.__class__)
class NullRay (Ray):
def __init__(self, origin=3*[np.NaN]):
super(NullRay, self).__init__(origin, 2*[np.NaN])
class Plane (object):
"""
Represents a plane in 3D space.
Specified by a plane origin and a normal.
A plane can be defined by a single Ray argument, otherwise requires
two separate 3D vectors.
We should consider allowing for planes to be confined to a specified
height and width.
"""
def __init__(self, *args):
if len(args) is 1:
if not isinstance(args[0], Ray):
raise TypeError('a single argument must be a Ray')
self.origin = args[0].origin
self.normal = args[0].dir
elif len(args) is 2:
# I really abuse the hell out of all(map(...))
if (not all(map(isinstance, args,
len(args)*((list,tuple,np.ndarray),)))
or not all(map(lambda a: len(a) is 3, args))):
raise TypeError('multiple arguments must be '\
'3D cartesian coordinates')
self.origin = np.array(args[0])
self.normal = np.array(args[1])/norm(args[1])
def __str__(self):
return '{}(O:{}, N:{})'.format(
self.__class__.__name__, self.origin, self.normal)
def __repr__(self):
return str(self.__class__)
class Sphere (object):
"""
Very simple sphere object; should consider expanding in the near future.
"""
def __init__(self, origin, radius):
if (not isinstance(origin, (list, tuple, np.ndarray))
or len(origin) is not 3):
raise TypeError('origin must be a 3D cartesian coordinate')
if not isinstance(radius, (int, float)):
raise TypeError('radius must be a numerical value')
self.origin = origin
self.radius = radius
def __str__(self):
return '{}(O:{}, R:{})'.format(
self.__class__.__name__, self.origin, self.radius)
def __repr__(self):
return str(self.__class__)
def plane_intersect(plane, ray):
"""
Returns the ray parameter associated with the ray's intersection
with a plane.
"""
numer = (plane.origin - ray.origin) @ plane.normal
denom = ray.dir @ plane.normal
if numer == 0 or denom == 0: return np.NaN
ret = numer/denom
return ret if ret > 0 else np.NaN
def sphere_intersect(ray, sphere):
"""
Returns the ray parameter associated with the ray's intersection
with a sphere.
"""
OS = ray.origin - sphere.origin
B = 2*ray.dir @ OS
C = OS @ OS - sphere.radius**2
disc = B**2 - 4*C
if disc > 0:
dist = np.sqrt(disc)
Q = (-B - dist)/2 if B < 0 else (-B + dist)/2
ret0, ret1 = sorted([Q, C/Q])
if ret1 >= 0: return ret1 if ret0 < 0 else ret0
return np.NaN
def rotate3D(angle, axis=[0,0,1]):
"""
Returns the rotation matrix about a given axis.
"""
axis = np.array(axis)/ | norm(axis) | numpy.linalg.norm |
'''
###############################################################################
"MajoranaNanowire" Python3 Module
v 1.0 (2020)
Created by <NAME> (2018)
###############################################################################
"H_class/Lutchyn_Oreg/builders" submodule
This sub-package builds Lutchyn-Oreg Hamiltonians.
###############################################################################
'''
#%%############################################################################
######################## Required Packages ############################
###############################################################################
import numpy as np
import scipy.sparse
import scipy.sparse.linalg
import scipy.linalg
import scipy.constants as cons
from MajoranaNanowires.Functions import diagonal
#%%
def LO_1D_builder(N,dis,m_eff,mu,B,aR,d, space='position', k_vec=np.nan ,sparse='no'):
"""
1D Lutchy-Oreg Hamiltonian builder. It obtaines the Hamiltoninan for a 1D
Lutchy-Oreg chain with superconductivity.
Parameters
----------
N: int or arr
Number of sites.
dis: int or arr
Distance (in nm) between sites.
m_eff: int or arr
Effective mass. If it is an array, each element is the on-site
effective mass.
mu: float or arr
Chemical potential. If it is an array, each element is the on-site
chemical potential
B: float or arr
Zeeman splitting. If it is an array, each element is the Zeeman
splitting in each direction.
aR: float or arr
Rashba coupling.
-If aR is a float, aR is the Rashba coupling along the z-direction,
with the same value in every site.
-If aR is a 1D array with length=3, each element of the array is
the rashba coupling in each direction.
-If aR is an array of arrays (3 x N), each element of aR[i] is
an array with the on-site Rashba couplings in the direction i.
d: float or arr
Superconductor paring amplitud.
-If d is a float, d is the Rashba coupling along the y-direction,
with the same value in every site.
-If d is an array, each element of the array is the on-site
superconducting paring amplitud
space: {"position","momentum"}
Space in which the Hamiltonian is built. "position" means
real-space (r-space). In this case the boundary conditions are open.
On the other hand, "momentum" means reciprocal space (k-space). In
this case the built Hamiltonian corresponds to the Hamiltonian of
the unit cell, with periodic boundary conditions along the
x-direction.
k_vec: arr
If space=='momentum', k_vec is the (discretized) momentum vector,
usually in the First Brillouin Zone.
sparse: {"yes","no"}
Sparsety of the built Hamiltonian. "yes" builds a dok_sparse matrix,
while "no" builds a dense matrix.
Returns
-------
H: arr
Hamiltonian matrix.
"""
#Make sure that the onsite parameters are arrays:
if np.isscalar(m_eff):
m_eff = m_eff * np.ones(N)
if np.isscalar(mu):
mu = mu * np.ones(N)
if np.isscalar(B):
Bx=B
By=0
Bz=0
Bx,By,Bz=Bx*np.ones(N),By*np.ones(N),Bz*np.ones(N)
elif np.ndim(B)==1 and len(B)==3:
Bx=B[0]
By=B[1]
Bz=B[2]
Bx,By,Bz=Bx*np.ones(N),By*np.ones(N),Bz*np.ones(N)
if np.ndim(aR)==0:
aRy=np.zeros(N)
aRz=aR*np.ones(N)/(2*dis)
elif np.ndim(aR)==1:
if len(aR)==3:
aRy=aR[1]*np.ones(N)/(2*dis)
aRz=aR[2]*np.ones(N)/(2*dis)
else:
aRy=np.zeros(N)
aRz=aR/(2*dis)
else:
aRy=aR[1]/(2*dis)
aRz=aR[2]/(2*dis)
if np.isscalar(d):
d = d * np.ones(N)
if space=='momentum':
n_k=len(k_vec)
#Obtain the hopping and on-site energies:
t=cons.hbar**2/(2*m_eff*cons.m_e*(dis*1e-9)**2)/cons.e*1e3
e = 2 * t - mu
##Build the Hamiltonian:
if sparse=='no':
H = np.zeros((int(4 * N), int(4 * N)),dtype=complex)
elif sparse=='yes':
H=scipy.sparse.dok_matrix((int(4*N),int(4*N)),dtype=complex)
t, aRy, Bz = np.repeat(t,2), np.repeat(aRy,2), np.repeat(Bz,2)
Bz[1::2], aRy[1::2] = -Bz[::2], -aRy[::2]
for i in range(2):
H[diagonal(2*N*(i+1),init=2*N*i,k=1,step=2)], H[diagonal(2*N*(i+1),init=2*N*i,k=-1,step=2)] = (-1)**(i)*Bx-1j*By, (-1)**(i)*Bx+1j*By
H[diagonal(2*N*(i+1),init=2*N*i)] = (-1)**i*(Bz+np.repeat(e,2))
H[diagonal(2*N*(i+1),init=2*N*i,k=-2)] = -1*(-1)**i*t[2::]+1j*aRy[2::]
H[diagonal(2*N*(i+1),init=2*N*i,k=2)] = -1*(-1)**i*t[2::]-1j*aRy[2::]
H[diagonal(2*N*(i+1),k=1,step=2,init=1+2*N*i)] += -1*(-1)**i*aRz[1::]
H[diagonal(2*N*(i+1),k=-1,step=2,init=1+2*N*i)] += -1*(-1)**i*aRz[1::]
H[diagonal(2*N*(i+1),init=2*N*i,k=3,step=2)] += (-1)**i*aRz[1::]
H[diagonal(2*N*(i+1),init=2*N*i,k=-3,step=2)] += (-1)**i*aRz[1::]
H[diagonal(4*N,k=2*N+1,step=2)], H[diagonal(4*N,k=-2*N-1,step=2)] = -np.conj(d), -d
H[diagonal(4*N,k=2*N-1,step=2,init=1)], H[diagonal(4*N,k=-2*N+1,step=2,init=1)] = np.conj(d), d
#Build it in momentum space if required:
if space=='momentum':
if sparse=='no':
H_k = np.zeros((int(4 * N), int(4 * N), int(n_k)),dtype=complex)
for i in range(n_k):
H_k[:,:,i]=H
H_k[2 * (N - 1):2 * (N - 1) + 2, 0: 2,i] += np.array([[-t[2]-1j*aRy[2], aRz[1]], [-aRz[1], -t[2]+1j*aRy[2]]])*np.exp(-1j*k_vec[i]*N)
H_k[2 * (N - 1)+2*N:2 * (N - 1) + 2+2*N, 2*N: 2+2*N,i] += -np.array([[-t[2]+1j*aRy[2], aRz[1]], [-aRz[1], -t[2]-1j*aRy[2]]])*np.exp(1j*k_vec[i]*N)
H_k[0: 2, 2 * (N - 1):2 * (N - 1) + 2,i] += np.array([[-t[2]+1j*aRy[2], -aRz[1]], [aRz[1], -t[2]-1j*aRy[2]]])*np.exp(1j*k_vec[i]*N)
H_k[2*N: 2+2*N, 2 * (N - 1)+2*N:2 * (N - 1) + 2+2*N,i] += -np.array([[-t[2]-1j*aRy[2], -aRz[1]], [aRz[1], -t[2]+1j*aRy[2]]])*np.exp(-1j*k_vec[i]*N)
return (H_k)
elif sparse=='yes':
return(H)
else:
return (H)
#%%
def LO_1D_builder_NoSC(N,dis,m_eff,mu,B,aR, space='position', k_vec=np.nan ,sparse='no'):
"""
1D Lutchy-Oreg Hamiltonian builder. It obtaines the Hamiltoninan for a 1D
Lutchy-Oreg chain without superconductivity.
Parameters
----------
N: int or arr
Number of sites.
dis: int or arr
Distance (in nm) between sites.
m_eff: int or arr
Effective mass. If it is an array, each element is the on-site
effective mass.
mu: float or arr
Chemical potential. If it is an array, each element is the on-site
chemical potential
B: float or arr
Zeeman splitting. If it is an array, each element is the Zeeman
splitting in each direction.
aR: float or arr
Rashba coupling.
-If aR is a float, aR is the Rashba coupling along the z-direction,
with the same value in every site.
-If aR is a 1D array with length=3, each element of the array is
the rashba coupling in each direction.
-If aR is an array of arrays (3 x N), each element of aR[i] is
an array with the on-site Rashba couplings in the direction i.
space: {"position","momentum"}
Space in which the Hamiltonian is built. "position" means
real-space (r-space). In this case the boundary conditions are open.
On the other hand, "momentum" means reciprocal space (k-space). In
this case the built Hamiltonian corresponds to the Hamiltonian of
the unit cell, with periodic boundary conditions along the
x-direction.
k_vec: arr
If space=='momentum', k_vec is the (discretized) momentum vector,
usually in the First Brillouin Zone.
sparse: {"yes","no"}
Sparsety of the built Hamiltonian. "yes" builds a dok_sparse matrix,
while "no" builds a dense matrix.
Returns
-------
H: arr
Hamiltonian matrix.
"""
#Make sure that the onsite parameters are arrays:
if np.isscalar(m_eff):
m_eff = m_eff * np.ones(N)
if np.isscalar(mu):
mu = mu * np.ones(N)
if np.isscalar(B):
Bx=B
By=0
Bz=0
Bx,By,Bz=Bx*np.ones(N),By*np.ones(N),Bz*np.ones(N)
elif np.ndim(B)==1 and len(B)==3:
Bx=B[0]
By=B[1]
Bz=B[2]
Bx,By,Bz=Bx*np.ones(N),By*np.ones(N),Bz*np.ones(N)
if np.ndim(aR)==0:
aRy=np.zeros(N)
aRz=aR*np.ones(N)/(2*dis)
elif np.ndim(aR)==1:
if len(aR)==3:
aRy=aR[1]*np.ones(N)/(2*dis)
aRz=aR[2]*np.ones(N)/(2*dis)
else:
aRy=np.zeros(N)
aRz=aR/(2*dis)
else:
aRy=aR[1]/(2*dis)
aRz=aR[2]/(2*dis)
if space=='momentum':
n_k=len(k_vec)
#Obtain the hopping and the on-site energies:
t=cons.hbar**2/(2*m_eff*cons.m_e*(dis*1e-9)**2)/cons.e*1e3
e = 2 * t - mu
##Build the Hamiltonian:
if sparse=='no':
H = np.zeros((int(2 * N), int(2 * N)),dtype=complex)
elif sparse=='yes':
H=scipy.sparse.dok_matrix((int(2*N),int(2*N)),dtype=complex)
Bz,Bx,By=np.repeat(Bz,2),np.repeat(Bx,2), 1j*np.repeat(By,2)
Bx[1::2], By[1::2], Bz[1::2] = 0, 0, -Bz[::2]
H[diagonal(2*N,k=1)], H[diagonal(2*N,k=-1)] = Bx[:-1]-By[:-1], Bx[:-1]+By[:-1]
H[diagonal(2*N)]=Bz+np.repeat(e,2)
t=-np.repeat(t,2)
aRy=np.repeat(aRy,2)
aRy[1::2]= -aRy[::2]
H[diagonal(2*N,k=-2)], H[diagonal(2*N,k=2)] = t[2::]+1j*aRy[2::], t[2::]-1j*aRy[2::]
H[diagonal(2*N,k=1,step=2,init=1)] += -aRz[1::]
H[diagonal(2*N,k=-1,step=2,init=1)] += -aRz[1::]
H[diagonal(2*N,k=3,step=2)] += aRz[1::]
H[diagonal(2*N,k=-3,step=2)] += aRz[1::]
#Build it in momentum space if required:
if space=='momentum':
if sparse=='no':
H_k = np.zeros((int(2 * N), int(2 * N), int(n_k)),dtype=complex)
for i in range(n_k):
H_k[:,:,i]=H
H_k[2 * (N - 1):2 * (N - 1) + 2, 0: 2,i] += np.array([[-t[2]-1j*aRy[2], aRz[1]], [-aRz[1], -t[2]+1j*aRy[2]]])*np.exp(-1j*k_vec[i]*N)
H_k[0: 2, 2 * (N - 1):2 * (N - 1) + 2,i] += np.array([[-t[2]+1j*aRy[2], -aRz[1]], [aRz[1], -t[2]-1j*aRy[2]]])*np.exp(1j*k_vec[i]*N)
return (H_k)
elif sparse=='yes':
return (H)
else:
return (H)
#%%
def LO_2D_builder(N,dis,m_eff,mu,B,aR, d, space='position', k_vec=np.nan ,sparse='no'):
"""
2D Lutchy-Oreg Hamiltonian builder. It obtaines the Hamiltoninan for a 2D
Lutchy-Oreg chain with superconductivity.
Parameters
----------
N: arr
Number of sites in each direction.
dis: int or arr
Distance (in nm) between sites.
m_eff: int or arr
Effective mass. If it is a 2D array, each element is the on-site
effective mass.
mu: float or arr
Chemical potential. If it is a 2D array, each element is the
on-site chemical potential
B: float or arr
Zeeman splitting. If it is an array, each element is the Zeeman
splitting in each direction.
aR: float or arr
Rashba coupling.
-If aR is a float, aR is the Rashba coupling along the z-direction,
with the same value in every site.
-If aR is a 1D array with length=3, each element of the array is
the rashba coupling in each direction.
-If aR is an array of arrays (3 x N), each element of aR[i] is
a 2D array with the on-site Rashba couplings in the direction i.
d: float or arr
Superconductor paring amplitud.
-If d is a float, d is the Rashba coupling along the y-direction,
with the same value in every site.
-If d is a 2D array, each element of the array is the on-site
superconducting paring amplitud
space: {"position","momentum"}
Space in which the Hamiltonian is built. "position" means
real-space (r-space). In this case the boundary conditions are open.
On the other hand, "momentum" means reciprocal space (k-space). In
this case the built Hamiltonian corresponds to the Hamiltonian of
the unit cell, with periodic boundary conditions along the
x-direction.
k_vec: arr
If space=='momentum', k_vec is the (discretized) momentum vector,
usually in the First Brillouin Zone.
sparse: {"yes","no"}
Sparsety of the built Hamiltonian. "yes" builds a dok_sparse matrix,
while "no" builds a dense matrix.
Returns
-------
H: arr
Hamiltonian matrix.
"""
#Obtain the dimensions:
Ny, Nz = N[0], N[1]
if np.ndim(dis)==0:
dis_y, dis_z = dis, dis
else:
dis_y, dis_z = dis[0], dis[1]
m = 4 * Ny * Nz
#Make sure that the onsite parameters are arrays:
if np.isscalar(m_eff):
m_eff = m_eff * np.ones((Ny,Nz))
if np.isscalar(mu):
mu = mu * np.ones((Ny,Nz))
if np.isscalar(B):
Bx=B
By=0
Bz=0
Bx,By,Bz=Bx*np.ones(N),By*np.ones(N),Bz*np.ones(N)
elif np.ndim(B)==1 and len(B)==3:
Bx=B[0]
By=B[1]
Bz=B[2]
Bx,By,Bz=Bx*np.ones(N),By*np.ones(N),Bz*np.ones(N)
if np.ndim(aR)==0:
aRx=np.zeros(N)
aRy=np.zeros(N)
aRz=aR*np.ones(N)
elif np.ndim(aR)==1:
if len(aR)==3:
aRx=aR[0]*np.ones(N)
aRy=aR[1]*np.ones(N)
aRz=aR[2]*np.ones(N)
else:
aRx=np.zeros(N)
aRy=np.zeros(N)
aRz=aR*np.ones(N)
else:
aRx=aR[0]
aRy=aR[1]
aRz=aR[2]
if np.isscalar(d):
d = d * np.ones(N)
#Obtain the eigenenergies:
ty=cons.hbar**2/(2*(m_eff[1::,:]+m_eff[:-1,:])/2*cons.m_e*(dis_y*1e-9)**2)/cons.e*1e3
tz=cons.hbar**2/(2*(m_eff[:,1::]+m_eff[:,:-1])/2*cons.m_e*(dis_z*1e-9)**2)/cons.e*1e3
e = - mu
e += np.append(2*ty[0,:].reshape(1,Nz),np.append(ty[1::,:]+ty[:-1,:],2*ty[-1,:].reshape(1,Nz),axis=0),axis=0)
e += np.append(2*tz[:,0].reshape(Ny,1),np.append(tz[:,1::]+tz[:,:-1],2*tz[:,-1].reshape(Ny,1),axis=1),axis=1)
#Build the Hamiltonian:
if sparse=='no':
H = np.zeros((int(m), int(m)),dtype=complex)
elif sparse=='yes':
H = scipy.sparse.dok_matrix((int(m),int(m)),dtype=complex)
e,d,Bx,By,Bz=e.flatten(),d.flatten(),Bx.flatten(),By.flatten(),Bz.flatten()
Bz=np.repeat(Bz,2)
Bz[1::2] = -Bz[::2]
ty, aRx_ky, aRz_ky = np.repeat(ty.flatten(),2), np.repeat(((aRx[1::,:]+aRx[:-1,:])/(4*dis_y)).flatten(),2), ((aRz[1::,:]+aRz[:-1,:])/(4*dis_y)).flatten()
tz, aRx_kz, aRy_kz = np.repeat(tz.flatten(),2), ((aRx[:,1::]+aRx[:,:-1])/(4*dis_z)).flatten(), ((aRy[:,1::]+aRy[:,:-1])/(4*dis_z)).flatten()
aRx_ky[1::2] = -aRx_ky[::2]
tz, aRx_kz, aRy_kz=np.insert(tz,np.repeat(np.arange(2*(Nz-1),2*(Nz-1)*Ny,2*(Nz-1)),2),np.zeros(2*(Ny-1))), np.insert(aRx_kz,np.arange((Nz-1),(Nz-1)*Ny,(Nz-1)),np.zeros((Ny-1))), np.insert(aRy_kz,np.arange((Nz-1),(Nz-1)*Ny,(Nz-1)),np.zeros((Ny-1)))
for i in range(2):
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=1,step=2)], H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=-1,step=2)] = (-1)**(i)*Bx-1j*By, (-1)**(i)*Bx+1j*By
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i)] = (-1)**(i)*(np.repeat(e,2) + Bz)
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=2*Nz)] = -1*(-1)**(i)*ty+1j*aRx_ky
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=-2*Nz)] = -1*(-1)**(i)*ty-1j*aRx_ky
H[diagonal(int(m/2)*(i+1),k=2*Nz-1,step=2,init=1+int(m/2)*i)] += -1j*aRz_ky
H[diagonal(int(m/2)*(i+1),k=-2*Nz+1,step=2,init=1+int(m/2)*i)] += 1j*aRz_ky
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=1+2*Nz,step=2)] += -1j*aRz_ky
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=-1-2*Nz,step=2)] += 1j*aRz_ky
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=2)] = -1*(-1)**(i)*tz
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=-2)] = -1*(-1)**(i)*tz
H[diagonal(int(m/2)*(i+1),k=1,step=2,init=1+int(m/2)*i)] += (-1)**(i)*aRx_kz+1j*aRy_kz
H[diagonal(int(m/2)*(i+1),k=-1,step=2,init=1+int(m/2)*i)] += (-1)**(i)*aRx_kz-1j*aRy_kz
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=3,step=2)] += -1*(-1)**(i)*aRx_kz+1j*aRy_kz
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=-3,step=2)] += -1*(-1)**(i)*aRx_kz-1j*aRy_kz
H[diagonal(m,k=int(m/2)+1,step=2)], H[diagonal(m,k=-int(m/2)-1,step=2)] = -np.conj(d), -d
H[diagonal(m,k=int(m/2)-1,step=2,init=1)], H[diagonal(m,k=-int(m/2)+1,step=2,init=1)] = np.conj(d), d
return (H)
#%%
def LO_2D_builder_NoSC(N,dis,m_eff,mu,B,aR, space='position', k_vec=np.nan ,sparse='no'):
"""
2D Lutchy-Oreg Hamiltonian builder. It obtaines the Hamiltoninan for a 2D
Lutchy-Oreg chain without superconductivity.
Parameters
----------
N: arr
Number of sites in each direction.
dis: int or arr
Distance (in nm) between sites.
m_eff: int or arr
Effective mass. If it is a 2D array, each element is the on-site
effective mass.
mu: float or arr
Chemical potential. If it is a 2D array, each element is the
on-site chemical potential
B: float or arr
Zeeman splitting. If it is an array, each element is the Zeeman
splitting in each direction.
aR: float or arr
Rashba coupling.
-If aR is a float, aR is the Rashba coupling along the z-direction,
with the same value in every site.
-If aR is a 1D array with length=3, each element of the array is
the rashba coupling in each direction.
-If aR is an array of arrays (3 x N), each element of aR[i] is
a 2D array with the on-site Rashba couplings in the direction i.
space: {"position","momentum"}
Space in which the Hamiltonian is built. "position" means
real-space (r-space). In this case the boundary conditions are open.
On the other hand, "momentum" means reciprocal space (k-space). In
this case the built Hamiltonian corresponds to the Hamiltonian of
the unit cell, with periodic boundary conditions along the
x-direction.
k_vec: arr
If space=='momentum', k_vec is the (discretized) momentum vector,
usually in the First Brillouin Zone.
sparse: {"yes","no"}
Sparsety of the built Hamiltonian. "yes" builds a dok_sparse matrix,
while "no" builds a dense matrix.
Returns
-------
H: arr
Hamiltonian matrix.
"""
#Obtain the dimensions:
Ny, Nz = N[0], N[1]
if np.ndim(dis)==0:
dis_y, dis_z = dis, dis
else:
dis_y, dis_z = dis[0], dis[1]
m = 2 * Ny * Nz
#Make sure that the onsite parameters are arrays:
if np.isscalar(m_eff):
m_eff = m_eff * np.ones((Ny,Nz))
if np.isscalar(mu):
mu = mu * np.ones((Ny,Nz))
if np.isscalar(B):
Bx=B
By=0
Bz=0
Bx,By,Bz=Bx*np.ones(N),By*np.ones(N),Bz*np.ones(N)
elif np.ndim(B)==1 and len(B)==3:
Bx=B[0]
By=B[1]
Bz=B[2]
Bx,By,Bz=Bx*np.ones(N),By*np.ones(N),Bz*np.ones(N)
if np.ndim(aR)==0:
aRx=np.zeros(N)
aRy=np.zeros(N)
aRz=aR*np.ones(N)
elif np.ndim(aR)==1:
if len(aR)==3:
aRx=aR[0]*np.ones(N)
aRy=aR[1]*np.ones(N)
aRz=aR[2]*np.ones(N)
else:
aRx=np.zeros(N)
aRy=np.zeros(N)
aRz=aR*np.ones(N)
else:
aRx=aR[0]
aRy=aR[1]
aRz=aR[2]
#Obtain the eigenenergies:
ty=cons.hbar**2/(2*(m_eff[1::,:]+m_eff[:-1,:])/2*cons.m_e*(dis_y*1e-9)**2)/cons.e*1e3
tz=cons.hbar**2/(2*(m_eff[:,1::]+m_eff[:,:-1])/2*cons.m_e*(dis_z*1e-9)**2)/cons.e*1e3
e = - mu
e += np.append(2*ty[0,:].reshape(1,Nz),np.append(ty[1::,:]+ty[:-1,:],2*ty[-1,:].reshape(1,Nz),axis=0),axis=0)
e += np.append(2*tz[:,0].reshape(Ny,1),np.append(tz[:,1::]+tz[:,:-1],2*tz[:,-1].reshape(Ny,1),axis=1),axis=1)
#Build the Hamiltonian:
if sparse=='no':
H = np.zeros((int(m), int(m)),dtype=complex)
elif sparse=='yes':
H = scipy.sparse.dok_matrix((int(m),int(m)),dtype=complex)
e,Bx,By,Bz=e.flatten(),Bx.flatten(),By.flatten(),Bz.flatten()
Bz=np.repeat(Bz,2)
Bz[1::2] = -Bz[::2]
ty, aRx_ky, aRz_ky = np.repeat(ty.flatten(),2), np.repeat(((aRx[1::,:]+aRx[:-1,:])/(4*dis_y)).flatten(),2), ((aRz[1::,:]+aRz[:-1,:])/(4*dis_y)).flatten()
tz, aRx_kz, aRy_kz = np.repeat(tz.flatten(),2), ((aRx[:,1::]+aRx[:,:-1])/(4*dis_z)).flatten(), ((aRy[:,1::]+aRy[:,:-1])/(4*dis_z)).flatten()
aRx_ky[1::2] = -aRx_ky[::2]
H[diagonal(m,k=1,step=2)], H[diagonal(m,k=-1,step=2)] = Bx-1j*By, Bx+1j*By
H[diagonal(m)] = np.repeat(e,2) + Bz
H[diagonal(m,k=2*Nz)] = -ty+1j*aRx_ky
H[diagonal(m,k=-2*Nz)] = -ty-1j*aRx_ky
H[diagonal(m,k=2*Nz-1,step=2,init=1)] += -1j*aRz_ky
H[diagonal(m,k=-2*Nz+1,step=2,init=1)] += 1j*aRz_ky
H[diagonal(m,k=1+2*Nz,step=2)] += -1j*aRz_ky
H[diagonal(m,k=-1-2*Nz,step=2)] += 1j*aRz_ky
tz, aRx_kz, aRy_kz=np.insert(tz,np.repeat(np.arange(2*(Nz-1),2*(Nz-1)*Ny,2*(Nz-1)),2),np.zeros(2*(Ny-1))), np.insert(aRx_kz,np.arange((Nz-1),(Nz-1)*Ny,(Nz-1)),np.zeros((Ny-1))), np.insert(aRy_kz,np.arange((Nz-1),(Nz-1)*Ny,(Nz-1)),np.zeros((Ny-1)))
H[diagonal(m,k=2)] = -tz
H[diagonal(m,k=-2)] = -tz
H[diagonal(m,k=1,step=2,init=1)] += aRx_kz+1j*aRy_kz
H[diagonal(m,k=-1,step=2,init=1)] += aRx_kz-1j*aRy_kz
H[diagonal(m,k=3,step=2)] += -aRx_kz+1j*aRy_kz
H[diagonal(m,k=-3,step=2)] += -aRx_kz-1j*aRy_kz
return (H)
#%%
def LO_3D_builder(N,dis,m_eff,mu,B,aR,d, space='position', k_vec=np.nan ,sparse='yes'):
"""
3D Lutchy-Oreg Hamiltonian builder. It obtaines the Hamiltoninan for a 3D
Lutchy-Oreg chain with superconductivity.
Parameters
----------
N: arr
Number of sites in each direction.
dis: int or arr
Distance (in nm) between sites.
m_eff: int or arr
Effective mass. If it is a 3D array, each element is the on-site
effective mass.
mu: float or arr
Chemical potential. If it is a 3D array, each element is the
on-site chemical potential
B: float or arr
Zeeman splitting. If it is an array, each element is the Zeeman
splitting in each direction.
aR: float or arr
Rashba coupling.
-If aR is a float, aR is the Rashba coupling along the z-direction,
with the same value in every site.
-If aR is a 1D array with length=3, each element of the array is
the rashba coupling in each direction.
-If aR is an array of arrays (3 x N), each element of aR[i] is
a 3D array with the on-site Rashba couplings in the direction i.
d: float or arr
Superconductor paring amplitud.
-If d is a float, d is the Rashba coupling along the y-direction,
with the same value in every site.
-If d is a 3D array, each element of the array is the on-site
superconducting paring amplitud
space: {"position","momentum"}
Space in which the Hamiltonian is built. "position" means
real-space (r-space). In this case the boundary conditions are open.
On the other hand, "momentum" means reciprocal space (k-space). In
this case the built Hamiltonian corresponds to the Hamiltonian of
the unit cell, with periodic boundary conditions along the
x-direction.
k_vec: arr
If space=='momentum', k_vec is the (discretized) momentum vector,
usually in the First Brillouin Zone.
sparse: {"yes","no"}
Sparsety of the built Hamiltonian. "yes" builds a dok_sparse matrix,
while "no" builds a dense matrix.
Returns
-------
H: arr
Hamiltonian matrix.
"""
#Obtain the dimensions:
Nx, Ny, Nz = N[0], N[1], N[2]
if np.ndim(dis)==0:
dis_x, dis_y, dis_z = dis, dis, dis
else:
dis_x, dis_y, dis_z = dis[0], dis[1], dis[2]
m = 4 * Nx * Ny * Nz
#Make sure that the onsite parameters are arrays:
if np.isscalar(m_eff):
m_eff = m_eff * np.ones((Nx,Ny,Nz))
if np.isscalar(mu):
mu = mu * np.ones((Nx,Ny,Nz))
if np.isscalar(B):
Bx=B
By=0
Bz=0
Bx,By,Bz=Bx*np.ones(N),By*np.ones(N),Bz*np.ones(N)
elif np.ndim(B)==1 and len(B)==3:
Bx=B[0]
By=B[1]
Bz=B[2]
Bx,By,Bz=Bx*np.ones(N),By*np.ones(N),Bz*np.ones(N)
if np.ndim(aR)==0:
aRx=np.zeros((Nx,Ny,Nz))
aRy=np.zeros((Nx,Ny,Nz))
aRz=aR*np.ones((Nx,Ny,Nz))
elif np.ndim(aR)==1:
if len(aR)==3:
aRx=aR[0]*np.ones((Nx,Ny,Nz))
aRy=aR[1]*np.ones((Nx,Ny,Nz))
aRz=aR[2]*np.ones((Nx,Ny,Nz))
else:
aRx=np.zeros((Nx,Ny,Nz))
aRy=np.zeros((Nx,Ny,Nz))
aRz=aR*np.ones((Nx,Ny,Nz))
else:
aRx=aR[0]
aRy=aR[1]
aRz=aR[2]
if np.isscalar(d):
d = d * np.ones((Nx,Ny,Nz))
if space=='momentum':
n_k=len(k_vec)
#Obtain the hoppings and the on-site energies:
tx=cons.hbar**2/(2*(m_eff[1::,:,:]+m_eff[:-1,:,:])/2*cons.m_e*(dis_x*1e-9)**2)/cons.e*1e3
ty=cons.hbar**2/(2*(m_eff[:,1::,:]+m_eff[:,:-1,:])/2*cons.m_e*(dis_y*1e-9)**2)/cons.e*1e3
tz=cons.hbar**2/(2*(m_eff[:,:,1::]+m_eff[:,:,:-1])/2*cons.m_e*(dis_z*1e-9)**2)/cons.e*1e3
e = - mu
e += np.append(2*tx[0,:,:].reshape(1,Ny,Nz),np.append(tx[1::,:,:]+tx[:-1,:,:],2*tx[-1,:,:].reshape(1,Ny,Nz),axis=0),axis=0)
e += np.append(2*ty[:,0,:].reshape(Nx,1,Nz),np.append(ty[:,1::,:]+ty[:,:-1,:],2*ty[:,-1,:].reshape(Nx,1,Nz),axis=1),axis=1)
e += np.append(2*tz[:,:,0].reshape(Nx,Ny,1),np.append(tz[:,:,1::]+tz[:,:,:-1],2*tz[:,:,-1].reshape(Nx,Ny,1),axis=2),axis=2)
#Built the Hamiltonian:
if sparse=='no':
H = np.zeros((int(m), int(m)),dtype=complex)
elif sparse=='yes':
H = scipy.sparse.dok_matrix((int(m),int(m)),dtype=complex)
e,d,Bx,By,Bz=e.flatten(),d.flatten(),Bx.flatten(),By.flatten(),Bz.flatten()
Bz=np.repeat(Bz,2)
Bz[1::2] = -Bz[::2]
tx, aRy_kx, aRz_kx = np.repeat(tx.flatten(),2), np.repeat(((aRy[1::,:,:]+aRy[:-1,:,:])/(4*dis_x)).flatten(),2), ((aRz[1::,:,:]+aRz[:-1,:,:])/(4*dis_x)).flatten()
ty, aRx_ky, aRz_ky = np.repeat(ty.flatten(),2), np.repeat(((aRx[:,1::,:]+aRx[:,:-1,:])/(4*dis_y)).flatten(),2), ((aRz[:,1::,:]+aRz[:,:-1,:])/(4*dis_y)).flatten()
tz, aRx_kz, aRy_kz = np.repeat(tz.flatten(),2), ((aRx[:,:,1::]+aRx[:,:,:-1])/(4*dis_z)).flatten(), ((aRy[:,:,1::]+aRy[:,:,:-1])/(4*dis_z)).flatten()
aRy_kx[1::2], aRx_ky[1::2] = -aRy_kx[::2], -aRx_ky[::2]
ty, aRx_ky, aRz_ky = np.insert(ty,np.repeat(np.arange(2*(Nz*Ny-Nz),2*(Ny*Nz-Nz)*Nx,2*(Ny*Nz-Nz)),2*Nz),np.zeros(2*Nz*(Nx-1))), np.insert(aRx_ky,np.repeat(np.arange(2*(Nz*Ny-Nz),2*(Ny*Nz-Nz)*Nx,2*(Ny*Nz-Nz)),2*Nz),np.zeros(2*Nz*(Nx-1))),np.insert(aRz_ky,np.repeat(np.arange((Nz*Ny-Nz),(Ny*Nz-Nz)*Nx,(Ny*Nz-Nz)),Nz),np.zeros(Nz*(Nx-1)))
tz, aRx_kz, aRy_kz=np.insert(tz,np.repeat(np.arange(2*(Nz-1),2*(Nz-1)*Ny*Nx,2*(Nz-1)),2),np.zeros(2*Nx*(Ny-1)+2*(Nx-1))), np.insert(aRx_kz,np.arange((Nz-1),(Nz-1)*Ny*Nx,(Nz-1)),np.zeros(Nx*(Ny-1)+(Nx-1))), np.insert(aRy_kz,np.arange((Nz-1),(Nz-1)*Ny*Nx,(Nz-1)),np.zeros(Nx*(Ny-1)+(Nx-1)))
for i in range(2):
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=1,step=2)], H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=-1,step=2)] = (-1)**(i)*Bx-1j*By, (-1)**(i)*Bx+1j*By
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i)] = (-1)**(i)*np.repeat(e,2) + (-1)**(i)*Bz
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=2*Ny*Nz)] = -1*(-1)**(i)*tx-1j*aRy_kx
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=-2*Ny*Nz)] = -1*(-1)**(i)*tx+1j*aRy_kx
H[diagonal(int(m/2)*(i+1),k=2*Ny*Nz-1,step=2,init=1+int(m/2)*i)] += -1*(-1)**(i)*aRz_kx
H[diagonal(int(m/2)*(i+1),k=-2*Ny*Nz+1,step=2,init=1+int(m/2)*i)] += -1*(-1)**(i)*aRz_kx
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=1+2*Ny*Nz,step=2)] += (-1)**(i)*aRz_kx
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=-1-2*Ny*Nz,step=2)] += (-1)**(i)*aRz_kx
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=2*Nz)] = -1*(-1)**(i)*ty+1j*aRx_ky
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=-2*Nz)] = -1*(-1)**(i)*ty-1j*aRx_ky
H[diagonal(int(m/2)*(i+1),k=2*Nz-1,step=2,init=1+int(m/2)*i)] += -1j*aRz_ky
H[diagonal(int(m/2)*(i+1),k=-2*Nz+1,step=2,init=1+int(m/2)*i)] += 1j*aRz_ky
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=1+2*Nz,step=2)] += -1j*aRz_ky
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=-1-2*Nz,step=2)] += 1j*aRz_ky
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=2)] = -1*(-1)**(i)*tz
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=-2)] = -1*(-1)**(i)*tz
H[diagonal(int(m/2)*(i+1),k=1,step=2,init=1+int(m/2)*i)] += (-1)**(i)*aRx_kz+1j*aRy_kz
H[diagonal(int(m/2)*(i+1),k=-1,step=2,init=1+int(m/2)*i)] += (-1)**(i)*aRx_kz-1j*aRy_kz
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=3,step=2)] += -1*(-1)**(i)*aRx_kz+1j*aRy_kz
H[diagonal(int(m/2)*(i+1),init=int(m/2)*i,k=-3,step=2)] += -1*(-1)**(i)*aRx_kz-1j*aRy_kz
H[diagonal(m,k=int(m/2)+1,step=2)], H[diagonal(m,k=-int(m/2)-1,step=2)] = -np.conj(d), -d
H[diagonal(m,k=int(m/2)-1,step=2,init=1)], H[diagonal(m,k=-int(m/2)+1,step=2,init=1)] = np.conj(d), d
#Build it in momentum space if required:
if space=='momentum':
if sparse=='no':
H_k = np.zeros((int(m), int(m), int(n_k)),dtype=complex)
for i in range(n_k):
H_k[:,:,i] = H
for j in range(2):
H_k[diagonal(int(m/2)*(j+1),init=int(m/2)*j,k=m-2*Ny*Nz),i] = (-1*(-1)**(j)*tx-1j*aRy_kx)*np.exp(-1j*(-1)**(i)*k_vec[i]*Nx)
H_k[diagonal(int(m/2)*(j+1),init=int(m/2)*j,k=-m+2*Ny*Nz),i] = (-1*(-1)**(j)*tx+1j*aRy_kx)*np.exp(1j*(-1)**(i)*k_vec[i]*Nx)
H_k[diagonal(int(m/2)*(j+1),k=m-2*Ny*Nz-1,step=2,init=1+int(m/2)*j),i] += (-1)**(j)*(-aRz_kx)*np.exp(-1j*(-1)**(i)*k_vec[i]*Nx)
H_k[diagonal(int(m/2)*(j+1),k=-m+2*Ny*Nz+1,step=2,init=1+int(m/2)*j),i] += (-1)**(j)*(-aRz_kx)*np.exp(1j*(-1)**(i)*k_vec[i]*Nx)
H_k[diagonal(int(m/2)*(j+1),init=int(m/2)*j,k=m+1-2*Ny*Nz,step=2),i] += (-1)**(j)*(aRz_kx)*np.exp(-1j*(-1)**(i)*k_vec[i]*Nx)
H_k[diagonal(int(m/2)*(j+1),init=int(m/2)*j,k=-m-1+2*Ny*Nz,step=2),i] += (-1)**(j)*(aRz_kx)*np.exp(1j*(-1)**(i)*k_vec[i]*Nx)
return (H_k)
elif sparse=='yes':
return(H)
else:
return (H)
#%%
def LO_3D_builder_NoSC(N,dis,m_eff,mu,B,aR, space='position', k_vec=np.nan ,sparse='no'):
"""
3D Lutchy-Oreg Hamiltonian builder. It obtaines the Hamiltoninan for a 3D
Lutchy-Oreg chain with superconductivity.
Parameters
----------
N: arr
Number of sites in each direction.
dis: int or arr
Distance (in nm) between sites.
m_eff: int or arr
Effective mass. If it is a 3D array, each element is the on-site
effective mass.
mu: float or arr
Chemical potential. If it is a 3D array, each element is the
on-site chemical potential
B: float or arr
Zeeman splitting. If it is an array, each element is the Zeeman
splitting in each direction.
aR: float or arr
Rashba coupling.
-If aR is a float, aR is the Rashba coupling along the z-direction,
with the same value in every site.
-If aR is a 1D array with length=3, each element of the array is
the rashba coupling in each direction.
-If aR is an array of arrays (3 x N), each element of aR[i] is
a 3D array with the on-site Rashba couplings in the direction i.
space: {"position","momentum"}
Space in which the Hamiltonian is built. "position" means
real-space (r-space). In this case the boundary conditions are open.
On the other hand, "momentum" means reciprocal space (k-space). In
this case the built Hamiltonian corresponds to the Hamiltonian of
the unit cell, with periodic boundary conditions along the
x-direction.
k_vec: arr
If space=='momentum', k_vec is the (discretized) momentum vector,
usually in the First Brillouin Zone.
sparse: {"yes","no"}
Sparsety of the built Hamiltonian. "yes" builds a dok_sparse matrix,
while "no" builds a dense matrix.
Returns
-------
H: arr
Hamiltonian matrix.
"""
#Obtain the dimensions:
Nx, Ny, Nz = N[0], N[1], N[2]
if np.ndim(dis)==0:
dis_x, dis_y, dis_z = dis, dis, dis
else:
dis_x, dis_y, dis_z = dis[0], dis[1], dis[2]
m = 2 * Nx * Ny * Nz
#Make sure that the onsite parameters are arrays:
if np.isscalar(m_eff):
m_eff = m_eff * np.ones((Nx,Ny,Nz))
if np.isscalar(mu):
mu = mu * np.ones((Nx,Ny,Nz))
if np.isscalar(B):
Bx=B
By=0
Bz=0
Bx,By,Bz=Bx*np.ones(N),By*np.ones(N),Bz*np.ones(N)
elif np.ndim(B)==1 and len(B)==3:
Bx=B[0]
By=B[1]
Bz=B[2]
Bx,By,Bz=Bx*np.ones(N),By*np.ones(N),Bz*np.ones(N)
if np.ndim(aR)==0:
aRx=np.zeros((Nx,Ny,Nz))
aRy=np.zeros((Nx,Ny,Nz))
aRz=aR*np.ones((Nx,Ny,Nz))
elif np.ndim(aR)==1:
if len(aR)==3:
aRx=aR[0]* | np.ones((Nx,Ny,Nz)) | numpy.ones |
#!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
=============================================
fMRI: OpenfMRI.org data, FSL, ANTS, c3daffine
=============================================
A growing number of datasets are available on `OpenfMRI <http://openfmri.org>`_.
This script demonstrates how to use nipype to analyze a data set::
python fmri_ants_openfmri.py --datasetdir ds107
This workflow also requires 2mm subcortical templates that are available from
`MindBoggle <http://mindboggle.info/data.html>`_.
Specifically the 2mm version of the `MNI template <http://mindboggle.info/data/templates/atropos/OASIS-30_Atropos_template_in_MNI152_2mm.nii.gz>`_.
Import necessary modules from nipype.
"""
from __future__ import division, unicode_literals
from builtins import open, range, str, bytes
from glob import glob
import os
from nipype import config
from nipype import LooseVersion
from nipype import Workflow, Node, MapNode
from nipype.utils.filemanip import filename_to_list
import nipype.pipeline.engine as pe
import nipype.algorithms.modelgen as model
import nipype.algorithms.rapidart as ra
from nipype.algorithms.misc import TSNR, CalculateMedian
from nipype.interfaces.c3 import C3dAffineTool
from nipype.interfaces import fsl, Function, ants, freesurfer as fs
import nipype.interfaces.io as nio
from nipype.interfaces.io import FreeSurferSource
import nipype.interfaces.utility as niu
from nipype.interfaces.utility import Merge, IdentityInterface
from niflow.nipype1.workflows.fmri.fsl import (create_featreg_preproc,
create_modelfit_workflow,
create_fixed_effects_flow)
config.enable_provenance()
version = 0
if (fsl.Info.version()
and LooseVersion(fsl.Info.version()) > LooseVersion('5.0.6')):
version = 507
fsl.FSLCommand.set_default_output_type('NIFTI_GZ')
imports = ['import os',
'import nibabel as nb',
'import numpy as np',
'import scipy as sp',
'from nipype.utils.filemanip import filename_to_list, list_to_filename, split_filename',
'from scipy.special import legendre'
]
def create_reg_workflow(name='registration'):
"""Create a FEAT preprocessing workflow together with freesurfer
Parameters
----------
name : name of workflow (default: 'registration')
Inputs:
inputspec.source_files : files (filename or list of filenames to register)
inputspec.mean_image : reference image to use
inputspec.anatomical_image : anatomical image to coregister to
inputspec.target_image : registration target
Outputs:
outputspec.func2anat_transform : FLIRT transform
outputspec.anat2target_transform : FLIRT+FNIRT transform
outputspec.transformed_files : transformed files in target space
outputspec.transformed_mean : mean image in target space
Example
-------
See code below
"""
register = pe.Workflow(name=name)
inputnode = pe.Node(
interface=niu.IdentityInterface(fields=[
'source_files', 'mean_image', 'anatomical_image', 'target_image',
'target_image_brain', 'config_file'
]),
name='inputspec')
outputnode = pe.Node(
interface=niu.IdentityInterface(fields=[
'func2anat_transform', 'anat2target_transform',
'transformed_files', 'transformed_mean', 'anat2target',
'mean2anat_mask'
]),
name='outputspec')
"""
Estimate the tissue classes from the anatomical image. But use spm's segment
as FSL appears to be breaking.
"""
stripper = pe.Node(fsl.BET(), name='stripper')
register.connect(inputnode, 'anatomical_image', stripper, 'in_file')
fast = pe.Node(fsl.FAST(), name='fast')
register.connect(stripper, 'out_file', fast, 'in_files')
"""
Binarize the segmentation
"""
binarize = pe.Node(
fsl.ImageMaths(op_string='-nan -thr 0.5 -bin'), name='binarize')
pickindex = lambda x, i: x[i]
register.connect(fast, ('partial_volume_files', pickindex, 2), binarize,
'in_file')
"""
Calculate rigid transform from mean image to anatomical image
"""
mean2anat = pe.Node(fsl.FLIRT(), name='mean2anat')
mean2anat.inputs.dof = 6
register.connect(inputnode, 'mean_image', mean2anat, 'in_file')
register.connect(stripper, 'out_file', mean2anat, 'reference')
"""
Now use bbr cost function to improve the transform
"""
mean2anatbbr = pe.Node(fsl.FLIRT(), name='mean2anatbbr')
mean2anatbbr.inputs.dof = 6
mean2anatbbr.inputs.cost = 'bbr'
mean2anatbbr.inputs.schedule = os.path.join(
os.getenv('FSLDIR'), 'etc/flirtsch/bbr.sch')
register.connect(inputnode, 'mean_image', mean2anatbbr, 'in_file')
register.connect(binarize, 'out_file', mean2anatbbr, 'wm_seg')
register.connect(inputnode, 'anatomical_image', mean2anatbbr, 'reference')
register.connect(mean2anat, 'out_matrix_file', mean2anatbbr,
'in_matrix_file')
"""
Create a mask of the median image coregistered to the anatomical image
"""
mean2anat_mask = Node(fsl.BET(mask=True), name='mean2anat_mask')
register.connect(mean2anatbbr, 'out_file', mean2anat_mask, 'in_file')
"""
Convert the BBRegister transformation to ANTS ITK format
"""
convert2itk = pe.Node(C3dAffineTool(), name='convert2itk')
convert2itk.inputs.fsl2ras = True
convert2itk.inputs.itk_transform = True
register.connect(mean2anatbbr, 'out_matrix_file', convert2itk,
'transform_file')
register.connect(inputnode, 'mean_image', convert2itk, 'source_file')
register.connect(stripper, 'out_file', convert2itk, 'reference_file')
"""
Compute registration between the subject's structural and MNI template
* All parameters are set using the example from:
#https://github.com/stnava/ANTs/blob/master/Scripts/newAntsExample.sh
* This is currently set to perform a very quick registration. However,
the registration can be made significantly more accurate for cortical
structures by increasing the number of iterations.
"""
reg = pe.Node(ants.Registration(), name='antsRegister')
reg.inputs.output_transform_prefix = "output_"
reg.inputs.transforms = ['Rigid', 'Affine', 'SyN']
reg.inputs.transform_parameters = [(0.1, ), (0.1, ), (0.2, 3.0, 0.0)]
reg.inputs.number_of_iterations = [[10000, 11110, 11110]] * 2 + [[
100, 30, 20
]]
reg.inputs.dimension = 3
reg.inputs.write_composite_transform = True
reg.inputs.collapse_output_transforms = True
reg.inputs.initial_moving_transform_com = True
reg.inputs.metric = ['Mattes'] * 2 + [['Mattes', 'CC']]
reg.inputs.metric_weight = [1] * 2 + [[0.5, 0.5]]
reg.inputs.radius_or_number_of_bins = [32] * 2 + [[32, 4]]
reg.inputs.sampling_strategy = ['Regular'] * 2 + [[None, None]]
reg.inputs.sampling_percentage = [0.3] * 2 + [[None, None]]
reg.inputs.convergence_threshold = [1.e-8] * 2 + [-0.01]
reg.inputs.convergence_window_size = [20] * 2 + [5]
reg.inputs.smoothing_sigmas = [[4, 2, 1]] * 2 + [[1, 0.5, 0]]
reg.inputs.sigma_units = ['vox'] * 3
reg.inputs.shrink_factors = [[3, 2, 1]] * 2 + [[4, 2, 1]]
reg.inputs.use_estimate_learning_rate_once = [True] * 3
reg.inputs.use_histogram_matching = [False] * 2 + [True]
reg.inputs.winsorize_lower_quantile = 0.005
reg.inputs.winsorize_upper_quantile = 0.995
reg.inputs.args = '--float'
reg.inputs.output_warped_image = 'output_warped_image.nii.gz'
reg.inputs.num_threads = 4
reg.plugin_args = {
'qsub_args': '-pe orte 4',
'sbatch_args': '--mem=6G -c 4'
}
register.connect(stripper, 'out_file', reg, 'moving_image')
register.connect(inputnode, 'target_image_brain', reg, 'fixed_image')
"""
Concatenate the affine and ants transforms into a list
"""
merge = pe.Node(niu.Merge(2), iterfield=['in2'], name='mergexfm')
register.connect(convert2itk, 'itk_transform', merge, 'in2')
register.connect(reg, 'composite_transform', merge, 'in1')
"""
Transform the mean image. First to anatomical and then to target
"""
warpmean = pe.Node(ants.ApplyTransforms(), name='warpmean')
warpmean.inputs.input_image_type = 0
warpmean.inputs.interpolation = 'Linear'
warpmean.inputs.invert_transform_flags = [False, False]
warpmean.terminal_output = 'file'
register.connect(inputnode, 'target_image_brain', warpmean,
'reference_image')
register.connect(inputnode, 'mean_image', warpmean, 'input_image')
register.connect(merge, 'out', warpmean, 'transforms')
"""
Transform the remaining images. First to anatomical and then to target
"""
warpall = pe.MapNode(
ants.ApplyTransforms(), iterfield=['input_image'], name='warpall')
warpall.inputs.input_image_type = 0
warpall.inputs.interpolation = 'Linear'
warpall.inputs.invert_transform_flags = [False, False]
warpall.terminal_output = 'file'
register.connect(inputnode, 'target_image_brain', warpall,
'reference_image')
register.connect(inputnode, 'source_files', warpall, 'input_image')
register.connect(merge, 'out', warpall, 'transforms')
"""
Assign all the output files
"""
register.connect(reg, 'warped_image', outputnode, 'anat2target')
register.connect(warpmean, 'output_image', outputnode, 'transformed_mean')
register.connect(warpall, 'output_image', outputnode, 'transformed_files')
register.connect(mean2anatbbr, 'out_matrix_file', outputnode,
'func2anat_transform')
register.connect(mean2anat_mask, 'mask_file', outputnode, 'mean2anat_mask')
register.connect(reg, 'composite_transform', outputnode,
'anat2target_transform')
return register
def get_aparc_aseg(files):
"""Return the aparc+aseg.mgz file"""
for name in files:
if 'aparc+aseg.mgz' in name:
return name
raise ValueError('aparc+aseg.mgz not found')
def create_fs_reg_workflow(name='registration'):
"""Create a FEAT preprocessing workflow together with freesurfer
Parameters
----------
name : name of workflow (default: 'registration')
Inputs:
inputspec.source_files : files (filename or list of filenames to register)
inputspec.mean_image : reference image to use
inputspec.target_image : registration target
Outputs:
outputspec.func2anat_transform : FLIRT transform
outputspec.anat2target_transform : FLIRT+FNIRT transform
outputspec.transformed_files : transformed files in target space
outputspec.transformed_mean : mean image in target space
Example
-------
See code below
"""
register = Workflow(name=name)
inputnode = Node(
interface=IdentityInterface(fields=[
'source_files', 'mean_image', 'subject_id', 'subjects_dir',
'target_image'
]),
name='inputspec')
outputnode = Node(
interface=IdentityInterface(fields=[
'func2anat_transform', 'out_reg_file', 'anat2target_transform',
'transforms', 'transformed_mean', 'transformed_files',
'min_cost_file', 'anat2target', 'aparc', 'mean2anat_mask'
]),
name='outputspec')
# Get the subject's freesurfer source directory
fssource = Node(FreeSurferSource(), name='fssource')
fssource.run_without_submitting = True
register.connect(inputnode, 'subject_id', fssource, 'subject_id')
register.connect(inputnode, 'subjects_dir', fssource, 'subjects_dir')
convert = Node(freesurfer.MRIConvert(out_type='nii'), name="convert")
register.connect(fssource, 'T1', convert, 'in_file')
# Coregister the median to the surface
bbregister = Node(
freesurfer.BBRegister(registered_file=True), name='bbregister')
bbregister.inputs.init = 'fsl'
bbregister.inputs.contrast_type = 't2'
bbregister.inputs.out_fsl_file = True
bbregister.inputs.epi_mask = True
register.connect(inputnode, 'subject_id', bbregister, 'subject_id')
register.connect(inputnode, 'mean_image', bbregister, 'source_file')
register.connect(inputnode, 'subjects_dir', bbregister, 'subjects_dir')
# Create a mask of the median coregistered to the anatomical image
mean2anat_mask = Node(fsl.BET(mask=True), name='mean2anat_mask')
register.connect(bbregister, 'registered_file', mean2anat_mask, 'in_file')
"""
use aparc+aseg's brain mask
"""
binarize = Node(
fs.Binarize(min=0.5, out_type="nii.gz", dilate=1),
name="binarize_aparc")
register.connect(fssource, ("aparc_aseg", get_aparc_aseg), binarize,
"in_file")
stripper = Node(fsl.ApplyMask(), name='stripper')
register.connect(binarize, "binary_file", stripper, "mask_file")
register.connect(convert, 'out_file', stripper, 'in_file')
"""
Apply inverse transform to aparc file
"""
aparcxfm = Node(
freesurfer.ApplyVolTransform(inverse=True, interp='nearest'),
name='aparc_inverse_transform')
register.connect(inputnode, 'subjects_dir', aparcxfm, 'subjects_dir')
register.connect(bbregister, 'out_reg_file', aparcxfm, 'reg_file')
register.connect(fssource, ('aparc_aseg', get_aparc_aseg), aparcxfm,
'target_file')
register.connect(inputnode, 'mean_image', aparcxfm, 'source_file')
"""
Convert the BBRegister transformation to ANTS ITK format
"""
convert2itk = Node(C3dAffineTool(), name='convert2itk')
convert2itk.inputs.fsl2ras = True
convert2itk.inputs.itk_transform = True
register.connect(bbregister, 'out_fsl_file', convert2itk, 'transform_file')
register.connect(inputnode, 'mean_image', convert2itk, 'source_file')
register.connect(stripper, 'out_file', convert2itk, 'reference_file')
"""
Compute registration between the subject's structural and MNI template
* All parameters are set using the example from:
#https://github.com/stnava/ANTs/blob/master/Scripts/newAntsExample.sh
* This is currently set to perform a very quick registration. However,
the registration can be made significantly more accurate for cortical
structures by increasing the number of iterations.
"""
reg = Node(ants.Registration(), name='antsRegister')
reg.inputs.output_transform_prefix = "output_"
reg.inputs.transforms = ['Rigid', 'Affine', 'SyN']
reg.inputs.transform_parameters = [(0.1, ), (0.1, ), (0.2, 3.0, 0.0)]
reg.inputs.number_of_iterations = [[10000, 11110, 11110]] * 2 + [[
100, 30, 20
]]
reg.inputs.dimension = 3
reg.inputs.write_composite_transform = True
reg.inputs.collapse_output_transforms = True
reg.inputs.initial_moving_transform_com = True
reg.inputs.metric = ['Mattes'] * 2 + [['Mattes', 'CC']]
reg.inputs.metric_weight = [1] * 2 + [[0.5, 0.5]]
reg.inputs.radius_or_number_of_bins = [32] * 2 + [[32, 4]]
reg.inputs.sampling_strategy = ['Regular'] * 2 + [[None, None]]
reg.inputs.sampling_percentage = [0.3] * 2 + [[None, None]]
reg.inputs.convergence_threshold = [1.e-8] * 2 + [-0.01]
reg.inputs.convergence_window_size = [20] * 2 + [5]
reg.inputs.smoothing_sigmas = [[4, 2, 1]] * 2 + [[1, 0.5, 0]]
reg.inputs.sigma_units = ['vox'] * 3
reg.inputs.shrink_factors = [[3, 2, 1]] * 2 + [[4, 2, 1]]
reg.inputs.use_estimate_learning_rate_once = [True] * 3
reg.inputs.use_histogram_matching = [False] * 2 + [True]
reg.inputs.winsorize_lower_quantile = 0.005
reg.inputs.winsorize_upper_quantile = 0.995
reg.inputs.float = True
reg.inputs.output_warped_image = 'output_warped_image.nii.gz'
reg.inputs.num_threads = 4
reg.plugin_args = {
'qsub_args': '-pe orte 4',
'sbatch_args': '--mem=6G -c 4'
}
register.connect(stripper, 'out_file', reg, 'moving_image')
register.connect(inputnode, 'target_image', reg, 'fixed_image')
"""
Concatenate the affine and ants transforms into a list
"""
merge = Node(Merge(2), iterfield=['in2'], name='mergexfm')
register.connect(convert2itk, 'itk_transform', merge, 'in2')
register.connect(reg, 'composite_transform', merge, 'in1')
"""
Transform the mean image. First to anatomical and then to target
"""
warpmean = Node(ants.ApplyTransforms(), name='warpmean')
warpmean.inputs.input_image_type = 0
warpmean.inputs.interpolation = 'Linear'
warpmean.inputs.invert_transform_flags = [False, False]
warpmean.terminal_output = 'file'
warpmean.inputs.args = '--float'
# warpmean.inputs.num_threads = 4
# warpmean.plugin_args = {'sbatch_args': '--mem=4G -c 4'}
"""
Transform the remaining images. First to anatomical and then to target
"""
warpall = pe.MapNode(
ants.ApplyTransforms(), iterfield=['input_image'], name='warpall')
warpall.inputs.input_image_type = 0
warpall.inputs.interpolation = 'Linear'
warpall.inputs.invert_transform_flags = [False, False]
warpall.terminal_output = 'file'
warpall.inputs.args = '--float'
warpall.inputs.num_threads = 2
warpall.plugin_args = {'sbatch_args': '--mem=6G -c 2'}
"""
Assign all the output files
"""
register.connect(warpmean, 'output_image', outputnode, 'transformed_mean')
register.connect(warpall, 'output_image', outputnode, 'transformed_files')
register.connect(inputnode, 'target_image', warpmean, 'reference_image')
register.connect(inputnode, 'mean_image', warpmean, 'input_image')
register.connect(merge, 'out', warpmean, 'transforms')
register.connect(inputnode, 'target_image', warpall, 'reference_image')
register.connect(inputnode, 'source_files', warpall, 'input_image')
register.connect(merge, 'out', warpall, 'transforms')
"""
Assign all the output files
"""
register.connect(reg, 'warped_image', outputnode, 'anat2target')
register.connect(aparcxfm, 'transformed_file', outputnode, 'aparc')
register.connect(bbregister, 'out_fsl_file', outputnode,
'func2anat_transform')
register.connect(bbregister, 'out_reg_file', outputnode, 'out_reg_file')
register.connect(bbregister, 'min_cost_file', outputnode, 'min_cost_file')
register.connect(mean2anat_mask, 'mask_file', outputnode, 'mean2anat_mask')
register.connect(reg, 'composite_transform', outputnode,
'anat2target_transform')
register.connect(merge, 'out', outputnode, 'transforms')
return register
"""
Get info for a given subject
"""
def get_subjectinfo(subject_id, base_dir, task_id, model_id):
"""Get info for a given subject
Parameters
----------
subject_id : string
Subject identifier (e.g., sub001)
base_dir : string
Path to base directory of the dataset
task_id : int
Which task to process
model_id : int
Which model to process
Returns
-------
run_ids : list of ints
Run numbers
conds : list of str
Condition names
TR : float
Repetition time
"""
from glob import glob
import os
import numpy as np
condition_info = []
cond_file = os.path.join(base_dir, 'models', 'model%03d' % model_id,
'condition_key.txt')
with open(cond_file, 'rt') as fp:
for line in fp:
info = line.strip().split()
condition_info.append([info[0], info[1], ' '.join(info[2:])])
if len(condition_info) == 0:
raise ValueError('No condition info found in %s' % cond_file)
taskinfo = np.array(condition_info)
n_tasks = len(np.unique(taskinfo[:, 0]))
conds = []
run_ids = []
if task_id > n_tasks:
raise ValueError('Task id %d does not exist' % task_id)
for idx in range(n_tasks):
taskidx = np.where(taskinfo[:, 0] == 'task%03d' % (idx + 1))
conds.append([
condition.replace(' ', '_')
for condition in taskinfo[taskidx[0], 2]
]) # if 'junk' not in condition])
files = sorted(
glob(
os.path.join(base_dir, subject_id, 'BOLD',
'task%03d_run*' % (idx + 1))))
runs = [int(val[-3:]) for val in files]
run_ids.insert(idx, runs)
json_info = os.path.join(base_dir, subject_id, 'BOLD', 'task%03d_run%03d' %
(task_id,
run_ids[task_id - 1][0]), 'bold_scaninfo.json')
if os.path.exists(json_info):
import json
with open(json_info, 'rt') as fp:
data = json.load(fp)
TR = data['global']['const']['RepetitionTime'] / 1000.
else:
task_scan_key = os.path.join(
base_dir, subject_id, 'BOLD', 'task%03d_run%03d' %
(task_id, run_ids[task_id - 1][0]), 'scan_key.txt')
if os.path.exists(task_scan_key):
TR = np.genfromtxt(task_scan_key)[1]
else:
TR = np.genfromtxt(os.path.join(base_dir, 'scan_key.txt'))[1]
return run_ids[task_id - 1], conds[task_id - 1], TR
"""
Analyzes an open fmri dataset
"""
def analyze_openfmri_dataset(data_dir,
subject=None,
model_id=None,
task_id=None,
output_dir=None,
subj_prefix='*',
hpcutoff=120.,
use_derivatives=True,
fwhm=6.0,
subjects_dir=None,
target=None):
"""Analyzes an open fmri dataset
Parameters
----------
data_dir : str
Path to the base data directory
work_dir : str
Nipype working directory (defaults to cwd)
"""
"""
Load nipype workflows
"""
preproc = create_featreg_preproc(whichvol='first')
modelfit = create_modelfit_workflow()
fixed_fx = create_fixed_effects_flow()
if subjects_dir:
registration = create_fs_reg_workflow()
else:
registration = create_reg_workflow()
"""
Remove the plotting connection so that plot iterables don't propagate
to the model stage
"""
preproc.disconnect(
preproc.get_node('plot_motion'), 'out_file',
preproc.get_node('outputspec'), 'motion_plots')
"""
Set up openfmri data specific components
"""
subjects = sorted([
path.split(os.path.sep)[-1]
for path in glob(os.path.join(data_dir, subj_prefix))
])
infosource = pe.Node(
niu.IdentityInterface(fields=['subject_id', 'model_id', 'task_id']),
name='infosource')
if len(subject) == 0:
infosource.iterables = [('subject_id', subjects),
('model_id', [model_id]), ('task_id', task_id)]
else:
infosource.iterables = [('subject_id', [
subjects[subjects.index(subj)] for subj in subject
]), ('model_id', [model_id]), ('task_id', task_id)]
subjinfo = pe.Node(
niu.Function(
input_names=['subject_id', 'base_dir', 'task_id', 'model_id'],
output_names=['run_id', 'conds', 'TR'],
function=get_subjectinfo),
name='subjectinfo')
subjinfo.inputs.base_dir = data_dir
"""
Return data components as anat, bold and behav
"""
contrast_file = os.path.join(data_dir, 'models', 'model%03d' % model_id,
'task_contrasts.txt')
has_contrast = os.path.exists(contrast_file)
if has_contrast:
datasource = pe.Node(
nio.DataGrabber(
infields=['subject_id', 'run_id', 'task_id', 'model_id'],
outfields=['anat', 'bold', 'behav', 'contrasts']),
name='datasource')
else:
datasource = pe.Node(
nio.DataGrabber(
infields=['subject_id', 'run_id', 'task_id', 'model_id'],
outfields=['anat', 'bold', 'behav']),
name='datasource')
datasource.inputs.base_directory = data_dir
datasource.inputs.template = '*'
if has_contrast:
datasource.inputs.field_template = {
'anat': '%s/anatomy/T1_001.nii.gz',
'bold': '%s/BOLD/task%03d_r*/bold.nii.gz',
'behav': ('%s/model/model%03d/onsets/task%03d_'
'run%03d/cond*.txt'),
'contrasts': ('models/model%03d/'
'task_contrasts.txt')
}
datasource.inputs.template_args = {
'anat': [['subject_id']],
'bold': [['subject_id', 'task_id']],
'behav': [['subject_id', 'model_id', 'task_id', 'run_id']],
'contrasts': [['model_id']]
}
else:
datasource.inputs.field_template = {
'anat': '%s/anatomy/T1_001.nii.gz',
'bold': '%s/BOLD/task%03d_r*/bold.nii.gz',
'behav': ('%s/model/model%03d/onsets/task%03d_'
'run%03d/cond*.txt')
}
datasource.inputs.template_args = {
'anat': [['subject_id']],
'bold': [['subject_id', 'task_id']],
'behav': [['subject_id', 'model_id', 'task_id', 'run_id']]
}
datasource.inputs.sort_filelist = True
"""
Create meta workflow
"""
wf = pe.Workflow(name='openfmri')
wf.connect(infosource, 'subject_id', subjinfo, 'subject_id')
wf.connect(infosource, 'model_id', subjinfo, 'model_id')
wf.connect(infosource, 'task_id', subjinfo, 'task_id')
wf.connect(infosource, 'subject_id', datasource, 'subject_id')
wf.connect(infosource, 'model_id', datasource, 'model_id')
wf.connect(infosource, 'task_id', datasource, 'task_id')
wf.connect(subjinfo, 'run_id', datasource, 'run_id')
wf.connect([
(datasource, preproc, [('bold', 'inputspec.func')]),
])
def get_highpass(TR, hpcutoff):
return hpcutoff / (2. * TR)
gethighpass = pe.Node(
niu.Function(
input_names=['TR', 'hpcutoff'],
output_names=['highpass'],
function=get_highpass),
name='gethighpass')
wf.connect(subjinfo, 'TR', gethighpass, 'TR')
wf.connect(gethighpass, 'highpass', preproc, 'inputspec.highpass')
"""
Setup a basic set of contrasts, a t-test per condition
"""
def get_contrasts(contrast_file, task_id, conds):
import numpy as np
import os
contrast_def = []
if os.path.exists(contrast_file):
with open(contrast_file, 'rt') as fp:
contrast_def.extend([
np.array(row.split()) for row in fp.readlines()
if row.strip()
])
contrasts = []
for row in contrast_def:
if row[0] != 'task%03d' % task_id:
continue
con = [
row[1], 'T', ['cond%03d' % (i + 1) for i in range(len(conds))],
row[2:].astype(float).tolist()
]
contrasts.append(con)
# add auto contrasts for each column
for i, cond in enumerate(conds):
con = [cond, 'T', ['cond%03d' % (i + 1)], [1]]
contrasts.append(con)
return contrasts
contrastgen = pe.Node(
niu.Function(
input_names=['contrast_file', 'task_id', 'conds'],
output_names=['contrasts'],
function=get_contrasts),
name='contrastgen')
art = pe.MapNode(
interface=ra.ArtifactDetect(
use_differences=[True, False],
use_norm=True,
norm_threshold=1,
zintensity_threshold=3,
parameter_source='FSL',
mask_type='file'),
iterfield=['realigned_files', 'realignment_parameters', 'mask_file'],
name="art")
modelspec = pe.Node(interface=model.SpecifyModel(), name="modelspec")
modelspec.inputs.input_units = 'secs'
def check_behav_list(behav, run_id, conds):
import numpy as np
num_conds = len(conds)
if isinstance(behav, (str, bytes)):
behav = [behav]
behav_array = np.array(behav).flatten()
num_elements = behav_array.shape[0]
return behav_array.reshape(int(num_elements / num_conds),
num_conds).tolist()
reshape_behav = pe.Node(
niu.Function(
input_names=['behav', 'run_id', 'conds'],
output_names=['behav'],
function=check_behav_list),
name='reshape_behav')
wf.connect(subjinfo, 'TR', modelspec, 'time_repetition')
wf.connect(datasource, 'behav', reshape_behav, 'behav')
wf.connect(subjinfo, 'run_id', reshape_behav, 'run_id')
wf.connect(subjinfo, 'conds', reshape_behav, 'conds')
wf.connect(reshape_behav, 'behav', modelspec, 'event_files')
wf.connect(subjinfo, 'TR', modelfit, 'inputspec.interscan_interval')
wf.connect(subjinfo, 'conds', contrastgen, 'conds')
if has_contrast:
wf.connect(datasource, 'contrasts', contrastgen, 'contrast_file')
else:
contrastgen.inputs.contrast_file = ''
wf.connect(infosource, 'task_id', contrastgen, 'task_id')
wf.connect(contrastgen, 'contrasts', modelfit, 'inputspec.contrasts')
wf.connect([(preproc, art,
[('outputspec.motion_parameters', 'realignment_parameters'),
('outputspec.realigned_files',
'realigned_files'), ('outputspec.mask', 'mask_file')]),
(preproc, modelspec,
[('outputspec.highpassed_files', 'functional_runs'),
('outputspec.motion_parameters', 'realignment_parameters')]),
(art, modelspec,
[('outlier_files', 'outlier_files')]), (modelspec, modelfit, [
('session_info', 'inputspec.session_info')
]), (preproc, modelfit, [('outputspec.highpassed_files',
'inputspec.functional_data')])])
# Comute TSNR on realigned data regressing polynomials upto order 2
tsnr = MapNode(TSNR(regress_poly=2), iterfield=['in_file'], name='tsnr')
wf.connect(preproc, "outputspec.realigned_files", tsnr, "in_file")
# Compute the median image across runs
calc_median = Node(CalculateMedian(), name='median')
wf.connect(tsnr, 'detrended_file', calc_median, 'in_files')
"""
Reorder the copes so that now it combines across runs
"""
def sort_copes(copes, varcopes, contrasts):
import numpy as np
if not isinstance(copes, list):
copes = [copes]
varcopes = [varcopes]
num_copes = len(contrasts)
n_runs = len(copes)
all_copes = np.array(copes).flatten()
all_varcopes = | np.array(varcopes) | numpy.array |
#!/usr/bin/env python
# coding: utf-8
import argparse
import os
import pickle
import random
from tqdm import tqdm
import pandas as pd
import numpy as np
import torch
from gmm_tree import gmm_clustering
from transformers import AutoConfig, AutoModelWithLMHead
def main(save_dir, transformers_cache_dir, sample_cols):
model_name = 'bert-base-cased'
model = AutoModelWithLMHead.from_pretrained(
model_name,
from_tf=bool(".ckpt" in model_name),
config= AutoConfig.from_pretrained(
model_name, cache_dir=transformers_cache_dir),
cache_dir=transformers_cache_dir
)
corr_path = os.path.join(save_dir, 'corr_matrix.pkl')
if os.path.isfile(corr_path):
print('> loading the correlation matrix')
with open(corr_path, 'rb') as handle:
corr_df = pickle.load(handle)
else:
print('> building the correlation matrix')
corr_df = pd.DataFrame.corr(pd.DataFrame(model.cls.predictions.decoder.weight.cpu().detach().numpy().T))
with open(corr_path, 'wb') as handle:
pickle.dump(corr_df, handle, protocol=pickle.HIGHEST_PROTOCOL)
print(corr_df.shape)
print('> creating the trees')
n_trees = 50
n_partitions = 16
cuts = np.linspace(0, corr_df.shape[0], n_partitions + 1).astype(int)
idx = np.arange(corr_df.shape[0])
idx_dict = {}
pbar = tqdm(range(n_trees))
for i in pbar:
| np.random.shuffle(idx) | numpy.random.shuffle |
'''
Deep Learning for Data Science: Assignment 3
Submitted by: <NAME> (<EMAIL>)
Description - Generalize to k-layer Neural Network
- Implement Batch Normalization
- Implement moving average
- Training using mini batch Gradient Descent
'''
import numpy as np
from numpy import genfromtxt
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import random
from scipy.spatial import distance
from sklearn import preprocessing
import copy
import os
import pickle
class kLayerNN(object):
def __init__(self, filePath, GradCheckParams, GradDescentParams, NNParams):
if NNParams['loadAllBatches']:
# Call LoadBatch function to get training, validation and test set data
X1, Y1, y1 = self.LoadBatch(
filePath + '/Datasets/cifar-10-python/cifar-10-batches-py/data_batch_1')
X2, Y2, y2 = self.LoadBatch(
filePath + '/Datasets/cifar-10-python/cifar-10-batches-py/data_batch_2')
X3, Y3, y3 = self.LoadBatch(
filePath + '/Datasets/cifar-10-python/cifar-10-batches-py/data_batch_3')
X4, Y4, y4 = self.LoadBatch(
filePath + '/Datasets/cifar-10-python/cifar-10-batches-py/data_batch_4')
X5, Y5, y5 = self.LoadBatch(
filePath + '/Datasets/cifar-10-python/cifar-10-batches-py/data_batch_5')
X6, Y6, y6 = self.LoadBatch(
filePath + '/Datasets/cifar-10-python/cifar-10-batches-py/test_batch')
self.Xtrain = np.concatenate((X1, X2, X3, X4, X5[:, 0:9000]), axis=1)
self.Ytrain = np.concatenate((Y1, Y2, Y3, Y4, Y5[:, 0:9000]), axis=1)
self.ytrain = np.concatenate((y1, y2, y3, y4, y5[0:9000]))
self.Xval = X5[:, 9000:10000]
self.Yval = Y5[:, 9000:10000]
self.yval = y5[9000:10000]
self.Xtest = X6
self.Ytest = Y6
self.ytest = y6
else:
# Call LoadBatch function to get training, validation and test set data
self.Xtrain, self.Ytrain, self.ytrain = self.LoadBatch(filePath +
'/Datasets/cifar-10-python/cifar-10-batches-py/data_batch_1')
self.Xval, self.Yval, self.yval = self.LoadBatch(filePath +
'/Datasets/cifar-10-python/cifar-10-batches-py/data_batch_2')
self.Xtest, self.Ytest, self.ytest = self.LoadBatch(filePath +
'/Datasets/cifar-10-python/cifar-10-batches-py/test_batch')
# Normalize Data by subtracting mean
self.ZeroMean()
# Assign all GradCheckParams
self.h = GradCheckParams['h']
self.eps = GradCheckParams['eps']
self.tol1 = GradCheckParams['tol1']
# Assign all GradDescentParams
self.sigma = GradDescentParams['sigma']
self.eta = GradDescentParams['eta']
self.lmbda = GradDescentParams['lmbda']
self.rho = GradDescentParams['rho']
self.nEpoch = GradDescentParams['nEpoch']
self.nBatch = GradDescentParams['nBatch']
#self.BatchSize = round(self.Xtrain.shape[1]/self.nBatch)
self.epsilon = GradDescentParams['epsilon']
self.alpha = GradDescentParams['alpha']
# Assign all NNParams
self.d = NNParams['d']
self.k = NNParams['k']
self.n = NNParams['n']
self.m = NNParams['m']
self.nLayers = len(self.m) + 1
self.batchNorm = NNParams['batchNorm']
# Initialize Weights
self.InitializeWeightAndBias('Gaussian')
# Initialize mu_avg and var_avg for exponential moving average
self.mu_avg = [np.zeros_like(self.b[i]) for i in range(1,self.nLayers)]
self.var_avg = [np.zeros_like(self.b[i]) for i in range(1,self.nLayers)]
def unpickle(self, file):
'''
Function: unpickle
Input: file name
Output: data in form of dictionary
'''
with open(file, 'rb') as fo:
dict = pickle.load(fo, encoding='bytes')
return dict
def LoadBatch(self, fileName):
'''
Function: LoadBatch
Input: path to a file
Output: Images (X), labels (y) and one-hot encoding (Y)
'''
dict = self.unpickle(fileName)
X = np.array(dict[b'data']/255)
y = np.array(dict[b'labels'])
binarizer = preprocessing.LabelBinarizer()
binarizer.fit(range(max(y.astype(int)) + 1))
Y1 = np.array(binarizer.transform(y.astype(int))).T
return np.transpose(X), np.transpose(Y1.T), y
def ZeroMean(self):
mean_Xtrain = np.reshape(np.mean(self.Xtrain, 1), (-1, 1))
self.Xtrain -= mean_Xtrain
self.Xval -= mean_Xtrain
self.Xtest -= mean_Xtrain
def InitializeWeightAndBias(self, type='Gaussian'):
'''
Input: Type of weights. Possible choices: Gaussian, Javier, He
Output: W and b; both are lists
'''
if type == 'Gaussian':
np.random.seed(400)
self.W = []
self.W.append([])
self.b = []
self.b.append([])
self.W.append(np.random.randn(
list(self.m)[0], self.d) * self.sigma)
self.b.append(np.zeros((list(self.m)[0], 1)))
for i in range(self.nLayers - 2):
self.W.append(np.random.randn(
self.m[i+1], self.m[i]) * self.sigma)
self.b.append(np.zeros((self.m[i+1], 1)))
self.W.append(np.random.randn(
self.k, list(self.m)[-1]) * self.sigma)
self.b.append(np.zeros((self.k, 1)))
# FUTURE: Add other initializations
def BatchNormalize(self, s, mu, var):
V = np.array([var + self.epsilon])
Vinv0_5 = V**-0.5
sHat = np.multiply((s-mu), Vinv0_5.T)
return sHat
def BatchNormBackPass(self, dJdsHat, s, mu, var):
'''
Input: g (dJ/dsHat), s, mu, var
Output: g (dJ/ds)
Comments: Refer to last slide of Lec 4
'''
N = dJdsHat.shape[0]
V = np.array([var + self.epsilon])
Vinv1_5 = V**-1.5
dJdvar = -0.5 * np.sum(np.multiply(np.multiply(dJdsHat, Vinv1_5),(s-mu).T), axis = 0)
Vinv0_5 = V**-0.5
dJdmu = - np.sum(np.multiply(dJdsHat, Vinv0_5), axis = 0)
dJds = np.multiply(dJdsHat, Vinv0_5) + 2/N * np.multiply(dJdvar, (s-mu).T) + dJdmu/N
return dJds
def EvaluateClassifier2(self, x, Wt, bias):
N = x.shape[1]
if x.ndim == 1:
x = np.reshape(x, (-1, 1))
h = []
s = []
sHat = []
mu = []
var = []
mu.append([])
var.append([])
h.append(x)
s.append([])
sHat.append([])
for i in range(self.nLayers-1):
s.append(np.dot(Wt[i+1], h[i]) + bias[i+1])
# calculate mu and variance
mu.append(np.reshape(np.mean(s[i+1], axis = 1), (-1, 1)))
# var.append(np.reshape(np.sum(((s[i+1]-mu[i+1])**2), 1)/N, (-1, 1))) #DIAG OF THIS IS SCALAR!!!
# DIAG OF THIS IS SQUARE MATRIX!!!
var.append(np.sum(((s[i+1]-mu[i+1])**2), 1)/N)
# Exponential Moving Average
# temp_var = 0
# for j in range(self.nLayers):
# if self.mu_avg[j].all() == 0:
# temp_var = temp_var + 1
if self.mu_avg[i].all() == 0:
# all elements are zero, so this is first ever evaluation step
self.mu_avg[i] = mu[i+1]
self.var_avg[i] = var[i+1]
else:
self.mu_avg[i] = self.alpha * self.mu_avg[i] + (1 - self.alpha) * mu[i+1]
self.var_avg[i] = self.alpha * self.var_avg[i] + (1 - self.alpha) * var[i+1]
sHat.append(self.BatchNormalize(s[i+1], mu[i+1], var[i+1]))
if self.batchNorm:
h.append(np.maximum(0, sHat[i+1])) ###CHANGE TO sHat
else:
h.append(np.maximum(0, s[i+1]))
# for final layer:
s.append(np.dot(Wt[self.nLayers],
h[self.nLayers-1]) + bias[self.nLayers])
# compute softmax function of s
p = np.exp(s[self.nLayers])
p = p / np.sum(p, axis=0)
return p, s, sHat, h, mu, var
def ComputeCost2(self, X, Y, Wt, bias):
N = X.shape[1]
p, _, _, _, _, _ = self.EvaluateClassifier2(X, Wt, bias)
A = np.diag(np.dot(Y.T, p))
B = -np.log(A)
C = np.sum(B)
Sum = 0
for i in range(self.nLayers):
Sum += np.sum(np.square(Wt[i]))
#D = self.lmbda * (np.sum(np.square(Wt[0]))+np.sum(np.square(Wt[1])))
D = self.lmbda * Sum
J = C/N + D
# J = (np.sum(-np.log(np.dot(Y.T, p))))/M + lmbda * np.sum(np.square(W))
return J
def ComputeAccuracy2(self, X, y, Wt, bias):
N = X.shape[1]
p, _, _, _, _, _ = self.EvaluateClassifier2(X, Wt, bias)
k = np.argmax(p, axis=0)
a = np.where((k.T - y) == 0, 1, 0)
acc = sum(a)/N
return acc
def PerformanceEval(self, grad_W, grad_b, numgrad_W, numgrad_b):
'''Method 2: Check absolute difference'''
# Layer 1
abs_W = []
abs_b = []
for i in range(self.nLayers):
abs_W.append(abs(np.array(grad_W[i+1]) - np.array(numgrad_W[i+1])))
abs_b.append(abs(np.array(grad_b[i+1]) - np.array(numgrad_b[i+1])))
'''Method 1: check if relative error is small'''
# Layer1
rel_W = []
rel_b = []
for i in range(self.nLayers):
rel_W.append(np.divide(abs(grad_W[i+1] - numgrad_W[i+1]),
max(self.eps, (abs(grad_W[i+1]) + abs(numgrad_W[i+1])).all())))
rel_b.append(np.divide(abs(grad_b[i+1] - numgrad_b[i+1]),
max(self.eps, (abs(grad_b[i+1]) + abs(numgrad_b[i+1])).all())))
avg_abs_W = np.zeros(self.nLayers)
avg_abs_b = np.zeros(self.nLayers)
avg_rel_W = np.zeros(self.nLayers)
avg_rel_b = np.zeros(self.nLayers)
for k in range(self.nLayers):
avg_abs_W[k] = np.mean(abs_W[k])
avg_abs_b[k] = np.mean(abs_b[k])
avg_rel_W[k] = np.mean(rel_W[k])
avg_rel_b[k] = np.mean(rel_b[k])
return np.mean(avg_abs_W), np.mean(avg_abs_b), np.mean(avg_rel_W), np.mean(avg_rel_b)
def ComputeGradients(self, X, Y, Wt, bias):
N = X.shape[1]
grad_W = []
grad_W.append([])
grad_b = []
grad_b.append([])
grad_W.append(np.zeros((list(self.m)[0], Wt[1].shape[1])))
grad_b.append(np.zeros((list(self.m)[0], 1)))
for i in range(self.nLayers - 2):
grad_W.append(np.zeros((list(self.m)[i], list(self.m)[i+1])))
grad_b.append(np.zeros((list(self.m)[i+1], 1)))
grad_W.append(np.zeros((self.k, list(self.m)[-1])))
grad_b.append(np.zeros((self.k, 1)))
# Forward Pass
p, s, sHat, h, mu, var = self.EvaluateClassifier2(X, Wt, bias)
# Backward Pass
# gradients for last layer
g = - (Y - p).T
grad_b[self.nLayers] = np.sum(g.T, 1)/N
grad_b[self.nLayers] = np.reshape(grad_b[self.nLayers], (-1, 1))
grad_W[self.nLayers] = (
np.dot(g.T, h[self.nLayers-1].T))/N + 2 * self.lmbda * Wt[self.nLayers]
# Propogate gradient vector gi to previous layer:
g = np.dot(g, Wt[self.nLayers])
if self.batchNorm:
### CHANGE s to sHat
sTemp = np.where(sHat[self.nLayers-1] > 0, 1, 0)
else:
sTemp = np.where(s[self.nLayers-1] > 0, 1, 0)
'''
THERE IS AN ERROR IN ASSIGNMENT NOTES: ref eq 22 on page 4.
instead of
g_i * diag(Ind(ŝ_i(k-1)> 0))
it was
g_i * Ind(ŝ_i(k-1)> 0)
which finally gave convergence of analytical and numerical
gradients. I wasted at least 50 hours on finding out this bug!!
'''
# if g.shape[0] < self.m[self.nLayers-2]:
# g = np.multiply(g, np.reshape(np.diag(sTemp), (-1, 1)))
# else:
# g = np.multiply(g, np.diag(sTemp))
if g.shape[0] < self.m[self.nLayers-2]:
g = np.multiply(g, np.reshape(np.diag(sTemp), (-1, 1)))
else:
g = np.multiply(g, sTemp.T)
for i in range(self.nLayers-1, 0, -1):
if self.batchNorm:
### UNCOMMENT THIS LINE IF NOT BATCH NORM
g = self.BatchNormBackPass(g, s[i], mu[i], var[i])
grad_b[i] = | np.sum(g.T, 1) | numpy.sum |
#
# LAMMPS.py
#
# Interface to LAMMPS (http://lammps.sandia.gov)
#
# Copyright (c) 2017 <NAME>
#
# This file is distributed under the terms of the MIT license.
# Please see the file 'LICENCE.txt' in the root directory
# or http://opensource.org/licenses/mit-license.php for information.
#
import numpy as np
def read_lammps_structure(file_in):
f = open(file_in, 'r')
header_comment = f.readline()
common_settings = []
for line in f:
if "Atoms" in line:
break
common_settings.append(line.rstrip())
atoms = []
for line in f:
if line.strip():
atoms.append(line.rstrip().split())
atoms = np.array(atoms)
nat = len(atoms)
kd = np.array(atoms[:, 1], dtype=np.int)
x = np.array(atoms[:, 2:5], dtype=np.float64)
return common_settings, nat, x, kd
def write_lammps_structure(prefix, counter, header, nzerofills,
common_settings, nat, kd, x_cart, disp):
filename = prefix + str(counter).zfill(nzerofills) + ".lammps"
f = open(filename, 'w')
f.write("%s\n" % header)
for line in common_settings:
f.write("%s\n" % line)
f.write("%s\n\n" % "Atoms")
for i in range(nat):
f.write("%5d %3d" % (i + 1, kd[i]))
for j in range(3):
f.write("%20.15f" % (x_cart[i][j] + disp[i][j]))
f.write("\n")
f.write("\n")
f.close()
def get_coordinate_LAMMPS(lammps_dump_file):
add_flag = False
coord = []
with open(lammps_dump_file) as f:
for line in f:
if "ITEM:" in line and "ITEM: ATOMS id xu yu zu" not in line:
add_flag = False
continue
elif "ITEM: ATOMS id xu yu zu" in line:
add_flag = True
continue
if add_flag:
if line.strip():
entries = line.strip().split()
coord_atom = [int(entries[0]),
[float(t) for t in entries[1:]]]
coord.append(coord_atom)
# This sort is necessary since the order atoms of LAMMPS dump files
# may change from the input structure file.
coord_sorted = sorted(coord)
coord = []
for coord_atom in coord_sorted:
coord.extend(coord_atom[1])
return np.array(coord)
def get_atomicforces_LAMMPS(lammps_dump_file):
add_flag = False
force = []
with open(lammps_dump_file) as f:
for line in f:
if "ITEM:" in line and "ITEM: ATOMS id fx fy fz " not in line:
add_flag = False
continue
elif "ITEM: ATOMS id fx fy fz " in line:
add_flag = True
continue
if add_flag:
if line.strip():
entries = line.strip().split()
force_atom = [int(entries[0]),
[float(t) for t in entries[1:]]]
force.append(force_atom)
force_sorted = sorted(force)
force = []
for force_atom in force_sorted:
force.extend(force_atom[1])
return np.array(force)
def get_coordinate_and_force_LAMMPS(lammps_dump_file):
add_flag = False
ret = []
with open(lammps_dump_file) as f:
for line in f:
if "ITEM:" in line and "ITEM: ATOMS id xu yu zu fx fy fz" not in line:
add_flag = False
continue
elif "ITEM: ATOMS id xu yu zu fx fy fz" in line:
add_flag = True
continue
if add_flag:
if line.strip():
entries = line.strip().split()
data_atom = [int(entries[0]),
[float(t) for t in entries[1:4]],
[float(t) for t in entries[4:]]]
ret.append(data_atom)
# This sort is necessary since the order atoms of LAMMPS dump files
# may change from the input structure file.
ret_sorted = sorted(ret)
ret_x = []
ret_f = []
for ret_atom in ret_sorted:
ret_x.extend(ret_atom[1])
ret_f.extend(ret_atom[2])
return np.array(ret_x), np.array(ret_f)
def print_displacements_LAMMPS(lammps_files, nat, x_cart0,
conversion_factor, file_offset):
if file_offset is None:
disp_offset = np.zeros((nat, 3))
else:
_, nat_tmp, x0_offset, _ = read_lammps_structure(file_offset)
if nat_tmp != nat:
print("File %s contains too many/few position entries"
% file_offset)
disp_offset = x0_offset - x_cart0
# Automatic detection of the input format
is_dumped_file = False
f = open(lammps_files[0], 'r')
for line in f:
if "ITEM: TIMESTEP" in line:
is_dumped_file = True
break
f.close()
if is_dumped_file:
# This version supports reading the data from MD trajectory
for search_target in lammps_files:
x = get_coordinate_LAMMPS(search_target)
ndata = len(x) // (3 * nat)
x = np.reshape(x, (ndata, nat, 3))
for idata in range(ndata):
disp = x[idata, :, :] - x_cart0 - disp_offset
disp *= conversion_factor
for i in range(nat):
print("%20.14f %20.14f %20.14f" % (disp[i, 0],
disp[i, 1],
disp[i, 2]))
else:
for search_target in lammps_files:
_, nat_tmp, x_cart, _ = read_lammps_structure(search_target)
if nat_tmp != nat:
print("File %s contains too many/few position entries" %
search_target)
disp = x_cart - x_cart0 - disp_offset
disp *= conversion_factor
for i in range(nat):
print("%20.14f %20.14f %20.14f" % (disp[i, 0],
disp[i, 1],
disp[i, 2]))
def print_atomicforces_LAMMPS(lammps_files, nat,
conversion_factor, file_offset):
if file_offset is None:
force_offset = np.zeros((nat, 3))
else:
data = get_atomicforces_LAMMPS(file_offset)
try:
force_offset = np.reshape(data, (nat, 3))
except:
print("File %s contains too many position entries" % file_offset)
# Automatic detection of the input format
is_dumped_file = False
f = open(lammps_files[0], 'r')
for line in f:
if "ITEM: TIMESTEP" in line:
is_dumped_file = True
break
f.close()
for search_target in lammps_files:
force = get_atomicforces_LAMMPS(search_target)
ndata = len(force) // (3 * nat)
force = np.reshape(force, (ndata, nat, 3))
for idata in range(ndata):
f = force[idata, :, :] - force_offset
f *= conversion_factor
for i in range(nat):
print("%19.11E %19.11E %19.11E" % (f[i][0], f[i][1], f[i][2]))
def print_displacements_and_forces_LAMMPS(lammps_files, nat,
x_cart0,
conversion_factor_disp,
conversion_factor_force,
file_offset):
if file_offset is None:
disp_offset = np.zeros((nat, 3))
force_offset = np.zeros((nat, 3))
else:
x0_offset, force_offset = get_coordinate_and_force_LAMMPS(file_offset)
try:
x0_offset = np.reshape(x0_offset, (nat, 3))
force_offset = | np.reshape(force_offset, (nat, 3)) | numpy.reshape |
import pandas as pd
import numpy as np
def _calc_class_accuracy(y_true=None, y_pred=None):
""" this is the name used for balanced accuracy where the
average of the accuracys of all respective classes is taken. This is used
to counter imbalanced datasets.
Returns
-------
float
the accuracy
array k dim
accuracy of each class
"""
self._model_metrics = True
from sklearn.metrics import confusion_matrix
state_count = self._model.K
lbls = np.arange(0, state_count)
# a_ij, observations to be in class i, but are predicted to be in class j
conf_mat = confusion_matrix(y_true, y_pred, labels=lbls) # type: np.ndarray
K, _ = conf_mat.shape
total = conf_mat.sum()
overall_tpr = conf_mat.diagonal().sum()/total
class_accs = np.zeros((K), dtype=np.float64)
for k in range(K):
kth_col_sum = conf_mat[:,k].sum()
kth_row_sum = conf_mat[k,:].sum()
# true alarm, it is true and i say true
tp = conf_mat[k][k]
# it is true but i say false
tn = kth_row_sum - conf_mat[k][k]
# false alarm, it is false but i say true
fp = kth_row_sum - conf_mat[k][k]
assert fp >= 0 and tp >= 0 and tn >= 0
# it is false and i say false
fn = total - (kth_row_sum + kth_col_sum - conf_mat[k][k])
class_accs[k] = (tp + tn) / (fp + fn + tn + tp)
class_acc = class_accs.sum()/K
return class_acc, class_accs
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.ticker as ticker
def time2numeric_day(time, res='1ms'):
""" maps a time to a numeric value for a day
"""
diff = time - time.floor('d')
return int(diff/pd.Timedelta(res))
def create_y(tmp2, t_res='ms'):
"""
Parameters
----------
tmp2 : pd.DataFrame
dataframe with timestamp index and one column for the predictions
t_res: String
string specifying the sampling rate
"""
assert t_res in ['ms', 's', 'h', 'min']
tmp = tmp2.copy()
col_name = tmp.columns[0]
# create start and end
last_row = pd.Series(data={col_name : tmp.iloc[-1,:][col_name]},
name=tmp.iloc[-1,:].name.ceil('d'))
first_row = pd.Series(data={col_name : np.nan},
name=tmp.iloc[-1,:].name.floor('d'))
tmp = tmp.append(first_row)
tmp = tmp.append(last_row)
tmp = tmp.resample(t_res).ffill()
return tmp
def create_cmap(cmap, n=20):
assert n <= 20
new_colors = cmap(np.arange(0, n))
new_cmap = colors.ListedColormap(new_colors)
return new_cmap
def plot_true_vs_inf_y(enc_lbl, y_true, y_pred, index=None):
"""
Parameters
----------
enc_lbl: scikit learn model
y_true: pd.DataFrame
time index and activity labels
y_pred: array like
activity labels
Returns
-------
"""
assert len(y_true) == len(y_pred)
assert isinstance(y_true, pd.Series)
assert isinstance(y_pred, np.ndarray)
if isinstance(y_pred[0], str):
y_pred_vals = enc_lbl.transform(y_pred)
elif isinstance(y_pred[0], float) or isinstance(y_pred[0], int) \
or isinstance(y_pred[0], np.int64):
y_pred_vals = y_pred
else:
print(y_pred[0])
print(type(y_pred[0]))
raise ValueError
if isinstance(y_true.iloc[0], str):
y_true_vals = enc_lbl.transform(y_true.values)
elif isinstance(y_true.iloc[0]):
y_true_vals = y_true.values
else:
raise ValueError
title = 'True vs. inferred labels'
# Plot the true and inferred discrete states
n_classes = len(enc_lbl._lbl_enc.classes_)
if index is not None:
df_ypred = pd.DataFrame(data=y_pred_vals, index=index, columns=['y_pred'])
df_ypred = create_y(df_ypred, t_res='s')
df_ytrue = pd.DataFrame(data=y_true_vals, index=index, columns=['y_true'])
df_ytrue = create_y(df_ytrue, t_res='s')
# plot
fig, axs = plt.subplots(2, figsize=(15, 5))
cmap = create_cmap(plt.get_cmap("tab20"), n_classes-1)
axs[0].imshow(df_ytrue.T.values,
aspect="auto",
interpolation='none',
cmap=cmap,
vmin=0,
vmax=n_classes-1)
axs[0].set_ylabel("$y_{\\mathrm{true}}$")
axs[0].set_yticks([])
axs[0].set_xticks([])
im = axs[1].imshow(df_ypred.T,
aspect="auto",
interpolation='none',
cmap=cmap,
vmin=0,
vmax=n_classes-1)
axs[1].set_ylabel("$y_{\\mathrm{pred}}$")
axs[1].set_yticks([])
# format the colorbar
def formatter_func(x, pos):
'The two args are the value and tick position'
val = val_lookup[x]
return val
ticks = np.arange(n_classes)
val_lookup = dict(zip(ticks,
enc_lbl.inverse_transform(ticks)))
formatter = plt.FuncFormatter(formatter_func)
fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
fig.colorbar(im, cax=cbar_ax, ticks=ticks, format=formatter)
im.set_clim(-0.5, n_classes-1.5)
# format the x-axis
def func(x,p):
if True:
if int(x/k) < 10:
return '0{}:00'.format(int(x/k)+1)
else:
return '{}:00'.format(int(x/k)+1)
# calculate the tick positions for lower image
a,b = axs[1].get_xlim()
k = (b-a)/24
tcks_pos = np.arange(0,24)*k + (-0.5 + k)
x_locator = ticker.FixedLocator(tcks_pos)
axs[1].xaxis.set_major_formatter(ticker.FuncFormatter(func))
axs[1].xaxis.set_major_locator(x_locator)
axs[1].set_aspect(aspect='auto')
axs[1].tick_params(labelrotation=45)
fig.suptitle(title)
plt.show()
else:
# just plot the sequences after another and ignore time information
fig, axs = plt.subplots(2, figsize=(15, 5))
cmap = create_cmap(plt.get_cmap("tab20"), n_classes-1)
y_true_vals = np.expand_dims(y_true_vals, axis=1)
y_pred_vals = np.expand_dims(y_pred_vals, axis=1)
axs[0].imshow(y_true_vals.T,
aspect="auto",
interpolation='none',
cmap=cmap,
vmin=0,
vmax=n_classes-1)
axs[0].set_ylabel("$y_{\\mathrm{true}}$")
axs[0].set_yticks([])
axs[0].set_xticks([])
im = axs[1].imshow(y_pred_vals.T,
aspect="auto",
interpolation='none',
cmap=cmap,
vmin=0,
vmax=n_classes-1)
axs[1].set_ylabel("$y_{\\mathrm{pred}}$")
axs[1].set_yticks([])
# format the colorbar
def formatter_func(x, pos):
'The two args are the value and tick position'
val = val_lookup[x]
return val
ticks = | np.arange(n_classes) | numpy.arange |
from __future__ import print_function
import numpy as np
import astropy.convolution
__all__ = ['shiftnd', 'cross_correlation_shifts']
try:
import fftw3
has_fftw = True
def fftwn(array, nthreads=1):
array = array.astype('complex').copy()
outarray = array.copy()
fft_forward = fftw3.Plan(array, outarray, direction='forward',
flags=['estimate'], nthreads=nthreads)
fft_forward.execute()
return outarray
def ifftwn(array, nthreads=1):
array = array.astype('complex').copy()
outarray = array.copy()
fft_backward = fftw3.Plan(array, outarray, direction='backward',
flags=['estimate'], nthreads=nthreads)
fft_backward.execute()
return outarray / np.size(array)
except ImportError:
fftn = np.fft.fftn
ifftn = np.fft.ifftn
has_fftw = False
# I performed some fft speed tests and found that scipy is slower than numpy
# http://code.google.com/p/agpy/source/browse/trunk/tests/test_ffts.py However,
# the speed varied on machines - YMMV. If someone finds that scipy's fft is
# faster, we should add that as an option here... not sure how exactly
def get_ffts(nthreads=1, use_numpy_fft=not has_fftw):
"""
Returns fftn,ifftn using either numpy's fft or fftw
"""
if has_fftw and not use_numpy_fft:
def fftn(*args, **kwargs):
return fftwn(*args, nthreads=nthreads, **kwargs)
def ifftn(*args, **kwargs):
return ifftwn(*args, nthreads=nthreads, **kwargs)
elif use_numpy_fft:
fftn = np.fft.fftn
ifftn = np.fft.ifftn
else:
# yes, this is redundant, but I feel like there could be a third option...
fftn = np.fft.fftn
ifftn = np.fft.ifftn
return fftn,ifftn
def shiftnd(data, offset, phase=0, nthreads=1, use_numpy_fft=False,
return_abs=False, return_real=True):
"""
FFT-based sub-pixel image shift.
Will turn NaNs into zeros
Shift Theorem:
.. math::
FT[f(t-t_0)](x) = e^{-2 \pi i x t_0} F(x)
Parameters
----------
data : np.ndarray
Data to shift
offset : (int,)*ndim
Offsets in each direction. Must be iterable.
phase : float
Phase, in radians
Other Parameters
----------------
use_numpy_fft : bool
Force use numpy's fft over fftw? (only matters if you have fftw
installed)
nthreads : bool
Number of threads to use for fft (only matters if you have fftw
installed)
return_real : bool
Return the real component of the shifted array
return_abs : bool
Return the absolute value of the shifted array
Returns
-------
The input array shifted by offsets
"""
fftn,ifftn = get_ffts(nthreads=nthreads, use_numpy_fft=use_numpy_fft)
if np.any(np.isnan(data)):
data = np.nan_to_num(data)
freq_grid = np.sum(
[off* | np.fft.fftfreq(nx) | numpy.fft.fftfreq |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""Python wrapper for synspec
Calculation of synthetic spectra of stars and convolution with a rotational/Gaussian kernel.
Makes the use of synspec simpler, and retains the main functionalities (when used from
python). The command line interface is even simpler but fairly limited.
For information on
synspec visit http://nova.astro.umd.edu/Synspec43/synspec.html.
Example
-------
To compute the solar spectrum between 6160 and 6164 angstroms, using a model atmosphere in
the file sun.mod (provided with the distribution), with the output going into the file
sun.syn
$synple.py sun.mod 6160. 6164.
To force a micro of 1.1 km/s, and convolve the spectrum with a Gaussian kernel with a fwhm
of 0.1 angstroms
$synple.py sun.mod 6160. 6164. 1.1 0.1
To perform the calculations above in python and compare the emergent normalized profiles
>>> from synple import syn
>>> x, y, z = syn('sun.mod', (6160.,6164.))
>>> x2, y2, z2 = syn('sun.mod', (6160.,6164.), vmicro=1.1, fwhm=0.1)
in plain python
>>> import matplotlib.pyplot as plt
>>> plt.ion()
>>> plt.plot(x,y/z, x2, y2/z2)
or ipython
In [1]: %pylab
In [2]: plot(x,y/z, x2, y2/z2)
"""
import os
import sys
import subprocess
import numpy as np
import glob
import time
import copy
import gzip
from scipy import interpolate
import matplotlib.pyplot as plt
from itertools import product
#configuration
#synpledir = /home/callende/synple
synpledir = os.path.dirname(os.path.realpath(__file__))
#relative paths
modeldir = synpledir + "/models"
modelatomdir = synpledir + "/data"
linelistdir = synpledir + "/linelists"
bindir = synpledir + "/bin"
synspec = bindir + "/s54d"
rotin = bindir + "/rotin3"
#other stuff
clight = 299792.458
epsilon = 0.6 #clv coeff.
bolk = 1.38054e-16 # erg/ K
zero = " 0 "
one = " 1 "
two = " 2 "
def syn(modelfile, wrange, dw=None, strength=1e-4, vmicro=None, abu=None, \
linelist=['gfallx3_bpo.19','kmol3_0.01_30.20'], atom='ap18', vrot=0.0, fwhm=0.0, \
steprot=0.0, stepfwhm=0.0, clean=True, save=False, synfile=None,
compute=True, tmpdir=None):
"""Computes a synthetic spectrum
Interface to the fortran codes synspec/rotin that only requires two mandatory inputs:
a model atmosphere (modelfile) and the limits of the spectral range (wrange). The code
recognizes Kurucz, MARCS and Phoenix LTE model atmospheres. The sampling of the frequency
grid is chosen internally, but can also be set by adding a constant wavelength step (dw).
The abundances and microturbulence velocity can be set through the abu and vmicro
parameters, but default values will be taken from the model atmosphere. Rotational and
Gaussian broadening can be introduced (vrot and fwhm parameters). The computed spectrum
can be written to a file (save == True).
Parameters
----------
modelfile : str
file with a model atmosphere
wrange: tuple or list of two floats
initial and ending wavelengths (angstroms)
dw: float, optional
wavelength step for the output fluxes
this will be the maximum interval for the radiative
transfer, and will trigger interpolation at the end
(default is None for automatic selection)
strength: float, optional
threshold in the line-to-continuum opacity ratio for
selecting lines (default is 1e-4)
vmicro: float, optional
microturbulence (km/s)
(default is taken from the model atmosphere)
abu: array of floats (99 elements), optional
chemical abundances relative to hydrogen (N(X)/N(H))
(default taken from input model atmosphere)
linelist: array of str
filenames of the line lists, the first one corresponds to
the atomic lines and all the following ones (optional) to
molecular lines
(default ['gfallx3_bpo.19','kmol3_0.01_30.20'] from Allende Prieto+ 2018)
atom: str
'ap18' -- generic opacities used in Allende Prieto+ 2018
'yo19' -- restricted set for NLTE calculations for APOGEE 2019 (Osorio+ 2019)
'hhm' -- continuum opacity is simplified to H and H-
(default 'ap18')
vrot: float
projected rotational velocity (km/s)
(default 0.)
steprot: float
wavelength step for convolution with rotational kernel (angstroms)
set to 0. for automatic adjustment (default 0.)
fwhm: float
Gaussian broadening: macroturbulence, instrumental, etc. (angstroms)
(default 0.)
stepfwhm: float
wavelength step for Gaussian convolution (angstroms)
set to 0. for automatic adjustment (default 0.)
clean: bool
True by the default, set to False to avoid the removal of the synspec
temporary files/links (default True)
save: bool
set to True to save the computed spectrum to a file (default False)
the root of the model atmosphere file, with an extension ".syn" will be used
but see the parameter synfile to change that
synfile: str
when save is True, this can be used to set the name of the output file
(default None)
compute: bool
set to False to skip the actual synspec run, triggering clean=False
(default True)
tmpdir: string
when is not None a temporary directory with this name will be created to store
the temporary synspec input/output files, and the synple log file (usually named
syn.log) will be named as tmpdir_syn.log.
Returns
-------
wave: numpy array of floats
wavelengths (angstroms)
flux: numpy array of floats
flux (H_lambda in ergs/s/cm2/A)
cont: numpy array of floats
continuum flux (same units as flux)
"""
#basic checks on the line list and model atmosphere
checksynspec(linelist,modelfile)
#read model atmosphere
atmostype, teff, logg, vmicro2, abu2, nd, atmos = read_model(modelfile)
if vmicro == None: vmicro = vmicro2
if abu == None: abu = abu2
if dw == None:
#space = 1e-2
space = np.mean(wrange) * np.sqrt(9.12e-15 * np.min(atmos['t']) + vmicro** 2) / clight / 3.
else:
space = dw
#check input parameters are valid
imode = checkinput(wrange, vmicro, linelist)
print ('teff,logg,vmicro=',teff,logg,vmicro)
#print ('abu=',abu)
#print (len(abu))
#print ('nd=',nd)
#print ('linelist=',linelist)
#print ('wrange=',wrange)
logfile = 'syn.log'
if tmpdir is not None:
startdir = os.getcwd()
logfile = os.path.join(startdir,os.path.split(tmpdir)[-1]) + "_" + logfile
try:
os.mkdir(tmpdir)
except OSError:
print( "cannot create tmpdir %s " % (tmpdir) )
try:
os.chdir(tmpdir)
except OSError:
print("cannot enter tmpdir %s " % (tmpdir) )
cleanup()
writetas('tas',nd,linelist) #non-std param. file
write5(teff,logg,abu,atom) #abundance/opacity file
write8(teff,logg,nd,atmos,atmostype) #model atmosphere
write55(wrange,space,imode,2,strength,vmicro,linelist,atmostype) #synspec control file
create_links(linelist) #auxiliary data
if compute == False:
wave = None
flux = None
cont = None
else:
synin = open('fort.5')
synout = open(logfile,'w')
start = time.time()
p = subprocess.Popen([synspec], stdin=synin, stdout = synout, stderr= synout, shell=True)
p.wait()
synout.flush()
synout.close()
synin.close()
assert (os.path.isfile('fort.7')), 'Error: I cannot read the file *fort.7* in '+tmpdir+' -- looks like synspec has crashed, please look at syn.log'
assert (os.path.isfile('fort.17')), 'Error: I cannot read the file *fort.17* in '+tmpdir+' -- looks like synspec has crashed, please look at syn.log'
wave, flux = np.loadtxt('fort.7', unpack=True)
wave2, flux2 = np.loadtxt('fort.17', unpack=True)
if dw == None and fwhm <= 0. and vrot <= 0.: cont = np.interp(wave, wave2, flux2)
end = time.time()
print('syn ellapsed time ',end - start, 'seconds')
if fwhm > 0. or vrot > 0.:
start = time.time()
print( vrot, fwhm, space, steprot, stepfwhm)
wave, flux = call_rotin (wave, flux, vrot, fwhm, space, steprot, stepfwhm, clean=False, reuseinputfiles=True)
if dw == None: cont = np.interp(wave, wave2, flux2)
end = time.time()
print('convol ellapsed time ',end - start, 'seconds')
if (dw != None):
nsamples = int((wrange[1] - wrange[0])/dw) + 1
wave3 = np.arange(nsamples)*dw + wrange[0]
#flux = np.interp(wave3, wave, flux)
flux = interp_spl(wave3, wave, flux)
cont = np.interp(wave3, wave2, flux2)
wave = wave3
if clean == True: cleanup()
if tmpdir is not None:
try:
os.chdir(startdir)
except OSError:
print("cannot change directory from tmpdir %s to startdir %s" % (tmpdir,startdir) )
if clean == True:
try:
os.rmdir(tmpdir)
except OSError:
print("cannot remove directory tmpdir %s" % (tmpdir) )
if save == True:
if synfile == None:
tmpstr = os.path.split(modelfile)[-1]
synfile = tmpstr[:tmpstr.rfind('.')]+'.syn'
np.savetxt(synfile,(wave,flux,cont))
return(wave, flux, cont)
def mpsyn(modelfile, wrange, dw=None, strength=1e-4, vmicro=None, abu=None, \
linelist=['gfallx3_bpo.19','kmol3_0.01_30.20'],atom='ap18', vrot=0.0, fwhm=0.0, \
steprot=0.0, stepfwhm=0.0, clean=True, save=False, synfile=None,
compute=True, nthreads=1):
"""Computes a synthetic spectrum, splitting the spectral range in nthreads parallel calculations
Wrapper for syn, using multiprocessing, to speed-up the calculation of a broad spectral range
Parameters
----------
modelfile : str
file with a model atmosphere
wrange: tuple or list of two floats
initial and ending wavelengths (angstroms)
dw: float, optional
wavelength step for the output fluxes
this will be the maximum interval for the radiative
transfer, and will trigger interpolation at the end
(default is None for automatic selection)
strength: float, optional
threshold in the line-to-continuum opacity ratio for
selecting lines (default is 1e-4)
vmicro: float, optional
microturbulence (km/s)
(default is taken from the model atmosphere)
abu: array of floats (99 elements), optional
chemical abundances relative to hydrogen (N(X)/N(H))
(default taken from input model atmosphere)
linelist: array of str
filenames of the line lists, the first one corresponds to
the atomic lines and all the following ones (optional) to
molecular lines
(default ['gfallx3_bpo.19','kmol3_0.01_30.20'] from Allende Prieto+ 2018)
atom: str
'ap18' -- generic opacities used in Allende Prieto+ 2018
'yo19' -- restricted set for NLTE calculations for APOGEE 2019 (Osorio+ 2019)
'hhm' -- continuum opacity is simplified to H and H-
(default 'ap18')
vrot: float
projected rotational velocity (km/s)
(default 0.)
steprot: float
wavelength step for convolution with rotational kernel (angstroms)
set to 0. for automatic adjustment (default 0.)
fwhm: float
Gaussian broadening: macroturbulence, instrumental, etc. (angstroms)
(default 0.)
stepfwhm: float
wavelength step for Gaussian convolution (angstroms)
set to 0. for automatic adjustment (default 0.)
clean: bool
True by the default, set to False to avoid the removal of the synspec
temporary files/links (default True)
save: bool
set to True to save the computed spectrum to a file (default False)
the root of the model atmosphere file, with an extension ".syn" will be used
but see the parameter synfile to change that
synfile: str
when save is True, this can be used to set the name of the output file
(default None)
compute: bool
set to False to skip the actual synspec run, triggering clean=False
(default True)
nthreads: int
choose the number of cores to use in the calculation
(default 1, 0 has the meaning that the code should take all the cores available)
Returns
-------
wave: numpy array of floats
wavelengths (angstroms)
flux: numpy array of floats
flux (H_lambda in ergs/s/cm2/A)
cont: numpy array of floats
continuum flux (same units as flux)
"""
from multiprocessing import Pool,cpu_count
if nthreads == 0:
nthreads = cpu_count()
delta = (wrange[1]-wrange[0])/nthreads
pars = []
for i in range(nthreads):
wrange1 = (wrange[0]+delta*i,wrange[0]+delta*(i+1))
pararr = [modelfile, wrange1, dw, strength, vmicro, abu, \
linelist, atom, vrot, fwhm, \
steprot, stepfwhm, clean, save, synfile,
compute, 'par'+str(i) ]
pars.append(pararr)
pool = Pool(nthreads)
results = pool.starmap(syn,pars)
pool.close()
pool.join()
x = results[0][0]
y = results[0][1]
z = results[0][2]
if len(results) > 1:
for i in range(len(results)-1):
x = np.concatenate((x, results[i+1][0][1:]) )
y = np.concatenate((y, results[i+1][1][1:]) )
z = np.concatenate((z, results[i+1][2][1:]) )
return(x,y,z)
def raysyn(modelfile, wrange, dw=None, strength=1e-4, vmicro=None, abu=None, \
linelist=['gfallx3_bpo.19','kmol3_0.01_30.20'], atom='ap18', vrot=0.0, fwhm=0.0, \
steprot=0.0, stepfwhm=0.0, clean=True, save=False, synfile=None,
compute=True, nthreads=1):
"""Computes a synthetic spectrum, splitting the spectral range in nthreads parallel calculations
Wrapper for syn, using ray, to speed-up the calculation of a broad spectral range
Parameters
----------
modelfile : str
file with a model atmosphere
wrange: tuple or list of two floats
initial and ending wavelengths (angstroms)
dw: float, optional
wavelength step for the output fluxes
this will be the maximum interval for the radiative
transfer, and will trigger interpolation at the end
(default is None for automatic selection)
strength: float, optional
threshold in the line-to-continuum opacity ratio for
selecting lines (default is 1e-4)
vmicro: float, optional
microturbulence (km/s)
(default is taken from the model atmosphere)
abu: array of floats (99 elements), optional
chemical abundances relative to hydrogen (N(X)/N(H))
(default taken from input model atmosphere)
linelist: array of str
filenames of the line lists, the first one corresponds to
the atomic lines and all the following ones (optional) to
molecular lines
(default ['gfallx3_bpo.19','kmol3_0.01_30.20'] from Allende Prieto+ 2018)
atom: str
'ap18' -- generic opacities used in Allende Prieto+ 2018
'yo19' -- restricted set for NLTE calculations for APOGEE 2019 (Osorio+ 2019)
'hhm' -- continuum opacity is simplified to H and H-
(default 'ap18')
vrot: float
projected rotational velocity (km/s)
(default 0.)
steprot: float
wavelength step for convolution with rotational kernel (angstroms)
set to 0. for automatic adjustment (default 0.)
fwhm: float
Gaussian broadening: macroturbulence, instrumental, etc. (angstroms)
(default 0.)
stepfwhm: float
wavelength step for Gaussian convolution (angstroms)
set to 0. for automatic adjustment (default 0.)
clean: bool
True by the default, set to False to avoid the removal of the synspec
temporary files/links (default True)
save: bool
set to True to save the computed spectrum to a file (default False)
the root of the model atmosphere file, with an extension ".syn" will be used
but see the parameter synfile to change that
synfile: str
when save is True, this can be used to set the name of the output file
(default None)
compute: bool
set to False to skip the actual synspec run, triggering clean=False
(default True)
nthreads: int
choose the number of cores to use in the calculation
(default 1, 0 has the meaning that the code should take all the cores available)
Returns
-------
wave: numpy array of floats
wavelengths (angstroms)
flux: numpy array of floats
flux (H_lambda in ergs/s/cm2/A)
cont: numpy array of floats
continuum flux (same units as flux)
"""
import psutil
import ray
@ray.remote
def fun(vari,cons):
wrange,tmpdir = vari
modelfile,dw,strength,vmicro,abu,linelist, \
atom,vrot,fwhm,steprot,stepfwhm,clean,save,synfile,compute = cons
x, y, z = syn(modelfile, wrange, dw, strength, vmicro, abu, \
linelist, atom, vrot, fwhm, \
steprot, stepfwhm, clean, save, synfile,
compute, tmpdir)
return(x,y,z)
if nthreads == 0:
nthreads = psutil.cpu_count(logical=False)
print('nthreads=',nthreads)
ray.init(num_cpus=nthreads)
rest = [ modelfile,dw,strength,vmicro,abu,linelist, \
atom,vrot,fwhm,steprot,stepfwhm,clean,save,synfile,compute ]
constants = ray.put(rest)
delta = (wrange[1]-wrange[0])/nthreads
pars = []
for i in range(nthreads):
wrange1 = (wrange[0]+delta*i,wrange[0]+delta*(i+1))
folder = 'par'+str(i)
pararr = [wrange1, 'par'+str(i) ]
pars.append(pararr)
results = ray.get([fun.remote(pars[i],constants) for i in range(nthreads)])
x = results[0][0]
y = results[0][1]
z = results[0][2]
if len(results) > 1:
for i in range(len(results)-1):
x = np.concatenate((x, results[i+1][0][1:]) )
y = np.concatenate((y, results[i+1][1][1:]) )
z = np.concatenate((z, results[i+1][2][1:]) )
return(x,y,z)
def multisyn(modelfiles, wrange, dw=None, strength=1e-4, abu=None, \
vmicro=None, vrot=0.0, fwhm=0.0, nfe=0.0, \
linelist=['gfallx3_bpo.19','kmol3_0.01_30.20'], atom='ap18', \
steprot=0.0, stepfwhm=0.0, clean=True, save=None, nthreads=1):
"""Computes synthetic spectra for a list of files. The values of vmicro, vrot,
fwhm, and nfe can be iterables. Whether or not dw is specified the results will be
placed on a common wavelength scale by interpolation. When not specified, dw will be
chosen as appropriate for the first model in modelfiles.
Parameters
----------
modelfiles : list of str
files with model atmospheres
wrange: tuple or list of two floats
initial and ending wavelengths (angstroms)
dw: float
wavelength step for the output fluxes.
Unlike in 'syn' this will not be used to set the maximum wavelength step for
synthesizing any of the spectra; the appropriate step will be chosen dynamically.
Unlike in 'syn', interpolation to a constant step will always be done
(default is None for automatic selection based on the first model of the list)
strength: float, optional
threshold in the line-to-continuum opacity ratio for
selecting lines (default is 1e-4)
abu: array of floats (99 elements), optional
chemical abundances relative to hydrogen (N(X)/N(H))
(default taken from input model atmosphere)
vmicro: float, optional, can be an iterable
microturbulence (km/s)
(default is taken from the model atmosphere)
vrot: float, can be an iterable
projected rotational velocity (km/s)
(default 0.)
fwhm: float, can be an iterable
Gaussian broadening: macroturbulence, instrumental, etc. (angstroms)
(default 0.)
nfe: float, can be an iterable
[N/Fe] nitrogen abundance change from the one specified in the array 'abu' (dex)
(default 0.)
linelist: array of str
filenames of the line lists, the first one corresponds to
the atomic lines and all the following ones (optional) to
molecular lines
(default ['gfallx3_bpo.19','kmol3_0.01_30.20'] from Allende Prieto+ 2018)
atom: str
'ap18' -- generic opacities used in Allende Prieto+ 2018
'yo19' -- restricted set for NLTE calculations for APOGEE 2019 (Osorio+ 2019)
'hhm' -- continuum opacity is simplified to H and H-
(default 'ap18')
steprot: float
wavelength step for convolution with rotational kernel (angstroms)
set to 0. for automatic adjustment (default 0.)
stepfwhm: float
wavelength step for Gaussian convolution (angstroms)
set to 0. for automatic adjustment (default 0.)
clean: bool
True by the default, set to False to avoid the removal of the synspec
temporary files/links (default True)
save: bool
set to True to save the computed spectra to files (default False)
the root of the model atmosphere file, with an extension ".syn" will be used
if multiple values of vmicro, vrot, fwhm or nfe are used, their values are
prepended to the file names
(default None)
nthreads: int
choose the number of cores to use in the calculation
(default 1, 0 has the meaning that the code should take all the cores available)
Returns
-------
wave: numpy array of floats (1D)
wavelengths (angstroms)
flux: numpy array of floats (2D -- as many rows as models input)
flux (H_lambda in ergs/s/cm2/A)
cont: numpy array of floats (2D -- as many rows as models input)
continuum flux (same units as flux)
"""
#when vmicro, vrot, fwhm or nitrogen are not iterables, we create ones, otherwise we copy them
try:
nvmicro = len(vmicro)
vmicros = vmicro
except TypeError:
nvmicro = 1
vmicros = [ vmicro ]
try:
nvrot = len(vrot)
vrots = vrots
except TypeError:
nvrot = 1
vrots = [ vrot ]
try:
nfwhm = len(fwhm)
fwhms = fwhm
except TypeError:
nfwhm = 1
fwhms = [ fwhm ]
try:
nnfe = len(nfe)
nnfes = nfe
except TypeError:
nnfe = 1
nfes = [ nfe ]
assert (len(modelfiles) > 0), 'multisyn needs at least one model to work with'
wave = None
flux = None
cont = None
for entry in modelfiles:
for vmicro1 in vmicros:
for nfe1 in nfes:
abu1 = copy.copy(abu)
#if need be, adjust nitrogen abundance according to nfe
if (abs(nfe1) > 1e-7):
if (abu1 == None):
checksynspec(linelist,entry)
atmostype, teff, logg, vmicro2, abu1, nd, atmos = read_model(entry)
abu1[6] = abu1[6] * 10.**nfe1
x, y, z = mpsyn(entry, wrange, dw=None, strength=strength, \
vmicro=vmicro1, abu=abu1, linelist=linelist, atom=atom, \
clean=clean, save=save, nthreads=nthreads)
space = np.mean(np.diff(x))
for vrot1 in vrots:
for fwhm1 in fwhms:
if fwhm1> 0. or vrot1 > 0.:
start = time.time()
print( entry, vmicro1, nfe1, vrot1, fwhm1, space)
x2, y2 = call_rotin (x, y, vrot, fwhm, space, steprot, stepfwhm, \
clean=False, reuseinputfiles=True)
z2 = np.interp(x2, x, z)
end = time.time()
print('convol ellapsed time ',end - start, 'seconds')
else:
x2, y2, z2 = x, y, z
if entry == modelfiles[0] and vmicro1 == vmicros[0] and vrot1 == vrots[0] and fwhm1 == fwhms[0] and nfe1 == nfes[0]:
if dw == None: dw = np.median(np.diff(x2))
nsamples = int((wrange[1] - wrange[0])/dw) + 1
wave = np.arange(nsamples)*dw + wrange[0]
#flux = np.interp(wave, x2, y2)
flux = interp_spl(wave, x2, y2)
cont = np.interp(wave, x2, z2)
else:
#flux = np.vstack ( (flux, np.interp(wave, x, y) ) )
flux = np.vstack ( (flux, interp_spl(wave, x, y) ) )
cont = np.vstack ( (cont, np.interp(wave, x, z) ) )
return(wave, flux, cont)
def polysyn(modelfiles, wrange, dw=None, strength=1e-4, abu=None, \
vmicro=None, vrot=0.0, fwhm=0.0, nfe=0.0, \
linelist=['gfallx3_bpo.19','kmol3_0.01_30.20'],atom='ap18', \
steprot=0.0, stepfwhm=0.0, clean=True, save=None):
"""Sets up a directory tree for computing synthetic spectra for a list of files in
parallel. The values of vmicro, vrot, fwhm, and nfe can be iterables. Whether or not
dw is specified the results will be placed on a common wavelength scale by interpolation.
When not specified, dw will be chosen as appropriate for the first model in modelfiles.
Parameters
----------
modelfiles : list of str
files with model atmospheres
wrange: tuple or list of two floats
initial and ending wavelengths (angstroms)
dw: float
Unlike in 'syn' this will not be used to set the maximum wavelength step for
synthesizing any of the spectra; the appropriate step will be chosen dynamically.
Unlike in 'syn', interpolation to a constant step will always be done
(default is None for automatic selection based on the first model of the list)
strength: float, optional
threshold in the line-to-continuum opacity ratio for
selecting lines (default is 1e-4)
abu: array of floats (99 elements), optional
chemical abundances relative to hydrogen (N(X)/N(H))
(default taken from input model atmosphere)
vmicro: float, optional, can be an iterable
microturbulence (km/s)
(default is taken from the model atmosphere)
vrot: float, can be an iterable
projected rotational velocity (km/s)
(default 0.)
fwhm: float, can be an iterable
Gaussian broadening: macroturbulence, instrumental, etc. (angstroms)
(default 0.)
nfe: float, can be an iterable
[N/Fe] nitrogen abundance change from the one specified in the array 'abu' (dex)
(default 0.)
linelist: array of str
filenames of the line lists, the first one corresponds to
the atomic lines and all the following ones (optional) to
molecular lines
(default ['gfallx3_bpo.19','kmol3_0.01_30.20'] from Allende Prieto+ 2018)
atom: str
'ap18' -- generic opacities used in Allende Prieto+ 2018
'yo19' -- restricted set for NLTE calculations for APOGEE 2019 (Osorio+ 2019)
'hhm' -- continuum opacity is simplified to H and H-
(default 'ap18')
steprot: float
wavelength step for convolution with rotational kernel (angstroms)
set to 0. for automatic adjustment (default 0.)
stepfwhm: float
wavelength step for Gaussian convolution (angstroms)
set to 0. for automatic adjustment (default 0.)
clean: bool
True by the default, set to False to avoid the removal of the synspec
temporary files/links (default True)
save: bool
set to True to save the computed spectra to files (default False)
the root of the model atmosphere file, with an extension ".syn" will be used
if multiple values of vmicro, vrot, fwhm or nfe are used, their values are
prepended to the file names
(default None)
Returns
-------
wave: numpy array of floats (1D)
wavelengths (angstroms)
flux: numpy array of floats (2D -- as many rows as models input)
flux (H_lambda in ergs/s/cm2/A)
cont: numpy array of floats (2D -- as many rows as models input)
continuum flux (same units as flux)
"""
#synspec does not currently run in parallel
nthreads = 1
#when vmicro, vrot, fwhm or nitrogen are not iterables, we create ones, otherwise we copy them
try:
nvmicro = len(vmicro)
vmicros = vmicro
except TypeError:
nvmicro = 1
vmicros = [ vmicro ]
try:
nvrot = len(vrot)
vrots = vrots
except TypeError:
nvrot = 1
vrots = [ vrot ]
try:
nfwhm = len(fwhm)
fwhms = fwhm
except TypeError:
nfwhm = 1
fwhms = [ fwhm ]
try:
nnfe = len(nfe)
nnfes = nfe
except TypeError:
nnfe = 1
nfes = [ nfe ]
idir = 0
for entry in modelfiles:
for vmicro1 in vmicros:
for nfe1 in nfes:
idir = idir + 1
dir = ( "hyd%07d" % (idir) )
try:
os.mkdir(dir)
except OSError:
print( "cannot create dir hyd%07d" % (idir) )
try:
os.chdir(dir)
except OSError:
print( "cannot change dir to hyd%07d" % (idir) )
if entry == 'missing':
pass
else:
#setup the slurm script
sfile = dir+".job"
now=time.strftime("%c")
s = open(sfile ,"w")
s.write("#!/bin/bash \n")
s.write("#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-# \n")
s.write("#This script was written by synple on "+now+" \n")
s.write("#SBATCH -J "+dir+" \n")
s.write("#SBATCH -o "+dir+"_%j.out"+" \n")
s.write("#SBATCH -e "+dir+"_%j.err"+" \n")
s.write("#SBATCH -n "+str(nthreads)+" \n")
s.write("#SBATCH -t 04:00:00"+" \n") #hh:mm:ss
s.write("#SBATCH -D "+os.path.abspath(os.curdir)+" \n")
s.write("#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-# \n\n\n")
abu1 = copy.copy(abu)
#if need be, adjust nitrogen abundance according to nfe
if (abs(nfe1) > 1e-7):
if (abu1 == None):
checksynspec(linelist,entry)
atmostype, teff, logg, vmicro2, abu1, nd, atmos = read_model(entry)
abu1[6] = abu1[6] * 10.**nfe1
x, y, z = syn(entry, wrange, dw=None, strength=strength, vmicro=vmicro1, \
abu=abu1, linelist=linelist, atom=atom, compute=False)
s.write(synspec+" < "+"fort.5"+"\n")
si = open("fort.55",'r')
for i in range(6): line = si.readline()
entries = line.split()
space = float(entries[5])
si.close()
iconv = 0
for vrot1 in vrots:
for fwhm1 in fwhms:
print('iconv=',iconv)
iconv = iconv + 1
inconv = ("%07dfort.5" % (iconv) )
outconv = ("'%07dfort.7'" % (iconv) )
if fwhm1> 0. or vrot1 > 0.:
f = open(inconv,'w')
f.write( ' %s %s %s \n' % ("'fort.7'", "'fort.17'", outconv) )
f.write( ' %f %f %f \n' % (vrot1, space, steprot) )
f.write( ' %f %f \n' % (fwhm1, stepfwhm) )
print('stepfwhm=',stepfwhm)
f.write( ' %f %f %i \n' % (wrange[0], wrange[1], 0) )
f.close()
s.write(rotin+" < "+inconv+"\n")
else:
s.write("cp "+" fort.7 "+outconv[1:-1]+"\n")
s.close()
os.chmod(sfile ,0o755)
try:
os.chdir('..')
except OSError:
print( "cannot exit dir hyd%07d" % (idir) )
return(None,None,None)
def polyopt(wrange=(9.e2,1.e5),dw=0.1,strength=1e-3, linelist=['gfallx3_bpo.19','kmol3_0.01_30.20'], \
tlt = (20,3.08,0.068), tlrho = (20,-14.0,0.59), \
tfeh=(1,0.0,0.0), tafe=(1,0.0,0.0), tcfe=(1,0.0,0.0), tnfe=(1,0.0,0.0), \
tofe=(1,0.0,0.0), trfe=(1,0.0,0.0), tsfe=(1,0.0,0.0), tvmicro=(1,1.0,0.0), \
zexclude=None, atom='ap18'):
"""Sets up a directory tree for computing opacity tables for TLUSTY. The table collection forms
a regular grid defined by triads in various parameters. Each triad has three values (n, llimit, step)
that define an array x = np.range(n)*step + llimit. Triads in teff (tteff) and logg
(tlogg) are mandatory. Triads in [Fe/H] (tfeh), [alpha/Fe] (tafe), [C/Fe] (tcfe),
[N/Fe] (tnfe), [O/Fe] (tofe), [r/Fe] (rfe), and [s/Fe] (sfe) are optional since
arrays with just one 0.0 are included by default.
Parameters
----------
wrange: tuple or list of two floats
initial and ending wavelengths (angstroms)
dw: float
Unlike in 'syn' this will not be used to set the maximum wavelength step for
synthesizing any of the spectra; the appropriate step will be chosen dynamically.
Unlike in 'syn', interpolation to a constant step will always be done
(default is None for automatic selection based on the first model of the list)
strength: float, optional
threshold in the line-to-continuum opacity ratio for
selecting lines (default is 1e-4)
linelist: array of str
filenames of the line lists, the first one corresponds to
the atomic lines and all the following ones (optional) to
molecular lines
(default ['gfallx3_bpo.19','kmol3_0.01_30.20'] from Allende Prieto+ 2018)
atom: str
'ap18' -- generic opacities used in Allende Prieto+ 2018
'yo19' -- restricted set for NLTE calculations for APOGEE 2019 (Osorio+ 2019)
'hhm' -- continuum opacity is simplified to H and H-
(default 'ap18')
tlt: tuple
log10(T) triad (n, llimit, step) for opacity grid
(default values chosen for grid lt = np.arange(20)*0.068 + 3.08,
to cover the range in the DR16 APOGEE MARCS grids)
tlrho: tuple
log10(rho) triad (n, llimit, step) for opacity grid
(default values chosen for grid lrho = np.arange(20)*0.59 -14.0,
to cover the range in the DR16 APOGEE MARCS grids)
tteff: tuple
Teff triad (n, llimit, step)
tlogg: tuple
logg triad (n, llimit, step)
tfeh: tuple
[Fe/H] triad
tafe: tuple
[alpha/Fe] triad
tcfe: tuple
[C/Fe] triad
tnfe: tuple
[N/Fe] triad
tofe: tuple
[O/Fe] triad
rfeh: tuple
[r/Fe] triad (r-elements abundance ratio)
sfeh: tuple
[s.Fe] triad (s-elements abundance ratio)
zexclude: list
atomic numbers of the elements whose opacity is NOT to be
included in the table
(default None)
"""
#pynspec does not currently run in parallel
nthreads = 1
#expanding the triads t* into iterables
try:
nfeh = len(tfeh)
assert (nfeh == 3), 'Error: feh triad must have three elements (n, llimit, step)'
fehs = np.arange(tfeh[0])*tfeh[2] + tfeh[1]
except TypeError:
print('Error: feh triad must have three elements (n, llimit, step)')
return ()
try:
nafe = len(tafe)
assert (nafe == 3), 'Error: afe triad must have three elements (n, llimit, step)'
afes = np.arange(tafe[0])*tafe[2] + tafe[1]
except TypeError:
print('Error: afe triad must have three elements (n, llimit, step)')
return ()
try:
ncfe = len(tcfe)
assert (ncfe == 3), 'Error: cfe triad must have three elements (n, llimit, step)'
cfes = np.arange(tcfe[0])*tcfe[2] + tcfe[1]
except TypeError:
print('Error: cfe triad must have three elements (n, llimit, step)')
return ()
try:
nnfe = len(tnfe)
assert (nnfe == 3), 'Error: nfe triad must have three elements (n, llimit, step)'
nfes = np.arange(tnfe[0])*tnfe[2] + tnfe[1]
except TypeError:
print('Error: nfe triad must have three elements (n, llimit, step)')
return ()
try:
nofe = len(tofe)
assert (nofe == 3), 'Error: ofe triad must have three elements (n, llimit, step)'
ofes = np.arange(tofe[0])*tofe[2] + tofe[1]
except TypeError:
print('Error: ofe triad must have three elements (n, llimit, step)')
return ()
try:
nrfe = len(trfe)
assert (nrfe == 3), 'Error: rfe triad must have three elements (n, llimit, step)'
rfes = np.arange(trfe[0])*trfe[2] + trfe[1]
except TypeError:
print('Error: rfe triad must have three elements (n, llimit, step)')
return ()
try:
nsfe = len(tsfe)
assert (nsfe == 3), 'Error: sfe triad must have three elements (n, llimit, step)'
sfes = np.arange(tsfe[0])*tsfe[2] + tsfe[1]
except TypeError:
print('Error: sfe triad must have three elements (n, llimit, step)')
return ()
try:
nvmicro = len(tvmicro)
assert (nvmicro == 3), 'Error: vmicro triad must have three elements (n, llimit, step)'
vmicros = np.arange(tvmicro[0])*tvmicro[2] + tvmicro[1]
except TypeError:
print('Error: vmicro triad must have three elements (n, llimit, step)')
return ()
#ranges for the opacity table
try:
nlt = len(tlt)
assert (nlt == 3), 'Error: lt triad must have three elements (n, llimit, step)'
lt = np.arange(tlt[0])*tlt[2] + tlt[1] #log10(T)
except TypeError:
print('Error: tlt triad must have three elements (n, llimit, step)')
return ()
try:
nlrho = len(tlrho)
assert (nlrho == 3), 'Error: lrho triad must have three elements (n, llimit, step)'
lrho = np.arange(tlrho[0])*tlrho[2] + tlrho[1] #log10(density)
except TypeError:
print('Error: tlrho triad must have three elements (n, llimit, step)')
return ()
symbol, mass, sol = elements()
z_metals = np.arange(97,dtype=int) + 3
#Ar usually included among alphas in MARCS and not in Kurucz/Meszaros
z_alphas = np.array([8,10,12,14,16,18,20,22],dtype=int)
# rs increases: notes and data below from comments in the MARCS code (provided by B.Edvardsson)
# Fractional r-process abundance for Ga-Bi (r+s simply assumed == 100%) | Date 2000-01-18
# (Note: Ga-Sr (31-38) was just copied from Kaeppeler et al. 1989, below)
# s-process from Stellar models: <NAME>., <NAME>., <NAME>.,
# <NAME>., <NAME>., <NAME>., 1999, Astrophys J. 525, 886-900
# Fractions corrected to the revised meteoritic abundances
# of <NAME>., <NAME>. 1998, Space Science Review 85, 161-174
# -0.99 is assigned to unstable elements
z_rs = | np.arange(62,dtype=int) | numpy.arange |
import transform
import unittest
import numpy as np
import sys
sys.path.insert(0, '../')
import pdb
import rotateCorrection as rc
# another crude transformation computer
def _angle(x1, y1, x2, y2):
# inputs are in angle
dx = x2 - x1
dy = y2 - y1
if dy < 0:
return np.arctan(abs(dy)/dx)
else:
return -np.arctan(abs(dy)/dx)
def simple_angle_converter(pointpx, top_right, top_left, bottom_left, bottom_right, imagesize):
"""
All coordinate tuples are in (x, y) i.e. (lon, lat) convention.
pointpx (x, y): pixel coordinates counted from top left corner.
top_right, top_left, bottom_left, bottom_right: (lon, lat) pairs
imagesize: (width, height) tuple
"""
# first wrangle inputs
image_width, image_height = imagesize
px, py = pointpx
tr, tl, bl, br = top_right, top_left, bottom_left, bottom_right
# now start converting
image_width_in_lon = (tr[0] - tl[0] + br[0] - bl[0])/2
image_height_in_lat = (tl[1] - bl[1] + tr[1] - br[1])/2
top_left_lon, top_left_lat = tl
# 2. now convert (px, py) -> (dlon, dlat)
dlon = px*image_width_in_lon/image_width
dlat = py*image_height_in_lat/image_height
# compute the angle via simple trig.
angle_est1 = _angle(tl[0], tl[1], tr[0], tr[1])
angle_est2 = _angle(bl[0], bl[1], br[0], br[1])
angle = (angle_est1+angle_est2)/2
print(f"angle: {angle}")
rot_matrix = np.array([[np.cos(angle), -np.sin(angle)],
[np.sin(angle), np.cos(angle)]])
# apply reverse rotation: x2, y2 (unit: meter)
x2, y2 = np.dot(rot_matrix, np.array([dlon, dlat]))
# convert x2, y2 to lon, lat
actual_lon = top_left_lon + x2
actual_lat = top_left_lat - y2
return actual_lon, actual_lat
class TestTransformLukas(unittest.TestCase):
def test_unrotated_picture(self):
width = 10
height = 60
lon_min = 20
lon_max = 30
lat_min = 10
lat_max = 70
top_left = np.array([lon_min, lat_max])
top_right = np.array([lon_max, lat_max])
bottom_left = np.array([lon_min, lat_min])
bottom_right = np.array([lon_max, lat_min])
# check that top left is sane
res = transform.transform(np.array([0, 0]), top_right, top_left,
bottom_left, bottom_right, np.array([width, height]))
self.assertTrue(np.allclose(res, top_left))
# check that top right is sane
res = transform.transform(np.array([width,0]), top_right, top_left,
bottom_left, bottom_right, np.array([width, height]))
self.assertTrue(np.allclose(res, top_right))
# check that bottom left is sane
res = transform.transform(np.array([0,height]), top_right, top_left,
bottom_left, bottom_right, np.array([width, height]))
self.assertTrue(np.allclose(res, bottom_left))
# check that bottom right is sane
res = transform.transform(np.array([width,height]), top_right, top_left,
bottom_left, bottom_right, np.array([width, height]))
self.assertTrue(np.allclose(res, bottom_right))
class TestBasicTransform(unittest.TestCase):
def test_unrotated_picture(self):
width = 10
height = 60
lon_min = 20
lon_max = 30
lat_min = 10
lat_max = 70
top_left = np.array([lon_min, lat_max])
top_right = np.array([lon_max, lat_max])
bottom_left = np.array([lon_min, lat_min])
bottom_right = np.array([lon_max, lat_min])
# check that top left is sane
res = simple_angle_converter(np.array([0, 0]), top_right, top_left,
bottom_left, bottom_right, np.array([width, height]))
self.assertTrue(np.allclose(res, top_left))
# check that top right is sane
res = simple_angle_converter(np.array([width,0]), top_right, top_left,
bottom_left, bottom_right, np.array([width, height]))
self.assertTrue(np.allclose(res, top_right))
# check that bottom left is sane
res = simple_angle_converter(np.array([0,height]), top_right, top_left,
bottom_left, bottom_right, np.array([width, height]))
self.assertTrue(np.allclose(res, bottom_left))
# check that bottom right is sane
res = simple_angle_converter(np.array([width,height]), top_right, top_left,
bottom_left, bottom_right, np.array([width, height]))
self.assertTrue(np.allclose(res, bottom_right))
def test_fourtyFive_deg(self):
width = 100
height = 100
top_left = np.array([50,50])
bottom_left = np.array([40,40])
bottom_right = np.array([50,30])
top_right = np.array([60,40])
res = simple_angle_converter((50,50),top_right,top_left, bottom_left, bottom_right, (width,height))
self.assertTrue(np.allclose(res, (40,40)))
class TestTransformVectorTransform(unittest.TestCase):
def test_unrotated_picture(self):
width = 10
height = 60
lon_min = 20
lon_max = 30
lat_min = 10
lat_max = 70
top_left = np.array([lon_min, lat_max])
top_right = np.array([lon_max, lat_max])
bottom_left = np.array([lon_min, lat_min])
bottom_right = np.array([lon_max, lat_min])
# check that top left is sane
res = rc.vector_converter(np.array([0, 0]), top_right, top_left,
bottom_left, bottom_right, np.array([width, height]))
self.assertTrue(np.allclose(res, top_left))
# check that top right is sane
res = rc.vector_converter(np.array([width,0]), top_right, top_left,
bottom_left, bottom_right, np.array([width, height]))
self.assertTrue(np.allclose(res, top_right))
# check that bottom left is sane
res = rc.vector_converter(np.array([0,height]), top_right, top_left,
bottom_left, bottom_right, np.array([width, height]))
self.assertTrue( | np.allclose(res, bottom_left) | numpy.allclose |
# Copyright 2019 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 numpy as np
import pytest
import matplotlib.pyplot as plt
from cirq import GridQubit
from cirq import circuits, ops, sim
from cirq.experiments import (rabi_oscillations,
single_qubit_randomized_benchmarking,
two_qubit_randomized_benchmarking,
single_qubit_state_tomography,
two_qubit_state_tomography)
def test_rabi_oscillations():
# Check that the excited state population matches the ideal case within a
# small statistical error.
simulator = sim.Simulator()
qubit = GridQubit(0, 0)
results = rabi_oscillations(simulator, qubit, np.pi, repetitions=1000)
data = np.asarray(results.data)
angles = data[:, 0]
actual_pops = data[:, 1]
target_pops = 0.5 - 0.5 * np.cos(angles)
rms_err = np.sqrt(np.mean((target_pops - actual_pops) ** 2))
assert rms_err < 0.1
def test_single_qubit_randomized_benchmarking():
# Check that the ground state population at the end of the Clifford
# sequences is always unity.
simulator = sim.Simulator()
qubit = GridQubit(0, 0)
num_cfds = range(5, 20, 5)
results = single_qubit_randomized_benchmarking(simulator,
qubit,
num_clifford_range=num_cfds,
repetitions=100)
g_pops = | np.asarray(results.data) | numpy.asarray |
import unittest
import numpy as np
import tensorflow as tf
import tensorflow_probability
import mvg_distributions.covariance_representations as cov_rep
from mvg_distributions.sqrt_gamma_gaussian import SqrtGammaGaussian, SparseSqrtGammaGaussian
from mvg_distributions.test.test_losses_base import LossesTestBase
tfd = tensorflow_probability.distributions
tfb = tensorflow_probability.bijectors
class TestSqrtGammaGaussian(LossesTestBase):
def setUp(self):
super().setUp()
self.x, self.x_cov_obj, self.sqrt_w_tfd, self.sqrt_gamma_gaussian = self._create_single_sqrt_wishart_pair()
def _create_single_sqrt_wishart_pair(self, add_sparse_gamma=False):
# Create a random scale matrix for the Wishart distribution
diag_precision_prior = np.abs( | np.random.normal(size=(self.batch_size, self.features_size)) | numpy.random.normal |
from typing import Any, Dict, Union
import numpy as np
from numpy.core.defchararray import center
import panda_gym
from panda_gym.envs.core import Task
from panda_gym.utils import distance
class ReachBimanual(Task):
def __init__(
self,
sim,
get_ee_position0,
get_ee_position1,
reward_type="sparse",
distance_threshold=0.05,
goal_range=0.35,
has_object = False,
absolute_pos = False,
obj_not_in_hand_rate = 1,
) -> None:
super().__init__(sim)
self.has_object = has_object
self.absolute_pos = absolute_pos
self.object_size = 0.04
self.reward_type = reward_type
self.distance_threshold = distance_threshold
self.obj_not_in_hand_rate = obj_not_in_hand_rate
self.get_ee_position0 = get_ee_position0
self.get_ee_position1 = get_ee_position1
self.goal_range_low = np.array([goal_range / 4, goal_range / 4, -goal_range/1.5])
self.goal_range_high = np.array([goal_range, goal_range, goal_range/1.5])
obj_xyz_range=[0.3, 0.3, 0]
self.obj_range_low = np.array([0.1, -obj_xyz_range[1] / 2, self.object_size/2])
self.obj_range_high = np.array(obj_xyz_range) + self.obj_range_low
with self.sim.no_rendering():
self._create_scene()
self.sim.place_visualizer(target_position=np.zeros(3), distance=0.9, yaw=45, pitch=-30)
self._max_episode_steps = 50
def _create_scene(self) -> None:
self.sim.create_plane(z_offset=-0.4)
self.sim.create_table(length=1., width=0.7, height=0.4, x_offset=-0.575)
self.sim.create_table(length=1., width=0.7, height=0.4, x_offset=0.575)
self.sim.create_sphere(
body_name="target0",
radius=0.02,
mass=0.0,
ghost=True,
position=np.zeros(3),
rgba_color=np.array([0.1, 0.9, 0.1, 0.3]),
)
self.sim.create_sphere(
body_name="target1",
radius=0.02,
mass=0.0,
ghost=True,
position=np.zeros(3),
rgba_color=np.array([0.9, 0.1, 0.1, 0.3]),
)
self.sim.create_sphere(
body_name="target2",
radius=0.03,
mass=0.0,
ghost=True,
position=np.zeros(3),
rgba_color=np.array([0.1, 0.1, 0.9, 0.5]),
)
if self.has_object:
self.sim.create_box(
body_name="object0",
half_extents=np.ones(3) * self.object_size / 2,
mass=0.5,
position=np.array([0.0, 0.0, self.object_size / 2]),
rgba_color=np.array([0.1, 0.9, 0.1, 1.0]),
)
self.sim.create_box(
body_name="object1",
half_extents=np.ones(3) * self.object_size / 2,
mass=0.5,
position=np.array([0.0, 0.0, self.object_size / 2]),
rgba_color=np.array([0.9, 0.1, 0.1, 1.0]),
)
# LOAD SHAPE TAMP
# self.sim.physics_client.setAdditionalSearchPath(panda_gym.assets.get_data_path())
# self.sim.loadURDF(
# body_name='object01',
# fileName='plate.urdf',
# basePosition=[-0.2,0,0.02],
# baseOrientation = [0,0,0,1],
# useFixedBase=False,
# )
# self.sim.loadURDF(
# body_name='object11',
# fileName='cup.urdf',
# basePosition=[0.2,0,0.02],
# baseOrientation = [0,0,0,1],
# useFixedBase=False,
# )
def get_obs(self) -> np.ndarray:
if self.has_object:
# position, rotation of the object
object1_position = np.array(self.sim.get_base_position("object1"))
object1_rotation = np.array(self.sim.get_base_rotation("object1"))
object1_velocity = np.array(self.sim.get_base_velocity("object1"))
object1_angular_velocity = np.array(self.sim.get_base_angular_velocity("object1"))
object0_position = np.array(self.sim.get_base_position("object0"))
object0_rotation = np.array(self.sim.get_base_rotation("object0"))
object0_velocity = np.array(self.sim.get_base_velocity("object0"))
object0_angular_velocity = np.array(self.sim.get_base_angular_velocity("object0"))
self.assemble_done = self.assemble_done or \
(np.linalg.norm(object1_position-object0_position-self.goal[3:]) < self.distance_threshold)
if self.assemble_done:
object1_position = object0_position + self.goal[3:]
observation = np.concatenate(
[
object0_position,
object0_rotation,
object0_velocity,
object0_angular_velocity,
object1_position,
object1_rotation,
object1_velocity,
object1_angular_velocity,
]
)
return observation
else:
return np.array([]) # no tasak-specific observation
def get_achieved_goal(self) -> np.ndarray:
if self.has_object:
object0_position = self.sim.get_base_position("object0")
if self.assemble_done:
object1_position = object0_position + self.goal[3:]
else:
object1_position = self.sim.get_base_position("object1")
obj_center = (object1_position + object0_position)/2
if self.absolute_pos:
self.sim.set_base_pose("target0", -self.goal[3:]/2 + obj_center, np.array([0.0, 0.0, 0.0, 1.0]))
self.sim.set_base_pose("target1", self.goal[3:]/2 + obj_center, np.array([0.0, 0.0, 0.0, 1.0]))
ag = np.append(object0_position, object1_position-object0_position)
else:
self.sim.set_base_pose("target0", -self.goal/2 + obj_center, np.array([0.0, 0.0, 0.0, 1.0]))
self.sim.set_base_pose("target1", self.goal/2 + obj_center, np.array([0.0, 0.0, 0.0, 1.0]))
ag = (object1_position - object0_position)
# CHANGE TAMP
# for i in range(2):
# pos = self.sim.get_base_positigiton("object"+str(i))
# ori = np.array([0, self.sim.get_base_rotation("object"+str(i))[1], 0])
# self.sim.set_base_pose("object"+str(i), pos, ori)
# self.sim.set_base_pose("object"+str(i)+"1",pos,np.array([0.0, 0.0, 0.0, 1.0]))
else:
ee_position0 = np.array(self.get_ee_position0())
ee_position1 = np.array(self.get_ee_position1())
ee_center = (ee_position0 + ee_position1)/2
self.sim.set_base_pose("target0", -self.goal/2 + ee_center, np.array([0.0, 0.0, 0.0, 1.0]))
self.sim.set_base_pose("target1", self.goal/2 + ee_center, np.array([0.0, 0.0, 0.0, 1.0]))
ag = (ee_position1 - ee_position0)
return ag
def reset(self) -> None:
self.goal = self._sample_goal()
object0_position, object1_position = self._sample_objects()
if self.has_object:
self.sim.set_base_pose("object0", object0_position, np.array([0.0, 0.0, 0.0, 1.0]))
self.sim.set_base_pose("object1", object1_position, np.array([0.0, 0.0, 0.0, 1.0]))
if self.absolute_pos:
self.sim.set_base_pose("target2", self.goal[:3], np.array([0.0, 0.0, 0.0, 1.0]))
self.assemble_done = False
def _sample_goal(self) -> np.ndarray:
"""Randomize goal."""
if self.absolute_pos:
goal_abs = self.np_random.uniform(self.obj_range_low, self.obj_range_high)
goal_abs[0] = -goal_abs[0]
goal_abs[2] += self.np_random.uniform(0, 0.27)
goal_relative = self.np_random.uniform(self.goal_range_low, self.goal_range_high)
# goal_relative = [0.12, 0, 0.08] # TAMP
# goal_abs = [-0.4, 0.18, 0.18] # TAMP
goal = np.append(goal_abs, goal_relative)
else:
goal = self.np_random.uniform(self.goal_range_low, self.goal_range_high)
return goal
def _sample_objects(self):
# while True: # make sure that cubes are distant enough
if self.np_random.uniform()<self.obj_not_in_hand_rate:
object0_position = self.np_random.uniform(self.obj_range_low, self.obj_range_high)
object0_position[0] =- object0_position[0]
object1_position = self.np_random.uniform(self.obj_range_low, self.obj_range_high)
else:
object0_position = np.array(self.get_ee_position0())
object1_position = np.array(self.get_ee_position1())
return object0_position, object1_position
def is_success(self, achieved_goal: np.ndarray, desired_goal: np.ndarray) -> Union[np.ndarray, float]:
if self.absolute_pos:
return np.array(\
distance(achieved_goal[..., :3], desired_goal[..., :3]) < self.distance_threshold and \
distance(achieved_goal[..., 3:], desired_goal[..., 3:]) < self.distance_threshold
, dtype=np.float64)
else:
d = distance(achieved_goal, desired_goal)
return np.array(d < self.distance_threshold, dtype=np.float64)
def compute_reward(self, achieved_goal, desired_goal, info: Dict[str, Any]) -> Union[np.ndarray, float]:
if self.absolute_pos:
# if info['assemble_done']:
d = distance(achieved_goal[..., :3], desired_goal[..., :3])
rew = -np.array(d > self.distance_threshold, dtype=np.float64).flatten()
# else:
d = distance(achieved_goal[...,3:], desired_goal[..., 3:])
rew -= | np.array(d > self.distance_threshold, dtype=np.float64) | numpy.array |
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import math
import random
import numpy as np
import matplotlib.pyplot as plt
from scipy.constants import N_A
from numba import jit
import copy
__author__ = "<NAME>, <NAME>, <NAME>"
__email__ = "<EMAIL>"
__copyright__ = "Copyright 2020, The Materials Project"
__version__ = "0.1"
"""
Kinetic Monte Carlo (kMC) simulation for a reaction network, assuming spatial homogeneity. Simulation can be performed
with and without ReactionNetwork objects. The version without ReactionNetwork objects is computationally cheaper.
The algorithm is described by Gillespie (1976).
"""
def initialize_simulation(reaction_network, initial_cond, volume=10 ** -24):
"""
Initial loop through reactions to create lists, mappings, and initial states needed for simulation without
reaction network objects.
Args:
reaction_network: Fully generated ReactionNetwork
initial_cond: dict mapping mol_index to initial concentration [M]. mol_index is entry position in
reaction_network.entries_list
volume: float of system volume
:return:
initial_state: array of initial molecule amounts, indexed corresponding to reaction_network.entries_list
initial_state_dict: dict mapping molecule index to initial molecule amounts
species_rxn_mapping: 2d array; each row i contains reactions which molecule_i takes part in
molid_index_mapping: mapping between species entry id and its molecule index
reactants_array: (n_rxns x 2) array, each row containing reactant mol_index of forward reaction
products_array: (n_rxns x 2) array, each row containing product mol_index of forward reaction
coord_array: (2*n_rxns x 1) array, with coordination number of each for and rev rxn: [c1_f, c1_r, c2_f, c2_r...]
rate_constants: (2*n_rxns x 1) array, with rate constant of each for and rev rxn: [k1_f, k1_r, k2_f, k2_r ...]
propensities: (2*n_rxns x 1) array of reaction propensities, defined as coord_num*rate_constant
"""
num_rxns = len(reaction_network.reactions)
num_species = len(reaction_network.entries_list)
molid_index_mapping = dict()
initial_state = [0 for i in range(num_species)]
initial_state_dict = dict()
for ind, mol in enumerate(reaction_network.entries_list):
molid_index_mapping[mol.entry_id] = ind
this_c = initial_cond.get(mol.entry_id, 0)
this_mol_amt = int(volume * N_A * 1000 * this_c)
initial_state[ind] = this_mol_amt
if mol.entry_id in initial_cond:
initial_state_dict[ind] = this_mol_amt
# Initially compile each species' reactions in lists, later convert to a 2d array
species_rxn_mapping_list = [[] for j in range(num_species)]
reactant_array = -1 * np.ones((num_rxns, 2), dtype=int)
product_array = -1 * np.ones((num_rxns, 2), dtype=int)
coord_array = np.zeros(2 * num_rxns)
rate_constants = np.zeros(2 * num_rxns)
for id, reaction in enumerate(reaction_network.reactions):
# Keep track of reactant amounts, for later calculating coordination number
num_reactants_for = list()
num_reactants_rev = list()
rate_constants[2 * id] = reaction.k_A
rate_constants[2 * id + 1] = reaction.k_B
for idx, react in enumerate(reaction.reactants):
# for each reactant, need to find the corresponding mol_id with the index
mol_ind = molid_index_mapping[react.entry_id]
reactant_array[id, idx] = mol_ind
species_rxn_mapping_list[mol_ind].append(2 * id)
num_reactants_for.append(initial_state[mol_ind])
for idx, prod in enumerate(reaction.products):
mol_ind = molid_index_mapping[prod.entry_id]
product_array[id, idx] = mol_ind
species_rxn_mapping_list[mol_ind].append(2 * id + 1)
num_reactants_rev.append(initial_state[mol_ind])
if len(reaction.reactants) == 1:
coord_array[2 * id] = num_reactants_for[0]
elif (len(reaction.reactants) == 2) and (
reaction.reactants[0] == reaction.reactants[1]
):
coord_array[2 * id] = num_reactants_for[0] * (num_reactants_for[0] - 1)
elif (len(reaction.reactants) == 2) and (
reaction.reactants[0] != reaction.reactants[1]
):
coord_array[2 * id] = num_reactants_for[0] * num_reactants_for[1]
else:
raise RuntimeError(
"Only single and bimolecular reactions supported by this simulation"
)
# For reverse reaction
if len(reaction.products) == 1:
coord_array[2 * id + 1] = num_reactants_rev[0]
elif (len(reaction.products) == 2) and (
reaction.products[0] == reaction.products[1]
):
coord_array[2 * id + 1] = num_reactants_rev[0] * (num_reactants_rev[0] - 1)
elif (len(reaction.products) == 2) and (
reaction.products[0] != reaction.products[1]
):
coord_array[2 * id + 1] = num_reactants_rev[0] * num_reactants_rev[1]
else:
raise RuntimeError(
"Only single and bimolecular reactions supported by this simulation"
)
rxn_mapping_lengths = [len(rxn_list) for rxn_list in species_rxn_mapping_list]
max_mapping_length = max(rxn_mapping_lengths)
species_rxn_mapping = -1 * np.ones((num_species, max_mapping_length), dtype=int)
for index, rxn_list in enumerate(species_rxn_mapping_list):
this_map_length = rxn_mapping_lengths[index]
if this_map_length == max_mapping_length:
species_rxn_mapping[index, :] = rxn_list
else:
species_rxn_mapping[
index, : this_map_length - max_mapping_length
] = rxn_list
propensities = np.multiply(coord_array, rate_constants)
return [
np.array(initial_state, dtype=int),
initial_state_dict,
species_rxn_mapping,
reactant_array,
product_array,
coord_array,
rate_constants,
propensities,
molid_index_mapping,
]
@jit(nopython=True, parallel=True)
def kmc_simulate(
time_steps,
coord_array,
rate_constants,
propensity_array,
species_rxn_mapping,
reactants,
products,
state,
):
"""
KMC Simulation of reaction network and specified initial conditions. Args are all Numpy arrays, to allow
computational speed up with Numba.
Args:
time_steps: int number of time steps desired to run
coord_array: array containing coordination numbers of for and rev rxns.
rate_constants: array containing rate constants of for and rev rxns
propensity_array: array containing propensities of for and rev rxns
species_rxn_mapping: 2d array; each row i contains reactions which molecule_i takes part in
reactants: (n_rxns x 2) array, each row containing reactant mol_index of forward reaction
products: (n_rxns x 2) array, each row containing product mol_index of forward reaction
state: array of initial molecule amounts, indexed corresponding to reaction_network.entries_list
:return: A (2 x time_steps) Numpy array. First row contains the indeces of reactions that occurred.
Second row are the time steps generated at each iteration.
"""
total_propensity = np.sum(propensity_array)
reaction_history = [0 for step in range(time_steps)]
times = [0.0 for step in range(time_steps)]
relevant_ind = np.where(propensity_array > 0)[
0
] # Take advantage of sparsity - many propensities will be 0.
for step_counter in range(time_steps):
r1 = random.random()
r2 = random.random()
tau = -np.log(r1) / total_propensity
random_propensity = r2 * total_propensity
abrgd_reaction_choice_ind = np.where(
np.cumsum(propensity_array[relevant_ind]) >= random_propensity
)[0][0]
reaction_choice_ind = relevant_ind[abrgd_reaction_choice_ind]
converted_rxn_ind = math.floor(reaction_choice_ind / 2)
if reaction_choice_ind % 2:
reverse = True
else:
reverse = False
state = update_state(reactants, products, state, converted_rxn_ind, reverse)
# Log the reactions that need to be altered after reaction is performed, for the coordination array
reactions_to_change = list()
for reactant_id in reactants[converted_rxn_ind, :]:
if reactant_id == -1:
continue
else:
reactions_to_change.extend(list(species_rxn_mapping[reactant_id, :]))
for product_id in products[converted_rxn_ind, :]:
if product_id == -1:
continue
else:
reactions_to_change.extend(list(species_rxn_mapping[product_id, :]))
rxns_change = set(reactions_to_change)
for rxn_ind in rxns_change:
if rxn_ind == -1:
continue
elif rxn_ind % 2:
this_reverse = True
else:
this_reverse = False
this_h = get_coordination(
reactants, products, state, math.floor(rxn_ind / 2), this_reverse
)
coord_array[rxn_ind] = this_h
propensity_array = np.multiply(rate_constants, coord_array)
relevant_ind = np.where(propensity_array > 0)[0]
total_propensity = np.sum(propensity_array[relevant_ind])
reaction_history[step_counter] = int(reaction_choice_ind)
times[step_counter] = tau
return np.vstack((np.array(reaction_history), np.array(times)))
@jit(nopython=True)
def update_state(reactants, products, state, rxn_ind, reverse):
"""
Updating the system state based on chosen reaction, during kMC simulation.
Args:
reactants: (n_rxns x 2) array, each row containing reactant mol_index of forward reaction
products: (n_rxns x 2) array, each row containing product mol_index of forward reaction
state: array of initial molecule amounts, indexed corresponding to reaction_network.entries_list
rxn_ind: int of reaction index, corresponding to position in reaction_network.reactions list
reverse: bool of whether this is the reverse reaction or not
:return: updated state array, after performing the specified reaction
"""
if rxn_ind == -1:
raise RuntimeError("Incorrect reaction index when updating state")
if reverse:
for reactant_id in products[rxn_ind, :]:
if reactant_id == -1:
continue
else:
state[reactant_id] -= 1
if state[reactant_id] < 0:
raise ValueError("State invalid! Negative specie encountered")
for product_id in reactants[rxn_ind, :]:
if product_id == -1:
continue
else:
state[product_id] += 1
else:
for reactant_id in reactants[rxn_ind, :]:
if reactant_id == -1:
continue
else:
state[reactant_id] -= 1
if state[reactant_id] < 0:
raise ValueError("State invalid! Negative specie encountered")
for product_id in products[rxn_ind, :]:
if product_id == -1:
continue
else:
state[product_id] += 1
return state
@jit(nopython=True)
def get_coordination(reactants, products, state, rxn_id, reverse):
"""
Calculate the coordination number of a reaction, for reactions involving two reactions of less.
They are defined as follows:
A -> B; coord = n(A)
A + A --> B; coord = n(A) * (n(A) - 1)
A + B --> C; coord = n(A) * n(B)
Args:
reactants: (n_rxns x 2) array, each row containing reactant mol_index of forward reaction
products: (n_rxns x 2) array, each row containing product mol_index of forward reaction
state: array of initial molecule amounts, indexed corresponding to reaction_network.entries_list
rxn_ind: int of reaction index, corresponding to position in reaction_network.reactions list
reverse: bool of whether this is the reverse reaction or not
:return: float of reaction coordination number
"""
if reverse:
reactant_array = products[rxn_id, :]
num_reactants = len(np.where(reactant_array != -1)[0])
else:
reactant_array = reactants[rxn_id, :]
num_reactants = len(np.where(reactant_array != -1)[0])
num_mols_list = list()
for reactant_id in reactant_array:
num_mols_list.append(state[reactant_id])
if num_reactants == 1:
h_prop = num_mols_list[0]
elif (num_reactants == 2) and (reactant_array[0] == reactant_array[1]):
h_prop = num_mols_list[0] * (num_mols_list[0] - 1) / 2
elif (num_reactants == 2) and (reactant_array[0] != reactant_array[1]):
h_prop = num_mols_list[0] * num_mols_list[1]
else:
raise RuntimeError(
"Only single and bimolecular reactions supported by this simulation"
)
return h_prop
class KmcDataAnalyzer:
"""
Functions to analyze (function-based) KMC outputs from many simulation runs. Ideally, the reaction history and
time history data are list of arrays.
Args:
reaction_network: fully generated ReactionNetwork, used for kMC simulation
molid_ind_mapping: dict mapping each entry's id to its index; of form {entry_id: mol_index, ... }
species_rxn_mapping: 2d array; each row i contains reactions which molecule_i takes part in
initial_state_dict: dict mapping mol_id to its initial amount {mol1_id: amt_1, mol2_id: amt2 ... }
products: (n_rxns x 2) array, each row containing product mol_index of forward reaction
reactants: (n_rxns x 2) array, each row containing reactant mol_index of forward reaction
reaction_history: list of arrays of reaction histories of each simulation.
time_history: list of arrays of time histories of each simulation.
"""
def __init__(
self,
reaction_network,
molid_ind_mapping,
species_rxn_mapping,
initial_state_dict,
products,
reactants,
reaction_history,
time_history,
):
self.reaction_network = reaction_network
self.molid_ind_mapping = molid_ind_mapping
self.species_rxn_mapping = species_rxn_mapping
self.initial_state_dict = initial_state_dict
self.products = products
self.reactants = reactants
self.reaction_history = reaction_history
self.time_history = time_history
self.num_sims = len(self.reaction_history)
if self.num_sims != len(self.time_history):
raise RuntimeError(
"Number of datasets for rxn history and time step history should be same!"
)
self.molind_id_mapping = [
mol.entry_id for mol in self.reaction_network.entries_list
]
def generate_time_dep_profiles(self):
"""
Generate plottable time-dependent profiles of species and rxns from raw KMC output, obtain final states.
:return dict containing species profiles, reaction profiles, and final states from each simulation.
{species_profiles: [ {mol_ind1: [(t0, n(t0)), (t1, n(t1)...], mol_ind2: [...] , ... }, {...}, ... ]
reaction_profiles: [ {rxn_ind1: [t0, t1, ...], rxn_ind2: ..., ...}, {...}, ...]
final_states: [ {mol_ind1: n1, mol_ind2: ..., ...}, {...}, ...] }
"""
species_profiles = list()
reaction_profiles = list()
final_states = list()
for n_sim in range(self.num_sims):
sim_time_history = self.time_history[n_sim]
sim_rxn_history = self.reaction_history[n_sim]
sim_species_profile = dict()
sim_rxn_profile = dict()
cumulative_time = list(np.cumsum(np.array(sim_time_history)))
state = copy.deepcopy(self.initial_state_dict)
for mol_ind in state:
sim_species_profile[mol_ind] = [(0.0, self.initial_state_dict[mol_ind])]
total_iterations = len(sim_rxn_history)
for iter in range(total_iterations):
rxn_ind = sim_rxn_history[iter]
t = cumulative_time[iter]
if rxn_ind not in sim_rxn_profile:
sim_rxn_profile[rxn_ind] = [t]
else:
sim_rxn_profile[rxn_ind].append(t)
converted_ind = math.floor(rxn_ind / 2)
if rxn_ind % 2:
reacts = self.products[converted_ind, :]
prods = self.reactants[converted_ind, :]
else:
reacts = self.reactants[converted_ind, :]
prods = self.products[converted_ind, :]
for r_ind in reacts:
if r_ind == -1:
continue
else:
try:
state[r_ind] -= 1
if state[r_ind] < 0:
raise ValueError(
"State invalid: negative specie: {}".format(r_ind)
)
sim_species_profile[r_ind].append((t, state[r_ind]))
except KeyError:
raise ValueError(
"Reactant specie {} given is not in state!".format(
r_ind
)
)
for p_ind in prods:
if p_ind == -1:
continue
else:
if (p_ind in state) and (p_ind in sim_species_profile):
state[p_ind] += 1
sim_species_profile[p_ind].append((t, state[p_ind]))
else:
state[p_ind] = 1
sim_species_profile[p_ind] = [(0.0, 0), (t, state[p_ind])]
# for plotting convenience, add data point at final time
for mol_ind in sim_species_profile:
sim_species_profile[mol_ind].append(
(cumulative_time[-1], state[mol_ind])
)
species_profiles.append(sim_species_profile)
reaction_profiles.append(sim_rxn_profile)
final_states.append(state)
return {
"species_profiles": species_profiles,
"reaction_profiles": reaction_profiles,
"final_states": final_states,
}
def final_state_analysis(self, final_states):
"""
Gather statistical analysis of the final states of simulation.
Args:
final_states: list of dicts of final states, as generated in generate_time_dep_profiles()
:return: list of tuples containing statistical data for each species, sorted from highest to low avg occurrence
"""
state_arrays = (
dict()
) # For each molecule, compile an array of its final amounts
for iter, final_state in enumerate(final_states):
for mol_ind, amt in final_state.items():
# Store the amount, and convert key from mol_ind to entry_id
if self.molind_id_mapping[mol_ind] not in state_arrays:
state_arrays[self.molind_id_mapping[mol_ind]] = np.zeros(
self.num_sims
)
state_arrays[self.molind_id_mapping[mol_ind]][iter] = amt
analyzed_states = dict() # will contain statistical results of final states
for mol_entry, state_array in state_arrays.items():
analyzed_states[mol_entry] = (np.mean(state_array), np.std(state_array))
# Sort from highest avg final amount to lowest
sorted_analyzed_states = sorted(
[(entry_id, data_tup) for entry_id, data_tup in analyzed_states.items()],
key=lambda x: x[1][0],
reverse=True,
)
return sorted_analyzed_states
def plot_species_profiles(
self,
species_profiles,
final_states,
num_label=12,
num_plots=None,
filename=None,
file_dir=None,
):
"""
Sorting and plotting species profiles for a specified number of simulations. The profiles might be very similar,
so may not need to plot all of the runs for good understanding of results.
Args:
species_profiles: list of dicts of species as function of time, for each simulation
final_states: list of dicts of final states of each simulation
num_label: integer number of species in the legend
filename (str)
file_dir (str)
"""
if num_plots is None:
num_plots = self.num_sims
elif num_plots > self.num_sims:
num_plots = self.num_sims
for n_sim in range(num_plots):
# Sorting and plotting:
fig, ax = plt.subplots()
sorted_state = sorted(
[(k, v) for k, v in final_states[n_sim].items()],
key=lambda x: x[1],
reverse=True,
)
sorted_inds = [mol_tuple[0] for mol_tuple in sorted_state]
sorted_ind_id_mapping = dict()
iter_counter = 0
for id, ind in self.molid_ind_mapping.items():
if ind in sorted_inds[:num_label]:
sorted_ind_id_mapping[ind] = id
iter_counter += 1
if iter_counter == num_label:
break
colors = plt.cm.get_cmap("hsv", num_label)
this_id = 0
t_end = sum(self.time_history[n_sim])
for mol_ind in species_profiles[n_sim]:
# ts = np.append(np.array([e[0] for e in species_profiles[n_sim][mol_ind]]), t_end)
ts = np.array([e[0] for e in species_profiles[n_sim][mol_ind]])
nums = np.array([e[1] for e in species_profiles[n_sim][mol_ind]])
if mol_ind in sorted_inds[:num_label]:
mol_id = sorted_ind_id_mapping[mol_ind]
for entry in self.reaction_network.entries_list:
if mol_id == entry.entry_id:
this_composition = (
entry.molecule.composition.alphabetical_formula
)
this_charge = entry.molecule.charge
this_label = this_composition + " " + str(this_charge)
this_color = colors(this_id)
this_id += 1
break
ax.plot(ts, nums, label=this_label, color=this_color)
else:
ax.plot(ts, nums)
title = "KMC simulation, total time {}".format(t_end)
ax.set(title=title, xlabel="Time (s)", ylabel="# Molecules")
ax.legend(
loc="upper right", bbox_to_anchor=(1, 1), ncol=2, fontsize="small"
)
sim_filename = filename + "_run_" + str(n_sim + 1)
if file_dir is None:
plt.show()
else:
plt.savefig(file_dir + "/" + sim_filename)
def analyze_intermediates(self, species_profiles, cutoff=0.9):
"""
Identify intermediates from species vs time profiles. Species are intermediates if consumed nearly as much
as they are created.
Args:
species_profile: Dict of list of tuples, as generated in generate_time_dep_profiles()
cutoff: (float) fraction to adjust definition of intermediate
:return: Analyzed data in a dict, of the form:
{mol1: {'freqency': (float), 'lifetime': (avg, std), 't_max': (avg, std), 'amt_produced': (avg, std)},
mol2: {...}, ... }
"""
intermediates = dict()
for n_sim in range(self.num_sims):
for mol_ind, prof in species_profiles[n_sim].items():
history = np.array([t[1] for t in prof])
diff_history = np.diff(history)
max_amt = max(history)
amt_produced = np.sum(diff_history == 1)
amt_consumed = np.sum(diff_history == -1)
# Identify the intermediate, accounting for fluctuations
if (amt_produced >= 3) and (amt_consumed > amt_produced * cutoff):
if mol_ind not in intermediates:
intermediates[mol_ind] = dict()
intermediates[mol_ind]["lifetime"] = list()
intermediates[mol_ind]["amt_produced"] = list()
intermediates[mol_ind]["t_max"] = list()
intermediates[mol_ind]["amt_consumed"] = list()
# Intermediate lifetime is approximately the time from its max amount to when nearly all consumed
max_ind = np.where(history == max_amt)[0][0]
t_max = prof[max_ind][0]
for state in prof[max_ind + 1 :]:
if state[1] < (1 - cutoff) * amt_produced + history[0]:
intermediates[mol_ind]["lifetime"].append(state[0] - t_max)
intermediates[mol_ind]["t_max"].append(t_max)
intermediates[mol_ind]["amt_produced"].append(amt_produced)
intermediates[mol_ind]["amt_consumed"].append(amt_consumed)
break
intermediates_analysis = dict()
for mol_ind in intermediates:
entry_id = self.molind_id_mapping[mol_ind]
intermediates_analysis[entry_id] = dict() # convert keys to entry id
if len(intermediates[mol_ind]["lifetime"]) != len(
intermediates[mol_ind]["t_max"]
):
raise RuntimeError("Intermediates data should be of the same length")
intermediates_analysis[entry_id]["frequency"] = (
len(intermediates[mol_ind]["lifetime"]) / self.num_sims
)
lifetime_array = np.array(intermediates[mol_ind]["lifetime"])
intermediates_analysis[entry_id]["lifetime"] = (
np.mean(lifetime_array),
np.std(lifetime_array),
)
t_max_array = np.array(intermediates[mol_ind]["t_max"])
intermediates_analysis[entry_id]["t_max"] = (
np.mean(t_max_array),
np.std(t_max_array),
)
amt_produced_array = np.array(intermediates[mol_ind]["amt_produced"])
intermediates_analysis[entry_id]["amt_produced"] = (
np.mean(amt_produced_array),
np.std(amt_produced_array),
)
amt_consumed_array = np.array(intermediates[mol_ind]["amt_consumed"])
intermediates_analysis[entry_id]["amt_consumed"] = (
np.mean(amt_consumed_array),
np.std(amt_produced_array),
)
# Sort by highest average amount produced
sorted_intermediates_analysis = sorted(
[
(entry_id, mol_data)
for entry_id, mol_data in intermediates_analysis.items()
],
key=lambda x: x[1]["amt_produced"][0],
reverse=True,
)
return sorted_intermediates_analysis
def correlate_reactions(self, reaction_inds):
"""
Correlate two reactions, by finding the average time and steps elapsed for rxn2 to fire after rxn1,
and vice-versa.
Args:
reaction_inds: list, array, or tuple of two reaction indexes
:return: dict containing analysis of how reactions are correlated {rxn1: {'time': (float), 'steps': (float),
'occurrences': float}, rxn2: {...} }
"""
correlation_data = dict()
correlation_analysis = dict()
for rxn_ind in reaction_inds:
correlation_data[rxn_ind] = dict()
correlation_data[rxn_ind]["time"] = list()
correlation_data[rxn_ind]["steps"] = list()
correlation_data[rxn_ind]["occurrences"] = list()
correlation_analysis[rxn_ind] = dict()
for n_sim in range(self.num_sims):
cum_time = np.cumsum(self.time_history[n_sim])
rxn_locations = dict()
# Find the step numbers when reactions fire in the simulation
for rxn_ind in reaction_inds:
rxn_locations[rxn_ind] = list(
np.where(self.reaction_history[n_sim] == rxn_ind)[0]
)
rxn_locations[rxn_ind].append(len(self.reaction_history[n_sim]))
# Correlate between each reaction
for (rxn_ind, location_list) in rxn_locations.items():
time_elapse = list()
step_elapse = list()
occurrences = 0
for (rxn_ind_j, location_list_j) in rxn_locations.items():
if rxn_ind == rxn_ind_j:
continue
for i in range(1, len(location_list)):
for loc_j in location_list_j:
# Find location where reaction j happens after reaction i, before reaction i fires again
if (loc_j > location_list[i - 1]) and (
loc_j < location_list[i]
):
time_elapse.append(
cum_time[loc_j] - cum_time[location_list[i - 1]]
)
step_elapse.append(loc_j - location_list[i - 1])
occurrences += 1
break
if len(time_elapse) == 0:
correlation_data[rxn_ind]["occurrences"].append(0)
else:
correlation_data[rxn_ind]["time"].append(
np.mean(np.array(time_elapse))
)
correlation_data[rxn_ind]["steps"].append(
np.mean(np.array(step_elapse))
)
correlation_data[rxn_ind]["occurrences"].append(occurrences)
for rxn_ind, data_dict in correlation_data.items():
if len(data_dict["time"]) != 0:
correlation_analysis[rxn_ind]["time"] = (
np.mean(np.array(data_dict["time"])),
np.std(np.array(data_dict["time"])),
)
correlation_analysis[rxn_ind]["steps"] = (
np.mean(np.array(data_dict["steps"])),
np.std(np.array(data_dict["steps"])),
)
correlation_analysis[rxn_ind]["occurrences"] = (
np.mean(np.array(data_dict["occurrences"])),
np.std(np.array(data_dict["occurrences"])),
)
else:
print(
"Reaction ",
rxn_ind,
"does not lead to the other reaction in simulation ",
n_sim,
)
return correlation_analysis
def quantify_specific_reaction(self, reaction_history, reaction_index):
"""
Quantify a reaction from one simulation reaction history
Args:
reaction_history: array containing sequence of reactions fired during a simulation.
reaction_index: integer of reaction index of interest
:return: integer number of times reaction is fired
"""
if reaction_index not in reaction_history:
reaction_count = 0
else:
reaction_count = len(reaction_history[reaction_index])
return reaction_count
def quantify_rank_reactions(self, reaction_type=None, num_rxns=None):
"""
Given reaction histories, identify the most commonly occurring reactions, on average.
Can rank generally, or by reactions of a certain type.
Args:
reaction_profiles (list of dicts): reactions fired as a function of time
reaction_type (string)
num_rxns (int): the amount of reactions interested in collecting data on. If None, record for all.
Returns:
reaction_data: list of reactions and their avg, std of times fired. Sorted by the average times fired.
[(rxn1, (avg, std)), (rxn2, (avg, std)) ... ]
"""
allowed_rxn_types = [
"One electron reduction",
"One electron oxidation",
"Intramolecular single bond breakage",
"Intramolecular single bond formation",
"Coordination bond breaking AM -> A+M",
"Coordination bond forming A+M -> AM",
"Molecular decomposition breaking one bond A -> B+C",
"Molecular formation from one new bond A+B -> C",
"Concerted",
]
if reaction_type is not None:
rxns_of_type = list()
if reaction_type not in allowed_rxn_types:
raise RuntimeError(
"This reaction type does not (yet) exist in our reaction networks."
)
for ind, rxn in enumerate(self.reaction_network.reactions):
if rxn.reaction_type()["rxn_type_A"] == reaction_type:
rxns_of_type.append(2 * ind)
elif rxn.reaction_type()["rxn_type_B"] == reaction_type:
rxns_of_type.append(2 * ind + 1)
reaction_data = dict() # keeping record of each iteration
# Loop to count all reactions fired
for n_sim in range(self.num_sims):
rxns_fired = set(self.reaction_history[n_sim])
if reaction_type is not None:
relevant_rxns = [r for r in rxns_fired if r in rxns_of_type]
else:
relevant_rxns = rxns_fired
for rxn_ind in relevant_rxns:
if rxn_ind not in reaction_data:
reaction_data[rxn_ind] = list()
reaction_data[rxn_ind].append(
np.sum(self.reaction_history[n_sim] == rxn_ind)
)
reaction_analysis = dict()
for rxn_ind, counts in reaction_data.items():
reaction_analysis[rxn_ind] = (
np.mean(np.array(counts)),
np.std(np.array(counts)),
)
# Sort reactions by the average amount fired
sorted_reaction_analysis = sorted(
[(i, c) for i, c in reaction_analysis.items()],
key=lambda x: x[1][0],
reverse=True,
)
if num_rxns is None:
return sorted_reaction_analysis
else:
return sorted_reaction_analysis[:num_rxns]
def frequency_analysis(self, rxn_inds, spec_inds, partitions=100):
"""
Calculate the frequency of reaction and species formation as a function of time. Simulation data is
discretized into time intervals, and probabilities in each set are obtained.
Args:
rxn_inds: list of indeces of reactions of interest
spec_inds: list of molecule indexes of interest
partitions: number of intervals in which to discretize time
:return: dict of dicts containing the statistics of reaction fired, product formed at each time interval.
{reaction_data: {rxn_ind1: [(t0, avg0, std0), (t1, avg1, std1), ...], rxn_ind2: [...], ... rxn_ind_n: [...]}
{species_data: {spec1: [(t0, avg0, std0), (t1, avg1, std1), ...], spec2: [...], ... specn: [...]}}
"""
reaction_frequency_data = dict()
reaction_frequency_array = (
dict()
) # Growing arrays of reaction frequencies as fxn of time
species_frequency_data = dict()
species_frequency_array = dict()
new_species_counters = dict()
for ind in rxn_inds:
reaction_frequency_data[ind] = [0 for j in range(partitions)]
for ind in spec_inds:
species_frequency_data[ind] = [0 for j in range(partitions)]
new_species_counters[ind] = 0
for n_sim in range(self.num_sims):
delta_t = np.sum(self.time_history[n_sim]) / partitions
ind_0 = 0
t = 0
n = 0 # for tracking which time interval we are in
species_counters = copy.deepcopy(
new_species_counters
) # for counting species as they appear
rxn_freq_data = copy.deepcopy(reaction_frequency_data)
spec_freq_data = copy.deepcopy(species_frequency_data)
for step_num, tau in enumerate(self.time_history[n_sim]):
t += tau
this_rxn_ind = int(self.reaction_history[n_sim][step_num])
if this_rxn_ind % 2: # reverse reaction
prods = self.reactants[math.floor(this_rxn_ind / 2), :]
else:
prods = self.products[math.floor(this_rxn_ind / 2), :]
for spec_ind in spec_inds:
if spec_ind in prods:
species_counters[spec_ind] += 1
# When t reaches the next discretized time step, or end of the simulation
if (t >= (n + 1) * delta_t) or (
step_num == len(self.reaction_history[n_sim]) - 1
):
n_to_fill = n
if t >= (n + 2) * delta_t:
n += math.floor(t / delta_t - n)
else:
n += 1
steps = step_num - ind_0 + 1
for spec_ind in spec_inds:
spec_freq_data[spec_ind][n_to_fill] = (
species_counters[spec_ind] / steps
)
for rxn_ind in rxn_inds:
rxn_freq = (
np.count_nonzero(
self.reaction_history[n_sim][ind_0 : step_num + 1]
== rxn_ind
)
/ steps
)
# t_mdpt = (self.time_history[n_sim][step_num] + self.time_history[n_sim][ind_0]) / 2
rxn_freq_data[rxn_ind][n_to_fill] = rxn_freq
# Reset and update counters
species_counters = copy.deepcopy(new_species_counters)
ind_0 = step_num + 1
for rxn_ind in rxn_inds:
if n_sim == 0:
reaction_frequency_array[rxn_ind] = np.array(rxn_freq_data[rxn_ind])
else:
reaction_frequency_array[rxn_ind] = np.vstack(
(reaction_frequency_array[rxn_ind], rxn_freq_data[rxn_ind])
)
# print('reaction freq array', reaction_frequency_array)
for spec_ind in spec_inds:
if n_sim == 0:
species_frequency_array[spec_ind] = np.array(
spec_freq_data[spec_ind]
)
else:
species_frequency_array[spec_ind] = np.vstack(
(species_frequency_array[spec_ind], spec_freq_data[spec_ind])
)
# Statistical analysis
statistical_rxn_data = dict()
statistical_spec_data = dict()
avg_delta_t = (
np.mean(np.array([sum(self.time_history[i]) for i in range(self.num_sims)]))
/ partitions
)
time_list = [i * avg_delta_t + avg_delta_t / 2 for i in range(partitions)]
# print('time_list: ', time_list)
for rxn_ind in rxn_inds:
if self.num_sims == 1:
avgs = reaction_frequency_array[rxn_ind]
stds = np.zeros(partitions)
else:
avgs = | np.mean(reaction_frequency_array[rxn_ind], 0) | numpy.mean |
import math
import numpy
import warnings
warnings.simplefilter('ignore', DeprecationWarning)
import scipy
import scipy.special
import scipy.optimize
warnings.simplefilter('default', DeprecationWarning)
def sqr(z):
return z*z
def faddeeva(z, NT=None):
"""computes w(z) = exp(-z^2) erfc(iz) according to
<NAME>, "Computation of the Complex Error Function,"
NT: number of terms to evaluate in approximation
Weideman claims that NT=16 yields about 6 digits,
NT=32 yields about 12 digits, for Im(z) >= 0.
However, faddeeva(100.,16) yields only 8 accurate digits.
For Im(z)>=0:
By graphing, we see that NT=16 does yield errors < 10^{-6}
and NT=32 errors < 10^{-12}
NT=36 yields errors < 10^{-14}.
For NT>=40, the errors will never be (everywhere) smaller
than 10^{-14}...values oscillate as NT increases above 40.
For Im(z)<0, the relative accuracy suffers near zeros
of w(z).
"""
if (type(z) != numpy.ndarray):
return faddeeva(numpy.array([z]), NT)
if (NT==None):
NT = 42
numSamplePts = 2*NT
ind = numpy.arange(-numSamplePts+1.,numSamplePts)
L = numpy.sqrt(NT/numpy.sqrt(2))
theta = (math.pi / numSamplePts) * ind
t = L * numpy.tan(0.5*theta)
fn = numpy.empty((ind.size+1,),dtype = t.dtype)
fn[0] = 0.
fn[1:] = numpy.exp(-t*t) * (L*L + t*t)
polyCoefs = numpy.fft.fft(numpy.fft.fftshift(fn)).real / (2*numSamplePts)
polyCoefs = numpy.flipud(polyCoefs[1:(NT+1)])
negzInd = z.imag < 0
signs = numpy.ones(z.shape, dtype=z.dtype)
signs[negzInd] *= -1.
# first use of z follows
polyArgs = (L + (0.+1.j)*signs*z)/(L-(0.+1.j)*signs*z)
polyVals = numpy.polyval(polyCoefs,polyArgs)
res = 2.*polyVals/ sqr(L-(0.+1.j)*signs*z) \
+ (1./math.sqrt(math.pi)) / (L-(0.+1.j)*signs*z)
res *= signs
res[negzInd] += 2.*numpy.exp(-z[negzInd]*z[negzInd])
#res=res.squeeze()
if not res.ndim: res=res.tolist()
return res
def graphFaddeevaAccuracy(nt1, nt2):
import pylab
xmin = 0.01
xmax = 100.3
nx = 437
ymin = 0.0099
ymax = 100.1
ny = 439
logxmin = numpy.log10(xmin)
logxmax = numpy.log10(xmax)
logymin = numpy.log10(ymin)
logymax = numpy.log10(ymax)
xs = | numpy.arange(logxmin,logxmax,(logxmax-logxmin)/nx) | numpy.arange |
import numpy as np
from gym import spaces
from gym import Env
class PointEnv(Env):
"""
point mass on a 2-D plane
goals are sampled randomly from a square
"""
def __init__(self, num_tasks=1, checkerboard_size=0.1):
self.checkerboard_size = checkerboard_size
self.reset_task()
self.reset()
self.observation_space = spaces.Box(low=-np.inf,
high=np.inf,
shape=(2,),
dtype=np.float32)
self.action_space = spaces.Box(low=-0.1,
high=0.1,
shape=(2,),
dtype=np.float32)
self._state = None
def reset_task(self, is_evaluation=False):
'''
sample a new task randomly
Problem 3: make training and evaluation goals disjoint sets
if `is_evaluation` is true, sample from the evaluation set,
otherwise sample from the training set
'''
# ==================================================================== #
# ----------PROBLEM 3----------
# ==================================================================== #
STATIC_SIZE = 10 # final normalized board range: -10..10
x_cell = np.random.uniform(0, 1)
y_cell = np.random.uniform(0, 1)
if self.checkerboard_size == 0:
# normalize to -10..10
self._goal = np.array([x_cell, y_cell]) * STATIC_SIZE * 2 - STATIC_SIZE
else:
# NB, size of the checkerboard should be quadratic and even to stay fair
WIDTH = HEIGHT = int(1. / self.checkerboard_size)
BLACK = int(np.ceil(WIDTH * HEIGHT / 2.)) # evaluation
WHITE = int(np.floor(WIDTH * HEIGHT / 2.)) # train
ROW_WIDTH = int(np.ceil(WIDTH / 2))
if is_evaluation:
pos = | np.random.randint(0, BLACK) | numpy.random.randint |
import collections
import csv
import datetime
import itertools
import logging
import math
import numpy
import os
import sys
import utility
MOVIE_COUNT = 17770
USER_COUNT = 480189
MAX_USER_ID = 2649429
NUM_RATING = 100480507
Datasets = collections.namedtuple('Datasets', ['train', 'validation', 'test'])
class DataSet(object):
@staticmethod
def fromfile(filename):
data = numpy.load(filename)
return DataSet(data['movie_ids'], data['user_ids'], data['dates'], data['ratings'], data['user_map'])
def __init__(self, movie_ids, user_ids, dates, ratings, user_map):
self.movie_ids_ = numpy.asarray(movie_ids)
self.user_ids_ = numpy.asarray(user_ids)
self.dates_ = numpy.asarray(dates)
self.ratings_ = numpy.asarray(ratings)
self.user_map_ = user_map
@property
def num_examples(self):
return len(self.ratings_)
@property
def movie_ids(self):
return self.movie_ids_
@property
def user_ids(self):
return self.user_ids_
@property
def dates(self):
return self.dates_
@property
def ratings(self):
return self.ratings_
@property
def user_map(self):
return self.user_map_
def iter_batch(self, batch_size, shuffle=True):
while True:
indices = numpy.random.choice(self.num_examples, batch_size)
movie_ids = self.movie_ids_[indices]
user_ids = self.user_ids_[indices]
dates = self.dates_[indices]
ratings = self.ratings_[indices]
yield DataSet(movie_ids, user_ids, dates, ratings, self.user_map)
def split(self, validation_size, test_size):
assert validation_size + test_size <= self.num_examples
train_size = self.num_examples - validation_size - test_size
perm = numpy.arange(self.num_examples)
numpy.random.shuffle(perm)
def genenerate_datasets():
for i,j in utility.pairwise(itertools.accumulate([0, train_size, validation_size, test_size, 1.0])):
indices = perm[i:j]
movie_ids = self.movie_ids_[indices]
user_ids = self.user_ids_[indices]
dates = self.dates_[indices]
ratings = self.ratings_[indices]
yield DataSet(movie_ids, user_ids, dates, ratings, self.user_map)
datasets = genenerate_datasets()
train = next(datasets)
validation = next(datasets)
test = next(datasets)
return Datasets(train=train, validation=validation, test=test)
def save(self, filename):
numpy.savez(filename,
movie_ids = self.movie_ids_,
user_ids = self.user_ids_,
dates = self.dates_,
ratings = self.ratings_,
user_map = self.user_map_)
def find_dense_subset(self, n_users, n_movies):
user_ratings = numpy.zeros(USER_COUNT)
movie_ratings = numpy.zeros(MOVIE_COUNT)
for user, movie in zip(self.user_ids_, self.movie_ids_):
user_ratings[user] += 1
movie_ratings[movie] += 1
user_subset = set(numpy.argpartition(user_ratings, -n_users)[-n_users:])
movie_subset = set(numpy.argpartition(movie_ratings, -n_movies)[-n_movies:])
n_couples = 0
for user, movie in zip(self.user_ids_, self.movie_ids_):
if user in user_subset and movie in movie_subset:
n_couples += 1
ratings = numpy.zeros(n_couples, dtype=numpy.int8)
movie_ids = numpy.zeros(n_couples, dtype=numpy.int16)
user_ids = | numpy.zeros(n_couples, dtype=numpy.int32) | numpy.zeros |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 5 21:02:07 2021
@author: lukepinkel
"""
import patsy
import numpy as np
import scipy as sp
import scipy.stats
import pandas as pd
import scipy.interpolate
import matplotlib.pyplot as plt
from .smooth_setup import parse_smooths, get_parametric_formula, get_smooth
from ..pyglm.families import Gaussian
from ..utilities.splines import (crspline_basis, bspline_basis, ccspline_basis,
absorb_constraints)
class GaussianAdditiveModel:
def __init__(self, formula, data):
family = Gaussian()
smooth_info = parse_smooths(formula, data)
formula = get_parametric_formula(formula)
y, Xp = patsy.dmatrices(formula, data, return_type='dataframe',
eval_env=1)
varnames = Xp.columns.tolist()
smooths = {}
start = p = Xp.shape[1]
ns = 0
for key, val in smooth_info.items():
slist = get_smooth(**val)
if len(slist)==1:
smooths[key], = slist
p_i = smooths[key]['X'].shape[1]
varnames += [f"{key}{j}" for j in range(1, p_i+1)]
p += p_i
ns += 1
else:
for i, x in enumerate(slist):
by_key = f"{key}_{x['by_cat']}"
smooths[by_key] = x
p_i = x['X'].shape[1]
varnames += [f"{by_key}_{j}" for j in range(1, p_i+1)]
p += p_i
ns += 1
X, S, Sj, ranks, ldS = [Xp], np.zeros((ns, p, p)), [], [], []
for i, (var, s) in enumerate(smooths.items()):
p_i = s['X'].shape[1]
Si, ix = np.zeros((p, p)), np.arange(start, start+p_i)
start += p_i
Si[ix, ix.reshape(-1, 1)] = s['S']
smooths[var]['ix'], smooths[var]['Si'] = ix, Si
X.append(smooths[var]['X'])
S[i] = Si
Sj.append(s['S'])
ranks.append(np.linalg.matrix_rank(Si))
u = np.linalg.eigvals(s['S'])
ldS.append(np.log(u[u>np.finfo(float).eps]).sum())
self.X, self.Xp, self.y = np.concatenate(X, axis=1), Xp.values, y.values[:, 0]
self.S, self.Sj, self.ranks, self.ldS = S, Sj, ranks, ldS
self.f, self.smooths = family, smooths
self.ns, self.n_obs, self.nx = ns, self.X.shape[0], self.X.shape[1]
self.mp = self.nx - np.sum(self.ranks)
self.data = data
theta = np.zeros(self.ns+1)
for i, (var, s) in enumerate(smooths.items()):
ix = smooths[var]['ix']
a = self.S[i][ix, ix[:, None].T]
d = np.diag(self.X[:, ix].T.dot(self.X[:, ix]))
lam = (1.5 * (d / a)[a>0]).mean()
theta[i] = np.log(lam)
varnames += [f"log_smooth_{var}"]
theta[-1] = 1.0
varnames += ["log_scale"]
self.theta = theta
self.varnames = varnames
self.smooth_info = smooth_info
def get_wz(self, eta):
mu = self.f.inv_link(eta)
v = self.f.var_func(mu=mu)
dg = self.f.dinv_link(eta)
r = self.y - mu
a = 1.0 + r * (self.f.dvar_dmu(mu) / v + self.f.d2link(mu) * dg)
z = eta + r / (dg * a)
w = a * dg**2 / v
return z, w
def solve_pls(self, eta, S):
z, w = self.get_wz(eta)
Xw = self.X * w[:, None]
beta_new = np.linalg.solve(Xw.T.dot(self.X)+S, Xw.T.dot(z))
return beta_new
def pirls(self, alpha, n_iters=200, tol=1e-7):
beta = np.zeros(self.X.shape[1])
S = self.get_penalty_mat(alpha)
eta = self.X.dot(beta)
dev = self.f.deviance(self.y, mu=self.f.inv_link(eta)).sum()
success = False
for i in range(n_iters):
beta_new = self.solve_pls(eta, S)
eta_new = self.X.dot(beta_new)
dev_new = self.f.deviance(self.y, mu=self.f.inv_link(eta_new)).sum()
if dev_new > dev:
success=False
break
if abs(dev - dev_new) / dev_new < tol:
success = True
break
eta = eta_new
dev = dev_new
beta = beta_new
return beta, eta, dev, success, i
def get_penalty_mat(self, alpha):
Sa = np.einsum('i,ijk->jk', alpha, self.S)
return Sa
def logdetS(self, alpha, phi):
logdet = 0.0
for i, (r, lds) in enumerate(list(zip(self.ranks, self.ldS))):
logdet += r * np.log(alpha[i]/phi) + lds
return logdet
def grad_beta_rho(self, beta, alpha):
S = self.get_penalty_mat(alpha)
A = np.linalg.inv(self.hess_dev_beta(beta, S))
dbdr = np.zeros((beta.shape[0], alpha.shape[0]))
for i in range(self.ns):
Si = self.S[i]
dbdr[:, i] = -alpha[i] * A.dot(Si.dot(beta))*2.0
return dbdr
def hess_dev_beta(self, beta, S):
mu = self.f.inv_link(self.X.dot(beta))
v0, g1 = self.f.var_func(mu=mu), self.f.dlink(mu)
v1, g2 = self.f.dvar_dmu(mu), self.f.d2link(mu)
r = self.y - mu
w = (1.0 + r * (v1 / v0 + g2 / g1)) / (v0 * g1**2)
d2Ddb2 = 2.0 * (self.X * w[:, None]).T.dot(self.X) + 2.0 * S
return d2Ddb2
def reml(self, theta):
lam, phi = np.exp(theta[:-1]), np.exp(theta[-1])
S, X, y = self.get_penalty_mat(lam), self.X, self.y
XtX = X.T.dot(X)
beta = np.linalg.solve(XtX + S, X.T.dot(y))
r = y - X.dot(beta)
rss = r.T.dot(r)
bsb = beta.T.dot(S).dot(beta)
_, ldh = np.linalg.slogdet(XtX / phi + S / phi)
lds = self.logdetS(lam, phi)
Dp = (rss + bsb) / phi
K = ldh - lds
ls = (self.n_obs) * | np.log(2.0*np.pi*phi) | numpy.log |
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import os.path as osp
import joblib
MAIN_PATH = '/scratch/gobi2/kamyar/oorl_rlkit/output'
WHAT_TO_PLOT = 'faster_all_eval_stats.pkl'
# WHAT_TO_PLOT = 'faster_all_eval_stats.pkl'
# WHAT_TO_PLOT = 'faster_all_eval_stats.pkl'
data_dirs = {
'np_airl': {
0.2: 'correct-saving-np-airl-KL-0p2-disc-512-dim-rew-2-NO-TARGET-ANYTHING-over-10-epochs',
0.15: 'correct-saving-np-airl-KL-0p15-disc-512-dim-rew-2-NO-TARGET-ANYTHING-over-10-epochs',
0.1: 'correct-saving-np-airl-KL-0p1-disc-512-dim-rew-2-NO-TARGET-ANYTHING-over-10-epochs',
0.05: 'correct-saving-np-airl-KL-0p05-disc-512-dim-rew-2-NO-TARGET-ANYTHING-over-10-epochs',
0.0: 'correct-saving-np-airl-KL-0-disc-512-dim-rew-2-NO-TARGET-ANYTHING-over-10-epochs'
},
'np_bc': {
0.2: 'np-bc-KL-0p2-FINAL-WITHOUT-TARGETS',
0.15: 'np-bc-KL-0p15-FINAL-WITHOUT-TARGETS',
0.1: 'np-bc-KL-0p1-FINAL-WITHOUT-TARGETS',
0.05: 'np-bc-KL-0p05-FINAL-WITHOUT-TARGETS',
0.0: 'np-bc-KL-0-FINAL-WITHOUT-TARGETS'
}
}
# fig, ax = plt.subplots(1, 5)
for i, beta in enumerate([0.0, 0.05, 0.1, 0.15, 0.2]):
fig, ax = plt.subplots(1)
ax.set_xlabel('$\\beta = %.2f$' % beta)
# np_airl
all_stats = joblib.load(osp.join(MAIN_PATH, data_dirs['np_airl'][beta], WHAT_TO_PLOT))['faster_all_eval_stats']
good_reaches_means = []
good_reaches_stds = []
solves_means = []
solves_stds = []
for c_size in range(1,7):
good_reaches = []
solves = []
for d in all_stats:
good_reaches.append(d[c_size]['Percent_Good_Reach'])
solves.append(d[c_size]['Percent_Solved'])
good_reaches_means.append(np.mean(good_reaches))
good_reaches_stds.append(np.std(good_reaches))
solves_means.append(np.mean(solves))
solves_stds.append(np.std(solves))
# ax.errorbar(list(range(1,7)), good_reaches_means, good_reaches_stds)
ax.errorbar(np.array(list(range(1,7))) + 0.1, solves_means, solves_stds,
elinewidth=2.0, capsize=4.0, barsabove=True, linewidth=2.0, label='Meta-AIRL'
)
# np_bc
all_stats = joblib.load(osp.join(MAIN_PATH, data_dirs['np_bc'][beta], WHAT_TO_PLOT))['faster_all_eval_stats']
good_reaches_means = []
good_reaches_stds = []
solves_means = []
solves_stds = []
for c_size in range(1,7):
good_reaches = []
solves = []
for d in all_stats:
good_reaches.append(d[c_size]['Percent_Good_Reach'])
solves.append(d[c_size]['Percent_Solved'])
good_reaches_means.append(np.mean(good_reaches))
good_reaches_stds.append( | np.std(good_reaches) | numpy.std |
#!/software/et_env/bin python
import numpy as np
from sklearn.decomposition import PCA
import argparse
def orig_to_trans(pars):
gamma=pars[6]
logM_env=pars[8]
beta=pars[7]
incl=pars[14]
pars[6]=np.log10(2.1-1*gamma)
pars[8]=np.log10(-1.5-1*logM_env)
s=np.sin(0.7)
c=np.cos(0.7)
pars[7]=1-np.cos(((beta*c) + (incl*s/60)-.5)*np.pi/2)
pars[14]=(-beta*s) + (incl*c/60)
return pars
param_names = ["Tstar","logLstar","logMdisk","logRdisk","h0","logRin",\
"gamma","beta","logMenv","logRenv","fcav","ksi","logamax","p","incl"]
seds_dict=np.load("./etgrid/et_dictionary_seds.npy",allow_pickle=True)
seds=np.load("./etgrid/seds.npy",allow_pickle=True)[:,100:500]
nanseds=np.load("./etgrid/seds.npy",allow_pickle=True)[:,100:500]
xvals=np.load("./etgrid/xvals.npy",allow_pickle=True)
# fix -infs: powerlaw cutoff
for i in range(len(seds)):
if -np.inf in seds[i]:
a = seds[i].tolist()
a.reverse()
ind = len(a)-a.index(-np.inf)
x1 = xvals[ind]
y1 = seds[i][ind]
for j in range(ind):
seds[i][j]=(100*(np.log10(xvals[j]/x1)))+y1
np.save("./etgrid/sedsflat.npy",np.ndarray.flatten(seds))
# subtracting from each SED its sample mean
nanseds[nanseds<-20]=np.nan
seds_msub = seds - np.nanmean(nanseds,axis=1)[:,np.newaxis]
# run PCA
pca = PCA(n_components=40).fit(seds_msub)
print("PCA finished")
eigenseds=np.array(pca.components_)
# compile PCA weight data
fitdata=[]
for i in range(len(seds)):
fitdata.append(pca.transform(seds_msub[i].reshape(1,-1))[0][0:15]) # first 15 weights for each SED
params_bypoint=[]
weights_bypoint=[]
means=[]
for i in range(len(seds)):
pars_orig=[]
for j in range(len(param_names)):
pars_orig.append(seds_dict[i][param_names[j]])
pars_trans=orig_to_trans(pars_orig)
params_bypoint.append(pars_trans) # coordinates in transformed parameter space
weights_bypoint.append(fitdata[i]) # set of first 15 weights
means.append(np.nanmean(nanseds,axis=1)[i]) # mean
weights_byweight=np.ndarray.tolist(np.transpose(weights_bypoint))
weights_byweight.append(means)
print("weights calculated")
parser=argparse.ArgumentParser()
parser.add_argument("--name", help="pca instance nickname",type=str)
args=parser.parse_args()
name=args.name
| np.save("./etgrid/"+name+"_coords.npy",params_bypoint) | numpy.save |
from collections import OrderedDict
import numpy as np
from robosuite_extra.env_base.sawyer import SawyerEnv
from robosuite.models.arenas import TableArena
from robosuite.models.objects import BoxObject, CylinderObject
from robosuite_extra.models.generated_objects import FullyFrictionalBoxObject
from robosuite_extra.models.tasks import UniformSelectiveSampler
from robosuite.utils.mjcf_utils import array_to_string
from robosuite_extra.push_env.push_task import PushTask
from robosuite_extra.utils import transform_utils as T
from robosuite_extra.controllers import SawyerEEFVelocityController
import copy
from collections import deque
class SawyerPush(SawyerEnv):
"""
This class corresponds to a Pushing task for the sawyer robot arm.
This task consists of pushing a rectangular puck from some initial position to a final goal.
The goal and initial positions are chosen randomly within some starting bounds
"""
def __init__(
self,
gripper_type="PushingGripper",
parameters_to_randomise=None,
randomise_initial_conditions=True,
table_full_size=(0.8, 1.6, 0.719),
table_friction=(1e-4, 5e-3, 1e-4),
use_camera_obs=False,
use_object_obs=True,
reward_shaping=True,
placement_initializer=None,
gripper_visualization=True,
use_indicator_object=False,
has_renderer=False,
has_offscreen_renderer=True,
render_collision_mesh=False,
render_visual_mesh=True,
control_freq=10,
horizon=80,
ignore_done=False,
camera_name="frontview",
camera_height=256,
camera_width=256,
camera_depth=False,
pid=True,
):
"""
Args:
gripper_type (str): type of gripper, used to instantiate
gripper models from gripper factory.
parameters_to_randomise [string,] : List of keys for parameters to randomise, None means all the available parameters are randomised
randomise_initial_conditions [bool,]: Whether or not to randomise the starting configuration of the task.
table_full_size (3-tuple): x, y, and z dimensions of the table.
table_friction (3-tuple): the three mujoco friction parameters for
the table.
use_camera_obs (bool): if True, every observation includes a
rendered image.
use_object_obs (bool): if True, include object (cube) information in
the observation.
reward_shaping (bool): if True, use dense rewards.
placement_initializer (ObjectPositionSampler instance): if provided, will
be used to place objects on every reset, else a UniformRandomSampler
is used by default.
gripper_visualization (bool): True if using gripper visualization.
Useful for teleoperation.
use_indicator_object (bool): if True, sets up an indicator object that
is useful for debugging.
has_renderer (bool): If true, render the simulation state in
a viewer instead of headless mode.
has_offscreen_renderer (bool): True if using off-screen rendering.
render_collision_mesh (bool): True if rendering collision meshes
in camera. False otherwise.
render_visual_mesh (bool): True if rendering visual meshes
in camera. False otherwise.
control_freq (float): how many control signals to receive
in every second. This sets the amount of simulation time
that passes between every action input.
horizon (int): Every episode lasts for exactly @horizon timesteps.
ignore_done (bool): True if never terminating the environment (ignore @horizon).
camera_name (str): name of camera to be rendered. Must be
set if @use_camera_obs is True.
camera_height (int): height of camera frame.
camera_width (int): width of camera frame.
camera_depth (bool): True if rendering RGB-D, and RGB otherwise.
pid (bool) : True if using a velocity PID controller for controlling the arm, false if using a
mujoco-implemented proportional controller.
"""
self.initialised = False
# settings for table
self.table_full_size = table_full_size
self.table_friction = table_friction
# whether to use ground-truth object states
self.use_object_obs = use_object_obs
# reward configuration
self.reward_shaping = reward_shaping
if (self.reward_shaping):
self.reward_range = [-np.inf, horizon * (0.1)]
else:
self.reward_range = [0, 1]
# Domain Randomisation Parameters
self.parameters_to_randomise = parameters_to_randomise
self.randomise_initial_conditions = randomise_initial_conditions
self.dynamics_parameters = OrderedDict()
self.default_dynamics_parameters = OrderedDict()
self.parameter_sampling_ranges = OrderedDict()
self.factors_for_param_randomisation = OrderedDict()
# object placement initializer
if placement_initializer:
self.placement_initializer = placement_initializer
else:
self.placement_initializer = UniformSelectiveSampler(
x_range=None,
y_range=None,
ensure_object_boundary_in_range=True,
z_rotation=None,
np_random=None
)
# Param for storing a specific goal and object starting positions
self.specific_goal_position = None
self.specific_gripper_position = None
self.gripper_pos_neutral = [0.44969246, 0.16029991, 1.00875409]
super().__init__(
gripper_type=gripper_type,
gripper_visualization=gripper_visualization,
use_indicator_object=use_indicator_object,
has_renderer=has_renderer,
has_offscreen_renderer=has_offscreen_renderer,
render_collision_mesh=render_collision_mesh,
render_visual_mesh=render_visual_mesh,
control_freq=control_freq,
horizon=horizon,
ignore_done=ignore_done,
use_camera_obs=use_camera_obs,
camera_name=camera_name,
camera_height=camera_height,
camera_width=camera_width,
camera_depth=camera_depth,
pid=pid,
)
self._set_default_dynamics_parameters(pid)
self._set_default_parameter_sampling_ranges()
self._set_dynamics_parameters(self.default_dynamics_parameters)
self._set_factors_for_param_randomisation(self.default_dynamics_parameters)
# Check that the parameters to randomise are within the allowed parameters
if (self.parameters_to_randomise is not None):
self._check_allowed_parameters(self.parameters_to_randomise)
# IK solver for placing the arm at desired locations during reset
self.IK_solver = SawyerEEFVelocityController()
self.placement_initializer.set_random_number_generator(self.np_random)
self.init_control_timestep = self.control_timestep
self.init_qpos = self.mujoco_robot.init_qpos
# Storing parameters for temporary switching
self.cached_parameters_to_randomise = None
self.cached_dynamics_parameters = None
self.initialised = True
self.reset()
def _set_dynamics_parameters(self, parameters):
self.dynamics_parameters = copy.deepcopy(parameters)
def _default_damping_params(self):
# return np.array([0.01566, 1.171, 0.4906, 0.1573, 1.293, 0.08688, 0.1942]) # -real world calibration
# return np.array([0.8824,2.3357,1.1729, 0.0 , 0.5894, 0.0 ,0.0082]) #- command calibration
return np.array([8.19520686e-01, 1.25425414e+00, 1.04222253e+00,
0.00000000e+00, 1.43146116e+00, 1.26807887e-01, 1.53680244e-01, ]) # - command calibration 2
def _default_armature_params(self):
return np.array([0.00000000e+00, 0.00000000e+00, 2.70022664e-02, 5.35581203e-02,
3.31204140e-01, 2.59623415e-01, 2.81964631e-01, ])
def _default_joint_friction_params(self):
return np.array([4.14390483e-03,
9.30938506e-02, 2.68656509e-02, 0.00000000e+00, 0.00000000e+00,
4.24867204e-04, 8.62040317e-04])
def _set_default_dynamics_parameters(self, use_pid):
"""
Setting the the default environment parameters.
"""
self.default_dynamics_parameters['joint_forces'] = np.zeros((7,))
self.default_dynamics_parameters['acceleration_forces'] = np.zeros((7,))
self.default_dynamics_parameters['eef_forces'] = np.zeros((6,))
self.default_dynamics_parameters['obj_forces'] = np.zeros((6,))
self.default_dynamics_parameters['eef_timedelay'] = np.asarray(0)
self.default_dynamics_parameters['obj_timedelay'] = np.asarray(0)
self.default_dynamics_parameters['timestep_parameter'] = np.asarray(0.0)
self.default_dynamics_parameters['pid_iteration_time'] = np.asarray(0.)
self.default_dynamics_parameters['mujoco_timestep'] = np.asarray(0.002)
self.default_dynamics_parameters['action_additive_noise'] = np.asarray(0.0)
self.default_dynamics_parameters['action_multiplicative_noise'] = np.asarray(0.0)
self.default_dynamics_parameters['action_systematic_noise'] = np.asarray(0.0)
self.default_dynamics_parameters['eef_obs_position_noise'] = np.asarray(0.0)
self.default_dynamics_parameters['eef_obs_velocity_noise'] = np.asarray(0.0)
self.default_dynamics_parameters['obj_obs_position_noise'] = np.asarray(0.0)
self.default_dynamics_parameters['obj_obs_velocity_noise'] = np.asarray(0.0)
self.default_dynamics_parameters['obj_angle_noise'] = np.asarray(0.0)
self.default_dynamics_parameters['obj_density'] = np.asarray(400)
self.default_dynamics_parameters['obj_size'] = np.array([0.0555 / 2, 0.0555 / 2, 0.03 / 2])
self.default_dynamics_parameters['obj_sliding_friction'] = np.asarray(0.4)
self.default_dynamics_parameters['obj_torsional_friction'] = np.asarray(0.01)
link_masses = np.zeros((7,))
for link_name, idx, body_node, mass_node, joint_node in self._robot_link_nodes_generator():
if (mass_node is not None):
dynamics_parameter_value = float(mass_node.get("mass"))
link_masses[idx] = dynamics_parameter_value
self.default_dynamics_parameters['link_masses'] = link_masses
self.default_dynamics_parameters['joint_dampings'] = self._default_damping_params()
self.default_dynamics_parameters['armatures'] = self._default_armature_params()
self.default_dynamics_parameters['joint_frictions'] = self._default_joint_friction_params()
if (use_pid):
gains = self.mujoco_robot.velocity_pid_gains
kps = np.array([gains['right_j{}'.format(actuator)]['p'] for actuator in range(7)])
kis = np.array([gains['right_j{}'.format(actuator)]['i'] for actuator in range(7)])
kds = np.array([gains['right_j{}'.format(actuator)]['d'] for actuator in range(7)])
#
self.default_dynamics_parameters['kps'] = kps
self.default_dynamics_parameters['kis'] = kis
self.default_dynamics_parameters['kds'] = kds
else:
kvs = np.zeros((7,))
for target_joint, jnt_idx, node in self._velocity_actuator_nodes_generator():
gains_value = float(node.get("kv"))
kvs[jnt_idx] = gains_value
self.default_dynamics_parameters['kvs'] = kvs
def _set_default_parameter_sampling_ranges(self):
"""
Returns the parameter ranges to draw samples from in the domain randomisation.
"""
parameter_ranges = {
'joint_forces': np.array([[0.,0.,0.,0.,0.,0.,0.], [1.5,1.5,1.5,1.5,1.5,1.5,1.5]]),#
'acceleration_forces': np.array([[0.,0.,0.,0.,0.,0.,0.], [0.05,0.05,0.05,0.05,0.05,0.05,0.05]]),#
'eef_forces': np.array([[0.,0.,0.,0.,0.,0.], [0.06 ,0.06,0.06,0.01,0.01,0.01,]]), #
'obj_forces': np.array([[0., 0., 0., 0., 0., 0., ], [0.0011, 0.0011, 0.0011, 0.0005, 0.0005, 0.0005, ]]),
'eef_timedelay': np.array([0, 1]),
'obj_timedelay': np.array([0,2]),
'timestep_parameter': np.array([0.0, 0.01]),
'pid_iteration_time': np.array([0., 0.04]),
'mujoco_timestep': np.array([0.001,0.002]),
'action_additive_noise': np.array([0.01, 0.1]),
'action_multiplicative_noise': np.array([0.005,0.02]),
'action_systematic_noise': np.array([-0.05, 0.05]),
'eef_obs_position_noise': np.array([0.0005, 0.001]),
'eef_obs_velocity_noise': np.array([0.0005, 0.001]),
'obj_obs_position_noise': np.array([0.0005, 0.001]),
'obj_obs_velocity_noise': np.array([0.0005, 0.0015]),
'obj_angle_noise': np.array([0.005, 0.05]),
'obj_density': np.array([100, 800]),
'obj_size': np.array([0.995, 1.005]),
'obj_sliding_friction': np.array([0.01, 0.8]),
'obj_torsional_friction': np.array([0.001, 0.3]),
'link_masses': | np.array([0.98, 1.02]) | numpy.array |
import pandas as pd
import numpy as np
import os
from sim.Bus import Bus
from sim.Route import Route
from sim.Busstop import Bus_stop
from sim.Passenger import Passenger
import matplotlib.pyplot as plt
pd.options.mode.chained_assignment = None
def getBusRoute(data):
my_path = os.path.abspath(os.path.dirname(__file__))
path = my_path + "/data/" + data + "/"
_path_trips = path + 'trips.txt'
_path_st = path + 'stop_times.txt'
trips = pd.DataFrame(pd.read_csv(_path_trips))
stop_times = pd.DataFrame(pd.read_csv(_path_st))
stop_times.dropna(subset=['arrival_time'], inplace=True)
bus_routes = {}
trip_ids = set(stop_times['trip_id'])
try:
service_id = trips.iloc[np.random.randint(0, trips.shape[0])]['service_id']
trips = trips[trips['service_id'] == service_id]
except:
pass
# each route_id may correspond to multiple trip_id
for trip_id in trip_ids:
# A completely same route indicates the same shape_id in trip file, but this field is not 100% provided by opendata
try:
if 'shape_id' in trips.columns:
route_id = str(trips[trips['trip_id'] == trip_id].iloc[0]['shape_id'])
block_id = ''
dir = ''
else:
route_id = str(trips[trips['trip_id'] == trip_id].iloc[0]['route_id'])
block_id = str(trips[trips['trip_id'] == trip_id].iloc[0]['block_id'])
dir = str(trips[trips['trip_id'] == trip_id].iloc[0]['trip_headsign'])
except:
continue
# Identifies a set of dates when service is available for one or more routes.
trip = stop_times[stop_times['trip_id'] == trip_id]
try:
trip['arrival_time'] = pd.to_datetime(trip['arrival_time'], format='%H:%M:%S')
except:
trip['arrival_time'] = pd.to_datetime(trip['arrival_time'], format="%Y-%m-%d %H:%M:%S")
trip = trip.sort_values(by='arrival_time')
trip_dist = trip.iloc[:]['shape_dist_traveled'].to_list()
if len(trip_dist) <= 0 or np.isnan(trip_dist[0]):
continue
schedule = ((trip.iloc[:]['arrival_time'].dt.hour * 60 + trip.iloc[:]['arrival_time'].dt.minute) * 60 +
trip.iloc[:]['arrival_time'].dt.second).to_list()
if len(schedule) <= 2 or np.isnan(schedule[0]):
continue
b = Bus(id=trip_id, route_id=route_id, stop_list=trip.iloc[:]['stop_id'].to_list(),
dispatch_time=schedule[0], block_id=block_id, dir=dir)
b.left_stop = []
b.speed = (trip_dist[1] - trip_dist[0]) / (schedule[1] - schedule[0])
b.c_speed = b.speed
for i in range(len(trip_dist)):
if str(b.stop_list[i]) in b.stop_dist:
b.left_stop.append(str(b.stop_list[i]) + '_' + str(i))
b.stop_dist[str(b.stop_list[i]) + '_' + str(i)] = trip_dist[i]
b.schedule[str(b.stop_list[i]) + '_' + str(i)] = schedule[i]
else:
b.left_stop.append(str(b.stop_list[i]))
b.stop_dist[str(b.stop_list[i])] = trip_dist[i]
b.schedule[str(b.stop_list[i])] = schedule[i]
b.stop_list = b.left_stop[:]
b.set()
if route_id in bus_routes:
bus_routes[route_id].append(b)
else:
bus_routes[route_id] = [b]
# Do not consider the route with only 1 trip
bus_routes_ = {}
for k, v in bus_routes.items():
if len(v) > 1:
bus_routes_[k] = v
return bus_routes_
def getStopList(data, read=0):
my_path = os.path.abspath(os.path.dirname(__file__))
path = my_path + "/data/" + data + "/"
_path_stops = path + 'stops.txt'
_path_st = path + 'stop_times.txt'
_path_trips = path + 'trips.txt'
stops = pd.DataFrame(pd.read_csv(_path_stops))
stop_times = pd.DataFrame(pd.read_csv(_path_st))
trips = pd.DataFrame(pd.read_csv(_path_trips))
stop_list = {}
select_stops = pd.merge(stops, stop_times, on=['stop_id'], how='left')
select_stops = select_stops.sort_values(by='shape_dist_traveled', ascending=False)
select_stops = select_stops.drop_duplicates(subset='stop_id', keep="first").sort_values(by='shape_dist_traveled',
ascending=True)
for i in range(select_stops.shape[0]):
stop = Bus_stop(id=str(select_stops.iloc[i]['stop_id']), lat=select_stops.iloc[i]['stop_lat'],
lon=select_stops.iloc[i]['stop_lon'])
stop.loc = select_stops.iloc[i]['shape_dist_traveled']
try:
stop.next_stop = str(select_stops.iloc[i + 1]['stop_id'])
except:
stop.next_stop = None
stop_list[str(select_stops.iloc[i]['stop_id'])] = stop
_path_demand = path + 'demand.csv'
pax_num = 0
try:
demand = pd.DataFrame(pd.read_csv(_path_demand))
except:
print('No available demand file')
return stop_list, 0
try:
demand['Ride_Start_Time'] = pd.to_datetime(demand['Ride_Start_Time'], format='%H:%M:%S')
except:
demand['Ride_Start_Time'] = pd.to_datetime(demand['Ride_Start_Time'], format="%Y-%m-%d %H:%M:%S")
demand['Ride_Start_Time_sec'] = (demand.iloc[:]['Ride_Start_Time'].dt.hour * 60 + demand.iloc[:][
'Ride_Start_Time'].dt.minute) * 60 + demand.iloc[:]['Ride_Start_Time'].dt.second
demand.dropna(subset=['ALIGHTING_STOP_STN'], inplace=True)
demand = demand[demand.ALIGHTING_STOP_STN != demand.BOARDING_STOP_STN]
demand = demand.sort_values(by='Ride_Start_Time_sec')
for stop_id, stop in stop_list.items():
demand_by_stop = demand[demand['BOARDING_STOP_STN'] == int(stop_id)]
# macro demand setting
if read == 0:
t = 0
while t < 24:
d = demand_by_stop[(demand_by_stop['Ride_Start_Time_sec'] >= t * 3600) & (
demand_by_stop['Ride_Start_Time_sec'] < (t + 1) * 3600)]
stop.dyna_arr_rate.append(d.shape[0] / 3600.)
for dest_id in stop_list.keys():
od = d[demand['ALIGHTING_STOP_STN'] == int(dest_id)]
if od.empty:
continue
if dest_id not in stop.dest:
stop.dest[dest_id] = [0 for _ in range(24)]
stop.dest[dest_id][t] = od.shape[0] / 3600.
t += 1
else:
# micro demand setting
for i in range(demand_by_stop.shape[0]):
pax = Passenger(id=demand_by_stop.iloc[i]['TripID'], origin=stop_id,
plan_board_time=float(demand_by_stop.iloc[i]['Ride_Start_Time_sec']))
pax.dest = str(int(demand_by_stop.iloc[i]['ALIGHTING_STOP_STN']))
pax.realcost = float(demand_by_stop.iloc[i]['Ride_Time']) * 60.
pax.route = str(demand_by_stop.iloc[i]['Srvc_Number']) + '_' + str(
int(demand_by_stop.iloc[i]['Direction']))
stop.pax[pax.id] = pax
pax_num += 1
return stop_list, pax_num
def demand_analysis(engine=None):
if engine is not None:
stop_list = list(engine.busstop_list.keys())
stop_hash = {}
i = 0
for p in stop_list:
stop_hash[p] = i
i += 1
# output data for stack area graph
demand = []
for t in range(24):
d = np.zeros(len(stop_list))
for s in stop_list:
for pid, pax in engine.busstop_list[s].pax.items():
if int((pax.plan_board_time - 0) / 3600) == t:
d[stop_hash[s]] += 1
demand.append(d)
df = pd.DataFrame(demand, columns=[str(i) for i in range(len(stop_list))])
df.to_csv('demand.csv')
return
def sim_validate(engine, data):
actual_onboard = []
sim_onboard = []
sim_travel_cost = []
actual_travel_cost = []
for pid, pax in engine.pax_list.items():
actual_onboard.append(pax.plan_board_time)
sim_onboard.append(pax.onboard_time)
sim_travel_cost.append(abs(pax.onboard_time - pax.alight_time))
actual_travel_cost.append(pax.realcost)
actual_onboard = np.array(actual_onboard)
sim_onboard = np.array(sim_onboard)
actual_travel_cost = np.array(actual_travel_cost)
sim_travel_cost = np.array(sim_travel_cost)
print('Boarding RMSE:%g' % (np.sqrt(np.mean((actual_onboard - sim_onboard) ** 2))))
print('Travel RMSE:%g' % (np.sqrt(np.mean((actual_travel_cost - sim_travel_cost) ** 2))))
sim_comp = pd.DataFrame()
sim_comp['actual_onboard'] = actual_onboard
sim_comp['sim_onboard'] = sim_onboard
sim_comp['sim_travel_cost'] = sim_travel_cost
sim_comp['actual_travel_cost'] = actual_travel_cost
sim_comp.to_csv('G:\\mcgill\\MAS\\gtfs_testbed\\result\\sim_comp' + str(data) + '.csv')
print('ok')
def visualize_pax(engine):
for pax_id, pax in engine.pax_list.items():
if pax.onboard_time < 999999999:
plt.plot([int(pax_id), int(pax_id)], [pax.arr_time, pax.onboard_time])
plt.show()
def train_result_track(eng, ep, qloss_log, ploss_log, log, name='', seed=0):
reward_bus_wise = []
reward_bus_wisep1 = []
reward_bus_wisep2 = []
rs = []
wait_cost = log['wait_cost']
travel_cost = log['travel_cost']
delay = log['delay']
hold_cost = log['hold_cost']
headways_var = log['headways_var']
headways_mean = log['headways_mean']
AOD = log["AOD"]
for bid, r in eng.reward_signal.items():
if len(r) > 0: # .bus_list[bid].forward_bus!=None and engine.bus_list[bid].backward_bus!=None :
reward_bus_wise.append(np.mean(r))
rs += r
reward_bus_wisep1.append(np.mean(eng.reward_signalp1[bid]))
reward_bus_wisep2.append(np.mean(eng.reward_signalp2[bid]))
if ep % 1 == 0:
train_log = pd.DataFrame()
train_log['bunching'] = [log['bunching']]
train_log['ploss'] = [np.mean(ploss_log)]
train_log['qloss'] = [np.mean(qloss_log)]
train_log['reward'] = [np.mean(reward_bus_wise)]
train_log['reward1'] = [np.mean(reward_bus_wisep1)]
train_log['reward2'] = [np.mean(reward_bus_wisep2)]
train_log['avg_hold'] = np.mean(hold_cost)
train_log['action'] = np.mean(np.array(eng.action_record))
train_log['wait'] = [np.mean(wait_cost)]
train_log['travel'] = [np.mean(travel_cost)]
train_log['delay'] = [np.mean(delay)]
train_log['AOD'] = AOD
for k, v in headways_mean.items():
train_log['headway_mean' + str(k)] = [np.mean(v)]
for k, v in headways_var.items():
train_log['headway_var' + str(k)] = [np.mean(v)]
res = pd.DataFrame()
res['stw'] = log['stw']
res['sto'] = log['sto']
res['sth'] = log['sth']
print(
'Episode: %g | reward: %g | reward_var: %g | reward1: %g | reward2: %g | ploss: %g | qloss: %g |\n wait '
'cost: %g | travel cost: %g | max hold :%g| min hold :%g| avg hold :%g | var hold :%g' % (
ep - 1, np.mean(reward_bus_wise), np.var(rs), np.mean(reward_bus_wisep1), np.mean(reward_bus_wisep2),
np.mean(ploss_log), np.mean(qloss_log), np.mean(wait_cost), np.mean(travel_cost), np.max(hold_cost),
| np.min(hold_cost) | numpy.min |
from __future__ import division
import collections
import re
import time
R_C_thres = 0.999
# file = codecs.open('out2.txt', 'r','utf-8') # for original utf with diacritics, does not help much
file = open('out2.txt', 'r')
texts = file.readlines()
file.close()
# taken from winLen.xls -- the numbers of documents for the individual days
# sum(ocNum) must match with len(texts)
# docNumDecJan=[7366,6591,6780,6640,6094,3542,3405,6405,6352,6586,6537,6166,3290,3335,6531,6227,6547,6873,6060,3276,3110,5582,4824,2704,2692,2878,2922,2947,5052,4750,3887,3123,4821,3291,3293,6550,6636,6599,6601,6410,3862,3759,6684,6589,6446,6498,6193,3416,3459,6626,6615,6625,6869,6544,3709,3701,6870,6586,6838,6765,6657,3882]
docNum = [3002, 5442, 5559, 3059, 3163, 6089, 6013, 6284, 5918, 5916, 3221, 3304, 6139, 5978, 6293, 6103, 5821, 3463,
3204, 6128, 6018, 6328, 6168, 3855, 4847, 3269, 6252, 5989, 6343, 6036, 6197, 3343, 3408, 6258, 6279, 6202,
6215, 5798, 3359, 3105, 6224, 6093, 6253, 6349, 5975, 3064, 3141, 6076, 6227, 6242, 6218, 5804, 3568, 3347,
6333, 6121, 6330, 6105, 6325, 3208, 3639, 6385, 6519, 6415, 6335, 5821, 3426, 3443, 6195, 6296, 6378, 6174,
6011, 3433, 3532, 6273, 6384, 6586, 6127, 6119, 3455, 3438, 6253, 6226, 6263, 6353, 6008, 3328, 2974, 6422,
6433, 6560, 6508, 6079, 3310, 3431, 6286, 6334, 6347, 6622, 5988, 3394, 3299, 6598, 6345, 6336, 6226, 5369,
3143, 2932, 3239, 6237, 6257, 6273, 6226, 3682, 3633, 6615, 6567, 6414, 4094, 5606, 3542, 3498, 6439, 6212,
6532, 3746, 5586, 3480, 3573, 6698, 6478, 6588, 6460, 5848, 3501, 3500, 6223, 6117, 6078, 6221, 5811, 3580,
3519, 6497, 6129, 6309, 6007, 5854, 3467, 3552, 6302, 6291, 6056, 6167, 5794, 3086, 3110, 6212, 6283, 6076,
6144, 5758, 3424, 3317, 6046, 6195, 5829, 5952, 5833, 3236, 2997, 5972, 5900, 6206, 6119, 5674, 3163, 2971,
5907, 5944, 5801, 5673, 5313, 3264, 2986, 5499, 3084, 7636, 5650, 5517, 3220, 3117, 5617, 5928, 5554, 5687,
5503, 3015, 2939, 5960, 5690, 5750, 6016, 5453, 3265, 3062, 5786, 6213, 5902, 5906, 5292, 3097, 3029, 5688,
5817, 5718, 5755, 5373, 2999, 2959, 5664, 5743, 5712, 5755, 5426, 3304, 3120, 5666, 5738, 5493, 5816, 5246,
3228, 3283, 5638, 5857, 5782, 5922, 5649, 3288, 3343, 6299, 6107, 6193, 6435, 5837, 3263, 3378, 6344, 6024,
6240, 6013, 5627, 3333, 3367, 6133, 6114, 6012, 6287, 6180, 3409, 3432, 6161, 6206, 6350, 6112, 6197, 3555,
3442, 6275, 6370, 6770, 6689, 6552, 3376, 3489, 6772, 6748, 6659, 6754, 6493, 3982, 3719, 6749, 6517, 6597,
6524, 6395, 3747, 3187, 6858, 6354, 6434, 3409, 8686, 3330, 3294, 5740, 3959, 6280, 6623, 6327, 3526, 3469,
6440, 6381, 6443, 6408, 6119, 3565, 3392, 6555, 6257, 6706, 6222, 6264, 3407, 3183, 3826, 6424, 6658, 6568,
6065, 3427, 3466, 6558, 6653, 6452, 6501, 6111, 3463, 3570, 7366, 6591, 6780, 6640, 6094, 3542, 3405, 6405,
6352, 6586, 6537, 6166, 3290, 3335, 6531, 6227, 6547, 6873, 6060, 3276, 3110, 5582, 4824, 2704, 2692, 2878,
2922, 2947, 5052, 4750, 3887, 3123, 4821, 3291, 3293, 6550, 6636, 6599, 6601, 6410, 3862, 3759, 6684, 6589,
6446, 6498, 6193, 3416, 3459, 6626, 6615, 6625, 6869, 6544, 3709, 3701, 6870, 6586, 6838, 6765, 6657, 3882]
N = round(sum(docNum) / len(docNum)) # set N to normalize the window sizes
docScale = [x / N for x in docNum]
print(texts[1].decode('string_escape')) # pouziti pro nacteni bez codecs, zobrazuje ceske znaky
# pomala varianta pres collections
# cte ve formatu: texts = ['John likes to watch movies. Mary likes too.','John also likes to watch football games.']
bagsofwords = [collections.Counter(re.findall(r'\w+', txt)) for txt in texts]
bagsofwords[0]
# get the document sums for the individual days, measue time
start = time.time()
sumbags = sum(bagsofwords[501:1000], collections.Counter()) # time consuming, 500 docs takes 76s
end = time.time()
print(end - start)
# rychlejsi varianta pres sparse matrices
from sklearn.feature_extraction.text import CountVectorizer
import numpy as np
c = CountVectorizer(min_df=30, max_df=100000) # ignore all the words that appear in fewer than min_df docs
# 2 months ... takes less than 1min, size 328468x450642, 30740640 stored elements for min_df=1, about 1/3 of the words
# for min_df=3, for the annual data and min_df=20 shape 2090635 x 157556
bow_matrix = c.fit_transform(texts).astype(bool)
# bow_matrix = c.fit_transform(texts[0:7366]) # sparse numpy int64 matrix originates, scipy.sparse.coo_matrix
# c.vocabulary_ # get mapping between words and column indices, for complete data extremely large to print
c.vocabulary_['rebel'] # index 127576
c.vocabulary_.keys()[127576] # list of keys but not the same order as in coo matrix
print(c.vocabulary_.keys()[c.vocabulary_.values().index(127576)]) # this works
inv_vocabulary = {v: k for k, v in c.vocabulary_.items()} # general vocabulary transpose
inv_vocabulary[127576] # rebel
inv_vocabulary[183107] # rebel
def annot_list(ind):
return [inv_vocabulary[k] for k in ind]
bow_matrix.sum(1) # total word counts in each document, fast
word_sums = bow_matrix.sum(0) # the counts of each word in all documents, slower but still works
bow_matrix.sum(0).shape
# get the counts for the individual days
offset = 0
sum_matrix = np.empty([len(docNum), bow_matrix.shape[1]], dtype=int)
offset_store = [0]
for i in range(len(docNum)):
sum_matrix[i] = bow_matrix[offset:offset + docNum[i]].sum(0)
offset += docNum[i]
offset_store.append(offset)
# dfidf ad He et al.: Analyzing feature trajectories for event detection
# idf ... word importance, more frequent words are less important
idf = np.log(sum(docNum) / sum_matrix.sum(0))
dfidf = sum_matrix / np.tile(docNum, [sum_matrix.shape[1], 1]).T * np.tile(idf, [len(docNum), 1])
# normalize to uniform N, round to simplify e.g. future computations of binomial coeffiecients
sum_matrix_norm = (np.round(sum_matrix / np.tile(docScale, [sum_matrix.shape[1], 1]).T)).astype(int)
# the final check, the sum of window counts must be the total sum
# the last window has to be +1 to make it work
check = sum_matrix.sum(0) - word_sums
check.sum()
from scipy.special import binom
from scipy.stats import binom as binm
from scipy.stats import logistic
# turn frequencies into probs
p_o = sum_matrix / np.tile(docNum, [sum_matrix.shape[1],
1]).T # observed word probs, check that "from __future__ import division" was called
p_o_norm = np.divide(sum_matrix, N) # observed word probs for normalized sum_matrix
# p_j = p_o.mean(0) # mean word observed prob vector, rewrite, zero probs do not count
def get_pj_slow(obs):
pj = np.empty(obs.shape[1])
for i in range(len(pj)):
pj[i] = obs[:, i][obs[:, i] > 0].mean()
return pj
def get_pj(obs):
obs[obs == 0] = np.nan
return np.nanmean(obs, 0)
p_j = get_pj(p_o)
# for normalized sum_matrix only, docNum replaced by N, faster but approximate probs only
# robust towards high binom coefficients, log approach taken
def get_p_g_norm_robust(N, sum_matrix, p_j):
# precompute binom coefs up to max number in sum_matrix
def mylogbc(max):
mylogbc = np.zeros(max + 1)
for i in range(max):
mylogbc[i + 1] = mylogbc[i] + np.log(N - i) - np.log(i + 1)
return mylogbc
def mylogbin(n, p):
return preclogbin[n] + n * np.log(p) + (N - n) * np.log(1 - p)
mylogbin = np.vectorize(mylogbin)
preclogbin = mylogbc(np.max(sum_matrix))
p_g = np.empty(sum_matrix.shape)
for words in range(p_g.shape[1]):
p_g[:, words] = mylogbin(sum_matrix[:, words], p_j[words])
return np.exp(p_g)
# for normalized sum_matrix only, docNum replaced by N, faster but approximate probs only
# fails for word counts and thus overflow binom coefficients!!!
def get_p_g_norm(N, sum_matrix, p_j):
def mybin(n, p):
return binom(N, n) * p ** n * (1 - p) ** (N - n)
mybin = np.vectorize(mybin)
p_g = np.empty(sum_matrix.shape)
for words in range(p_g.shape[1]):
p_g[:, words] = mybin(sum_matrix[:, words], p_j[words])
return p_g
# for normalized sum_matrix only, docNum replaced by N, faster but approximate probs only
def get_r_c_thres_norm(N, sum_matrix, p_j):
r_c_thres = np.empty(sum_matrix.shape[1])
for words in range(sum_matrix.shape[1]):
r_c_thres[words] = binm.ppf(R_C_thres, N, p_j[words])
return r_c_thres
# at the moment, the most time consuming part
# can be made faster by normalizing to the same window size -- use docScale
np.mean(p_o, axis=0) # p_o.mean(0) changes p_o, places nans there
p_g = np.empty([len(docNum), bow_matrix.shape[
1]]) # prob that the given number of words is observed in the given day purely randomly
r_c_thres = np.empty(p_g.shape)
for days in range(len(docNum)):
for words in range(len(p_j)):
p_g[days, words] = binom(docNum[days], sum_matrix[days, words]) * p_j[words] ** sum_matrix[days, words] * (1 -
p_j[
words]) ** (
docNum[
days] -
sum_matrix[
days, words])
# find the border of R_C region
r_c_thres[days, words] = binm.ppf(R_C_thres, docNum[days], p_j[words])
p_g_norm = get_p_g_norm_robust(N, sum_matrix_norm, p_j)
r_c_thres_norm = get_r_c_thres_norm(N, sum_matrix_norm, p_j)
# construct bursty features, start with the individual ones
p_b = np.zeros(p_o.shape)
# p_b[p_o>np.tile(p_j,[p_o.shape[0],1])]=1 # the initial necessary condition, not in R_A region
# p_b[sum_matrix>r_c_thres]=1 # the sufficient condition, in R_C region
p_b[sum_matrix_norm > np.tile(r_c_thres_norm,
[sum_matrix_norm.shape[0], 1])] = 1 # the sufficient condition, in R_C region
# sigmoid function for R_B region
# p_b[np.logical_and(sum_matrix<r_c_thres,p_o>np.tile(p_j,[p_o.shape[0],1]))]=...
for days in range(len(docNum)):
for words in range(len(p_j)):
# if sum_matrix[days,words]<r_c_thres[days,words] and p_o[days,words]>p_j[words]:
# p_b[days,words] = logistic.cdf(sum_matrix[days,words]-(r_c_thres[days,words]+p_j[words]*docNum[days])/2)
if sum_matrix_norm[days, words] < r_c_thres_norm[words] and p_o[days, words] > p_j[words]:
p_b[days, words] = logistic.cdf(sum_matrix_norm[days, words] - (r_c_thres_norm[words] + p_j[words] * N) / 2)
# find the most striking bursts
# there are many features with at least one non-zero burst signal ..., get their indeces
[j for (i, j) in zip(sum(p_b), range(p_b.shape[1])) if i > 0]
# find bursty features, those whose mean burstyness is more than thres times above average -- this rather promotes high frequency features
def get_bwords_mean(p_b, thres):
bbool = p_b.mean(0) > thres * np.mean(p_b)
return np.where(bbool)[0]
def docOverlap(bow_matrix_bin, w1, w2):
# tests the document overlap between twor words, i.e., in what percentage of docs the words appear together
# the calculation is limited to a specific period under consideration
intersec = np.logical_and(bow_matrix_bin[:, w1], bow_matrix_bin[:, w2]).sum()
if intersec > 0:
intersec = intersec / min(bow_matrix_bin[:, w1].sum(), bow_matrix_bin[:, w2].sum())
return (intersec)
# an alternative definition would be to find at least one strong burst -- a consecutive series of non-zero series in its p_b vector
# it makes no sense to search for individual days, nearly every word is bursty at least in one day
# thres gives the minimum length of the series (in days here)
def get_bwords_series(p_b, thres):
def bseries(a):
# count the longest nonzero series in array a
return np.max(np.diff(np.where(a == 0))) - 1
bbool = [False] * p_b.shape[1]
for words in range(p_b.shape[1]):
bbool[words] = bseries(p_b[:, words]) > thres
return np.where(bbool)[0]
def wherebseries(a):
# find where is the longest bseries
ls = np.diff(np.where(a == 0))[0]
l = np.max(ls)
# take the first occurence only
f = np.sum(ls[0:np.where(ls == l)[0][0]])
return [f + 1, f + l]
def wheretseries(a, thres):
# find where are all the above-threshold series
ls = np.diff(np.where(a == 0))[0]
ts = np.where(ls > thres)[0]
w = []
for t in ts:
# repeat for every subseries
f = np.sum(ls[0:t])
w.append([f + 1, f + ls[t]])
return w
# identify events based on the overlaps between words with a long series of above-average days
# thres is the minimum length of series in days
# sim_thres is the minimum time overlap bwetween a pair of series in %
# doc_sim_thres is the minimum overlap bwetween a pair of words in the given period in terms of the particular documkents in %
def get_series_overlaps(p_b_slice, bwords, thres, sim_thres, doc_sim_thres):
def getOverlap(a, b):
# finds the overlap between two ranges in terms of the percentage of the size of the smaller range
return max(0, min(a[1], b[1]) - max(a[0], b[0])) / max(a[1] - a[0], b[1] - b[0])
def newEvent(e, eList):
# tests whether e is contained in the list or not
newEvent = True
for eL in eList:
if len(np.intersect1d(e, eL[1])) == min(len(e), len(eL[1])):
newEvent = False
break
return (newEvent)
# find all the individual bword series (i.e., the longest consecutive range where p_b is non-zero for each feature)
# bseries is a list of lists, for each bursty word there is a list of its continuous bursty periods longer than the threshold
bseries = []
for b in range(p_b_slice.shape[1]):
bseries.append(wheretseries(p_b_slice[:, b], thres))
# make a flat equivalent
bseries_flat = [item for sublist in bseries for item in sublist]
bseries_len = [len(x) for x in bseries]
# map bseries_flat back to the bursty words
bseries_ind = []
for i in range(len(bseries_len)):
bseries_ind += [i] * bseries_len[i]
bseries_ind = np.array(bseries_ind)
# get an overlap similarity matrix, for each pair of periods in bseries_flat
overmat = np.triu([1.0] * len(bseries_flat))
for r in range(len(bseries_flat)):
for c in range(r + 1, len(bseries_flat)):
overmat[r, c] = getOverlap(bseries_flat[r], bseries_flat[c])
# merge the bursty periods/series into events
# for each event, build the list of words whose overlap is higher than sim_thres
bevents = []
for r in range(len(bseries_flat)): # iterate over all the bursty perioeds and all the bursty words
e_periods = np.where(overmat[r, :] > sim_thres)[0]
# there is a chance to build an event for the given word and period
if len(e_periods) > 1:
e_words = bseries_ind[e_periods]
# pruning based on coocurence in the same docs, relate to the core (first) word only
period_slice = bow_matrix[offset_store[bseries_flat[r][0]]:offset_store[bseries_flat[r][1]],
bwords[e_words]].todense()
todel = []
for w in range(1, len(e_words)): # skip the period index
if docOverlap(period_slice, 0, w) < doc_sim_thres:
todel.append(w)
e_words = np.delete(e_words, todel)
if (newEvent(e_words, bevents) and len(e_words) > 1):
e = [bseries_flat[r], e_words.tolist()]
bevents.append(e)
return (bevents)
# get a binary word vector for an event, return p(ek)
# the unioin of burst probability series is given by their total sum
# the intersection of burst probability series is given by sum of miinimum values achieved in all the windows
def get_p_ek(p_b, E):
return np.log(sum(p_b[:, E].min(1)) / np.sum(p_b[:, E]))
# no infinity values
def get_p_ek_nolog(p_b, E):
return sum(p_b[:, E].min(1)) / np.sum(p_b[:, E])
# get a binary word vector for the list of bursty features and a specific bursty event, return p(d|ek)
def get_p_d_ek(D_sizes_norm, D_sizes_all, E):
# E=np.searchsorted(bwords,ewords) # find local event indices in bwords and thus D_sezes array
negE = np.delete(np.arange(np.alen(range(len(D_sizes_norm)))), E) # find its complement
return np.sum(np.log(np.concatenate([D_sizes_norm[E], 1 - D_sizes_all[negE]])))
# finds the optimal event a subset of bursty features that minimizes -log(p_ek_d), ie. maximizes the prob
# employs greedy stepwise search
def find_ek(bow_slice, p_b_slice, D_sizes, D_all):
best_p_ek_d = float("inf")
# find the best pair of bursty features first
for i in range(len(D_sizes)):
for j in range(i + 1, len(D_sizes)):
# get sum of docs that contain any of the event words
M_size = np.sum(bow_slice[:, [i, j]].sum(
1) > 0) # sums the ewords in the individual documents first, then gets the number of docs that have non-zero sums
D_sizes_norm = D_sizes / float(M_size)
D_sizes_all = D_sizes / float(D_all)
# M_size=np.sum(D_sizes) # not the same as previous row, uses D-sizes, does not implement union
p_ek_d = (-get_p_ek(p_b_slice, [i, j]) - get_p_d_ek(D_sizes_norm, D_sizes_all, [i, j]))
if p_ek_d < best_p_ek_d:
best_p_ek_d = p_ek_d
ek = [i, j]
print(ek)
# extend the best pair
while True:
extendable = False # tests that the last extension helped
for i in np.delete(range(len(D_sizes)), ek):
ek_cand = np.concatenate([ek, [i]])
M_size = np.sum(bow_slice[:, ek_cand].sum(
1) > 0) # sums the ewords in the individual documents first, then gets the number of docs that have non-zero sums
D_sizes_norm = D_sizes / float(M_size)
D_sizes_all = D_sizes / float(D_all)
p_ek_d = (-get_p_ek(p_b_slice, ek_cand) - get_p_d_ek(D_sizes_norm, D_sizes_all, ek_cand))
if p_ek_d < best_p_ek_d:
best_p_ek_d = p_ek_d
ek = np.concatenate([ek, i])
extendable = True
if not extendable:
break
return ek
# finds the optimal split of bursty words into events, HB event algorithm
def find_all_ek(bow_matrix, p_b, bwords):
# get sums of docs that contain individual bursty words
D_sizes = np.squeeze(
np.asarray((bow_matrix[:, bwords] > 0).sum(0))) # squeeze and asarray to turn [1,n] matrix into array
ek_list = []
while True:
ek = find_ek(bow_matrix[:, bwords], p_b[:, bwords], D_sizes, bow_matrix.shape[0])
ek_list.append(bwords[ek])
bwords = np.delete(bwords, ek)
D_sizes = np.delete(D_sizes, ek)
if len(bwords) < 2:
break
return (ek_list)
# performs a greedy search through a dist matrix starting at the position where
# return all the words who match the pair of seed words above threshold
def greedyMat(p_ek_mat, where, thres):
ek = np.intersect1d(np.where(p_ek_mat[where[0], :] > thres), np.where(p_ek_mat[where[1], :] > thres))
return (np.union1d(where, ek))
# finds the optimal split of bursty words into events, based on calculation of pairwise p_ek and greedy search
def find_all_ek_fast(bow_matrix, p_b, bwords):
# get an p_ek pairwise matrix, for each pair of bwords
# p_ek_mat=np.triu([0.0]*len(bwords))
p_ek_mat = np.zeros([len(bwords), len(bwords)])
for r in range(len(bwords)):
for c in range(r + 1, len(bwords)):
p_ek_mat[r, c] = get_p_ek_nolog(p_b, [r, c])
p_ek_mat[c, r] = p_ek_mat[r, c]
ek_list = []
thres = np.percentile(np.triu(p_ek_mat), 95)
while True:
seed_val = np.max(p_ek_mat)
if seed_val < thres:
break
where = np.where(p_ek_mat == seed_val)
where = [where[0][0], where[1][0]]
ek = greedyMat(p_ek_mat, where, thres)
# validate against document overlap
# find the longest common peridd for the seed
ek_period = wherebseries(p_b[:, where].min(1))
seed = np.where(np.logical_or(ek == where[0], ek == where[1]))
period_slice = bow_matrix[offset_store[ek_period[0]]:offset_store[ek_period[1]], bwords[ek]].todense()
todel = []
for w in range(len(ek)): # skip the period index
if (docOverlap(period_slice, seed[0][0], w) < 0.2) | (docOverlap(period_slice, seed[0][1], w) < 0.2):
todel.append(w)
ek = np.delete(ek, todel)
if len(ek) > 1:
ek_list.append([ek_period, ek.tolist()])
# delete the event from the p_ek_mat in order not to repeat it
for w1 in ek:
for w2 in ek:
p_ek_mat[w1, w2] = 0
# delete the seed anyway
p_ek_mat[where] = 0
p_ek_mat[where[1], where[0]] = 0
# perform DBSCAN, does not need prior k
# db=DBSCAN(eps=2,metric='precomputed').fit(p_ek_mat)
# however, results seem weird
# labels=db.labels_
return (ek_list)
import matplotlib.pyplot as plt
# red dashes, blue squares and green triangles
# plt.plot(range(len(docNum)), sum_matrix[:,0], 'r--', range(len(docNum)), sum_matrix[:,183107], 'bs-', range(len(docNum)), sum_matrix[:,127576], 'g^-')
def comp_freq_plot(words, mode='f', tofile=False, num='', period=''):
l = list()
a = annot_list(words)
if mode == 'f':
toplot = sum_matrix
title = 'Word frequency in time windows'
ylabel = 'frequency'
elif mode == 'p':
toplot = p_g_norm
title = 'Prob that the given frequency was observed randomly'
ylabel = 'rand prob'
else:
toplot = p_o
title = 'Observed prob, the burst period' + period
ylabel = 'prob'
for i in range(len(words)):
temp, = plt.plot(toplot[:, words[i]], label=a[i])
l.append(temp)
plt.xlabel('day')
plt.ylabel(ylabel)
plt.title(title)
plt.grid(True)
plt.legend(l, a)
if tofile:
fig = plt.gcf()
fig.savefig('graphs/' + num + '_' + a[0] + '.png')
plt.close(fig)
else:
plt.show()
def bevents_plots(bevents, bwords):
# generates and saves a set of plots for all the bevents
for e in bevents:
comp_freq_plot(bwords[e[1]], 'o', True, str(e[1][0]), str(e[0]))
# the approach ad Fung
bwords = get_bwords_mean(p_b,
5) # generate a short list of bursty words, words must have x times higher mean burstyness than the average
bevents = find_all_ek(bow_matrix, p_b, bwords) # slow, use the next call instead
bevents = find_all_ek_fast(bow_matrix, p_b, bwords)
bevents_plots(bevents, bwords)
# period-based approach
# the minimum length of bursty event
len_thres = 12
bwords = get_bwords_series(p_b, len_thres) # generate a short list of bursty words, a high threshold selected
bevents = get_series_overlaps(p_b[:, bwords], bwords, len_thres, 0.9, 0.1)
bevents_plots(bevents, bwords)
annot_list(bwords)
comp_freq_plot(
bwords) # plot frequencies in the individual windows, it is not informative as e.g. weekend windows are shorter
comp_freq_plot(bwords, 'p') # plot observed probs
eks = find_all_ek(bow_matrix, p_b, bwords)
comp_freq_plot([4025, 15300, 37341, 73946, 73617, 85483, 87802, 95719, 111648, 118184],
'o') # u'async', u'configuration', u'pasting', u'push', u'replac', u'size', u'variables', u'webpag'
comp_freq_plot([14441, 31984, 86332], 'o') # u'civilista', u'hamas', u'raketa
comp_freq_plot([70027, 76395], 'o') # u'off, u'play
comp_freq_plot([7025, 17222, 76429, 80995, 84213, 101669, 111570],
'o') # u'betlem', u'darek', u'pleas', u'predplatit', u'prosinec', u'stromecek', u'vanoce
comp_freq_plot(bwords[[0, 2]], 'o')
comp_freq_plot(eks[0], 'o')
l1, = plt.plot(p_g[:, 127576], label=inv_vocabulary[127576])
l2, = plt.plot(p_g[:, 183107], label=inv_vocabulary[183107])
plt.xlabel('day')
plt.ylabel('rand prob')
plt.title('Prob that the given frequency was observed randomly')
plt.grid(True)
plt.legend([l1, l2], [inv_vocabulary[127576], inv_vocabulary[183107]])
plt.show()
# fft approach
def get_dps(t):
# for a time series finds its dominant period and dominant power spectrum
fft = np.fft.fft(t, n=int(len(t) / 2))
dps = max(fft)
dp = len(t) / (np.where(fft == dps)[0][0] + 1)
return ([fft, dp, abs(dps)])
dps = []
for w in range(dfidf.shape[1]):
dps.append(get_dps(dfidf[:, w]))
# turning to dense format is not possible
ba = bow_matrix[0:7366].toarray() # for the whole matrix a memory error
ba.shape
np.sum(ba, axis=0)
| np.where() | numpy.where |
import numpy as np
def RotX(th):
sth, cth = np.sin(th), np.cos(th)
return np.array([[1,0,0],[0,cth,-sth],[0,sth,cth]])
def RotY(th):
sth, cth = np.sin(th), np.cos(th)
return np.array([[cth,0,sth],[0,1,0],[-sth,0,cth]])
def RotZ(th):
sth, cth = np.sin(th), np.cos(th)
return np.array([[cth,-sth,0],[sth,cth,0],[0,0,1]])
class CoordSys:
"""A coordinate system against which to measure surfaces or rays.
Coordinate systems consist of an origin and a rotation. The ``origin``
attribute specifies where in 3D space the current coordinate system's
origin lands in the global coordinate system. The rotation ``rot``
specifies the 3D rotation matrix to apply to the global coordinate axes to
yield the axes of the this coordinate system.
Parameters
----------
origin : ndarray of float, shape (3,)
Origin of coordinate system in global coordinates.
rot : ndarray of float, shape (3, 3)
Rotation matrix taking global axes into current system axes.
"""
def __init__(self, origin=None, rot=None):
if origin is None:
origin = | np.zeros(3, dtype=float) | numpy.zeros |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.